]> git.proxmox.com Git - ceph.git/blob - ceph/src/fmt/test/gmock-gtest-all.cc
buildsys: switch source download to quincy
[ceph.git] / ceph / src / fmt / test / gmock-gtest-all.cc
1 // Copyright 2008, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: mheule@google.com (Markus Heule)
31 //
32 // Google C++ Testing Framework (Google Test)
33 //
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
36
37 // This line ensures that gtest.h can be compiled on its own, even
38 // when it's fused.
39 #include "gtest.h"
40
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
44 //
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
47 // met:
48 //
49 // * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 // * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
54 // distribution.
55 // * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
58 //
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70 //
71 // Author: wan@google.com (Zhanyong Wan)
72 //
73 // The Google C++ Testing Framework (Google Test)
74
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
77 //
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
80 // met:
81 //
82 // * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 // * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
87 // distribution.
88 // * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
91 //
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
103 //
104 // Author: wan@google.com (Zhanyong Wan)
105 //
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
108
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 # define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
111
112 namespace testing {
113
114 // This helper class can be used to mock out Google Test failure reporting
115 // so that we can test Google Test or code that builds on Google Test.
116 //
117 // An object of this class appends a TestPartResult object to the
118 // TestPartResultArray object given in the constructor whenever a Google Test
119 // failure is reported. It can either intercept only failures that are
120 // generated in the same thread that created this object or it can intercept
121 // all generated failures. The scope of this mock object can be controlled with
122 // the second argument to the two arguments constructor.
123 class GTEST_API_ ScopedFakeTestPartResultReporter
124 : public TestPartResultReporterInterface {
125 public:
126 // The two possible mocking modes of this object.
127 enum InterceptMode {
128 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
129 INTERCEPT_ALL_THREADS // Intercepts all failures.
130 };
131
132 // The c'tor sets this object as the test part result reporter used
133 // by Google Test. The 'result' parameter specifies where to report the
134 // results. This reporter will only catch failures generated in the current
135 // thread. DEPRECATED
136 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
137
138 // Same as above, but you can choose the interception scope of this object.
139 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
140 TestPartResultArray* result);
141
142 // The d'tor restores the previous test part result reporter.
143 virtual ~ScopedFakeTestPartResultReporter();
144
145 // Appends the TestPartResult object to the TestPartResultArray
146 // received in the constructor.
147 //
148 // This method is from the TestPartResultReporterInterface
149 // interface.
150 virtual void ReportTestPartResult(const TestPartResult& result);
151
152 private:
153 void Init();
154
155 const InterceptMode intercept_mode_;
156 TestPartResultReporterInterface* old_reporter_;
157 TestPartResultArray* const result_;
158
159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
160 };
161
162 namespace internal {
163
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring. If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker {
170 public:
171 // The constructor remembers the arguments.
172 SingleFailureChecker(const TestPartResultArray* results,
173 TestPartResult::Type type, const string& substr);
174 ~SingleFailureChecker();
175
176 private:
177 const TestPartResultArray* const results_;
178 const TestPartResult::Type type_;
179 const string substr_;
180
181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
182 };
183
184 } // namespace internal
185
186 } // namespace testing
187
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures. It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
192 //
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
196 //
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
199 //
200 // Known restrictions:
201 // - 'statement' cannot reference local non-static variables or
202 // non-static members of the current object.
203 // - 'statement' cannot return a value.
204 // - You cannot stream a failure message to this macro.
205 //
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 # define EXPECT_FATAL_FAILURE(statement, substr) \
212 do { \
213 class GTestExpectFatalFailureHelper { \
214 public: \
215 static void Execute() { statement; } \
216 }; \
217 ::testing::TestPartResultArray gtest_failures; \
218 ::testing::internal::SingleFailureChecker gtest_checker( \
219 &gtest_failures, ::testing::TestPartResult::kFatalFailure, \
220 (substr)); \
221 { \
222 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
223 ::testing::ScopedFakeTestPartResultReporter:: \
224 INTERCEPT_ONLY_CURRENT_THREAD, \
225 &gtest_failures); \
226 GTestExpectFatalFailureHelper::Execute(); \
227 } \
228 } while (::testing::internal::AlwaysFalse())
229
230 # define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
231 do { \
232 class GTestExpectFatalFailureHelper { \
233 public: \
234 static void Execute() { statement; } \
235 }; \
236 ::testing::TestPartResultArray gtest_failures; \
237 ::testing::internal::SingleFailureChecker gtest_checker( \
238 &gtest_failures, ::testing::TestPartResult::kFatalFailure, \
239 (substr)); \
240 { \
241 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
242 ::testing::ScopedFakeTestPartResultReporter:: \
243 INTERCEPT_ALL_THREADS, \
244 &gtest_failures); \
245 GTestExpectFatalFailureHelper::Execute(); \
246 } \
247 } while (::testing::internal::AlwaysFalse())
248
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures. It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
253 //
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257 //
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
260 //
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
263 //
264 // Known restrictions:
265 // - You cannot stream a failure message to this macro.
266 //
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works. If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma. The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274 // catches that.
275 //
276 // For the same reason, we have to write
277 // if (::testing::internal::AlwaysTrue()) { statement; }
278 // instead of
279 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 # define EXPECT_NONFATAL_FAILURE(statement, substr) \
282 do { \
283 ::testing::TestPartResultArray gtest_failures; \
284 ::testing::internal::SingleFailureChecker gtest_checker( \
285 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
286 (substr)); \
287 { \
288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
289 ::testing::ScopedFakeTestPartResultReporter:: \
290 INTERCEPT_ONLY_CURRENT_THREAD, \
291 &gtest_failures); \
292 if (::testing::internal::AlwaysTrue()) { \
293 statement; \
294 } \
295 } \
296 } while (::testing::internal::AlwaysFalse())
297
298 # define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
299 do { \
300 ::testing::TestPartResultArray gtest_failures; \
301 ::testing::internal::SingleFailureChecker gtest_checker( \
302 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
303 (substr)); \
304 { \
305 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
306 ::testing::ScopedFakeTestPartResultReporter:: \
307 INTERCEPT_ALL_THREADS, \
308 &gtest_failures); \
309 if (::testing::internal::AlwaysTrue()) { \
310 statement; \
311 } \
312 } \
313 } while (::testing::internal::AlwaysFalse())
314
315 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
316
317 #include <ctype.h>
318 #include <math.h>
319 #include <stdarg.h>
320 #include <stdio.h>
321 #include <stdlib.h>
322 #include <time.h>
323 #include <wchar.h>
324 #include <wctype.h>
325
326 #include <algorithm>
327 #include <iomanip>
328 #include <limits>
329 #include <ostream> // NOLINT
330 #include <sstream>
331 #include <vector>
332
333 #if GTEST_OS_LINUX
334
335 // TODO(kenton@google.com): Use autoconf to detect availability of
336 // gettimeofday().
337 # define GTEST_HAS_GETTIMEOFDAY_ 1
338
339 # include <fcntl.h> // NOLINT
340 # include <limits.h> // NOLINT
341 # include <sched.h> // NOLINT
342 // Declares vsnprintf(). This header is not available on Windows.
343 # include <strings.h> // NOLINT
344 # include <sys/mman.h> // NOLINT
345 # include <sys/time.h> // NOLINT
346 # include <unistd.h> // NOLINT
347
348 # include <string>
349
350 #elif GTEST_OS_SYMBIAN
351 # define GTEST_HAS_GETTIMEOFDAY_ 1
352 # include <sys/time.h> // NOLINT
353
354 #elif GTEST_OS_ZOS
355 # define GTEST_HAS_GETTIMEOFDAY_ 1
356 # include <sys/time.h> // NOLINT
357
358 // On z/OS we additionally need strings.h for strcasecmp.
359 # include <strings.h> // NOLINT
360
361 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
362
363 # include <windows.h> // NOLINT
364
365 #elif GTEST_OS_WINDOWS // We are on Windows proper.
366
367 # include <io.h> // NOLINT
368 # include <sys/stat.h> // NOLINT
369 # include <sys/timeb.h> // NOLINT
370 # include <sys/types.h> // NOLINT
371
372 # if GTEST_OS_WINDOWS_MINGW
373 // MinGW has gettimeofday() but not _ftime64().
374 // TODO(kenton@google.com): Use autoconf to detect availability of
375 // gettimeofday().
376 // TODO(kenton@google.com): There are other ways to get the time on
377 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
378 // supports these. consider using them instead.
379 # define GTEST_HAS_GETTIMEOFDAY_ 1
380 # include <sys/time.h> // NOLINT
381 # endif // GTEST_OS_WINDOWS_MINGW
382
383 // cpplint thinks that the header is already included, so we want to
384 // silence it.
385 # include <windows.h> // NOLINT
386
387 #else
388
389 // Assume other platforms have gettimeofday().
390 // TODO(kenton@google.com): Use autoconf to detect availability of
391 // gettimeofday().
392 # define GTEST_HAS_GETTIMEOFDAY_ 1
393
394 // cpplint thinks that the header is already included, so we want to
395 // silence it.
396 # include <sys/time.h> // NOLINT
397 # include <unistd.h> // NOLINT
398
399 #endif // GTEST_OS_LINUX
400
401 #if GTEST_HAS_EXCEPTIONS
402 # include <stdexcept>
403 #endif
404
405 #if GTEST_CAN_STREAM_RESULTS_
406 # include <arpa/inet.h> // NOLINT
407 # include <netdb.h> // NOLINT
408 #endif
409
410 // Indicates that this translation unit is part of Google Test's
411 // implementation. It must come before gtest-internal-inl.h is
412 // included, or there will be a compiler error. This trick is to
413 // prevent a user from accidentally including gtest-internal-inl.h in
414 // his code.
415 #define GTEST_IMPLEMENTATION_ 1
416 // Copyright 2005, Google Inc.
417 // All rights reserved.
418 //
419 // Redistribution and use in source and binary forms, with or without
420 // modification, are permitted provided that the following conditions are
421 // met:
422 //
423 // * Redistributions of source code must retain the above copyright
424 // notice, this list of conditions and the following disclaimer.
425 // * Redistributions in binary form must reproduce the above
426 // copyright notice, this list of conditions and the following disclaimer
427 // in the documentation and/or other materials provided with the
428 // distribution.
429 // * Neither the name of Google Inc. nor the names of its
430 // contributors may be used to endorse or promote products derived from
431 // this software without specific prior written permission.
432 //
433 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
434 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
435 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
436 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
437 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
438 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
439 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
440 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
441 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
442 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
443 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
444
445 // Utility functions and classes used by the Google C++ testing framework.
446 //
447 // Author: wan@google.com (Zhanyong Wan)
448 //
449 // This file contains purely Google Test's internal implementation. Please
450 // DO NOT #INCLUDE IT IN A USER PROGRAM.
451
452 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
453 # define GTEST_SRC_GTEST_INTERNAL_INL_H_
454
455 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
456 // part of Google Test's implementation; otherwise it's undefined.
457 # if !GTEST_IMPLEMENTATION_
458 // A user is trying to include this from his code - just say no.
459 # error \
460 "gtest-internal-inl.h is part of Google Test's internal implementation."
461 # error "It must not be included except by Google Test itself."
462 # endif // GTEST_IMPLEMENTATION_
463
464 # ifndef _WIN32_WCE
465 # include <errno.h>
466 # endif // !_WIN32_WCE
467 # include <stddef.h>
468 # include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
469 # include <string.h> // For memmove.
470
471 # include <algorithm>
472 # include <string>
473 # include <vector>
474
475 # if GTEST_CAN_STREAM_RESULTS_
476 # include <arpa/inet.h> // NOLINT
477 # include <netdb.h> // NOLINT
478 # endif
479
480 # if GTEST_OS_WINDOWS
481 # include <windows.h> // NOLINT
482 # endif // GTEST_OS_WINDOWS
483
484 namespace testing {
485
486 // Declares the flags.
487 //
488 // We don't want the users to modify this flag in the code, but want
489 // Google Test's own unit tests to be able to access it. Therefore we
490 // declare it here as opposed to in gtest.h.
491 GTEST_DECLARE_bool_(death_test_use_fork);
492
493 namespace internal {
494
495 // The value of GetTestTypeId() as seen from within the Google Test
496 // library. This is solely for testing GetTestTypeId().
497 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
498
499 // Names of the flags (needed for parsing Google Test flags).
500 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
501 const char kBreakOnFailureFlag[] = "break_on_failure";
502 const char kCatchExceptionsFlag[] = "catch_exceptions";
503 const char kColorFlag[] = "color";
504 const char kFilterFlag[] = "filter";
505 const char kListTestsFlag[] = "list_tests";
506 const char kOutputFlag[] = "output";
507 const char kPrintTimeFlag[] = "print_time";
508 const char kRandomSeedFlag[] = "random_seed";
509 const char kRepeatFlag[] = "repeat";
510 const char kShuffleFlag[] = "shuffle";
511 const char kStackTraceDepthFlag[] = "stack_trace_depth";
512 const char kStreamResultToFlag[] = "stream_result_to";
513 const char kThrowOnFailureFlag[] = "throw_on_failure";
514
515 // A valid random seed must be in [1, kMaxRandomSeed].
516 const int kMaxRandomSeed = 99999;
517
518 // g_help_flag is true iff the --help flag or an equivalent form is
519 // specified on the command line.
520 GTEST_API_ extern bool g_help_flag;
521
522 // Returns the current time in milliseconds.
523 GTEST_API_ TimeInMillis GetTimeInMillis();
524
525 // Returns true iff Google Test should use colors in the output.
526 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
527
528 // Formats the given time in milliseconds as seconds.
529 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
530
531 // Converts the given time in milliseconds to a date string in the ISO 8601
532 // format, without the timezone information. N.B.: due to the use the
533 // non-reentrant localtime() function, this function is not thread safe. Do
534 // not use it in any code that can be called from multiple threads.
535 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
536
537 // Parses a string for an Int32 flag, in the form of "--flag=value".
538 //
539 // On success, stores the value of the flag in *value, and returns
540 // true. On failure, returns false without changing *value.
541 GTEST_API_ bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
542
543 // Returns a random seed in range [1, kMaxRandomSeed] based on the
544 // given --gtest_random_seed flag value.
545 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
546 const unsigned int raw_seed =
547 (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
548 : static_cast<unsigned int>(random_seed_flag);
549
550 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
551 // it's easy to type.
552 const int normalized_seed =
553 static_cast<int>((raw_seed - 1U) %
554 static_cast<unsigned int>(kMaxRandomSeed)) +
555 1;
556 return normalized_seed;
557 }
558
559 // Returns the first valid random seed after 'seed'. The behavior is
560 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
561 // considered to be 1.
562 inline int GetNextRandomSeed(int seed) {
563 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
564 << "Invalid random seed " << seed << " - must be in [1, "
565 << kMaxRandomSeed << "].";
566 const int next_seed = seed + 1;
567 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
568 }
569
570 // This class saves the values of all Google Test flags in its c'tor, and
571 // restores them in its d'tor.
572 class GTestFlagSaver {
573 public:
574 // The c'tor.
575 GTestFlagSaver() {
576 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
577 break_on_failure_ = GTEST_FLAG(break_on_failure);
578 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
579 color_ = GTEST_FLAG(color);
580 death_test_style_ = GTEST_FLAG(death_test_style);
581 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
582 filter_ = GTEST_FLAG(filter);
583 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
584 list_tests_ = GTEST_FLAG(list_tests);
585 output_ = GTEST_FLAG(output);
586 print_time_ = GTEST_FLAG(print_time);
587 random_seed_ = GTEST_FLAG(random_seed);
588 repeat_ = GTEST_FLAG(repeat);
589 shuffle_ = GTEST_FLAG(shuffle);
590 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
591 stream_result_to_ = GTEST_FLAG(stream_result_to);
592 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
593 }
594
595 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
596 ~GTestFlagSaver() {
597 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
598 GTEST_FLAG(break_on_failure) = break_on_failure_;
599 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
600 GTEST_FLAG(color) = color_;
601 GTEST_FLAG(death_test_style) = death_test_style_;
602 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
603 GTEST_FLAG(filter) = filter_;
604 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
605 GTEST_FLAG(list_tests) = list_tests_;
606 GTEST_FLAG(output) = output_;
607 GTEST_FLAG(print_time) = print_time_;
608 GTEST_FLAG(random_seed) = random_seed_;
609 GTEST_FLAG(repeat) = repeat_;
610 GTEST_FLAG(shuffle) = shuffle_;
611 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
612 GTEST_FLAG(stream_result_to) = stream_result_to_;
613 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
614 }
615
616 private:
617 // Fields for saving the original values of flags.
618 bool also_run_disabled_tests_;
619 bool break_on_failure_;
620 bool catch_exceptions_;
621 std::string color_;
622 std::string death_test_style_;
623 bool death_test_use_fork_;
624 std::string filter_;
625 std::string internal_run_death_test_;
626 bool list_tests_;
627 std::string output_;
628 bool print_time_;
629 internal::Int32 random_seed_;
630 internal::Int32 repeat_;
631 bool shuffle_;
632 internal::Int32 stack_trace_depth_;
633 std::string stream_result_to_;
634 bool throw_on_failure_;
635 } GTEST_ATTRIBUTE_UNUSED_;
636
637 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
638 // code_point parameter is of type UInt32 because wchar_t may not be
639 // wide enough to contain a code point.
640 // If the code_point is not a valid Unicode code point
641 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
642 // to "(Invalid Unicode 0xXXXXXXXX)".
643 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
644
645 // Converts a wide string to a narrow string in UTF-8 encoding.
646 // The wide string is assumed to have the following encoding:
647 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
648 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
649 // Parameter str points to a null-terminated wide string.
650 // Parameter num_chars may additionally limit the number
651 // of wchar_t characters processed. -1 is used when the entire string
652 // should be processed.
653 // If the string contains code points that are not valid Unicode code points
654 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
655 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
656 // and contains invalid UTF-16 surrogate pairs, values in those pairs
657 // will be encoded as individual Unicode characters from Basic Normal Plane.
658 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
659
660 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
661 // if the variable is present. If a file already exists at this location, this
662 // function will write over it. If the variable is present, but the file cannot
663 // be created, prints an error and exits.
664 void WriteToShardStatusFileIfNeeded();
665
666 // Checks whether sharding is enabled by examining the relevant
667 // environment variable values. If the variables are present,
668 // but inconsistent (e.g., shard_index >= total_shards), prints
669 // an error and exits. If in_subprocess_for_death_test, sharding is
670 // disabled because it must only be applied to the original test
671 // process. Otherwise, we could filter out death tests we intended to execute.
672 GTEST_API_ bool ShouldShard(const char* total_shards_str,
673 const char* shard_index_str,
674 bool in_subprocess_for_death_test);
675
676 // Parses the environment variable var as an Int32. If it is unset,
677 // returns default_val. If it is not an Int32, prints an error and
678 // and aborts.
679 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
680
681 // Given the total number of shards, the shard index, and the test id,
682 // returns true iff the test should be run on this shard. The test id is
683 // some arbitrary but unique non-negative integer assigned to each test
684 // method. Assumes that 0 <= shard_index < total_shards.
685 GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
686 int test_id);
687
688 // STL container utilities.
689
690 // Returns the number of elements in the given container that satisfy
691 // the given predicate.
692 template <class Container, typename Predicate>
693 inline int CountIf(const Container& c, Predicate predicate) {
694 // Implemented as an explicit loop since std::count_if() in libCstd on
695 // Solaris has a non-standard signature.
696 int count = 0;
697 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
698 if (predicate(*it)) ++count;
699 }
700 return count;
701 }
702
703 // Applies a function/functor to each element in the container.
704 template <class Container, typename Functor>
705 void ForEach(const Container& c, Functor functor) {
706 std::for_each(c.begin(), c.end(), functor);
707 }
708
709 // Returns the i-th element of the vector, or default_value if i is not
710 // in range [0, v.size()).
711 template <typename E>
712 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
713 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
714 }
715
716 // Performs an in-place shuffle of a range of the vector's elements.
717 // 'begin' and 'end' are element indices as an STL-style range;
718 // i.e. [begin, end) are shuffled, where 'end' == size() means to
719 // shuffle to the end of the vector.
720 template <typename E>
721 void ShuffleRange(internal::Random* random, int begin, int end,
722 std::vector<E>* v) {
723 const int size = static_cast<int>(v->size());
724 GTEST_CHECK_(0 <= begin && begin <= size)
725 << "Invalid shuffle range start " << begin << ": must be in range [0, "
726 << size << "].";
727 GTEST_CHECK_(begin <= end && end <= size)
728 << "Invalid shuffle range finish " << end << ": must be in range ["
729 << begin << ", " << size << "].";
730
731 // Fisher-Yates shuffle, from
732 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
733 for (int range_width = end - begin; range_width >= 2; range_width--) {
734 const int last_in_range = begin + range_width - 1;
735 const int selected = begin + random->Generate(range_width);
736 std::swap((*v)[selected], (*v)[last_in_range]);
737 }
738 }
739
740 // Performs an in-place shuffle of the vector's elements.
741 template <typename E>
742 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
743 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
744 }
745
746 // A function for deleting an object. Handy for being used as a
747 // functor.
748 template <typename T> static void Delete(T* x) { delete x; }
749
750 // A predicate that checks the key of a TestProperty against a known key.
751 //
752 // TestPropertyKeyIs is copyable.
753 class TestPropertyKeyIs {
754 public:
755 // Constructor.
756 //
757 // TestPropertyKeyIs has NO default constructor.
758 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
759
760 // Returns true iff the test name of test property matches on key_.
761 bool operator()(const TestProperty& test_property) const {
762 return test_property.key() == key_;
763 }
764
765 private:
766 std::string key_;
767 };
768
769 // Class UnitTestOptions.
770 //
771 // This class contains functions for processing options the user
772 // specifies when running the tests. It has only static members.
773 //
774 // In most cases, the user can specify an option using either an
775 // environment variable or a command line flag. E.g. you can set the
776 // test filter using either GTEST_FILTER or --gtest_filter. If both
777 // the variable and the flag are present, the latter overrides the
778 // former.
779 class GTEST_API_ UnitTestOptions {
780 public:
781 // Functions for processing the gtest_output flag.
782
783 // Returns the output format, or "" for normal printed output.
784 static std::string GetOutputFormat();
785
786 // Returns the absolute path of the requested output file, or the
787 // default (test_detail.xml in the original working directory) if
788 // none was explicitly specified.
789 static std::string GetAbsolutePathToOutputFile();
790
791 // Functions for processing the gtest_filter flag.
792
793 // Returns true iff the wildcard pattern matches the string. The
794 // first ':' or '\0' character in pattern marks the end of it.
795 //
796 // This recursive algorithm isn't very efficient, but is clear and
797 // works well enough for matching test names, which are short.
798 static bool PatternMatchesString(const char* pattern, const char* str);
799
800 // Returns true iff the user-specified filter matches the test case
801 // name and the test name.
802 static bool FilterMatchesTest(const std::string& test_case_name,
803 const std::string& test_name);
804
805 # if GTEST_OS_WINDOWS
806 // Function for supporting the gtest_catch_exception flag.
807
808 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
809 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
810 // This function is useful as an __except condition.
811 static int GTestShouldProcessSEH(DWORD exception_code);
812 # endif // GTEST_OS_WINDOWS
813
814 // Returns true if "name" matches the ':' separated list of glob-style
815 // filters in "filter".
816 static bool MatchesFilter(const std::string& name, const char* filter);
817 };
818
819 // Returns the current application's name, removing directory path if that
820 // is present. Used by UnitTestOptions::GetOutputFile.
821 GTEST_API_ FilePath GetCurrentExecutableName();
822
823 // The role interface for getting the OS stack trace as a string.
824 class OsStackTraceGetterInterface {
825 public:
826 OsStackTraceGetterInterface() {}
827 virtual ~OsStackTraceGetterInterface() {}
828
829 // Returns the current OS stack trace as an std::string. Parameters:
830 //
831 // max_depth - the maximum number of stack frames to be included
832 // in the trace.
833 // skip_count - the number of top frames to be skipped; doesn't count
834 // against max_depth.
835 virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
836
837 // UponLeavingGTest() should be called immediately before Google Test calls
838 // user code. It saves some information about the current stack that
839 // CurrentStackTrace() will use to find and hide Google Test stack frames.
840 virtual void UponLeavingGTest() = 0;
841
842 private:
843 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
844 };
845
846 // A working implementation of the OsStackTraceGetterInterface interface.
847 class OsStackTraceGetter : public OsStackTraceGetterInterface {
848 public:
849 OsStackTraceGetter() : caller_frame_(NULL) {}
850
851 virtual string CurrentStackTrace(int max_depth, int skip_count)
852 GTEST_LOCK_EXCLUDED_(mutex_);
853
854 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
855
856 // This string is inserted in place of stack frames that are part of
857 // Google Test's implementation.
858 static const char* const kElidedFramesMarker;
859
860 private:
861 Mutex mutex_; // protects all internal state
862
863 // We save the stack frame below the frame that calls user code.
864 // We do this because the address of the frame immediately below
865 // the user code changes between the call to UponLeavingGTest()
866 // and any calls to CurrentStackTrace() from within the user code.
867 void* caller_frame_;
868
869 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
870 };
871
872 // Information about a Google Test trace point.
873 struct TraceInfo {
874 const char* file;
875 int line;
876 std::string message;
877 };
878
879 // This is the default global test part result reporter used in UnitTestImpl.
880 // This class should only be used by UnitTestImpl.
881 class DefaultGlobalTestPartResultReporter
882 : public TestPartResultReporterInterface {
883 public:
884 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
885 // Implements the TestPartResultReporterInterface. Reports the test part
886 // result in the current test.
887 virtual void ReportTestPartResult(const TestPartResult& result);
888
889 private:
890 UnitTestImpl* const unit_test_;
891
892 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
893 };
894
895 // This is the default per thread test part result reporter used in
896 // UnitTestImpl. This class should only be used by UnitTestImpl.
897 class DefaultPerThreadTestPartResultReporter
898 : public TestPartResultReporterInterface {
899 public:
900 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
901 // Implements the TestPartResultReporterInterface. The implementation just
902 // delegates to the current global test part result reporter of *unit_test_.
903 virtual void ReportTestPartResult(const TestPartResult& result);
904
905 private:
906 UnitTestImpl* const unit_test_;
907
908 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
909 };
910
911 // The private implementation of the UnitTest class. We don't protect
912 // the methods under a mutex, as this class is not accessible by a
913 // user and the UnitTest class that delegates work to this class does
914 // proper locking.
915 class GTEST_API_ UnitTestImpl {
916 public:
917 explicit UnitTestImpl(UnitTest* parent);
918 virtual ~UnitTestImpl();
919
920 // There are two different ways to register your own TestPartResultReporter.
921 // You can register your own repoter to listen either only for test results
922 // from the current thread or for results from all threads.
923 // By default, each per-thread test result repoter just passes a new
924 // TestPartResult to the global test result reporter, which registers the
925 // test part result for the currently running test.
926
927 // Returns the global test part result reporter.
928 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
929
930 // Sets the global test part result reporter.
931 void SetGlobalTestPartResultReporter(
932 TestPartResultReporterInterface* reporter);
933
934 // Returns the test part result reporter for the current thread.
935 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
936
937 // Sets the test part result reporter for the current thread.
938 void SetTestPartResultReporterForCurrentThread(
939 TestPartResultReporterInterface* reporter);
940
941 // Gets the number of successful test cases.
942 int successful_test_case_count() const;
943
944 // Gets the number of failed test cases.
945 int failed_test_case_count() const;
946
947 // Gets the number of all test cases.
948 int total_test_case_count() const;
949
950 // Gets the number of all test cases that contain at least one test
951 // that should run.
952 int test_case_to_run_count() const;
953
954 // Gets the number of successful tests.
955 int successful_test_count() const;
956
957 // Gets the number of failed tests.
958 int failed_test_count() const;
959
960 // Gets the number of disabled tests that will be reported in the XML report.
961 int reportable_disabled_test_count() const;
962
963 // Gets the number of disabled tests.
964 int disabled_test_count() const;
965
966 // Gets the number of tests to be printed in the XML report.
967 int reportable_test_count() const;
968
969 // Gets the number of all tests.
970 int total_test_count() const;
971
972 // Gets the number of tests that should run.
973 int test_to_run_count() const;
974
975 // Gets the time of the test program start, in ms from the start of the
976 // UNIX epoch.
977 TimeInMillis start_timestamp() const { return start_timestamp_; }
978
979 // Gets the elapsed time, in milliseconds.
980 TimeInMillis elapsed_time() const { return elapsed_time_; }
981
982 // Returns true iff the unit test passed (i.e. all test cases passed).
983 bool Passed() const { return !Failed(); }
984
985 // Returns true iff the unit test failed (i.e. some test case failed
986 // or something outside of all tests failed).
987 bool Failed() const {
988 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
989 }
990
991 // Gets the i-th test case among all the test cases. i can range from 0 to
992 // total_test_case_count() - 1. If i is not in that range, returns NULL.
993 const TestCase* GetTestCase(int i) const {
994 const int index = GetElementOr(test_case_indices_, i, -1);
995 return index < 0 ? NULL : test_cases_[i];
996 }
997
998 // Gets the i-th test case among all the test cases. i can range from 0 to
999 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1000 TestCase* GetMutableTestCase(int i) {
1001 const int index = GetElementOr(test_case_indices_, i, -1);
1002 return index < 0 ? NULL : test_cases_[index];
1003 }
1004
1005 // Provides access to the event listener list.
1006 TestEventListeners* listeners() { return &listeners_; }
1007
1008 // Returns the TestResult for the test that's currently running, or
1009 // the TestResult for the ad hoc test if no test is running.
1010 TestResult* current_test_result();
1011
1012 // Returns the TestResult for the ad hoc test.
1013 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1014
1015 // Sets the OS stack trace getter.
1016 //
1017 // Does nothing if the input and the current OS stack trace getter
1018 // are the same; otherwise, deletes the old getter and makes the
1019 // input the current getter.
1020 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1021
1022 // Returns the current OS stack trace getter if it is not NULL;
1023 // otherwise, creates an OsStackTraceGetter, makes it the current
1024 // getter, and returns it.
1025 OsStackTraceGetterInterface* os_stack_trace_getter();
1026
1027 // Returns the current OS stack trace as an std::string.
1028 //
1029 // The maximum number of stack frames to be included is specified by
1030 // the gtest_stack_trace_depth flag. The skip_count parameter
1031 // specifies the number of top frames to be skipped, which doesn't
1032 // count against the number of frames to be included.
1033 //
1034 // For example, if Foo() calls Bar(), which in turn calls
1035 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1036 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1037 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1038
1039 // Finds and returns a TestCase with the given name. If one doesn't
1040 // exist, creates one and returns it.
1041 //
1042 // Arguments:
1043 //
1044 // test_case_name: name of the test case
1045 // type_param: the name of the test's type parameter, or NULL if
1046 // this is not a typed or a type-parameterized test.
1047 // set_up_tc: pointer to the function that sets up the test case
1048 // tear_down_tc: pointer to the function that tears down the test case
1049 TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1050 Test::SetUpTestCaseFunc set_up_tc,
1051 Test::TearDownTestCaseFunc tear_down_tc);
1052
1053 // Adds a TestInfo to the unit test.
1054 //
1055 // Arguments:
1056 //
1057 // set_up_tc: pointer to the function that sets up the test case
1058 // tear_down_tc: pointer to the function that tears down the test case
1059 // test_info: the TestInfo object
1060 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1061 Test::TearDownTestCaseFunc tear_down_tc,
1062 TestInfo* test_info) {
1063 // In order to support thread-safe death tests, we need to
1064 // remember the original working directory when the test program
1065 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1066 // the user may have changed the current directory before calling
1067 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1068 // AddTestInfo(), which is called to register a TEST or TEST_F
1069 // before main() is reached.
1070 if (original_working_dir_.IsEmpty()) {
1071 original_working_dir_.Set(FilePath::GetCurrentDir());
1072 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1073 << "Failed to get the current working directory.";
1074 }
1075
1076 GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc,
1077 tear_down_tc)
1078 ->AddTestInfo(test_info);
1079 }
1080
1081 # if GTEST_HAS_PARAM_TEST
1082 // Returns ParameterizedTestCaseRegistry object used to keep track of
1083 // value-parameterized tests and instantiate and register them.
1084 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1085 return parameterized_test_registry_;
1086 }
1087 # endif // GTEST_HAS_PARAM_TEST
1088
1089 // Sets the TestCase object for the test that's currently running.
1090 void set_current_test_case(TestCase* a_current_test_case) {
1091 current_test_case_ = a_current_test_case;
1092 }
1093
1094 // Sets the TestInfo object for the test that's currently running. If
1095 // current_test_info is NULL, the assertion results will be stored in
1096 // ad_hoc_test_result_.
1097 void set_current_test_info(TestInfo* a_current_test_info) {
1098 current_test_info_ = a_current_test_info;
1099 }
1100
1101 // Registers all parameterized tests defined using TEST_P and
1102 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1103 // combination. This method can be called more then once; it has guards
1104 // protecting from registering the tests more then once. If
1105 // value-parameterized tests are disabled, RegisterParameterizedTests is
1106 // present but does nothing.
1107 void RegisterParameterizedTests();
1108
1109 // Runs all tests in this UnitTest object, prints the result, and
1110 // returns true if all tests are successful. If any exception is
1111 // thrown during a test, this test is considered to be failed, but
1112 // the rest of the tests will still be run.
1113 bool RunAllTests();
1114
1115 // Clears the results of all tests, except the ad hoc tests.
1116 void ClearNonAdHocTestResult() {
1117 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1118 }
1119
1120 // Clears the results of ad-hoc test assertions.
1121 void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
1122
1123 // Adds a TestProperty to the current TestResult object when invoked in a
1124 // context of a test or a test case, or to the global property set. If the
1125 // result already contains a property with the same key, the value will be
1126 // updated.
1127 void RecordProperty(const TestProperty& test_property);
1128
1129 enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
1130
1131 // Matches the full name of each test against the user-specified
1132 // filter to decide whether the test should run, then records the
1133 // result in each TestCase and TestInfo object.
1134 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1135 // based on sharding variables in the environment.
1136 // Returns the number of tests that should run.
1137 int FilterTests(ReactionToSharding shard_tests);
1138
1139 // Prints the names of the tests matching the user-specified filter flag.
1140 void ListTestsMatchingFilter();
1141
1142 const TestCase* current_test_case() const { return current_test_case_; }
1143 TestInfo* current_test_info() { return current_test_info_; }
1144 const TestInfo* current_test_info() const { return current_test_info_; }
1145
1146 // Returns the vector of environments that need to be set-up/torn-down
1147 // before/after the tests are run.
1148 std::vector<Environment*>& environments() { return environments_; }
1149
1150 // Getters for the per-thread Google Test trace stack.
1151 std::vector<TraceInfo>& gtest_trace_stack() {
1152 return *(gtest_trace_stack_.pointer());
1153 }
1154 const std::vector<TraceInfo>& gtest_trace_stack() const {
1155 return gtest_trace_stack_.get();
1156 }
1157
1158 # if GTEST_HAS_DEATH_TEST
1159 void InitDeathTestSubprocessControlInfo() {
1160 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1161 }
1162 // Returns a pointer to the parsed --gtest_internal_run_death_test
1163 // flag, or NULL if that flag was not specified.
1164 // This information is useful only in a death test child process.
1165 // Must not be called before a call to InitGoogleTest.
1166 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1167 return internal_run_death_test_flag_.get();
1168 }
1169
1170 // Returns a pointer to the current death test factory.
1171 internal::DeathTestFactory* death_test_factory() {
1172 return death_test_factory_.get();
1173 }
1174
1175 void SuppressTestEventsIfInSubprocess();
1176
1177 friend class ReplaceDeathTestFactory;
1178 # endif // GTEST_HAS_DEATH_TEST
1179
1180 // Initializes the event listener performing XML output as specified by
1181 // UnitTestOptions. Must not be called before InitGoogleTest.
1182 void ConfigureXmlOutput();
1183
1184 # if GTEST_CAN_STREAM_RESULTS_
1185 // Initializes the event listener for streaming test results to a socket.
1186 // Must not be called before InitGoogleTest.
1187 void ConfigureStreamingOutput();
1188 # endif
1189
1190 // Performs initialization dependent upon flag values obtained in
1191 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1192 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1193 // this function is also called from RunAllTests. Since this function can be
1194 // called more than once, it has to be idempotent.
1195 void PostFlagParsingInit();
1196
1197 // Gets the random seed used at the start of the current test iteration.
1198 int random_seed() const { return random_seed_; }
1199
1200 // Gets the random number generator.
1201 internal::Random* random() { return &random_; }
1202
1203 // Shuffles all test cases, and the tests within each test case,
1204 // making sure that death tests are still run first.
1205 void ShuffleTests();
1206
1207 // Restores the test cases and tests to their order before the first shuffle.
1208 void UnshuffleTests();
1209
1210 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1211 // UnitTest::Run() starts.
1212 bool catch_exceptions() const { return catch_exceptions_; }
1213
1214 private:
1215 friend class ::testing::UnitTest;
1216
1217 // Used by UnitTest::Run() to capture the state of
1218 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1219 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1220
1221 // The UnitTest object that owns this implementation object.
1222 UnitTest* const parent_;
1223
1224 // The working directory when the first TEST() or TEST_F() was
1225 // executed.
1226 internal::FilePath original_working_dir_;
1227
1228 // The default test part result reporters.
1229 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1230 DefaultPerThreadTestPartResultReporter
1231 default_per_thread_test_part_result_reporter_;
1232
1233 // Points to (but doesn't own) the global test part result reporter.
1234 TestPartResultReporterInterface* global_test_part_result_repoter_;
1235
1236 // Protects read and write access to global_test_part_result_reporter_.
1237 internal::Mutex global_test_part_result_reporter_mutex_;
1238
1239 // Points to (but doesn't own) the per-thread test part result reporter.
1240 internal::ThreadLocal<TestPartResultReporterInterface*>
1241 per_thread_test_part_result_reporter_;
1242
1243 // The vector of environments that need to be set-up/torn-down
1244 // before/after the tests are run.
1245 std::vector<Environment*> environments_;
1246
1247 // The vector of TestCases in their original order. It owns the
1248 // elements in the vector.
1249 std::vector<TestCase*> test_cases_;
1250
1251 // Provides a level of indirection for the test case list to allow
1252 // easy shuffling and restoring the test case order. The i-th
1253 // element of this vector is the index of the i-th test case in the
1254 // shuffled order.
1255 std::vector<int> test_case_indices_;
1256
1257 # if GTEST_HAS_PARAM_TEST
1258 // ParameterizedTestRegistry object used to register value-parameterized
1259 // tests.
1260 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1261
1262 // Indicates whether RegisterParameterizedTests() has been called already.
1263 bool parameterized_tests_registered_;
1264 # endif // GTEST_HAS_PARAM_TEST
1265
1266 // Index of the last death test case registered. Initially -1.
1267 int last_death_test_case_;
1268
1269 // This points to the TestCase for the currently running test. It
1270 // changes as Google Test goes through one test case after another.
1271 // When no test is running, this is set to NULL and Google Test
1272 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1273 TestCase* current_test_case_;
1274
1275 // This points to the TestInfo for the currently running test. It
1276 // changes as Google Test goes through one test after another. When
1277 // no test is running, this is set to NULL and Google Test stores
1278 // assertion results in ad_hoc_test_result_. Initially NULL.
1279 TestInfo* current_test_info_;
1280
1281 // Normally, a user only writes assertions inside a TEST or TEST_F,
1282 // or inside a function called by a TEST or TEST_F. Since Google
1283 // Test keeps track of which test is current running, it can
1284 // associate such an assertion with the test it belongs to.
1285 //
1286 // If an assertion is encountered when no TEST or TEST_F is running,
1287 // Google Test attributes the assertion result to an imaginary "ad hoc"
1288 // test, and records the result in ad_hoc_test_result_.
1289 TestResult ad_hoc_test_result_;
1290
1291 // The list of event listeners that can be used to track events inside
1292 // Google Test.
1293 TestEventListeners listeners_;
1294
1295 // The OS stack trace getter. Will be deleted when the UnitTest
1296 // object is destructed. By default, an OsStackTraceGetter is used,
1297 // but the user can set this field to use a custom getter if that is
1298 // desired.
1299 OsStackTraceGetterInterface* os_stack_trace_getter_;
1300
1301 // True iff PostFlagParsingInit() has been called.
1302 bool post_flag_parse_init_performed_;
1303
1304 // The random number seed used at the beginning of the test run.
1305 int random_seed_;
1306
1307 // Our random number generator.
1308 internal::Random random_;
1309
1310 // The time of the test program start, in ms from the start of the
1311 // UNIX epoch.
1312 TimeInMillis start_timestamp_;
1313
1314 // How long the test took to run, in milliseconds.
1315 TimeInMillis elapsed_time_;
1316
1317 # if GTEST_HAS_DEATH_TEST
1318 // The decomposed components of the gtest_internal_run_death_test flag,
1319 // parsed when RUN_ALL_TESTS is called.
1320 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1321 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1322 # endif // GTEST_HAS_DEATH_TEST
1323
1324 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1325 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1326
1327 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1328 // starts.
1329 bool catch_exceptions_;
1330
1331 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1332 }; // class UnitTestImpl
1333
1334 // Convenience function for accessing the global UnitTest
1335 // implementation object.
1336 inline UnitTestImpl* GetUnitTestImpl() {
1337 return UnitTest::GetInstance()->impl();
1338 }
1339
1340 # if GTEST_USES_SIMPLE_RE
1341
1342 // Internal helper functions for implementing the simple regular
1343 // expression matcher.
1344 GTEST_API_ bool IsInSet(char ch, const char* str);
1345 GTEST_API_ bool IsAsciiDigit(char ch);
1346 GTEST_API_ bool IsAsciiPunct(char ch);
1347 GTEST_API_ bool IsRepeat(char ch);
1348 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1349 GTEST_API_ bool IsAsciiWordChar(char ch);
1350 GTEST_API_ bool IsValidEscape(char ch);
1351 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1352 GTEST_API_ bool ValidateRegex(const char* regex);
1353 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1354 GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
1355 char repeat, const char* regex,
1356 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) ::CloseHandle(handle_);
1386 handle_ = handle;
1387 }
1388 }
1389
1390 private:
1391 HANDLE handle_;
1392
1393 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1394 };
1395 # endif // GTEST_OS_WINDOWS
1396
1397 // Attempts to parse a string into a positive integer pointed to by the
1398 // number parameter. Returns true if that is possible.
1399 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1400 // it here.
1401 template <typename Integer>
1402 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1403 // Fail fast if the given string does not begin with a digit;
1404 // this bypasses strtoXXX's "optional leading whitespace and plus
1405 // or minus sign" semantics, which are undesirable here.
1406 if (str.empty() || !IsDigit(str[0])) {
1407 return false;
1408 }
1409 errno = 0;
1410
1411 char* end;
1412 // BiggestConvertible is the largest integer type that system-provided
1413 // string-to-number conversion routines can return.
1414
1415 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1416
1417 // MSVC and C++ Builder define __int64 instead of the standard long long.
1418 typedef unsigned __int64 BiggestConvertible;
1419 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1420
1421 # else
1422
1423 typedef unsigned long long BiggestConvertible; // NOLINT
1424 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1425
1426 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1427
1428 const bool parse_success = *end == '\0' && errno == 0;
1429
1430 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1431 // available.
1432 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1433
1434 const Integer result = static_cast<Integer>(parsed);
1435 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1436 *number = result;
1437 return true;
1438 }
1439 return false;
1440 }
1441 # endif // GTEST_HAS_DEATH_TEST
1442
1443 // TestResult contains some private methods that should be hidden from
1444 // Google Test user but are required for testing. This class allow our tests
1445 // to access them.
1446 //
1447 // This class is supplied only for the purpose of testing Google Test's own
1448 // constructs. Do not use it in user tests, either directly or indirectly.
1449 class TestResultAccessor {
1450 public:
1451 static void RecordProperty(TestResult* test_result,
1452 const std::string& xml_element,
1453 const TestProperty& property) {
1454 test_result->RecordProperty(xml_element, property);
1455 }
1456
1457 static void ClearTestPartResults(TestResult* test_result) {
1458 test_result->ClearTestPartResults();
1459 }
1460
1461 static const std::vector<testing::TestPartResult>& test_part_results(
1462 const TestResult& test_result) {
1463 return test_result.test_part_results();
1464 }
1465 };
1466
1467 # if GTEST_CAN_STREAM_RESULTS_
1468
1469 // Streams test results to the given port on the given host machine.
1470 class StreamingListener : public EmptyTestEventListener {
1471 public:
1472 // Abstract base class for writing strings to a socket.
1473 class AbstractSocketWriter {
1474 public:
1475 virtual ~AbstractSocketWriter() {}
1476
1477 // Sends a string to the socket.
1478 virtual void Send(const string& message) = 0;
1479
1480 // Closes the socket.
1481 virtual void CloseConnection() {}
1482
1483 // Sends a string and a newline to the socket.
1484 void SendLn(const string& message) { Send(message + "\n"); }
1485 };
1486
1487 // Concrete class for actually writing strings to a socket.
1488 class SocketWriter : public AbstractSocketWriter {
1489 public:
1490 SocketWriter(const string& host, const string& port)
1491 : sockfd_(-1), host_name_(host), port_num_(port) {
1492 MakeConnection();
1493 }
1494
1495 virtual ~SocketWriter() {
1496 if (sockfd_ != -1) CloseConnection();
1497 }
1498
1499 // Sends a string to the socket.
1500 virtual void Send(const string& message) {
1501 GTEST_CHECK_(sockfd_ != -1)
1502 << "Send() can be called only when there is a connection.";
1503
1504 const int len = static_cast<int>(message.length());
1505 if (write(sockfd_, message.c_str(), len) != len) {
1506 GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
1507 << host_name_ << ":" << port_num_;
1508 }
1509 }
1510
1511 private:
1512 // Creates a client socket and connects to the server.
1513 void MakeConnection();
1514
1515 // Closes the socket.
1516 void CloseConnection() {
1517 GTEST_CHECK_(sockfd_ != -1)
1518 << "CloseConnection() can be called only when there is a connection.";
1519
1520 close(sockfd_);
1521 sockfd_ = -1;
1522 }
1523
1524 int sockfd_; // socket file descriptor
1525 const string host_name_;
1526 const string port_num_;
1527
1528 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1529 }; // class SocketWriter
1530
1531 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1532 static string UrlEncode(const char* str);
1533
1534 StreamingListener(const string& host, const string& port)
1535 : socket_writer_(new SocketWriter(host, port)) {
1536 Start();
1537 }
1538
1539 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1540 : socket_writer_(socket_writer) {
1541 Start();
1542 }
1543
1544 void OnTestProgramStart(const UnitTest& /* unit_test */) {
1545 SendLn("event=TestProgramStart");
1546 }
1547
1548 void OnTestProgramEnd(const UnitTest& unit_test) {
1549 // Note that Google Test current only report elapsed time for each
1550 // test iteration, not for the entire test program.
1551 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1552
1553 // Notify the streaming server to stop.
1554 socket_writer_->CloseConnection();
1555 }
1556
1557 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1558 SendLn("event=TestIterationStart&iteration=" +
1559 StreamableToString(iteration));
1560 }
1561
1562 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1563 SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
1564 "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
1565 "ms");
1566 }
1567
1568 void OnTestCaseStart(const TestCase& test_case) {
1569 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1570 }
1571
1572 void OnTestCaseEnd(const TestCase& test_case) {
1573 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1574 "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1575 "ms");
1576 }
1577
1578 void OnTestStart(const TestInfo& test_info) {
1579 SendLn(std::string("event=TestStart&name=") + test_info.name());
1580 }
1581
1582 void OnTestEnd(const TestInfo& test_info) {
1583 SendLn("event=TestEnd&passed=" +
1584 FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
1585 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1586 }
1587
1588 void OnTestPartResult(const TestPartResult& test_part_result) {
1589 const char* file_name = test_part_result.file_name();
1590 if (file_name == NULL) file_name = "";
1591 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1592 "&line=" + StreamableToString(test_part_result.line_number()) +
1593 "&message=" + UrlEncode(test_part_result.message()));
1594 }
1595
1596 private:
1597 // Sends the given message and a newline to the socket.
1598 void SendLn(const string& message) { socket_writer_->SendLn(message); }
1599
1600 // Called at the start of streaming to notify the receiver what
1601 // protocol we are using.
1602 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1603
1604 string FormatBool(bool value) { return value ? "1" : "0"; }
1605
1606 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1607
1608 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1609 }; // class StreamingListener
1610
1611 # endif // GTEST_CAN_STREAM_RESULTS_
1612
1613 } // namespace internal
1614 } // namespace testing
1615
1616 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1617 #undef GTEST_IMPLEMENTATION_
1618
1619 #if GTEST_OS_WINDOWS
1620 # define vsnprintf _vsnprintf
1621 #endif // GTEST_OS_WINDOWS
1622
1623 namespace testing {
1624
1625 using internal::CountIf;
1626 using internal::ForEach;
1627 using internal::GetElementOr;
1628 using internal::Shuffle;
1629
1630 // Constants.
1631
1632 // A test whose test case name or test name matches this filter is
1633 // disabled and not run.
1634 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1635
1636 // A test case whose name matches this filter is considered a death
1637 // test case and will be run before test cases whose name doesn't
1638 // match this filter.
1639 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1640
1641 // A test filter that matches everything.
1642 static const char kUniversalFilter[] = "*";
1643
1644 // The default output file for XML output.
1645 static const char kDefaultOutputFile[] = "test_detail.xml";
1646
1647 // The environment variable name for the test shard index.
1648 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1649 // The environment variable name for the total number of test shards.
1650 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1651 // The environment variable name for the test shard status file.
1652 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1653
1654 namespace internal {
1655
1656 // The text used in failure messages to indicate the start of the
1657 // stack trace.
1658 const char kStackTraceMarker[] = "\nStack trace:\n";
1659
1660 // g_help_flag is true iff the --help flag or an equivalent form is
1661 // specified on the command line.
1662 bool g_help_flag = false;
1663
1664 } // namespace internal
1665
1666 static const char* GetDefaultFilter() { return kUniversalFilter; }
1667
1668 GTEST_DEFINE_bool_(
1669 also_run_disabled_tests,
1670 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1671 "Run disabled tests too, in addition to the tests normally being run.");
1672
1673 GTEST_DEFINE_bool_(
1674 break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
1675 "True iff a failed assertion should be a debugger break-point.");
1676
1677 GTEST_DEFINE_bool_(catch_exceptions,
1678 internal::BoolFromGTestEnv("catch_exceptions", true),
1679 "True iff " GTEST_NAME_
1680 " should catch exceptions and treat them as test failures.");
1681
1682 GTEST_DEFINE_string_(
1683 color, internal::StringFromGTestEnv("color", "auto"),
1684 "Whether to use colors in the output. Valid values: yes, no, "
1685 "and auto. 'auto' means to use colors if the output is "
1686 "being sent to a terminal and the TERM environment variable "
1687 "is set to a terminal type that supports colors.");
1688
1689 GTEST_DEFINE_string_(
1690 filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1691 "A colon-separated list of glob (not regex) patterns "
1692 "for filtering the tests to run, optionally followed by a "
1693 "'-' and a : separated list of negative patterns (tests to "
1694 "exclude). A test is run if it matches one of the positive "
1695 "patterns and does not match any of the negative patterns.");
1696
1697 GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
1698
1699 GTEST_DEFINE_string_(
1700 output, internal::StringFromGTestEnv("output", ""),
1701 "A format (currently must be \"xml\"), optionally followed "
1702 "by a colon and an output file name or directory. A directory "
1703 "is indicated by a trailing pathname separator. "
1704 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1705 "If a directory is specified, output files will be created "
1706 "within that directory, with file-names based on the test "
1707 "executable's name and, if necessary, made unique by adding "
1708 "digits.");
1709
1710 GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
1711 "True iff " GTEST_NAME_
1712 " should display elapsed time in text output.");
1713
1714 GTEST_DEFINE_int32_(
1715 random_seed, internal::Int32FromGTestEnv("random_seed", 0),
1716 "Random number seed to use when shuffling test orders. Must be in range "
1717 "[1, 99999], or 0 to use a seed based on the current time.");
1718
1719 GTEST_DEFINE_int32_(
1720 repeat, internal::Int32FromGTestEnv("repeat", 1),
1721 "How many times to repeat each test. Specify a negative number "
1722 "for repeating forever. Useful for shaking out flaky tests.");
1723
1724 GTEST_DEFINE_bool_(show_internal_stack_frames, false,
1725 "True iff " GTEST_NAME_
1726 " should include internal stack frames when "
1727 "printing test failure stack traces.");
1728
1729 GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
1730 "True iff " GTEST_NAME_
1731 " should randomize tests' order on every run.");
1732
1733 GTEST_DEFINE_int32_(
1734 stack_trace_depth,
1735 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1736 "The maximum number of stack frames to print when an "
1737 "assertion fails. The valid range is 0 through 100, inclusive.");
1738
1739 GTEST_DEFINE_string_(
1740 stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""),
1741 "This flag specifies the host name and the port number on which to stream "
1742 "test results. Example: \"localhost:555\". The flag is effective only on "
1743 "Linux.");
1744
1745 GTEST_DEFINE_bool_(
1746 throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false),
1747 "When this flag is specified, a failed assertion will throw an exception "
1748 "if exceptions are enabled or exit the program with a non-zero code "
1749 "otherwise.");
1750
1751 namespace internal {
1752
1753 // Generates a random number from [0, range), using a Linear
1754 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1755 // than kMaxRange.
1756 UInt32 Random::Generate(UInt32 range) {
1757 // These constants are the same as are used in glibc's rand(3).
1758 state_ = (1103515245U * state_ + 12345U) % kMaxRange;
1759
1760 GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
1761 GTEST_CHECK_(range <= kMaxRange)
1762 << "Generation of a number in [0, " << range << ") was requested, "
1763 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1764
1765 // Converting via modulus introduces a bit of downward bias, but
1766 // it's simple, and a linear congruential generator isn't too good
1767 // to begin with.
1768 return state_ % range;
1769 }
1770
1771 // GTestIsInitialized() returns true iff the user has initialized
1772 // Google Test. Useful for catching the user mistake of not initializing
1773 // Google Test before calling RUN_ALL_TESTS().
1774 //
1775 // A user must call testing::InitGoogleTest() to initialize Google
1776 // Test. g_init_gtest_count is set to the number of times
1777 // InitGoogleTest() has been called. We don't protect this variable
1778 // under a mutex as it is only accessed in the main thread.
1779 GTEST_API_ int g_init_gtest_count = 0;
1780 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1781
1782 // Iterates over a vector of TestCases, keeping a running sum of the
1783 // results of calling a given int-returning method on each.
1784 // Returns the sum.
1785 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1786 int (TestCase::*method)() const) {
1787 int sum = 0;
1788 for (size_t i = 0; i < case_list.size(); i++) {
1789 sum += (case_list[i]->*method)();
1790 }
1791 return sum;
1792 }
1793
1794 // Returns true iff the test case passed.
1795 static bool TestCasePassed(const TestCase* test_case) {
1796 return test_case->should_run() && test_case->Passed();
1797 }
1798
1799 // Returns true iff the test case failed.
1800 static bool TestCaseFailed(const TestCase* test_case) {
1801 return test_case->should_run() && test_case->Failed();
1802 }
1803
1804 // Returns true iff test_case contains at least one test that should
1805 // run.
1806 static bool ShouldRunTestCase(const TestCase* test_case) {
1807 return test_case->should_run();
1808 }
1809
1810 // AssertHelper constructor.
1811 AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
1812 int line, const char* message)
1813 : data_(new AssertHelperData(type, file, line, message)) {}
1814
1815 AssertHelper::~AssertHelper() { delete data_; }
1816
1817 // Message assignment, for assertion streaming support.
1818 void AssertHelper::operator=(const Message& message) const {
1819 UnitTest::GetInstance()->AddTestPartResult(
1820 data_->type, data_->file, data_->line,
1821 AppendUserMessage(data_->message, message),
1822 UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
1823 // Skips the stack frame for this function itself.
1824 ); // NOLINT
1825 }
1826
1827 // Mutex for linked pointers.
1828 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1829
1830 // Application pathname gotten in InitGoogleTest.
1831 std::string g_executable_path;
1832
1833 // Returns the current application's name, removing directory path if that
1834 // is present.
1835 FilePath GetCurrentExecutableName() {
1836 FilePath result;
1837
1838 #if GTEST_OS_WINDOWS
1839 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1840 #else
1841 result.Set(FilePath(g_executable_path));
1842 #endif // GTEST_OS_WINDOWS
1843
1844 return result.RemoveDirectoryName();
1845 }
1846
1847 // Functions for processing the gtest_output flag.
1848
1849 // Returns the output format, or "" for normal printed output.
1850 std::string UnitTestOptions::GetOutputFormat() {
1851 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1852 if (gtest_output_flag == NULL) return std::string("");
1853
1854 const char* const colon = strchr(gtest_output_flag, ':');
1855 return (colon == NULL)
1856 ? std::string(gtest_output_flag)
1857 : std::string(gtest_output_flag, colon - gtest_output_flag);
1858 }
1859
1860 // Returns the name of the requested output file, or the default if none
1861 // was explicitly specified.
1862 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1863 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1864 if (gtest_output_flag == NULL) return "";
1865
1866 const char* const colon = strchr(gtest_output_flag, ':');
1867 if (colon == NULL)
1868 return internal::FilePath::ConcatPaths(
1869 internal::FilePath(
1870 UnitTest::GetInstance()->original_working_dir()),
1871 internal::FilePath(kDefaultOutputFile))
1872 .string();
1873
1874 internal::FilePath output_name(colon + 1);
1875 if (!output_name.IsAbsolutePath())
1876 // TODO(wan@google.com): on Windows \some\path is not an absolute
1877 // path (as its meaning depends on the current drive), yet the
1878 // following logic for turning it into an absolute path is wrong.
1879 // Fix it.
1880 output_name = internal::FilePath::ConcatPaths(
1881 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1882 internal::FilePath(colon + 1));
1883
1884 if (!output_name.IsDirectory()) return output_name.string();
1885
1886 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1887 output_name, internal::GetCurrentExecutableName(),
1888 GetOutputFormat().c_str()));
1889 return result.string();
1890 }
1891
1892 // Returns true iff the wildcard pattern matches the string. The
1893 // first ':' or '\0' character in pattern marks the end of it.
1894 //
1895 // This recursive algorithm isn't very efficient, but is clear and
1896 // works well enough for matching test names, which are short.
1897 bool UnitTestOptions::PatternMatchesString(const char* pattern,
1898 const char* str) {
1899 switch (*pattern) {
1900 case '\0':
1901 case ':': // Either ':' or '\0' marks the end of the pattern.
1902 return *str == '\0';
1903 case '?': // Matches any single character.
1904 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1905 case '*': // Matches any string (possibly empty) of characters.
1906 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1907 PatternMatchesString(pattern + 1, str);
1908 default: // Non-special character. Matches itself.
1909 return *pattern == *str && PatternMatchesString(pattern + 1, str + 1);
1910 }
1911 }
1912
1913 bool UnitTestOptions::MatchesFilter(const std::string& name,
1914 const char* filter) {
1915 const char* cur_pattern = filter;
1916 for (;;) {
1917 if (PatternMatchesString(cur_pattern, name.c_str())) {
1918 return true;
1919 }
1920
1921 // Finds the next pattern in the filter.
1922 cur_pattern = strchr(cur_pattern, ':');
1923
1924 // Returns if no more pattern can be found.
1925 if (cur_pattern == NULL) {
1926 return false;
1927 }
1928
1929 // Skips the pattern separater (the ':' character).
1930 cur_pattern++;
1931 }
1932 }
1933
1934 // Returns true iff the user-specified filter matches the test case
1935 // name and the test name.
1936 bool UnitTestOptions::FilterMatchesTest(const std::string& test_case_name,
1937 const std::string& test_name) {
1938 const std::string& full_name = test_case_name + "." + test_name.c_str();
1939
1940 // Split --gtest_filter at '-', if there is one, to separate into
1941 // positive filter and negative filter portions
1942 const char* const p = GTEST_FLAG(filter).c_str();
1943 const char* const dash = strchr(p, '-');
1944 std::string positive;
1945 std::string negative;
1946 if (dash == NULL) {
1947 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1948 negative = "";
1949 } else {
1950 positive = std::string(p, dash); // Everything up to the dash
1951 negative = std::string(dash + 1); // Everything after the dash
1952 if (positive.empty()) {
1953 // Treat '-test1' as the same as '*-test1'
1954 positive = kUniversalFilter;
1955 }
1956 }
1957
1958 // A filter is a colon-separated list of patterns. It matches a
1959 // test if any pattern in it matches the test.
1960 return (MatchesFilter(full_name, positive.c_str()) &&
1961 !MatchesFilter(full_name, negative.c_str()));
1962 }
1963
1964 #if GTEST_HAS_SEH
1965 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1966 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1967 // This function is useful as an __except condition.
1968 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1969 // Google Test should handle a SEH exception if:
1970 // 1. the user wants it to, AND
1971 // 2. this is not a breakpoint exception, AND
1972 // 3. this is not a C++ exception (VC++ implements them via SEH,
1973 // apparently).
1974 //
1975 // SEH exception code for C++ exceptions.
1976 // (see http://support.microsoft.com/kb/185294 for more information).
1977 const DWORD kCxxExceptionCode = 0xe06d7363;
1978
1979 bool should_handle = true;
1980
1981 if (!GTEST_FLAG(catch_exceptions))
1982 should_handle = false;
1983 else if (exception_code == EXCEPTION_BREAKPOINT)
1984 should_handle = false;
1985 else if (exception_code == kCxxExceptionCode)
1986 should_handle = false;
1987
1988 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
1989 }
1990 #endif // GTEST_HAS_SEH
1991
1992 } // namespace internal
1993
1994 // The c'tor sets this object as the test part result reporter used by
1995 // Google Test. The 'result' parameter specifies where to report the
1996 // results. Intercepts only failures from the current thread.
1997 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1998 TestPartResultArray* result)
1999 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
2000 Init();
2001 }
2002
2003 // The c'tor sets this object as the test part result reporter used by
2004 // Google Test. The 'result' parameter specifies where to report the
2005 // results.
2006 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2007 InterceptMode intercept_mode, TestPartResultArray* result)
2008 : intercept_mode_(intercept_mode), result_(result) {
2009 Init();
2010 }
2011
2012 void ScopedFakeTestPartResultReporter::Init() {
2013 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2014 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2015 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2016 impl->SetGlobalTestPartResultReporter(this);
2017 } else {
2018 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2019 impl->SetTestPartResultReporterForCurrentThread(this);
2020 }
2021 }
2022
2023 // The d'tor restores the test part result reporter used by Google Test
2024 // before.
2025 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2026 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2027 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2028 impl->SetGlobalTestPartResultReporter(old_reporter_);
2029 } else {
2030 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2031 }
2032 }
2033
2034 // Increments the test part result count and remembers the result.
2035 // This method is from the TestPartResultReporterInterface interface.
2036 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2037 const TestPartResult& result) {
2038 result_->Append(result);
2039 }
2040
2041 namespace internal {
2042
2043 // Returns the type ID of ::testing::Test. We should always call this
2044 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2045 // testing::Test. This is to work around a suspected linker bug when
2046 // using Google Test as a framework on Mac OS X. The bug causes
2047 // GetTypeId< ::testing::Test>() to return different values depending
2048 // on whether the call is from the Google Test framework itself or
2049 // from user test code. GetTestTypeId() is guaranteed to always
2050 // return the same value, as it always calls GetTypeId<>() from the
2051 // gtest.cc, which is within the Google Test framework.
2052 TypeId GetTestTypeId() { return GetTypeId<Test>(); }
2053
2054 // The value of GetTestTypeId() as seen from within the Google Test
2055 // library. This is solely for testing GetTestTypeId().
2056 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2057
2058 // This predicate-formatter checks that 'results' contains a test part
2059 // failure of the given type and that the failure message contains the
2060 // given substring.
2061 AssertionResult HasOneFailure(const char* /* results_expr */,
2062 const char* /* type_expr */,
2063 const char* /* substr_expr */,
2064 const TestPartResultArray& results,
2065 TestPartResult::Type type, const string& substr) {
2066 const std::string expected(type == TestPartResult::kFatalFailure
2067 ? "1 fatal failure"
2068 : "1 non-fatal failure");
2069 Message msg;
2070 if (results.size() != 1) {
2071 msg << "Expected: " << expected << "\n"
2072 << " Actual: " << results.size() << " failures";
2073 for (int i = 0; i < results.size(); i++) {
2074 msg << "\n" << results.GetTestPartResult(i);
2075 }
2076 return AssertionFailure() << msg;
2077 }
2078
2079 const TestPartResult& r = results.GetTestPartResult(0);
2080 if (r.type() != type) {
2081 return AssertionFailure() << "Expected: " << expected << "\n"
2082 << " Actual:\n"
2083 << r;
2084 }
2085
2086 if (strstr(r.message(), substr.c_str()) == NULL) {
2087 return AssertionFailure()
2088 << "Expected: " << expected << " containing \"" << substr << "\"\n"
2089 << " Actual:\n"
2090 << r;
2091 }
2092
2093 return AssertionSuccess();
2094 }
2095
2096 // The constructor of SingleFailureChecker remembers where to look up
2097 // test part results, what type of failure we expect, and what
2098 // substring the failure message should contain.
2099 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2100 TestPartResult::Type type,
2101 const string& substr)
2102 : results_(results), type_(type), substr_(substr) {}
2103
2104 // The destructor of SingleFailureChecker verifies that the given
2105 // TestPartResultArray contains exactly one failure that has the given
2106 // type and contains the given substring. If that's not the case, a
2107 // non-fatal failure will be generated.
2108 SingleFailureChecker::~SingleFailureChecker() {
2109 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2110 }
2111
2112 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2113 UnitTestImpl* unit_test)
2114 : unit_test_(unit_test) {}
2115
2116 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2117 const TestPartResult& result) {
2118 unit_test_->current_test_result()->AddTestPartResult(result);
2119 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2120 }
2121
2122 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2123 UnitTestImpl* unit_test)
2124 : unit_test_(unit_test) {}
2125
2126 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2127 const TestPartResult& result) {
2128 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2129 }
2130
2131 // Returns the global test part result reporter.
2132 TestPartResultReporterInterface*
2133 UnitTestImpl::GetGlobalTestPartResultReporter() {
2134 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2135 return global_test_part_result_repoter_;
2136 }
2137
2138 // Sets the global test part result reporter.
2139 void UnitTestImpl::SetGlobalTestPartResultReporter(
2140 TestPartResultReporterInterface* reporter) {
2141 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2142 global_test_part_result_repoter_ = reporter;
2143 }
2144
2145 // Returns the test part result reporter for the current thread.
2146 TestPartResultReporterInterface*
2147 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2148 return per_thread_test_part_result_reporter_.get();
2149 }
2150
2151 // Sets the test part result reporter for the current thread.
2152 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2153 TestPartResultReporterInterface* reporter) {
2154 per_thread_test_part_result_reporter_.set(reporter);
2155 }
2156
2157 // Gets the number of successful test cases.
2158 int UnitTestImpl::successful_test_case_count() const {
2159 return CountIf(test_cases_, TestCasePassed);
2160 }
2161
2162 // Gets the number of failed test cases.
2163 int UnitTestImpl::failed_test_case_count() const {
2164 return CountIf(test_cases_, TestCaseFailed);
2165 }
2166
2167 // Gets the number of all test cases.
2168 int UnitTestImpl::total_test_case_count() const {
2169 return static_cast<int>(test_cases_.size());
2170 }
2171
2172 // Gets the number of all test cases that contain at least one test
2173 // that should run.
2174 int UnitTestImpl::test_case_to_run_count() const {
2175 return CountIf(test_cases_, ShouldRunTestCase);
2176 }
2177
2178 // Gets the number of successful tests.
2179 int UnitTestImpl::successful_test_count() const {
2180 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2181 }
2182
2183 // Gets the number of failed tests.
2184 int UnitTestImpl::failed_test_count() const {
2185 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2186 }
2187
2188 // Gets the number of disabled tests that will be reported in the XML report.
2189 int UnitTestImpl::reportable_disabled_test_count() const {
2190 return SumOverTestCaseList(test_cases_,
2191 &TestCase::reportable_disabled_test_count);
2192 }
2193
2194 // Gets the number of disabled tests.
2195 int UnitTestImpl::disabled_test_count() const {
2196 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2197 }
2198
2199 // Gets the number of tests to be printed in the XML report.
2200 int UnitTestImpl::reportable_test_count() const {
2201 return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2202 }
2203
2204 // Gets the number of all tests.
2205 int UnitTestImpl::total_test_count() const {
2206 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2207 }
2208
2209 // Gets the number of tests that should run.
2210 int UnitTestImpl::test_to_run_count() const {
2211 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2212 }
2213
2214 // Returns the current OS stack trace as an std::string.
2215 //
2216 // The maximum number of stack frames to be included is specified by
2217 // the gtest_stack_trace_depth flag. The skip_count parameter
2218 // specifies the number of top frames to be skipped, which doesn't
2219 // count against the number of frames to be included.
2220 //
2221 // For example, if Foo() calls Bar(), which in turn calls
2222 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2223 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2224 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2225 (void)skip_count;
2226 return "";
2227 }
2228
2229 // Returns the current time in milliseconds.
2230 TimeInMillis GetTimeInMillis() {
2231 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2232 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2233 // http://analogous.blogspot.com/2005/04/epoch.html
2234 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2235 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2236 const DWORD kTenthMicrosInMilliSecond = 10000;
2237
2238 SYSTEMTIME now_systime;
2239 FILETIME now_filetime;
2240 ULARGE_INTEGER now_int64;
2241 // TODO(kenton@google.com): Shouldn't this just use
2242 // GetSystemTimeAsFileTime()?
2243 GetSystemTime(&now_systime);
2244 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2245 now_int64.LowPart = now_filetime.dwLowDateTime;
2246 now_int64.HighPart = now_filetime.dwHighDateTime;
2247 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2248 kJavaEpochToWinFileTimeDelta;
2249 return now_int64.QuadPart;
2250 }
2251 return 0;
2252 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2253 __timeb64 now;
2254
2255 # ifdef _MSC_VER
2256
2257 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2258 // (deprecated function) there.
2259 // TODO(kenton@google.com): Use GetTickCount()? Or use
2260 // SystemTimeToFileTime()
2261 # pragma warning(push) // Saves the current warning state.
2262 # pragma warning(disable : 4996) // Temporarily disables warning 4996.
2263 _ftime64(&now);
2264 # pragma warning(pop) // Restores the warning state.
2265 # else
2266
2267 _ftime64(&now);
2268
2269 # endif // _MSC_VER
2270
2271 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2272 #elif GTEST_HAS_GETTIMEOFDAY_
2273 struct timeval now;
2274 gettimeofday(&now, NULL);
2275 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2276 #else
2277 # error "Don't know how to get the current time on your system."
2278 #endif
2279 }
2280
2281 // Utilities
2282
2283 // class String.
2284
2285 #if GTEST_OS_WINDOWS_MOBILE
2286 // Creates a UTF-16 wide string from the given ANSI string, allocating
2287 // memory using new. The caller is responsible for deleting the return
2288 // value using delete[]. Returns the wide string, or NULL if the
2289 // input is NULL.
2290 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2291 if (!ansi) return NULL;
2292 const int length = strlen(ansi);
2293 const int unicode_length =
2294 MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0);
2295 WCHAR* unicode = new WCHAR[unicode_length + 1];
2296 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
2297 unicode[unicode_length] = 0;
2298 return unicode;
2299 }
2300
2301 // Creates an ANSI string from the given wide string, allocating
2302 // memory using new. The caller is responsible for deleting the return
2303 // value using delete[]. Returns the ANSI string, or NULL if the
2304 // input is NULL.
2305 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2306 if (!utf16_str) return NULL;
2307 const int ansi_length =
2308 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL);
2309 char* ansi = new char[ansi_length + 1];
2310 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL);
2311 ansi[ansi_length] = 0;
2312 return ansi;
2313 }
2314
2315 #endif // GTEST_OS_WINDOWS_MOBILE
2316
2317 // Compares two C strings. Returns true iff they have the same content.
2318 //
2319 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2320 // C string is considered different to any non-NULL C string,
2321 // including the empty string.
2322 bool String::CStringEquals(const char* lhs, const char* rhs) {
2323 if (lhs == NULL) return rhs == NULL;
2324
2325 if (rhs == NULL) return false;
2326
2327 return strcmp(lhs, rhs) == 0;
2328 }
2329
2330 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2331
2332 // Converts an array of wide chars to a narrow string using the UTF-8
2333 // encoding, and streams the result to the given Message object.
2334 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2335 Message* msg) {
2336 for (size_t i = 0; i != length;) { // NOLINT
2337 if (wstr[i] != L'\0') {
2338 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2339 while (i != length && wstr[i] != L'\0') i++;
2340 } else {
2341 *msg << '\0';
2342 i++;
2343 }
2344 }
2345 }
2346
2347 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2348
2349 } // namespace internal
2350
2351 // Constructs an empty Message.
2352 // We allocate the stringstream separately because otherwise each use of
2353 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2354 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2355 // the stack space.
2356 Message::Message() : ss_(new ::std::stringstream) {
2357 // By default, we want there to be enough precision when printing
2358 // a double to a Message.
2359 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2360 }
2361
2362 // These two overloads allow streaming a wide C string to a Message
2363 // using the UTF-8 encoding.
2364 Message& Message::operator<<(const wchar_t* wide_c_str) {
2365 return *this << internal::String::ShowWideCString(wide_c_str);
2366 }
2367 Message& Message::operator<<(wchar_t* wide_c_str) {
2368 return *this << internal::String::ShowWideCString(wide_c_str);
2369 }
2370
2371 #if GTEST_HAS_STD_WSTRING
2372 // Converts the given wide string to a narrow string using the UTF-8
2373 // encoding, and streams the result to this Message object.
2374 Message& Message::operator<<(const ::std::wstring& wstr) {
2375 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2376 return *this;
2377 }
2378 #endif // GTEST_HAS_STD_WSTRING
2379
2380 #if GTEST_HAS_GLOBAL_WSTRING
2381 // Converts the given wide string to a narrow string using the UTF-8
2382 // encoding, and streams the result to this Message object.
2383 Message& Message::operator<<(const ::wstring& wstr) {
2384 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2385 return *this;
2386 }
2387 #endif // GTEST_HAS_GLOBAL_WSTRING
2388
2389 // Gets the text streamed to this object so far as an std::string.
2390 // Each '\0' character in the buffer is replaced with "\\0".
2391 std::string Message::GetString() const {
2392 return internal::StringStreamToString(ss_.get());
2393 }
2394
2395 // AssertionResult constructors.
2396 // Used in EXPECT_TRUE/FALSE(assertion_result).
2397 AssertionResult::AssertionResult(const AssertionResult& other)
2398 : success_(other.success_),
2399 message_(other.message_.get() != NULL
2400 ? new ::std::string(*other.message_)
2401 : static_cast< ::std::string*>(NULL)) {}
2402
2403 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2404 AssertionResult AssertionResult::operator!() const {
2405 AssertionResult negation(!success_);
2406 if (message_.get() != NULL) negation << *message_;
2407 return negation;
2408 }
2409
2410 // Makes a successful assertion result.
2411 AssertionResult AssertionSuccess() { return AssertionResult(true); }
2412
2413 // Makes a failed assertion result.
2414 AssertionResult AssertionFailure() { return AssertionResult(false); }
2415
2416 // Makes a failed assertion result with the given failure message.
2417 // Deprecated; use AssertionFailure() << message.
2418 AssertionResult AssertionFailure(const Message& message) {
2419 return AssertionFailure() << message;
2420 }
2421
2422 namespace internal {
2423
2424 // Constructs and returns the message for an equality assertion
2425 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2426 //
2427 // The first four parameters are the expressions used in the assertion
2428 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2429 // where foo is 5 and bar is 6, we have:
2430 //
2431 // expected_expression: "foo"
2432 // actual_expression: "bar"
2433 // expected_value: "5"
2434 // actual_value: "6"
2435 //
2436 // The ignoring_case parameter is true iff the assertion is a
2437 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2438 // be inserted into the message.
2439 AssertionResult EqFailure(const char* expected_expression,
2440 const char* actual_expression,
2441 const std::string& expected_value,
2442 const std::string& actual_value, bool ignoring_case) {
2443 Message msg;
2444 msg << "Value of: " << actual_expression;
2445 if (actual_value != actual_expression) {
2446 msg << "\n Actual: " << actual_value;
2447 }
2448
2449 msg << "\nExpected: " << expected_expression;
2450 if (ignoring_case) {
2451 msg << " (ignoring case)";
2452 }
2453 if (expected_value != expected_expression) {
2454 msg << "\nWhich is: " << expected_value;
2455 }
2456
2457 return AssertionFailure() << msg;
2458 }
2459
2460 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2461 std::string GetBoolAssertionFailureMessage(
2462 const AssertionResult& assertion_result, const char* expression_text,
2463 const char* actual_predicate_value, const char* expected_predicate_value) {
2464 const char* actual_message = assertion_result.message();
2465 Message msg;
2466 msg << "Value of: " << expression_text
2467 << "\n Actual: " << actual_predicate_value;
2468 if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
2469 msg << "\nExpected: " << expected_predicate_value;
2470 return msg.GetString();
2471 }
2472
2473 // Helper function for implementing ASSERT_NEAR.
2474 AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
2475 const char* abs_error_expr, double val1,
2476 double val2, double abs_error) {
2477 const double diff = fabs(val1 - val2);
2478 if (diff <= abs_error) return AssertionSuccess();
2479
2480 // TODO(wan): do not print the value of an expression if it's
2481 // already a literal.
2482 return AssertionFailure()
2483 << "The difference between " << expr1 << " and " << expr2 << " is "
2484 << diff << ", which exceeds " << abs_error_expr << ", where\n"
2485 << expr1 << " evaluates to " << val1 << ",\n"
2486 << expr2 << " evaluates to " << val2 << ", and\n"
2487 << abs_error_expr << " evaluates to " << abs_error << ".";
2488 }
2489
2490 // Helper template for implementing FloatLE() and DoubleLE().
2491 template <typename RawType>
2492 AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
2493 RawType val1, RawType val2) {
2494 // Returns success if val1 is less than val2,
2495 if (val1 < val2) {
2496 return AssertionSuccess();
2497 }
2498
2499 // or if val1 is almost equal to val2.
2500 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2501 if (lhs.AlmostEquals(rhs)) {
2502 return AssertionSuccess();
2503 }
2504
2505 // Note that the above two checks will both fail if either val1 or
2506 // val2 is NaN, as the IEEE floating-point standard requires that
2507 // any predicate involving a NaN must return false.
2508
2509 ::std::stringstream val1_ss;
2510 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2511 << val1;
2512
2513 ::std::stringstream val2_ss;
2514 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2515 << val2;
2516
2517 return AssertionFailure()
2518 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2519 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2520 << StringStreamToString(&val2_ss);
2521 }
2522
2523 } // namespace internal
2524
2525 // Asserts that val1 is less than, or almost equal to, val2. Fails
2526 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2527 AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
2528 float val2) {
2529 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2530 }
2531
2532 // Asserts that val1 is less than, or almost equal to, val2. Fails
2533 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2534 AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
2535 double val2) {
2536 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2537 }
2538
2539 namespace internal {
2540
2541 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2542 // arguments.
2543 AssertionResult CmpHelperEQ(const char* expected_expression,
2544 const char* actual_expression, BiggestInt expected,
2545 BiggestInt actual) {
2546 if (expected == actual) {
2547 return AssertionSuccess();
2548 }
2549
2550 return EqFailure(expected_expression, actual_expression,
2551 FormatForComparisonFailureMessage(expected, actual),
2552 FormatForComparisonFailureMessage(actual, expected), false);
2553 }
2554
2555 // A macro for implementing the helper functions needed to implement
2556 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2557 // just to avoid copy-and-paste of similar code.
2558 #define GTEST_IMPL_CMP_HELPER_(op_name, op) \
2559 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2560 BiggestInt val1, BiggestInt val2) { \
2561 if (val1 op val2) { \
2562 return AssertionSuccess(); \
2563 } else { \
2564 return AssertionFailure() \
2565 << "Expected: (" << expr1 << ") " #op " (" << expr2 \
2566 << "), actual: " << FormatForComparisonFailureMessage(val1, val2) \
2567 << " vs " << FormatForComparisonFailureMessage(val2, val1); \
2568 } \
2569 }
2570
2571 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2572 // enum arguments.
2573 GTEST_IMPL_CMP_HELPER_(NE, !=)
2574 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2575 // enum arguments.
2576 GTEST_IMPL_CMP_HELPER_(LE, <=)
2577 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2578 // enum arguments.
2579 GTEST_IMPL_CMP_HELPER_(LT, <)
2580 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2581 // enum arguments.
2582 GTEST_IMPL_CMP_HELPER_(GE, >=)
2583 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2584 // enum arguments.
2585 GTEST_IMPL_CMP_HELPER_(GT, >)
2586
2587 #undef GTEST_IMPL_CMP_HELPER_
2588
2589 // The helper function for {ASSERT|EXPECT}_STREQ.
2590 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2591 const char* actual_expression,
2592 const char* expected, const char* actual) {
2593 if (String::CStringEquals(expected, actual)) {
2594 return AssertionSuccess();
2595 }
2596
2597 return EqFailure(expected_expression, actual_expression,
2598 PrintToString(expected), PrintToString(actual), false);
2599 }
2600
2601 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2602 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2603 const char* actual_expression,
2604 const char* expected, const char* actual) {
2605 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2606 return AssertionSuccess();
2607 }
2608
2609 return EqFailure(expected_expression, actual_expression,
2610 PrintToString(expected), PrintToString(actual), true);
2611 }
2612
2613 // The helper function for {ASSERT|EXPECT}_STRNE.
2614 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2615 const char* s2_expression, const char* s1,
2616 const char* s2) {
2617 if (!String::CStringEquals(s1, s2)) {
2618 return AssertionSuccess();
2619 } else {
2620 return AssertionFailure()
2621 << "Expected: (" << s1_expression << ") != (" << s2_expression
2622 << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
2623 }
2624 }
2625
2626 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2627 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2628 const char* s2_expression, const char* s1,
2629 const char* s2) {
2630 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2631 return AssertionSuccess();
2632 } else {
2633 return AssertionFailure()
2634 << "Expected: (" << s1_expression << ") != (" << s2_expression
2635 << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
2636 }
2637 }
2638
2639 } // namespace internal
2640
2641 namespace {
2642
2643 // Helper functions for implementing IsSubString() and IsNotSubstring().
2644
2645 // This group of overloaded functions return true iff needle is a
2646 // substring of haystack. NULL is considered a substring of itself
2647 // only.
2648
2649 bool IsSubstringPred(const char* needle, const char* haystack) {
2650 if (needle == NULL || haystack == NULL) return needle == haystack;
2651
2652 return strstr(haystack, needle) != NULL;
2653 }
2654
2655 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2656 if (needle == NULL || haystack == NULL) return needle == haystack;
2657
2658 return wcsstr(haystack, needle) != NULL;
2659 }
2660
2661 // StringType here can be either ::std::string or ::std::wstring.
2662 template <typename StringType>
2663 bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
2664 return haystack.find(needle) != StringType::npos;
2665 }
2666
2667 // This function implements either IsSubstring() or IsNotSubstring(),
2668 // depending on the value of the expected_to_be_substring parameter.
2669 // StringType here can be const char*, const wchar_t*, ::std::string,
2670 // or ::std::wstring.
2671 template <typename StringType>
2672 AssertionResult IsSubstringImpl(bool expected_to_be_substring,
2673 const char* needle_expr,
2674 const char* haystack_expr,
2675 const StringType& needle,
2676 const StringType& haystack) {
2677 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2678 return AssertionSuccess();
2679
2680 const bool is_wide_string = sizeof(needle[0]) > 1;
2681 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2682 return AssertionFailure()
2683 << "Value of: " << needle_expr << "\n"
2684 << " Actual: " << begin_string_quote << needle << "\"\n"
2685 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2686 << "a substring of " << haystack_expr << "\n"
2687 << "Which is: " << begin_string_quote << haystack << "\"";
2688 }
2689
2690 } // namespace
2691
2692 // IsSubstring() and IsNotSubstring() check whether needle is a
2693 // substring of haystack (NULL is considered a substring of itself
2694 // only), and return an appropriate error message when they fail.
2695
2696 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2697 const char* needle, const char* haystack) {
2698 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2699 }
2700
2701 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2702 const wchar_t* needle, const wchar_t* haystack) {
2703 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2704 }
2705
2706 AssertionResult IsNotSubstring(const char* needle_expr,
2707 const char* haystack_expr, const char* needle,
2708 const char* haystack) {
2709 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2710 }
2711
2712 AssertionResult IsNotSubstring(const char* needle_expr,
2713 const char* haystack_expr, const wchar_t* needle,
2714 const wchar_t* haystack) {
2715 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2716 }
2717
2718 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2719 const ::std::string& needle,
2720 const ::std::string& haystack) {
2721 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2722 }
2723
2724 AssertionResult IsNotSubstring(const char* needle_expr,
2725 const char* haystack_expr,
2726 const ::std::string& needle,
2727 const ::std::string& haystack) {
2728 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2729 }
2730
2731 #if GTEST_HAS_STD_WSTRING
2732 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2733 const ::std::wstring& needle,
2734 const ::std::wstring& haystack) {
2735 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2736 }
2737
2738 AssertionResult IsNotSubstring(const char* needle_expr,
2739 const char* haystack_expr,
2740 const ::std::wstring& needle,
2741 const ::std::wstring& haystack) {
2742 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2743 }
2744 #endif // GTEST_HAS_STD_WSTRING
2745
2746 namespace internal {
2747
2748 #if GTEST_OS_WINDOWS
2749
2750 namespace {
2751
2752 // Helper function for IsHRESULT{SuccessFailure} predicates
2753 AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
2754 long hr) { // NOLINT
2755 # if GTEST_OS_WINDOWS_MOBILE
2756
2757 // Windows CE doesn't support FormatMessage.
2758 const char error_text[] = "";
2759
2760 # else
2761
2762 // Looks up the human-readable system message for the HRESULT code
2763 // and since we're not passing any params to FormatMessage, we don't
2764 // want inserts expanded.
2765 const DWORD kFlags =
2766 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
2767 const DWORD kBufSize = 4096;
2768 // Gets the system's human readable message string for this HRESULT.
2769 char error_text[kBufSize] = {'\0'};
2770 DWORD message_length = ::FormatMessageA(kFlags,
2771 0, // no source, we're asking system
2772 hr, // the error
2773 0, // no line width restrictions
2774 error_text, // output buffer
2775 kBufSize, // buf size
2776 NULL); // no arguments for inserts
2777 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2778 for (; message_length && IsSpace(error_text[message_length - 1]);
2779 --message_length) {
2780 error_text[message_length - 1] = '\0';
2781 }
2782
2783 # endif // GTEST_OS_WINDOWS_MOBILE
2784
2785 const std::string error_hex("0x" + String::FormatHexInt(hr));
2786 return ::testing::AssertionFailure()
2787 << "Expected: " << expr << " " << expected << ".\n"
2788 << " Actual: " << error_hex << " " << error_text << "\n";
2789 }
2790
2791 } // namespace
2792
2793 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2794 if (SUCCEEDED(hr)) {
2795 return AssertionSuccess();
2796 }
2797 return HRESULTFailureHelper(expr, "succeeds", hr);
2798 }
2799
2800 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2801 if (FAILED(hr)) {
2802 return AssertionSuccess();
2803 }
2804 return HRESULTFailureHelper(expr, "fails", hr);
2805 }
2806
2807 #endif // GTEST_OS_WINDOWS
2808
2809 // Utility functions for encoding Unicode text (wide strings) in
2810 // UTF-8.
2811
2812 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2813 // like this:
2814 //
2815 // Code-point length Encoding
2816 // 0 - 7 bits 0xxxxxxx
2817 // 8 - 11 bits 110xxxxx 10xxxxxx
2818 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2819 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2820
2821 // The maximum code-point a one-byte UTF-8 sequence can represent.
2822 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2823
2824 // The maximum code-point a two-byte UTF-8 sequence can represent.
2825 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2826
2827 // The maximum code-point a three-byte UTF-8 sequence can represent.
2828 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2 * 6)) - 1;
2829
2830 // The maximum code-point a four-byte UTF-8 sequence can represent.
2831 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3 * 6)) - 1;
2832
2833 // Chops off the n lowest bits from a bit pattern. Returns the n
2834 // lowest bits. As a side effect, the original bit pattern will be
2835 // shifted to the right by n bits.
2836 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2837 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2838 *bits >>= n;
2839 return low_bits;
2840 }
2841
2842 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2843 // code_point parameter is of type UInt32 because wchar_t may not be
2844 // wide enough to contain a code point.
2845 // If the code_point is not a valid Unicode code point
2846 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2847 // to "(Invalid Unicode 0xXXXXXXXX)".
2848 std::string CodePointToUtf8(UInt32 code_point) {
2849 if (code_point > kMaxCodePoint4) {
2850 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
2851 }
2852
2853 char str[5]; // Big enough for the largest valid code point.
2854 if (code_point <= kMaxCodePoint1) {
2855 str[1] = '\0';
2856 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2857 } else if (code_point <= kMaxCodePoint2) {
2858 str[2] = '\0';
2859 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2860 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2861 } else if (code_point <= kMaxCodePoint3) {
2862 str[3] = '\0';
2863 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2864 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2865 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2866 } else { // code_point <= kMaxCodePoint4
2867 str[4] = '\0';
2868 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2869 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2870 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2871 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2872 }
2873 return str;
2874 }
2875
2876 // The following two functions only make sense if the the system
2877 // uses UTF-16 for wide string encoding. All supported systems
2878 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2879
2880 // Determines if the arguments constitute UTF-16 surrogate pair
2881 // and thus should be combined into a single Unicode code point
2882 // using CreateCodePointFromUtf16SurrogatePair.
2883 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2884 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
2885 (second & 0xFC00) == 0xDC00;
2886 }
2887
2888 // Creates a Unicode code point from UTF16 surrogate pair.
2889 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2890 wchar_t second) {
2891 const UInt32 mask = (1 << 10) - 1;
2892 return (sizeof(wchar_t) == 2)
2893 ? (((first & mask) << 10) | (second & mask)) + 0x10000
2894 :
2895 // This function should not be called when the condition is
2896 // false, but we provide a sensible default in case it is.
2897 static_cast<UInt32>(first);
2898 }
2899
2900 // Converts a wide string to a narrow string in UTF-8 encoding.
2901 // The wide string is assumed to have the following encoding:
2902 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2903 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2904 // Parameter str points to a null-terminated wide string.
2905 // Parameter num_chars may additionally limit the number
2906 // of wchar_t characters processed. -1 is used when the entire string
2907 // should be processed.
2908 // If the string contains code points that are not valid Unicode code points
2909 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2910 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2911 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2912 // will be encoded as individual Unicode characters from Basic Normal Plane.
2913 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2914 if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
2915
2916 ::std::stringstream stream;
2917 for (int i = 0; i < num_chars; ++i) {
2918 UInt32 unicode_code_point;
2919
2920 if (str[i] == L'\0') {
2921 break;
2922 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2923 unicode_code_point =
2924 CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
2925 i++;
2926 } else {
2927 unicode_code_point = static_cast<UInt32>(str[i]);
2928 }
2929
2930 stream << CodePointToUtf8(unicode_code_point);
2931 }
2932 return StringStreamToString(&stream);
2933 }
2934
2935 // Converts a wide C string to an std::string using the UTF-8 encoding.
2936 // NULL will be converted to "(null)".
2937 std::string String::ShowWideCString(const wchar_t* wide_c_str) {
2938 if (wide_c_str == NULL) return "(null)";
2939
2940 return internal::WideStringToUtf8(wide_c_str, -1);
2941 }
2942
2943 // Compares two wide C strings. Returns true iff they have the same
2944 // content.
2945 //
2946 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2947 // C string is considered different to any non-NULL C string,
2948 // including the empty string.
2949 bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
2950 if (lhs == NULL) return rhs == NULL;
2951
2952 if (rhs == NULL) return false;
2953
2954 return wcscmp(lhs, rhs) == 0;
2955 }
2956
2957 // Helper function for *_STREQ on wide strings.
2958 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2959 const char* actual_expression,
2960 const wchar_t* expected, const wchar_t* actual) {
2961 if (String::WideCStringEquals(expected, actual)) {
2962 return AssertionSuccess();
2963 }
2964
2965 return EqFailure(expected_expression, actual_expression,
2966 PrintToString(expected), PrintToString(actual), false);
2967 }
2968
2969 // Helper function for *_STRNE on wide strings.
2970 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2971 const char* s2_expression, const wchar_t* s1,
2972 const wchar_t* s2) {
2973 if (!String::WideCStringEquals(s1, s2)) {
2974 return AssertionSuccess();
2975 }
2976
2977 return AssertionFailure()
2978 << "Expected: (" << s1_expression << ") != (" << s2_expression
2979 << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
2980 }
2981
2982 // Compares two C strings, ignoring case. Returns true iff they have
2983 // the same content.
2984 //
2985 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2986 // NULL C string is considered different to any non-NULL C string,
2987 // including the empty string.
2988 bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
2989 if (lhs == NULL) return rhs == NULL;
2990 if (rhs == NULL) return false;
2991 return posix::StrCaseCmp(lhs, rhs) == 0;
2992 }
2993
2994 // Compares two wide C strings, ignoring case. Returns true iff they
2995 // have the same content.
2996 //
2997 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2998 // A NULL C string is considered different to any non-NULL wide C string,
2999 // including the empty string.
3000 // NB: The implementations on different platforms slightly differ.
3001 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3002 // environment variable. On GNU platform this method uses wcscasecmp
3003 // which compares according to LC_CTYPE category of the current locale.
3004 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3005 // current locale.
3006 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3007 const wchar_t* rhs) {
3008 if (lhs == NULL) return rhs == NULL;
3009
3010 if (rhs == NULL) return false;
3011
3012 #if GTEST_OS_WINDOWS
3013 return _wcsicmp(lhs, rhs) == 0;
3014 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3015 return wcscasecmp(lhs, rhs) == 0;
3016 #else
3017 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3018 // Other unknown OSes may not define it either.
3019 wint_t left, right;
3020 do {
3021 left = towlower(*lhs++);
3022 right = towlower(*rhs++);
3023 } while (left && left == right);
3024 return left == right;
3025 #endif // OS selector
3026 }
3027
3028 // Returns true iff str ends with the given suffix, ignoring case.
3029 // Any string is considered to end with an empty suffix.
3030 bool String::EndsWithCaseInsensitive(const std::string& str,
3031 const std::string& suffix) {
3032 const size_t str_len = str.length();
3033 const size_t suffix_len = suffix.length();
3034 return (str_len >= suffix_len) &&
3035 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3036 suffix.c_str());
3037 }
3038
3039 // Formats an int value as "%02d".
3040 std::string String::FormatIntWidth2(int value) {
3041 std::stringstream ss;
3042 ss << std::setfill('0') << std::setw(2) << value;
3043 return ss.str();
3044 }
3045
3046 // Formats an int value as "%X".
3047 std::string String::FormatHexInt(int value) {
3048 std::stringstream ss;
3049 ss << std::hex << std::uppercase << value;
3050 return ss.str();
3051 }
3052
3053 // Formats a byte as "%02X".
3054 std::string String::FormatByte(unsigned char value) {
3055 std::stringstream ss;
3056 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3057 << static_cast<unsigned int>(value);
3058 return ss.str();
3059 }
3060
3061 // Converts the buffer in a stringstream to an std::string, converting NUL
3062 // bytes to "\\0" along the way.
3063 std::string StringStreamToString(::std::stringstream* ss) {
3064 const ::std::string& str = ss->str();
3065 const char* const start = str.c_str();
3066 const char* const end = start + str.length();
3067
3068 std::string result;
3069 result.reserve(2 * (end - start));
3070 for (const char* ch = start; ch != end; ++ch) {
3071 if (*ch == '\0') {
3072 result += "\\0"; // Replaces NUL with "\\0";
3073 } else {
3074 result += *ch;
3075 }
3076 }
3077
3078 return result;
3079 }
3080
3081 // Appends the user-supplied message to the Google-Test-generated message.
3082 std::string AppendUserMessage(const std::string& gtest_msg,
3083 const Message& user_msg) {
3084 // Appends the user message if it's non-empty.
3085 const std::string user_msg_string = user_msg.GetString();
3086 if (user_msg_string.empty()) {
3087 return gtest_msg;
3088 }
3089
3090 return gtest_msg + "\n" + user_msg_string;
3091 }
3092
3093 } // namespace internal
3094
3095 // class TestResult
3096
3097 // Creates an empty TestResult.
3098 TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) {}
3099
3100 // D'tor.
3101 TestResult::~TestResult() {}
3102
3103 // Returns the i-th test part result among all the results. i can
3104 // range from 0 to total_part_count() - 1. If i is not in that range,
3105 // aborts the program.
3106 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3107 if (i < 0 || i >= total_part_count()) internal::posix::Abort();
3108 return test_part_results_.at(i);
3109 }
3110
3111 // Returns the i-th test property. i can range from 0 to
3112 // test_property_count() - 1. If i is not in that range, aborts the
3113 // program.
3114 const TestProperty& TestResult::GetTestProperty(int i) const {
3115 if (i < 0 || i >= test_property_count()) internal::posix::Abort();
3116 return test_properties_.at(i);
3117 }
3118
3119 // Clears the test part results.
3120 void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
3121
3122 // Adds a test part result to the list.
3123 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3124 test_part_results_.push_back(test_part_result);
3125 }
3126
3127 // Adds a test property to the list. If a property with the same key as the
3128 // supplied property is already represented, the value of this test_property
3129 // replaces the old value for that key.
3130 void TestResult::RecordProperty(const std::string& xml_element,
3131 const TestProperty& test_property) {
3132 if (!ValidateTestProperty(xml_element, test_property)) {
3133 return;
3134 }
3135 internal::MutexLock lock(&test_properites_mutex_);
3136 const std::vector<TestProperty>::iterator property_with_matching_key =
3137 std::find_if(test_properties_.begin(), test_properties_.end(),
3138 internal::TestPropertyKeyIs(test_property.key()));
3139 if (property_with_matching_key == test_properties_.end()) {
3140 test_properties_.push_back(test_property);
3141 return;
3142 }
3143 property_with_matching_key->SetValue(test_property.value());
3144 }
3145
3146 // The list of reserved attributes used in the <testsuites> element of XML
3147 // output.
3148 static const char* const kReservedTestSuitesAttributes[] = {
3149 "disabled", "errors", "failures", "name",
3150 "random_seed", "tests", "time", "timestamp"};
3151
3152 // The list of reserved attributes used in the <testsuite> element of XML
3153 // output.
3154 static const char* const kReservedTestSuiteAttributes[] = {
3155 "disabled", "errors", "failures", "name", "tests", "time"};
3156
3157 // The list of reserved attributes used in the <testcase> element of XML output.
3158 static const char* const kReservedTestCaseAttributes[] = {
3159 "classname", "name", "status", "time", "type_param", "value_param"};
3160
3161 template <int kSize>
3162 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3163 return std::vector<std::string>(array, array + kSize);
3164 }
3165
3166 static std::vector<std::string> GetReservedAttributesForElement(
3167 const std::string& xml_element) {
3168 if (xml_element == "testsuites") {
3169 return ArrayAsVector(kReservedTestSuitesAttributes);
3170 } else if (xml_element == "testsuite") {
3171 return ArrayAsVector(kReservedTestSuiteAttributes);
3172 } else if (xml_element == "testcase") {
3173 return ArrayAsVector(kReservedTestCaseAttributes);
3174 } else {
3175 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3176 }
3177 // This code is unreachable but some compilers may not realizes that.
3178 return std::vector<std::string>();
3179 }
3180
3181 static std::string FormatWordList(const std::vector<std::string>& words) {
3182 Message word_list;
3183 for (size_t i = 0; i < words.size(); ++i) {
3184 if (i > 0 && words.size() > 2) {
3185 word_list << ", ";
3186 }
3187 if (i == words.size() - 1) {
3188 word_list << "and ";
3189 }
3190 word_list << "'" << words[i] << "'";
3191 }
3192 return word_list.GetString();
3193 }
3194
3195 bool ValidateTestPropertyName(const std::string& property_name,
3196 const std::vector<std::string>& reserved_names) {
3197 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3198 reserved_names.end()) {
3199 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3200 << " (" << FormatWordList(reserved_names)
3201 << " are reserved by " << GTEST_NAME_ << ")";
3202 return false;
3203 }
3204 return true;
3205 }
3206
3207 // Adds a failure if the key is a reserved attribute of the element named
3208 // xml_element. Returns true if the property is valid.
3209 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3210 const TestProperty& test_property) {
3211 return ValidateTestPropertyName(test_property.key(),
3212 GetReservedAttributesForElement(xml_element));
3213 }
3214
3215 // Clears the object.
3216 void TestResult::Clear() {
3217 test_part_results_.clear();
3218 test_properties_.clear();
3219 death_test_count_ = 0;
3220 elapsed_time_ = 0;
3221 }
3222
3223 // Returns true iff the test failed.
3224 bool TestResult::Failed() const {
3225 for (int i = 0; i < total_part_count(); ++i) {
3226 if (GetTestPartResult(i).failed()) return true;
3227 }
3228 return false;
3229 }
3230
3231 // Returns true iff the test part fatally failed.
3232 static bool TestPartFatallyFailed(const TestPartResult& result) {
3233 return result.fatally_failed();
3234 }
3235
3236 // Returns true iff the test fatally failed.
3237 bool TestResult::HasFatalFailure() const {
3238 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3239 }
3240
3241 // Returns true iff the test part non-fatally failed.
3242 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3243 return result.nonfatally_failed();
3244 }
3245
3246 // Returns true iff the test has a non-fatal failure.
3247 bool TestResult::HasNonfatalFailure() const {
3248 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3249 }
3250
3251 // Gets the number of all test parts. This is the sum of the number
3252 // of successful test parts and the number of failed test parts.
3253 int TestResult::total_part_count() const {
3254 return static_cast<int>(test_part_results_.size());
3255 }
3256
3257 // Returns the number of the test properties.
3258 int TestResult::test_property_count() const {
3259 return static_cast<int>(test_properties_.size());
3260 }
3261
3262 // class Test
3263
3264 // Creates a Test object.
3265
3266 // The c'tor saves the values of all Google Test flags.
3267 Test::Test() : gtest_flag_saver_(new internal::GTestFlagSaver) {}
3268
3269 // The d'tor restores the values of all Google Test flags.
3270 Test::~Test() { delete gtest_flag_saver_; }
3271
3272 // Sets up the test fixture.
3273 //
3274 // A sub-class may override this.
3275 void Test::SetUp() {}
3276
3277 // Tears down the test fixture.
3278 //
3279 // A sub-class may override this.
3280 void Test::TearDown() {}
3281
3282 // Allows user supplied key value pairs to be recorded for later output.
3283 void Test::RecordProperty(const std::string& key, const std::string& value) {
3284 UnitTest::GetInstance()->RecordProperty(key, value);
3285 }
3286
3287 // Allows user supplied key value pairs to be recorded for later output.
3288 void Test::RecordProperty(const std::string& key, int value) {
3289 Message value_message;
3290 value_message << value;
3291 RecordProperty(key, value_message.GetString().c_str());
3292 }
3293
3294 namespace internal {
3295
3296 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3297 const std::string& message) {
3298 // This function is a friend of UnitTest and as such has access to
3299 // AddTestPartResult.
3300 UnitTest::GetInstance()->AddTestPartResult(
3301 result_type,
3302 NULL, // No info about the source file where the exception occurred.
3303 -1, // We have no info on which line caused the exception.
3304 message,
3305 ""); // No stack trace, either.
3306 }
3307
3308 } // namespace internal
3309
3310 // Google Test requires all tests in the same test case to use the same test
3311 // fixture class. This function checks if the current test has the
3312 // same fixture class as the first test in the current test case. If
3313 // yes, it returns true; otherwise it generates a Google Test failure and
3314 // returns false.
3315 bool Test::HasSameFixtureClass() {
3316 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3317 const TestCase* const test_case = impl->current_test_case();
3318
3319 // Info about the first test in the current test case.
3320 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3321 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3322 const char* const first_test_name = first_test_info->name();
3323
3324 // Info about the current test.
3325 const TestInfo* const this_test_info = impl->current_test_info();
3326 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3327 const char* const this_test_name = this_test_info->name();
3328
3329 if (this_fixture_id != first_fixture_id) {
3330 // Is the first test defined using TEST?
3331 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3332 // Is this test defined using TEST?
3333 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3334
3335 if (first_is_TEST || this_is_TEST) {
3336 // The user mixed TEST and TEST_F in this test case - we'll tell
3337 // him/her how to fix it.
3338
3339 // Gets the name of the TEST and the name of the TEST_F. Note
3340 // that first_is_TEST and this_is_TEST cannot both be true, as
3341 // the fixture IDs are different for the two tests.
3342 const char* const TEST_name =
3343 first_is_TEST ? first_test_name : this_test_name;
3344 const char* const TEST_F_name =
3345 first_is_TEST ? this_test_name : first_test_name;
3346
3347 ADD_FAILURE()
3348 << "All tests in the same test case must use the same test fixture\n"
3349 << "class, so mixing TEST_F and TEST in the same test case is\n"
3350 << "illegal. In test case " << this_test_info->test_case_name()
3351 << ",\n"
3352 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3353 << "test " << TEST_name << " is defined using TEST. You probably\n"
3354 << "want to change the TEST to TEST_F or move it to another test\n"
3355 << "case.";
3356 } else {
3357 // The user defined two fixture classes with the same name in
3358 // two namespaces - we'll tell him/her how to fix it.
3359 ADD_FAILURE()
3360 << "All tests in the same test case must use the same test fixture\n"
3361 << "class. However, in test case "
3362 << this_test_info->test_case_name() << ",\n"
3363 << "you defined test " << first_test_name << " and test "
3364 << this_test_name << "\n"
3365 << "using two different test fixture classes. This can happen if\n"
3366 << "the two classes are from different namespaces or translation\n"
3367 << "units and have the same name. You should probably rename one\n"
3368 << "of the classes to put the tests into different test cases.";
3369 }
3370 return false;
3371 }
3372
3373 return true;
3374 }
3375
3376 #if GTEST_HAS_SEH
3377
3378 // Adds an "exception thrown" fatal failure to the current test. This
3379 // function returns its result via an output parameter pointer because VC++
3380 // prohibits creation of objects with destructors on stack in functions
3381 // using __try (see error C2712).
3382 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3383 const char* location) {
3384 Message message;
3385 message << "SEH exception with code 0x" << std::setbase(16) << exception_code
3386 << std::setbase(10) << " thrown in " << location << ".";
3387
3388 return new std::string(message.GetString());
3389 }
3390
3391 #endif // GTEST_HAS_SEH
3392
3393 namespace internal {
3394
3395 #if GTEST_HAS_EXCEPTIONS
3396
3397 // Adds an "exception thrown" fatal failure to the current test.
3398 static std::string FormatCxxExceptionMessage(const char* description,
3399 const char* location) {
3400 Message message;
3401 if (description != NULL) {
3402 message << "C++ exception with description \"" << description << "\"";
3403 } else {
3404 message << "Unknown C++ exception";
3405 }
3406 message << " thrown in " << location << ".";
3407
3408 return message.GetString();
3409 }
3410
3411 static std::string PrintTestPartResultToString(
3412 const TestPartResult& test_part_result);
3413
3414 GoogleTestFailureException::GoogleTestFailureException(
3415 const TestPartResult& failure)
3416 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3417
3418 #endif // GTEST_HAS_EXCEPTIONS
3419
3420 // We put these helper functions in the internal namespace as IBM's xlC
3421 // compiler rejects the code if they were declared static.
3422
3423 // Runs the given method and handles SEH exceptions it throws, when
3424 // SEH is supported; returns the 0-value for type Result in case of an
3425 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3426 // exceptions in the same function. Therefore, we provide a separate
3427 // wrapper function for handling SEH exceptions.)
3428 template <class T, typename Result>
3429 Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
3430 const char* location) {
3431 #if GTEST_HAS_SEH
3432 __try {
3433 return (object->*method)();
3434 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3435 GetExceptionCode())) {
3436 // We create the exception message on the heap because VC++ prohibits
3437 // creation of objects with destructors on stack in functions using __try
3438 // (see error C2712).
3439 std::string* exception_message =
3440 FormatSehExceptionMessage(GetExceptionCode(), location);
3441 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3442 *exception_message);
3443 delete exception_message;
3444 return static_cast<Result>(0);
3445 }
3446 #else
3447 (void)location;
3448 return (object->*method)();
3449 #endif // GTEST_HAS_SEH
3450 }
3451
3452 // Runs the given method and catches and reports C++ and/or SEH-style
3453 // exceptions, if they are supported; returns the 0-value for type
3454 // Result in case of an SEH exception.
3455 template <class T, typename Result>
3456 Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
3457 const char* location) {
3458 // NOTE: The user code can affect the way in which Google Test handles
3459 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3460 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3461 // after the exception is caught and either report or re-throw the
3462 // exception based on the flag's value:
3463 //
3464 // try {
3465 // // Perform the test method.
3466 // } catch (...) {
3467 // if (GTEST_FLAG(catch_exceptions))
3468 // // Report the exception as failure.
3469 // else
3470 // throw; // Re-throws the original exception.
3471 // }
3472 //
3473 // However, the purpose of this flag is to allow the program to drop into
3474 // the debugger when the exception is thrown. On most platforms, once the
3475 // control enters the catch block, the exception origin information is
3476 // lost and the debugger will stop the program at the point of the
3477 // re-throw in this function -- instead of at the point of the original
3478 // throw statement in the code under test. For this reason, we perform
3479 // the check early, sacrificing the ability to affect Google Test's
3480 // exception handling in the method where the exception is thrown.
3481 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3482 #if GTEST_HAS_EXCEPTIONS
3483 try {
3484 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3485 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3486 // This exception type can only be thrown by a failed Google
3487 // Test assertion with the intention of letting another testing
3488 // framework catch it. Therefore we just re-throw it.
3489 throw;
3490 } catch (const std::exception& e) { // NOLINT
3491 internal::ReportFailureInUnknownLocation(
3492 TestPartResult::kFatalFailure,
3493 FormatCxxExceptionMessage(e.what(), location));
3494 } catch (...) { // NOLINT
3495 internal::ReportFailureInUnknownLocation(
3496 TestPartResult::kFatalFailure,
3497 FormatCxxExceptionMessage(NULL, location));
3498 }
3499 return static_cast<Result>(0);
3500 #else
3501 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3502 #endif // GTEST_HAS_EXCEPTIONS
3503 } else {
3504 return (object->*method)();
3505 }
3506 }
3507
3508 } // namespace internal
3509
3510 // Runs the test and updates the test result.
3511 void Test::Run() {
3512 if (!HasSameFixtureClass()) return;
3513
3514 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3515 impl->os_stack_trace_getter()->UponLeavingGTest();
3516 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3517 // We will run the test only if SetUp() was successful.
3518 if (!HasFatalFailure()) {
3519 impl->os_stack_trace_getter()->UponLeavingGTest();
3520 internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
3521 "the test body");
3522 }
3523
3524 // However, we want to clean up as much as possible. Hence we will
3525 // always call TearDown(), even if SetUp() or the test body has
3526 // failed.
3527 impl->os_stack_trace_getter()->UponLeavingGTest();
3528 internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
3529 "TearDown()");
3530 }
3531
3532 // Returns true iff the current test has a fatal failure.
3533 bool Test::HasFatalFailure() {
3534 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3535 }
3536
3537 // Returns true iff the current test has a non-fatal failure.
3538 bool Test::HasNonfatalFailure() {
3539 return internal::GetUnitTestImpl()
3540 ->current_test_result()
3541 ->HasNonfatalFailure();
3542 }
3543
3544 // class TestInfo
3545
3546 // Constructs a TestInfo object. It assumes ownership of the test factory
3547 // object.
3548 TestInfo::TestInfo(const std::string& a_test_case_name,
3549 const std::string& a_name, const char* a_type_param,
3550 const char* a_value_param, internal::TypeId fixture_class_id,
3551 internal::TestFactoryBase* factory)
3552 : test_case_name_(a_test_case_name),
3553 name_(a_name),
3554 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3555 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3556 fixture_class_id_(fixture_class_id),
3557 should_run_(false),
3558 is_disabled_(false),
3559 matches_filter_(false),
3560 factory_(factory),
3561 result_() {}
3562
3563 // Destructs a TestInfo object.
3564 TestInfo::~TestInfo() { delete factory_; }
3565
3566 namespace internal {
3567
3568 // Creates a new TestInfo object and registers it with Google Test;
3569 // returns the created object.
3570 //
3571 // Arguments:
3572 //
3573 // test_case_name: name of the test case
3574 // name: name of the test
3575 // type_param: the name of the test's type parameter, or NULL if
3576 // this is not a typed or a type-parameterized test.
3577 // value_param: text representation of the test's value parameter,
3578 // or NULL if this is not a value-parameterized test.
3579 // fixture_class_id: ID of the test fixture class
3580 // set_up_tc: pointer to the function that sets up the test case
3581 // tear_down_tc: pointer to the function that tears down the test case
3582 // factory: pointer to the factory that creates a test object.
3583 // The newly created TestInfo instance will assume
3584 // ownership of the factory object.
3585 TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name,
3586 const char* type_param,
3587 const char* value_param,
3588 TypeId fixture_class_id,
3589 SetUpTestCaseFunc set_up_tc,
3590 TearDownTestCaseFunc tear_down_tc,
3591 TestFactoryBase* factory) {
3592 TestInfo* const test_info = new TestInfo(
3593 test_case_name, name, type_param, value_param, fixture_class_id, factory);
3594 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3595 return test_info;
3596 }
3597
3598 #if GTEST_HAS_PARAM_TEST
3599 void ReportInvalidTestCaseType(const char* test_case_name, const char* file,
3600 int line) {
3601 Message errors;
3602 errors
3603 << "Attempted redefinition of test case " << test_case_name << ".\n"
3604 << "All tests in the same test case must use the same test fixture\n"
3605 << "class. However, in test case " << test_case_name << ", you tried\n"
3606 << "to define a test using a fixture class different from the one\n"
3607 << "used earlier. This can happen if the two fixture classes are\n"
3608 << "from different namespaces and have the same name. You should\n"
3609 << "probably rename one of the classes to put the tests into different\n"
3610 << "test cases.";
3611
3612 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3613 errors.GetString().c_str());
3614 }
3615 #endif // GTEST_HAS_PARAM_TEST
3616
3617 } // namespace internal
3618
3619 namespace {
3620
3621 // A predicate that checks the test name of a TestInfo against a known
3622 // value.
3623 //
3624 // This is used for implementation of the TestCase class only. We put
3625 // it in the anonymous namespace to prevent polluting the outer
3626 // namespace.
3627 //
3628 // TestNameIs is copyable.
3629 class TestNameIs {
3630 public:
3631 // Constructor.
3632 //
3633 // TestNameIs has NO default constructor.
3634 explicit TestNameIs(const char* name) : name_(name) {}
3635
3636 // Returns true iff the test name of test_info matches name_.
3637 bool operator()(const TestInfo* test_info) const {
3638 return test_info && test_info->name() == name_;
3639 }
3640
3641 private:
3642 std::string name_;
3643 };
3644
3645 } // namespace
3646
3647 namespace internal {
3648
3649 // This method expands all parameterized tests registered with macros TEST_P
3650 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3651 // This will be done just once during the program runtime.
3652 void UnitTestImpl::RegisterParameterizedTests() {
3653 #if GTEST_HAS_PARAM_TEST
3654 if (!parameterized_tests_registered_) {
3655 parameterized_test_registry_.RegisterTests();
3656 parameterized_tests_registered_ = true;
3657 }
3658 #endif
3659 }
3660
3661 } // namespace internal
3662
3663 // Creates the test object, runs it, records its result, and then
3664 // deletes it.
3665 void TestInfo::Run() {
3666 if (!should_run_) return;
3667
3668 // Tells UnitTest where to store test result.
3669 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3670 impl->set_current_test_info(this);
3671
3672 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3673
3674 // Notifies the unit test event listeners that a test is about to start.
3675 repeater->OnTestStart(*this);
3676
3677 const TimeInMillis start = internal::GetTimeInMillis();
3678
3679 impl->os_stack_trace_getter()->UponLeavingGTest();
3680
3681 // Creates the test object.
3682 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3683 factory_, &internal::TestFactoryBase::CreateTest,
3684 "the test fixture's constructor");
3685
3686 // Runs the test only if the test object was created and its
3687 // constructor didn't generate a fatal failure.
3688 if ((test != NULL) && !Test::HasFatalFailure()) {
3689 // This doesn't throw as all user code that can throw are wrapped into
3690 // exception handling code.
3691 test->Run();
3692 }
3693
3694 // Deletes the test object.
3695 impl->os_stack_trace_getter()->UponLeavingGTest();
3696 internal::HandleExceptionsInMethodIfSupported(
3697 test, &Test::DeleteSelf_, "the test fixture's destructor");
3698
3699 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3700
3701 // Notifies the unit test event listener that a test has just finished.
3702 repeater->OnTestEnd(*this);
3703
3704 // Tells UnitTest to stop associating assertion results to this
3705 // test.
3706 impl->set_current_test_info(NULL);
3707 }
3708
3709 // class TestCase
3710
3711 // Gets the number of successful tests in this test case.
3712 int TestCase::successful_test_count() const {
3713 return CountIf(test_info_list_, TestPassed);
3714 }
3715
3716 // Gets the number of failed tests in this test case.
3717 int TestCase::failed_test_count() const {
3718 return CountIf(test_info_list_, TestFailed);
3719 }
3720
3721 // Gets the number of disabled tests that will be reported in the XML report.
3722 int TestCase::reportable_disabled_test_count() const {
3723 return CountIf(test_info_list_, TestReportableDisabled);
3724 }
3725
3726 // Gets the number of disabled tests in this test case.
3727 int TestCase::disabled_test_count() const {
3728 return CountIf(test_info_list_, TestDisabled);
3729 }
3730
3731 // Gets the number of tests to be printed in the XML report.
3732 int TestCase::reportable_test_count() const {
3733 return CountIf(test_info_list_, TestReportable);
3734 }
3735
3736 // Get the number of tests in this test case that should run.
3737 int TestCase::test_to_run_count() const {
3738 return CountIf(test_info_list_, ShouldRunTest);
3739 }
3740
3741 // Gets the number of all tests.
3742 int TestCase::total_test_count() const {
3743 return static_cast<int>(test_info_list_.size());
3744 }
3745
3746 // Creates a TestCase with the given name.
3747 //
3748 // Arguments:
3749 //
3750 // name: name of the test case
3751 // a_type_param: the name of the test case's type parameter, or NULL if
3752 // this is not a typed or a type-parameterized test case.
3753 // set_up_tc: pointer to the function that sets up the test case
3754 // tear_down_tc: pointer to the function that tears down the test case
3755 TestCase::TestCase(const char* a_name, const char* a_type_param,
3756 Test::SetUpTestCaseFunc set_up_tc,
3757 Test::TearDownTestCaseFunc tear_down_tc)
3758 : name_(a_name),
3759 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3760 set_up_tc_(set_up_tc),
3761 tear_down_tc_(tear_down_tc),
3762 should_run_(false),
3763 elapsed_time_(0) {}
3764
3765 // Destructor of TestCase.
3766 TestCase::~TestCase() {
3767 // Deletes every Test in the collection.
3768 ForEach(test_info_list_, internal::Delete<TestInfo>);
3769 }
3770
3771 // Returns the i-th test among all the tests. i can range from 0 to
3772 // total_test_count() - 1. If i is not in that range, returns NULL.
3773 const TestInfo* TestCase::GetTestInfo(int i) const {
3774 const int index = GetElementOr(test_indices_, i, -1);
3775 return index < 0 ? NULL : test_info_list_[index];
3776 }
3777
3778 // Returns the i-th test among all the tests. i can range from 0 to
3779 // total_test_count() - 1. If i is not in that range, returns NULL.
3780 TestInfo* TestCase::GetMutableTestInfo(int i) {
3781 const int index = GetElementOr(test_indices_, i, -1);
3782 return index < 0 ? NULL : test_info_list_[index];
3783 }
3784
3785 // Adds a test to this test case. Will delete the test upon
3786 // destruction of the TestCase object.
3787 void TestCase::AddTestInfo(TestInfo* test_info) {
3788 test_info_list_.push_back(test_info);
3789 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3790 }
3791
3792 // Runs every test in this TestCase.
3793 void TestCase::Run() {
3794 if (!should_run_) return;
3795
3796 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3797 impl->set_current_test_case(this);
3798
3799 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3800
3801 repeater->OnTestCaseStart(*this);
3802 impl->os_stack_trace_getter()->UponLeavingGTest();
3803 internal::HandleExceptionsInMethodIfSupported(
3804 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3805
3806 const internal::TimeInMillis start = internal::GetTimeInMillis();
3807 for (int i = 0; i < total_test_count(); i++) {
3808 GetMutableTestInfo(i)->Run();
3809 }
3810 elapsed_time_ = internal::GetTimeInMillis() - start;
3811
3812 impl->os_stack_trace_getter()->UponLeavingGTest();
3813 internal::HandleExceptionsInMethodIfSupported(
3814 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3815
3816 repeater->OnTestCaseEnd(*this);
3817 impl->set_current_test_case(NULL);
3818 }
3819
3820 // Clears the results of all tests in this test case.
3821 void TestCase::ClearResult() {
3822 ad_hoc_test_result_.Clear();
3823 ForEach(test_info_list_, TestInfo::ClearTestResult);
3824 }
3825
3826 // Shuffles the tests in this test case.
3827 void TestCase::ShuffleTests(internal::Random* random) {
3828 Shuffle(random, &test_indices_);
3829 }
3830
3831 // Restores the test order to before the first shuffle.
3832 void TestCase::UnshuffleTests() {
3833 for (size_t i = 0; i < test_indices_.size(); i++) {
3834 test_indices_[i] = static_cast<int>(i);
3835 }
3836 }
3837
3838 // Formats a countable noun. Depending on its quantity, either the
3839 // singular form or the plural form is used. e.g.
3840 //
3841 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3842 // FormatCountableNoun(5, "book", "books") returns "5 books".
3843 static std::string FormatCountableNoun(int count, const char* singular_form,
3844 const char* plural_form) {
3845 return internal::StreamableToString(count) + " " +
3846 (count == 1 ? singular_form : plural_form);
3847 }
3848
3849 // Formats the count of tests.
3850 static std::string FormatTestCount(int test_count) {
3851 return FormatCountableNoun(test_count, "test", "tests");
3852 }
3853
3854 // Formats the count of test cases.
3855 static std::string FormatTestCaseCount(int test_case_count) {
3856 return FormatCountableNoun(test_case_count, "test case", "test cases");
3857 }
3858
3859 // Converts a TestPartResult::Type enum to human-friendly string
3860 // representation. Both kNonFatalFailure and kFatalFailure are translated
3861 // to "Failure", as the user usually doesn't care about the difference
3862 // between the two when viewing the test result.
3863 static const char* TestPartResultTypeToString(TestPartResult::Type type) {
3864 switch (type) {
3865 case TestPartResult::kSuccess:
3866 return "Success";
3867
3868 case TestPartResult::kNonFatalFailure:
3869 case TestPartResult::kFatalFailure:
3870 #ifdef _MSC_VER
3871 return "error: ";
3872 #else
3873 return "Failure\n";
3874 #endif
3875 default:
3876 return "Unknown result type";
3877 }
3878 }
3879
3880 namespace internal {
3881
3882 // Prints a TestPartResult to an std::string.
3883 static std::string PrintTestPartResultToString(
3884 const TestPartResult& test_part_result) {
3885 return (Message() << internal::FormatFileLocation(
3886 test_part_result.file_name(),
3887 test_part_result.line_number())
3888 << " "
3889 << TestPartResultTypeToString(test_part_result.type())
3890 << test_part_result.message())
3891 .GetString();
3892 }
3893
3894 // Prints a TestPartResult.
3895 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3896 const std::string& result = PrintTestPartResultToString(test_part_result);
3897 printf("%s\n", result.c_str());
3898 fflush(stdout);
3899 // If the test program runs in Visual Studio or a debugger, the
3900 // following statements add the test part result message to the Output
3901 // window such that the user can double-click on it to jump to the
3902 // corresponding source code location; otherwise they do nothing.
3903 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3904 // We don't call OutputDebugString*() on Windows Mobile, as printing
3905 // to stdout is done by OutputDebugString() there already - we don't
3906 // want the same message printed twice.
3907 ::OutputDebugStringA(result.c_str());
3908 ::OutputDebugStringA("\n");
3909 #endif
3910 }
3911
3912 // class PrettyUnitTestResultPrinter
3913
3914 enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
3915
3916 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3917
3918 // Returns the character attribute for the given color.
3919 WORD GetColorAttribute(GTestColor color) {
3920 switch (color) {
3921 case COLOR_RED:
3922 return FOREGROUND_RED;
3923 case COLOR_GREEN:
3924 return FOREGROUND_GREEN;
3925 case COLOR_YELLOW:
3926 return FOREGROUND_RED | FOREGROUND_GREEN;
3927 default:
3928 return 0;
3929 }
3930 }
3931
3932 #else
3933
3934 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
3935 // an invalid input.
3936 const char* GetAnsiColorCode(GTestColor color) {
3937 switch (color) {
3938 case COLOR_RED:
3939 return "1";
3940 case COLOR_GREEN:
3941 return "2";
3942 case COLOR_YELLOW:
3943 return "3";
3944 default:
3945 return NULL;
3946 };
3947 }
3948
3949 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3950
3951 // Returns true iff Google Test should use colors in the output.
3952 bool ShouldUseColor(bool stdout_is_tty) {
3953 const char* const gtest_color = GTEST_FLAG(color).c_str();
3954
3955 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3956 #if GTEST_OS_WINDOWS
3957 // On Windows the TERM variable is usually not set, but the
3958 // console there does support colors.
3959 return stdout_is_tty;
3960 #else
3961 // On non-Windows platforms, we rely on the TERM variable.
3962 const char* const term = posix::GetEnv("TERM");
3963 const bool term_supports_color =
3964 String::CStringEquals(term, "xterm") ||
3965 String::CStringEquals(term, "xterm-color") ||
3966 String::CStringEquals(term, "xterm-256color") ||
3967 String::CStringEquals(term, "screen") ||
3968 String::CStringEquals(term, "screen-256color") ||
3969 String::CStringEquals(term, "linux") ||
3970 String::CStringEquals(term, "cygwin");
3971 return stdout_is_tty && term_supports_color;
3972 #endif // GTEST_OS_WINDOWS
3973 }
3974
3975 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3976 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3977 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3978 String::CStringEquals(gtest_color, "1");
3979 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3980 // value is neither one of these nor "auto", we treat it as "no" to
3981 // be conservative.
3982 }
3983
3984 // Helpers for printing colored strings to stdout. Note that on Windows, we
3985 // cannot simply emit special characters and have the terminal change colors.
3986 // This routine must actually emit the characters rather than return a string
3987 // that would be colored when printed, as can be done on Linux.
3988 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3989 va_list args;
3990 va_start(args, fmt);
3991
3992 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
3993 const bool use_color = false;
3994 #else
3995 static const bool in_color_mode =
3996 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3997 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3998 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3999 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4000
4001 if (!use_color) {
4002 vprintf(fmt, args);
4003 va_end(args);
4004 return;
4005 }
4006
4007 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4008 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4009
4010 // Gets the current text color.
4011 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4012 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4013 const WORD old_color_attrs = buffer_info.wAttributes;
4014
4015 // We need to flush the stream buffers into the console before each
4016 // SetConsoleTextAttribute call lest it affect the text that is already
4017 // printed but has not yet reached the console.
4018 fflush(stdout);
4019 SetConsoleTextAttribute(stdout_handle,
4020 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4021 vprintf(fmt, args);
4022
4023 fflush(stdout);
4024 // Restores the text color.
4025 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4026 #else
4027 printf("\033[0;3%sm", GetAnsiColorCode(color));
4028 vprintf(fmt, args);
4029 printf("\033[m"); // Resets the terminal to default.
4030 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4031 va_end(args);
4032 }
4033
4034 // Text printed in Google Test's text output and --gunit_list_tests
4035 // output to label the type parameter and value parameter for a test.
4036 static const char kTypeParamLabel[] = "TypeParam";
4037 static const char kValueParamLabel[] = "GetParam()";
4038
4039 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4040 const char* const type_param = test_info.type_param();
4041 const char* const value_param = test_info.value_param();
4042
4043 if (type_param != NULL || value_param != NULL) {
4044 printf(", where ");
4045 if (type_param != NULL) {
4046 printf("%s = %s", kTypeParamLabel, type_param);
4047 if (value_param != NULL) printf(" and ");
4048 }
4049 if (value_param != NULL) {
4050 printf("%s = %s", kValueParamLabel, value_param);
4051 }
4052 }
4053 }
4054
4055 // This class implements the TestEventListener interface.
4056 //
4057 // Class PrettyUnitTestResultPrinter is copyable.
4058 class PrettyUnitTestResultPrinter : public TestEventListener {
4059 public:
4060 PrettyUnitTestResultPrinter() {}
4061 static void PrintTestName(const char* test_case, const char* test) {
4062 printf("%s.%s", test_case, test);
4063 }
4064
4065 // The following methods override what's in the TestEventListener class.
4066 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4067 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4068 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4069 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4070 virtual void OnTestCaseStart(const TestCase& test_case);
4071 virtual void OnTestStart(const TestInfo& test_info);
4072 virtual void OnTestPartResult(const TestPartResult& result);
4073 virtual void OnTestEnd(const TestInfo& test_info);
4074 virtual void OnTestCaseEnd(const TestCase& test_case);
4075 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4076 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4077 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4078 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4079
4080 private:
4081 static void PrintFailedTests(const UnitTest& unit_test);
4082 };
4083
4084 // Fired before each iteration of tests starts.
4085 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4086 const UnitTest& unit_test, int iteration) {
4087 if (GTEST_FLAG(repeat) != 1)
4088 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4089
4090 const char* const filter = GTEST_FLAG(filter).c_str();
4091
4092 // Prints the filter if it's not *. This reminds the user that some
4093 // tests may be skipped.
4094 if (!String::CStringEquals(filter, kUniversalFilter)) {
4095 ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter);
4096 }
4097
4098 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4099 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4100 ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n",
4101 static_cast<int>(shard_index) + 1,
4102 internal::posix::GetEnv(kTestTotalShards));
4103 }
4104
4105 if (GTEST_FLAG(shuffle)) {
4106 ColoredPrintf(COLOR_YELLOW,
4107 "Note: Randomizing tests' orders with a seed of %d .\n",
4108 unit_test.random_seed());
4109 }
4110
4111 ColoredPrintf(COLOR_GREEN, "[==========] ");
4112 printf("Running %s from %s.\n",
4113 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4114 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4115 fflush(stdout);
4116 }
4117
4118 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4119 const UnitTest& /*unit_test*/) {
4120 ColoredPrintf(COLOR_GREEN, "[----------] ");
4121 printf("Global test environment set-up.\n");
4122 fflush(stdout);
4123 }
4124
4125 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4126 const std::string counts =
4127 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4128 ColoredPrintf(COLOR_GREEN, "[----------] ");
4129 printf("%s from %s", counts.c_str(), test_case.name());
4130 if (test_case.type_param() == NULL) {
4131 printf("\n");
4132 } else {
4133 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4134 }
4135 fflush(stdout);
4136 }
4137
4138 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4139 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4140 PrintTestName(test_info.test_case_name(), test_info.name());
4141 printf("\n");
4142 fflush(stdout);
4143 }
4144
4145 // Called after an assertion failure.
4146 void PrettyUnitTestResultPrinter::OnTestPartResult(
4147 const TestPartResult& result) {
4148 // If the test part succeeded, we don't need to do anything.
4149 if (result.type() == TestPartResult::kSuccess) return;
4150
4151 // Print failure message from the assertion (e.g. expected this and got that).
4152 PrintTestPartResult(result);
4153 fflush(stdout);
4154 }
4155
4156 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4157 if (test_info.result()->Passed()) {
4158 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4159 } else {
4160 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4161 }
4162 PrintTestName(test_info.test_case_name(), test_info.name());
4163 if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
4164
4165 if (GTEST_FLAG(print_time)) {
4166 printf(" (%s ms)\n",
4167 internal::StreamableToString(test_info.result()->elapsed_time())
4168 .c_str());
4169 } else {
4170 printf("\n");
4171 }
4172 fflush(stdout);
4173 }
4174
4175 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4176 if (!GTEST_FLAG(print_time)) return;
4177
4178 const std::string counts =
4179 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4180 ColoredPrintf(COLOR_GREEN, "[----------] ");
4181 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
4182 internal::StreamableToString(test_case.elapsed_time()).c_str());
4183 fflush(stdout);
4184 }
4185
4186 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4187 const UnitTest& /*unit_test*/) {
4188 ColoredPrintf(COLOR_GREEN, "[----------] ");
4189 printf("Global test environment tear-down\n");
4190 fflush(stdout);
4191 }
4192
4193 // Internal helper for printing the list of failed tests.
4194 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4195 const int failed_test_count = unit_test.failed_test_count();
4196 if (failed_test_count == 0) {
4197 return;
4198 }
4199
4200 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4201 const TestCase& test_case = *unit_test.GetTestCase(i);
4202 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4203 continue;
4204 }
4205 for (int j = 0; j < test_case.total_test_count(); ++j) {
4206 const TestInfo& test_info = *test_case.GetTestInfo(j);
4207 if (!test_info.should_run() || test_info.result()->Passed()) {
4208 continue;
4209 }
4210 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4211 printf("%s.%s", test_case.name(), test_info.name());
4212 PrintFullTestCommentIfPresent(test_info);
4213 printf("\n");
4214 }
4215 }
4216 }
4217
4218 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4219 int /*iteration*/) {
4220 ColoredPrintf(COLOR_GREEN, "[==========] ");
4221 printf("%s from %s ran.",
4222 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4223 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4224 if (GTEST_FLAG(print_time)) {
4225 printf(" (%s ms total)",
4226 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4227 }
4228 printf("\n");
4229 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4230 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4231
4232 int num_failures = unit_test.failed_test_count();
4233 if (!unit_test.Passed()) {
4234 const int failed_test_count = unit_test.failed_test_count();
4235 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4236 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4237 PrintFailedTests(unit_test);
4238 printf("\n%2d FAILED %s\n", num_failures,
4239 num_failures == 1 ? "TEST" : "TESTS");
4240 }
4241
4242 int num_disabled = unit_test.reportable_disabled_test_count();
4243 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4244 if (!num_failures) {
4245 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4246 }
4247 ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled,
4248 num_disabled == 1 ? "TEST" : "TESTS");
4249 }
4250 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4251 fflush(stdout);
4252 }
4253
4254 // End PrettyUnitTestResultPrinter
4255
4256 // class TestEventRepeater
4257 //
4258 // This class forwards events to other event listeners.
4259 class TestEventRepeater : public TestEventListener {
4260 public:
4261 TestEventRepeater() : forwarding_enabled_(true) {}
4262 virtual ~TestEventRepeater();
4263 void Append(TestEventListener* listener);
4264 TestEventListener* Release(TestEventListener* listener);
4265
4266 // Controls whether events will be forwarded to listeners_. Set to false
4267 // in death test child processes.
4268 bool forwarding_enabled() const { return forwarding_enabled_; }
4269 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4270
4271 virtual void OnTestProgramStart(const UnitTest& unit_test);
4272 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4273 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4274 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4275 virtual void OnTestCaseStart(const TestCase& test_case);
4276 virtual void OnTestStart(const TestInfo& test_info);
4277 virtual void OnTestPartResult(const TestPartResult& result);
4278 virtual void OnTestEnd(const TestInfo& test_info);
4279 virtual void OnTestCaseEnd(const TestCase& test_case);
4280 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4281 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4282 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4283 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4284
4285 private:
4286 // Controls whether events will be forwarded to listeners_. Set to false
4287 // in death test child processes.
4288 bool forwarding_enabled_;
4289 // The list of listeners that receive events.
4290 std::vector<TestEventListener*> listeners_;
4291
4292 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4293 };
4294
4295 TestEventRepeater::~TestEventRepeater() {
4296 ForEach(listeners_, Delete<TestEventListener>);
4297 }
4298
4299 void TestEventRepeater::Append(TestEventListener* listener) {
4300 listeners_.push_back(listener);
4301 }
4302
4303 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4304 TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
4305 for (size_t i = 0; i < listeners_.size(); ++i) {
4306 if (listeners_[i] == listener) {
4307 listeners_.erase(listeners_.begin() + i);
4308 return listener;
4309 }
4310 }
4311
4312 return NULL;
4313 }
4314
4315 // Since most methods are very similar, use macros to reduce boilerplate.
4316 // This defines a member that forwards the call to all listeners.
4317 #define GTEST_REPEATER_METHOD_(Name, Type) \
4318 void TestEventRepeater::Name(const Type& parameter) { \
4319 if (forwarding_enabled_) { \
4320 for (size_t i = 0; i < listeners_.size(); i++) { \
4321 listeners_[i]->Name(parameter); \
4322 } \
4323 } \
4324 }
4325 // This defines a member that forwards the call to all listeners in reverse
4326 // order.
4327 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4328 void TestEventRepeater::Name(const Type& parameter) { \
4329 if (forwarding_enabled_) { \
4330 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4331 listeners_[i]->Name(parameter); \
4332 } \
4333 } \
4334 }
4335
4336 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4337 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4338 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4339 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4340 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4341 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4342 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4343 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4344 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4345 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4346 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4347
4348 #undef GTEST_REPEATER_METHOD_
4349 #undef GTEST_REVERSE_REPEATER_METHOD_
4350
4351 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4352 int iteration) {
4353 if (forwarding_enabled_) {
4354 for (size_t i = 0; i < listeners_.size(); i++) {
4355 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4356 }
4357 }
4358 }
4359
4360 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4361 int iteration) {
4362 if (forwarding_enabled_) {
4363 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4364 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4365 }
4366 }
4367 }
4368
4369 // End TestEventRepeater
4370
4371 // This class generates an XML output file.
4372 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4373 public:
4374 explicit XmlUnitTestResultPrinter(const char* output_file);
4375
4376 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4377
4378 private:
4379 // Is c a whitespace character that is normalized to a space character
4380 // when it appears in an XML attribute value?
4381 static bool IsNormalizableWhitespace(char c) {
4382 return c == 0x9 || c == 0xA || c == 0xD;
4383 }
4384
4385 // May c appear in a well-formed XML document?
4386 static bool IsValidXmlCharacter(char c) {
4387 return IsNormalizableWhitespace(c) || c >= 0x20;
4388 }
4389
4390 // Returns an XML-escaped copy of the input string str. If
4391 // is_attribute is true, the text is meant to appear as an attribute
4392 // value, and normalizable whitespace is preserved by replacing it
4393 // with character references.
4394 static std::string EscapeXml(const std::string& str, bool is_attribute);
4395
4396 // Returns the given string with all characters invalid in XML removed.
4397 static std::string RemoveInvalidXmlCharacters(const std::string& str);
4398
4399 // Convenience wrapper around EscapeXml when str is an attribute value.
4400 static std::string EscapeXmlAttribute(const std::string& str) {
4401 return EscapeXml(str, true);
4402 }
4403
4404 // Convenience wrapper around EscapeXml when str is not an attribute value.
4405 static std::string EscapeXmlText(const char* str) {
4406 return EscapeXml(str, false);
4407 }
4408
4409 // Verifies that the given attribute belongs to the given element and
4410 // streams the attribute as XML.
4411 static void OutputXmlAttribute(std::ostream* stream,
4412 const std::string& element_name,
4413 const std::string& name,
4414 const std::string& value);
4415
4416 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4417 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4418
4419 // Streams an XML representation of a TestInfo object.
4420 static void OutputXmlTestInfo(::std::ostream* stream,
4421 const char* test_case_name,
4422 const TestInfo& test_info);
4423
4424 // Prints an XML representation of a TestCase object
4425 static void PrintXmlTestCase(::std::ostream* stream,
4426 const TestCase& test_case);
4427
4428 // Prints an XML summary of unit_test to output stream out.
4429 static void PrintXmlUnitTest(::std::ostream* stream,
4430 const UnitTest& unit_test);
4431
4432 // Produces a string representing the test properties in a result as space
4433 // delimited XML attributes based on the property key="value" pairs.
4434 // When the std::string is not empty, it includes a space at the beginning,
4435 // to delimit this attribute from prior attributes.
4436 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4437
4438 // The output file.
4439 const std::string output_file_;
4440
4441 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4442 };
4443
4444 // Creates a new XmlUnitTestResultPrinter.
4445 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4446 : output_file_(output_file) {
4447 if (output_file_.c_str() == NULL || output_file_.empty()) {
4448 fprintf(stderr, "XML output file may not be null\n");
4449 fflush(stderr);
4450 exit(EXIT_FAILURE);
4451 }
4452 }
4453
4454 // Called after the unit test ends.
4455 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4456 int /*iteration*/) {
4457 FILE* xmlout = NULL;
4458 FilePath output_file(output_file_);
4459 FilePath output_dir(output_file.RemoveFileName());
4460
4461 if (output_dir.CreateDirectoriesRecursively()) {
4462 xmlout = posix::FOpen(output_file_.c_str(), "w");
4463 }
4464 if (xmlout == NULL) {
4465 // TODO(wan): report the reason of the failure.
4466 //
4467 // We don't do it for now as:
4468 //
4469 // 1. There is no urgent need for it.
4470 // 2. It's a bit involved to make the errno variable thread-safe on
4471 // all three operating systems (Linux, Windows, and Mac OS).
4472 // 3. To interpret the meaning of errno in a thread-safe way,
4473 // we need the strerror_r() function, which is not available on
4474 // Windows.
4475 fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str());
4476 fflush(stderr);
4477 exit(EXIT_FAILURE);
4478 }
4479 std::stringstream stream;
4480 PrintXmlUnitTest(&stream, unit_test);
4481 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4482 fclose(xmlout);
4483 }
4484
4485 // Returns an XML-escaped copy of the input string str. If is_attribute
4486 // is true, the text is meant to appear as an attribute value, and
4487 // normalizable whitespace is preserved by replacing it with character
4488 // references.
4489 //
4490 // Invalid XML characters in str, if any, are stripped from the output.
4491 // It is expected that most, if not all, of the text processed by this
4492 // module will consist of ordinary English text.
4493 // If this module is ever modified to produce version 1.1 XML output,
4494 // most invalid characters can be retained using character references.
4495 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4496 // escaping scheme for invalid characters, rather than dropping them.
4497 std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
4498 bool is_attribute) {
4499 Message m;
4500
4501 for (size_t i = 0; i < str.size(); ++i) {
4502 const char ch = str[i];
4503 switch (ch) {
4504 case '<':
4505 m << "&lt;";
4506 break;
4507 case '>':
4508 m << "&gt;";
4509 break;
4510 case '&':
4511 m << "&amp;";
4512 break;
4513 case '\'':
4514 if (is_attribute)
4515 m << "&apos;";
4516 else
4517 m << '\'';
4518 break;
4519 case '"':
4520 if (is_attribute)
4521 m << "&quot;";
4522 else
4523 m << '"';
4524 break;
4525 default:
4526 if (IsValidXmlCharacter(ch)) {
4527 if (is_attribute && IsNormalizableWhitespace(ch))
4528 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4529 << ";";
4530 else
4531 m << ch;
4532 }
4533 break;
4534 }
4535 }
4536
4537 return m.GetString();
4538 }
4539
4540 // Returns the given string with all characters invalid in XML removed.
4541 // Currently invalid characters are dropped from the string. An
4542 // alternative is to replace them with certain characters such as . or ?.
4543 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4544 const std::string& str) {
4545 std::string output;
4546 output.reserve(str.size());
4547 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4548 if (IsValidXmlCharacter(*it)) output.push_back(*it);
4549
4550 return output;
4551 }
4552
4553 // The following routines generate an XML representation of a UnitTest
4554 // object.
4555 //
4556 // This is how Google Test concepts map to the DTD:
4557 //
4558 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4559 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4560 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4561 // <failure message="...">...</failure>
4562 // <failure message="...">...</failure>
4563 // <failure message="...">...</failure>
4564 // <-- individual assertion failures
4565 // </testcase>
4566 // </testsuite>
4567 // </testsuites>
4568
4569 // Formats the given time in milliseconds as seconds.
4570 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4571 ::std::stringstream ss;
4572 ss << ms / 1000.0;
4573 return ss.str();
4574 }
4575
4576 // Converts the given epoch time in milliseconds to a date string in the ISO
4577 // 8601 format, without the timezone information.
4578 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4579 // Using non-reentrant version as localtime_r is not portable.
4580 time_t seconds = static_cast<time_t>(ms / 1000);
4581 #ifdef _MSC_VER
4582 # pragma warning(push) // Saves the current warning state.
4583 # pragma warning(disable : 4996) // Temporarily disables warning 4996
4584 // (function or variable may be unsafe).
4585 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4586 # pragma warning(pop) // Restores the warning state again.
4587 #else
4588 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4589 #endif
4590 if (time_struct == NULL) return ""; // Invalid ms value
4591
4592 // YYYY-MM-DDThh:mm:ss
4593 return StreamableToString(time_struct->tm_year + 1900) + "-" +
4594 String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4595 String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4596 String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4597 String::FormatIntWidth2(time_struct->tm_min) + ":" +
4598 String::FormatIntWidth2(time_struct->tm_sec);
4599 }
4600
4601 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4602 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4603 const char* data) {
4604 const char* segment = data;
4605 *stream << "<![CDATA[";
4606 for (;;) {
4607 const char* const next_segment = strstr(segment, "]]>");
4608 if (next_segment != NULL) {
4609 stream->write(segment,
4610 static_cast<std::streamsize>(next_segment - segment));
4611 *stream << "]]>]]&gt;<![CDATA[";
4612 segment = next_segment + strlen("]]>");
4613 } else {
4614 *stream << segment;
4615 break;
4616 }
4617 }
4618 *stream << "]]>";
4619 }
4620
4621 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4622 std::ostream* stream, const std::string& element_name,
4623 const std::string& name, const std::string& value) {
4624 const std::vector<std::string>& allowed_names =
4625 GetReservedAttributesForElement(element_name);
4626
4627 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4628 allowed_names.end())
4629 << "Attribute " << name << " is not allowed for element <" << element_name
4630 << ">.";
4631
4632 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4633 }
4634
4635 // Prints an XML representation of a TestInfo object.
4636 // TODO(wan): There is also value in printing properties with the plain printer.
4637 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4638 const char* test_case_name,
4639 const TestInfo& test_info) {
4640 const TestResult& result = *test_info.result();
4641 const std::string kTestcase = "testcase";
4642
4643 *stream << " <testcase";
4644 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
4645
4646 if (test_info.value_param() != NULL) {
4647 OutputXmlAttribute(stream, kTestcase, "value_param",
4648 test_info.value_param());
4649 }
4650 if (test_info.type_param() != NULL) {
4651 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
4652 }
4653
4654 OutputXmlAttribute(stream, kTestcase, "status",
4655 test_info.should_run() ? "run" : "notrun");
4656 OutputXmlAttribute(stream, kTestcase, "time",
4657 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4658 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4659 *stream << TestPropertiesAsXmlAttributes(result);
4660
4661 int failures = 0;
4662 for (int i = 0; i < result.total_part_count(); ++i) {
4663 const TestPartResult& part = result.GetTestPartResult(i);
4664 if (part.failed()) {
4665 if (++failures == 1) {
4666 *stream << ">\n";
4667 }
4668 const string location = internal::FormatCompilerIndependentFileLocation(
4669 part.file_name(), part.line_number());
4670 const string summary = location + "\n" + part.summary();
4671 *stream << " <failure message=\""
4672 << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">";
4673 const string detail = location + "\n" + part.message();
4674 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4675 *stream << "</failure>\n";
4676 }
4677 }
4678
4679 if (failures == 0)
4680 *stream << " />\n";
4681 else
4682 *stream << " </testcase>\n";
4683 }
4684
4685 // Prints an XML representation of a TestCase object
4686 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
4687 const TestCase& test_case) {
4688 const std::string kTestsuite = "testsuite";
4689 *stream << " <" << kTestsuite;
4690 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4691 OutputXmlAttribute(stream, kTestsuite, "tests",
4692 StreamableToString(test_case.reportable_test_count()));
4693 OutputXmlAttribute(stream, kTestsuite, "failures",
4694 StreamableToString(test_case.failed_test_count()));
4695 OutputXmlAttribute(
4696 stream, kTestsuite, "disabled",
4697 StreamableToString(test_case.reportable_disabled_test_count()));
4698 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4699 OutputXmlAttribute(stream, kTestsuite, "time",
4700 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
4701 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4702 << ">\n";
4703
4704 for (int i = 0; i < test_case.total_test_count(); ++i) {
4705 if (test_case.GetTestInfo(i)->is_reportable())
4706 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4707 }
4708 *stream << " </" << kTestsuite << ">\n";
4709 }
4710
4711 // Prints an XML summary of unit_test to output stream out.
4712 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4713 const UnitTest& unit_test) {
4714 const std::string kTestsuites = "testsuites";
4715
4716 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4717 *stream << "<" << kTestsuites;
4718
4719 OutputXmlAttribute(stream, kTestsuites, "tests",
4720 StreamableToString(unit_test.reportable_test_count()));
4721 OutputXmlAttribute(stream, kTestsuites, "failures",
4722 StreamableToString(unit_test.failed_test_count()));
4723 OutputXmlAttribute(
4724 stream, kTestsuites, "disabled",
4725 StreamableToString(unit_test.reportable_disabled_test_count()));
4726 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4727 OutputXmlAttribute(
4728 stream, kTestsuites, "timestamp",
4729 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4730 OutputXmlAttribute(stream, kTestsuites, "time",
4731 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4732
4733 if (GTEST_FLAG(shuffle)) {
4734 OutputXmlAttribute(stream, kTestsuites, "random_seed",
4735 StreamableToString(unit_test.random_seed()));
4736 }
4737
4738 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4739
4740 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4741 *stream << ">\n";
4742
4743 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4744 if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
4745 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4746 }
4747 *stream << "</" << kTestsuites << ">\n";
4748 }
4749
4750 // Produces a string representing the test properties in a result as space
4751 // delimited XML attributes based on the property key="value" pairs.
4752 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4753 const TestResult& result) {
4754 Message attributes;
4755 for (int i = 0; i < result.test_property_count(); ++i) {
4756 const TestProperty& property = result.GetTestProperty(i);
4757 attributes << " " << property.key() << "="
4758 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4759 }
4760 return attributes.GetString();
4761 }
4762
4763 // End XmlUnitTestResultPrinter
4764
4765 #if GTEST_CAN_STREAM_RESULTS_
4766
4767 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4768 // replaces them by "%xx" where xx is their hexadecimal value. For
4769 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4770 // in both time and space -- important as the input str may contain an
4771 // arbitrarily long test failure message and stack trace.
4772 string StreamingListener::UrlEncode(const char* str) {
4773 string result;
4774 result.reserve(strlen(str) + 1);
4775 for (char ch = *str; ch != '\0'; ch = *++str) {
4776 switch (ch) {
4777 case '%':
4778 case '=':
4779 case '&':
4780 case '\n':
4781 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4782 break;
4783 default:
4784 result.push_back(ch);
4785 break;
4786 }
4787 }
4788 return result;
4789 }
4790
4791 void StreamingListener::SocketWriter::MakeConnection() {
4792 GTEST_CHECK_(sockfd_ == -1)
4793 << "MakeConnection() can't be called when there is already a connection.";
4794
4795 addrinfo hints;
4796 memset(&hints, 0, sizeof(hints));
4797 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4798 hints.ai_socktype = SOCK_STREAM;
4799 addrinfo* servinfo = NULL;
4800
4801 // Use the getaddrinfo() to get a linked list of IP addresses for
4802 // the given host name.
4803 const int error_num =
4804 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4805 if (error_num != 0) {
4806 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4807 << gai_strerror(error_num);
4808 }
4809
4810 // Loop through all the results and connect to the first we can.
4811 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4812 cur_addr = cur_addr->ai_next) {
4813 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4814 cur_addr->ai_protocol);
4815 if (sockfd_ != -1) {
4816 // Connect the client socket to the server socket.
4817 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4818 close(sockfd_);
4819 sockfd_ = -1;
4820 }
4821 }
4822 }
4823
4824 freeaddrinfo(servinfo); // all done with this structure
4825
4826 if (sockfd_ == -1) {
4827 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4828 << host_name_ << ":" << port_num_;
4829 }
4830 }
4831
4832 // End of class Streaming Listener
4833 #endif // GTEST_CAN_STREAM_RESULTS__
4834
4835 // Class ScopedTrace
4836
4837 // Pushes the given source file location and message onto a per-thread
4838 // trace stack maintained by Google Test.
4839 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4840 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4841 TraceInfo trace;
4842 trace.file = file;
4843 trace.line = line;
4844 trace.message = message.GetString();
4845
4846 UnitTest::GetInstance()->PushGTestTrace(trace);
4847 }
4848
4849 // Pops the info pushed by the c'tor.
4850 ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4851 UnitTest::GetInstance()->PopGTestTrace();
4852 }
4853
4854 // class OsStackTraceGetter
4855
4856 // Returns the current OS stack trace as an std::string. Parameters:
4857 //
4858 // max_depth - the maximum number of stack frames to be included
4859 // in the trace.
4860 // skip_count - the number of top frames to be skipped; doesn't count
4861 // against max_depth.
4862 //
4863 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4864 int /* skip_count */)
4865 GTEST_LOCK_EXCLUDED_(mutex_) {
4866 return "";
4867 }
4868
4869 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {}
4870
4871 const char* const OsStackTraceGetter::kElidedFramesMarker =
4872 "... " GTEST_NAME_ " internal frames ...";
4873
4874 // A helper class that creates the premature-exit file in its
4875 // constructor and deletes the file in its destructor.
4876 class ScopedPrematureExitFile {
4877 public:
4878 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
4879 : premature_exit_filepath_(premature_exit_filepath) {
4880 // If a path to the premature-exit file is specified...
4881 if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
4882 // create the file with a single "0" character in it. I/O
4883 // errors are ignored as there's nothing better we can do and we
4884 // don't want to fail the test because of this.
4885 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
4886 fwrite("0", 1, 1, pfile);
4887 fclose(pfile);
4888 }
4889 }
4890
4891 ~ScopedPrematureExitFile() {
4892 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
4893 remove(premature_exit_filepath_);
4894 }
4895 }
4896
4897 private:
4898 const char* const premature_exit_filepath_;
4899
4900 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
4901 };
4902
4903 } // namespace internal
4904
4905 // class TestEventListeners
4906
4907 TestEventListeners::TestEventListeners()
4908 : repeater_(new internal::TestEventRepeater()),
4909 default_result_printer_(NULL),
4910 default_xml_generator_(NULL) {}
4911
4912 TestEventListeners::~TestEventListeners() { delete repeater_; }
4913
4914 // Returns the standard listener responsible for the default console
4915 // output. Can be removed from the listeners list to shut down default
4916 // console output. Note that removing this object from the listener list
4917 // with Release transfers its ownership to the user.
4918 void TestEventListeners::Append(TestEventListener* listener) {
4919 repeater_->Append(listener);
4920 }
4921
4922 // Removes the given event listener from the list and returns it. It then
4923 // becomes the caller's responsibility to delete the listener. Returns
4924 // NULL if the listener is not found in the list.
4925 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4926 if (listener == default_result_printer_)
4927 default_result_printer_ = NULL;
4928 else if (listener == default_xml_generator_)
4929 default_xml_generator_ = NULL;
4930 return repeater_->Release(listener);
4931 }
4932
4933 // Returns repeater that broadcasts the TestEventListener events to all
4934 // subscribers.
4935 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4936
4937 // Sets the default_result_printer attribute to the provided listener.
4938 // The listener is also added to the listener list and previous
4939 // default_result_printer is removed from it and deleted. The listener can
4940 // also be NULL in which case it will not be added to the list. Does
4941 // nothing if the previous and the current listener objects are the same.
4942 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4943 if (default_result_printer_ != listener) {
4944 // It is an error to pass this method a listener that is already in the
4945 // list.
4946 delete Release(default_result_printer_);
4947 default_result_printer_ = listener;
4948 if (listener != NULL) Append(listener);
4949 }
4950 }
4951
4952 // Sets the default_xml_generator attribute to the provided listener. The
4953 // listener is also added to the listener list and previous
4954 // default_xml_generator is removed from it and deleted. The listener can
4955 // also be NULL in which case it will not be added to the list. Does
4956 // nothing if the previous and the current listener objects are the same.
4957 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4958 if (default_xml_generator_ != listener) {
4959 // It is an error to pass this method a listener that is already in the
4960 // list.
4961 delete Release(default_xml_generator_);
4962 default_xml_generator_ = listener;
4963 if (listener != NULL) Append(listener);
4964 }
4965 }
4966
4967 // Controls whether events will be forwarded by the repeater to the
4968 // listeners in the list.
4969 bool TestEventListeners::EventForwardingEnabled() const {
4970 return repeater_->forwarding_enabled();
4971 }
4972
4973 void TestEventListeners::SuppressEventForwarding() {
4974 repeater_->set_forwarding_enabled(false);
4975 }
4976
4977 // class UnitTest
4978
4979 // Gets the singleton UnitTest object. The first time this method is
4980 // called, a UnitTest object is constructed and returned. Consecutive
4981 // calls will return the same object.
4982 //
4983 // We don't protect this under mutex_ as a user is not supposed to
4984 // call this before main() starts, from which point on the return
4985 // value will never change.
4986 UnitTest* UnitTest::GetInstance() {
4987 // When compiled with MSVC 7.1 in optimized mode, destroying the
4988 // UnitTest object upon exiting the program messes up the exit code,
4989 // causing successful tests to appear failed. We have to use a
4990 // different implementation in this case to bypass the compiler bug.
4991 // This implementation makes the compiler happy, at the cost of
4992 // leaking the UnitTest object.
4993
4994 // CodeGear C++Builder insists on a public destructor for the
4995 // default implementation. Use this implementation to keep good OO
4996 // design with private destructor.
4997
4998 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4999 static UnitTest* const instance = new UnitTest;
5000 return instance;
5001 #else
5002 static UnitTest instance;
5003 return &instance;
5004 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5005 }
5006
5007 // Gets the number of successful test cases.
5008 int UnitTest::successful_test_case_count() const {
5009 return impl()->successful_test_case_count();
5010 }
5011
5012 // Gets the number of failed test cases.
5013 int UnitTest::failed_test_case_count() const {
5014 return impl()->failed_test_case_count();
5015 }
5016
5017 // Gets the number of all test cases.
5018 int UnitTest::total_test_case_count() const {
5019 return impl()->total_test_case_count();
5020 }
5021
5022 // Gets the number of all test cases that contain at least one test
5023 // that should run.
5024 int UnitTest::test_case_to_run_count() const {
5025 return impl()->test_case_to_run_count();
5026 }
5027
5028 // Gets the number of successful tests.
5029 int UnitTest::successful_test_count() const {
5030 return impl()->successful_test_count();
5031 }
5032
5033 // Gets the number of failed tests.
5034 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5035
5036 // Gets the number of disabled tests that will be reported in the XML report.
5037 int UnitTest::reportable_disabled_test_count() const {
5038 return impl()->reportable_disabled_test_count();
5039 }
5040
5041 // Gets the number of disabled tests.
5042 int UnitTest::disabled_test_count() const {
5043 return impl()->disabled_test_count();
5044 }
5045
5046 // Gets the number of tests to be printed in the XML report.
5047 int UnitTest::reportable_test_count() const {
5048 return impl()->reportable_test_count();
5049 }
5050
5051 // Gets the number of all tests.
5052 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5053
5054 // Gets the number of tests that should run.
5055 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5056
5057 // Gets the time of the test program start, in ms from the start of the
5058 // UNIX epoch.
5059 internal::TimeInMillis UnitTest::start_timestamp() const {
5060 return impl()->start_timestamp();
5061 }
5062
5063 // Gets the elapsed time, in milliseconds.
5064 internal::TimeInMillis UnitTest::elapsed_time() const {
5065 return impl()->elapsed_time();
5066 }
5067
5068 // Returns true iff the unit test passed (i.e. all test cases passed).
5069 bool UnitTest::Passed() const { return impl()->Passed(); }
5070
5071 // Returns true iff the unit test failed (i.e. some test case failed
5072 // or something outside of all tests failed).
5073 bool UnitTest::Failed() const { return impl()->Failed(); }
5074
5075 // Gets the i-th test case among all the test cases. i can range from 0 to
5076 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5077 const TestCase* UnitTest::GetTestCase(int i) const {
5078 return impl()->GetTestCase(i);
5079 }
5080
5081 // Returns the TestResult containing information on test failures and
5082 // properties logged outside of individual test cases.
5083 const TestResult& UnitTest::ad_hoc_test_result() const {
5084 return *impl()->ad_hoc_test_result();
5085 }
5086
5087 // Gets the i-th test case among all the test cases. i can range from 0 to
5088 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5089 TestCase* UnitTest::GetMutableTestCase(int i) {
5090 return impl()->GetMutableTestCase(i);
5091 }
5092
5093 // Returns the list of event listeners that can be used to track events
5094 // inside Google Test.
5095 TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
5096
5097 // Registers and returns a global test environment. When a test
5098 // program is run, all global test environments will be set-up in the
5099 // order they were registered. After all tests in the program have
5100 // finished, all global test environments will be torn-down in the
5101 // *reverse* order they were registered.
5102 //
5103 // The UnitTest object takes ownership of the given environment.
5104 //
5105 // We don't protect this under mutex_, as we only support calling it
5106 // from the main thread.
5107 Environment* UnitTest::AddEnvironment(Environment* env) {
5108 if (env == NULL) {
5109 return NULL;
5110 }
5111
5112 impl_->environments().push_back(env);
5113 return env;
5114 }
5115
5116 // Adds a TestPartResult to the current TestResult object. All Google Test
5117 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5118 // this to report their results. The user code should use the
5119 // assertion macros instead of calling this directly.
5120 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5121 const char* file_name, int line_number,
5122 const std::string& message,
5123 const std::string& os_stack_trace)
5124 GTEST_LOCK_EXCLUDED_(mutex_) {
5125 Message msg;
5126 msg << message;
5127
5128 internal::MutexLock lock(&mutex_);
5129 if (impl_->gtest_trace_stack().size() > 0) {
5130 msg << "\n" << GTEST_NAME_ << " trace:";
5131
5132 for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0;
5133 --i) {
5134 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5135 msg << "\n"
5136 << internal::FormatFileLocation(trace.file, trace.line) << " "
5137 << trace.message;
5138 }
5139 }
5140
5141 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5142 msg << internal::kStackTraceMarker << os_stack_trace;
5143 }
5144
5145 const TestPartResult result = TestPartResult(
5146 result_type, file_name, line_number, msg.GetString().c_str());
5147 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5148 result);
5149
5150 if (result_type != TestPartResult::kSuccess) {
5151 // gtest_break_on_failure takes precedence over
5152 // gtest_throw_on_failure. This allows a user to set the latter
5153 // in the code (perhaps in order to use Google Test assertions
5154 // with another testing framework) and specify the former on the
5155 // command line for debugging.
5156 if (GTEST_FLAG(break_on_failure)) {
5157 #if GTEST_OS_WINDOWS
5158 // Using DebugBreak on Windows allows gtest to still break into a debugger
5159 // when a failure happens and both the --gtest_break_on_failure and
5160 // the --gtest_catch_exceptions flags are specified.
5161 DebugBreak();
5162 #else
5163 // Dereference NULL through a volatile pointer to prevent the compiler
5164 // from removing. We use this rather than abort() or __builtin_trap() for
5165 // portability: Symbian doesn't implement abort() well, and some debuggers
5166 // don't correctly trap abort().
5167 *static_cast<volatile int*>(NULL) = 1;
5168 #endif // GTEST_OS_WINDOWS
5169 } else if (GTEST_FLAG(throw_on_failure)) {
5170 #if GTEST_HAS_EXCEPTIONS
5171 throw internal::GoogleTestFailureException(result);
5172 #else
5173 // We cannot call abort() as it generates a pop-up in debug mode
5174 // that cannot be suppressed in VC 7.1 or below.
5175 exit(1);
5176 #endif
5177 }
5178 }
5179 }
5180
5181 // Adds a TestProperty to the current TestResult object when invoked from
5182 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5183 // from SetUpTestCase or TearDownTestCase, or to the global property set
5184 // when invoked elsewhere. If the result already contains a property with
5185 // the same key, the value will be updated.
5186 void UnitTest::RecordProperty(const std::string& key,
5187 const std::string& value) {
5188 impl_->RecordProperty(TestProperty(key, value));
5189 }
5190
5191 // Runs all tests in this UnitTest object and prints the result.
5192 // Returns 0 if successful, or 1 otherwise.
5193 //
5194 // We don't protect this under mutex_, as we only support calling it
5195 // from the main thread.
5196 int UnitTest::Run() {
5197 const bool in_death_test_child_process =
5198 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5199
5200 // Google Test implements this protocol for catching that a test
5201 // program exits before returning control to Google Test:
5202 //
5203 // 1. Upon start, Google Test creates a file whose absolute path
5204 // is specified by the environment variable
5205 // TEST_PREMATURE_EXIT_FILE.
5206 // 2. When Google Test has finished its work, it deletes the file.
5207 //
5208 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5209 // running a Google-Test-based test program and check the existence
5210 // of the file at the end of the test execution to see if it has
5211 // exited prematurely.
5212
5213 // If we are in the child process of a death test, don't
5214 // create/delete the premature exit file, as doing so is unnecessary
5215 // and will confuse the parent process. Otherwise, create/delete
5216 // the file upon entering/leaving this function. If the program
5217 // somehow exits before this function has a chance to return, the
5218 // premature-exit file will be left undeleted, causing a test runner
5219 // that understands the premature-exit-file protocol to report the
5220 // test as having failed.
5221 const internal::ScopedPrematureExitFile premature_exit_file(
5222 in_death_test_child_process
5223 ? NULL
5224 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5225
5226 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5227 // used for the duration of the program.
5228 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5229
5230 #if GTEST_HAS_SEH
5231 // Either the user wants Google Test to catch exceptions thrown by the
5232 // tests or this is executing in the context of death test child
5233 // process. In either case the user does not want to see pop-up dialogs
5234 // about crashes - they are expected.
5235 if (impl()->catch_exceptions() || in_death_test_child_process) {
5236 # if !GTEST_OS_WINDOWS_MOBILE
5237 // SetErrorMode doesn't exist on CE.
5238 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5239 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5240 # endif // !GTEST_OS_WINDOWS_MOBILE
5241
5242 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5243 // Death test children can be terminated with _abort(). On Windows,
5244 // _abort() can show a dialog with a warning message. This forces the
5245 // abort message to go to stderr instead.
5246 _set_error_mode(_OUT_TO_STDERR);
5247 # endif
5248
5249 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5250 // In the debug version, Visual Studio pops up a separate dialog
5251 // offering a choice to debug the aborted program. We need to suppress
5252 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5253 // executed. Google Test will notify the user of any unexpected
5254 // failure via stderr.
5255 //
5256 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5257 // Users of prior VC versions shall suffer the agony and pain of
5258 // clicking through the countless debug dialogs.
5259 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5260 // debug mode when compiled with VC 7.1 or lower.
5261 if (!GTEST_FLAG(break_on_failure))
5262 _set_abort_behavior(
5263 0x0, // Clear the following flags:
5264 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5265 # endif
5266 }
5267 #endif // GTEST_HAS_SEH
5268
5269 return internal::HandleExceptionsInMethodIfSupported(
5270 impl(), &internal::UnitTestImpl::RunAllTests,
5271 "auxiliary test code (environments or event listeners)")
5272 ? 0
5273 : 1;
5274 }
5275
5276 // Returns the working directory when the first TEST() or TEST_F() was
5277 // executed.
5278 const char* UnitTest::original_working_dir() const {
5279 return impl_->original_working_dir_.c_str();
5280 }
5281
5282 // Returns the TestCase object for the test that's currently running,
5283 // or NULL if no test is running.
5284 const TestCase* UnitTest::current_test_case() const
5285 GTEST_LOCK_EXCLUDED_(mutex_) {
5286 internal::MutexLock lock(&mutex_);
5287 return impl_->current_test_case();
5288 }
5289
5290 // Returns the TestInfo object for the test that's currently running,
5291 // or NULL if no test is running.
5292 const TestInfo* UnitTest::current_test_info() const
5293 GTEST_LOCK_EXCLUDED_(mutex_) {
5294 internal::MutexLock lock(&mutex_);
5295 return impl_->current_test_info();
5296 }
5297
5298 // Returns the random seed used at the start of the current test run.
5299 int UnitTest::random_seed() const { return impl_->random_seed(); }
5300
5301 #if GTEST_HAS_PARAM_TEST
5302 // Returns ParameterizedTestCaseRegistry object used to keep track of
5303 // value-parameterized tests and instantiate and register them.
5304 internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry()
5305 GTEST_LOCK_EXCLUDED_(mutex_) {
5306 return impl_->parameterized_test_registry();
5307 }
5308 #endif // GTEST_HAS_PARAM_TEST
5309
5310 // Creates an empty UnitTest.
5311 UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
5312
5313 // Destructor of UnitTest.
5314 UnitTest::~UnitTest() { delete impl_; }
5315
5316 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5317 // Google Test trace stack.
5318 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5319 GTEST_LOCK_EXCLUDED_(mutex_) {
5320 internal::MutexLock lock(&mutex_);
5321 impl_->gtest_trace_stack().push_back(trace);
5322 }
5323
5324 // Pops a trace from the per-thread Google Test trace stack.
5325 void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5326 internal::MutexLock lock(&mutex_);
5327 impl_->gtest_trace_stack().pop_back();
5328 }
5329
5330 namespace internal {
5331
5332 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5333 : parent_(parent),
5334 #ifdef _MSC_VER
5335 # pragma warning(push) // Saves the current warning state.
5336 # pragma warning(disable : 4355) // Temporarily disables warning 4355
5337 // (using this in initializer).
5338 default_global_test_part_result_reporter_(this),
5339 default_per_thread_test_part_result_reporter_(this),
5340 # pragma warning(pop) // Restores the warning state again.
5341 #else
5342 default_global_test_part_result_reporter_(this),
5343 default_per_thread_test_part_result_reporter_(this),
5344 #endif // _MSC_VER
5345 global_test_part_result_repoter_(
5346 &default_global_test_part_result_reporter_),
5347 per_thread_test_part_result_reporter_(
5348 &default_per_thread_test_part_result_reporter_),
5349 #if GTEST_HAS_PARAM_TEST
5350 parameterized_test_registry_(),
5351 parameterized_tests_registered_(false),
5352 #endif // GTEST_HAS_PARAM_TEST
5353 last_death_test_case_(-1),
5354 current_test_case_(NULL),
5355 current_test_info_(NULL),
5356 ad_hoc_test_result_(),
5357 os_stack_trace_getter_(NULL),
5358 post_flag_parse_init_performed_(false),
5359 random_seed_(0), // Will be overridden by the flag before first use.
5360 random_(0), // Will be reseeded before first use.
5361 start_timestamp_(0),
5362 elapsed_time_(0),
5363 #if GTEST_HAS_DEATH_TEST
5364 death_test_factory_(new DefaultDeathTestFactory),
5365 #endif
5366 // Will be overridden by the flag before first use.
5367 catch_exceptions_(false) {
5368 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5369 }
5370
5371 UnitTestImpl::~UnitTestImpl() {
5372 // Deletes every TestCase.
5373 ForEach(test_cases_, internal::Delete<TestCase>);
5374
5375 // Deletes every Environment.
5376 ForEach(environments_, internal::Delete<Environment>);
5377
5378 delete os_stack_trace_getter_;
5379 }
5380
5381 // Adds a TestProperty to the current TestResult object when invoked in a
5382 // context of a test, to current test case's ad_hoc_test_result when invoke
5383 // from SetUpTestCase/TearDownTestCase, or to the global property set
5384 // otherwise. If the result already contains a property with the same key,
5385 // the value will be updated.
5386 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5387 std::string xml_element;
5388 TestResult* test_result; // TestResult appropriate for property recording.
5389
5390 if (current_test_info_ != NULL) {
5391 xml_element = "testcase";
5392 test_result = &(current_test_info_->result_);
5393 } else if (current_test_case_ != NULL) {
5394 xml_element = "testsuite";
5395 test_result = &(current_test_case_->ad_hoc_test_result_);
5396 } else {
5397 xml_element = "testsuites";
5398 test_result = &ad_hoc_test_result_;
5399 }
5400 test_result->RecordProperty(xml_element, test_property);
5401 }
5402
5403 #if GTEST_HAS_DEATH_TEST
5404 // Disables event forwarding if the control is currently in a death test
5405 // subprocess. Must not be called before InitGoogleTest.
5406 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5407 if (internal_run_death_test_flag_.get() != NULL)
5408 listeners()->SuppressEventForwarding();
5409 }
5410 #endif // GTEST_HAS_DEATH_TEST
5411
5412 // Initializes event listeners performing XML output as specified by
5413 // UnitTestOptions. Must not be called before InitGoogleTest.
5414 void UnitTestImpl::ConfigureXmlOutput() {
5415 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5416 if (output_format == "xml") {
5417 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5418 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5419 } else if (output_format != "") {
5420 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5421 output_format.c_str());
5422 fflush(stdout);
5423 }
5424 }
5425
5426 #if GTEST_CAN_STREAM_RESULTS_
5427 // Initializes event listeners for streaming test results in string form.
5428 // Must not be called before InitGoogleTest.
5429 void UnitTestImpl::ConfigureStreamingOutput() {
5430 const std::string& target = GTEST_FLAG(stream_result_to);
5431 if (!target.empty()) {
5432 const size_t pos = target.find(':');
5433 if (pos != std::string::npos) {
5434 listeners()->Append(
5435 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5436 } else {
5437 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5438 target.c_str());
5439 fflush(stdout);
5440 }
5441 }
5442 }
5443 #endif // GTEST_CAN_STREAM_RESULTS_
5444
5445 // Performs initialization dependent upon flag values obtained in
5446 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5447 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5448 // this function is also called from RunAllTests. Since this function can be
5449 // called more than once, it has to be idempotent.
5450 void UnitTestImpl::PostFlagParsingInit() {
5451 // Ensures that this function does not execute more than once.
5452 if (!post_flag_parse_init_performed_) {
5453 post_flag_parse_init_performed_ = true;
5454
5455 #if GTEST_HAS_DEATH_TEST
5456 InitDeathTestSubprocessControlInfo();
5457 SuppressTestEventsIfInSubprocess();
5458 #endif // GTEST_HAS_DEATH_TEST
5459
5460 // Registers parameterized tests. This makes parameterized tests
5461 // available to the UnitTest reflection API without running
5462 // RUN_ALL_TESTS.
5463 RegisterParameterizedTests();
5464
5465 // Configures listeners for XML output. This makes it possible for users
5466 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5467 ConfigureXmlOutput();
5468
5469 #if GTEST_CAN_STREAM_RESULTS_
5470 // Configures listeners for streaming test results to the specified server.
5471 ConfigureStreamingOutput();
5472 #endif // GTEST_CAN_STREAM_RESULTS_
5473 }
5474 }
5475
5476 // A predicate that checks the name of a TestCase against a known
5477 // value.
5478 //
5479 // This is used for implementation of the UnitTest class only. We put
5480 // it in the anonymous namespace to prevent polluting the outer
5481 // namespace.
5482 //
5483 // TestCaseNameIs is copyable.
5484 class TestCaseNameIs {
5485 public:
5486 // Constructor.
5487 explicit TestCaseNameIs(const std::string& name) : name_(name) {}
5488
5489 // Returns true iff the name of test_case matches name_.
5490 bool operator()(const TestCase* test_case) const {
5491 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5492 }
5493
5494 private:
5495 std::string name_;
5496 };
5497
5498 // Finds and returns a TestCase with the given name. If one doesn't
5499 // exist, creates one and returns it. It's the CALLER'S
5500 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5501 // TESTS ARE NOT SHUFFLED.
5502 //
5503 // Arguments:
5504 //
5505 // test_case_name: name of the test case
5506 // type_param: the name of the test case's type parameter, or NULL if
5507 // this is not a typed or a type-parameterized test case.
5508 // set_up_tc: pointer to the function that sets up the test case
5509 // tear_down_tc: pointer to the function that tears down the test case
5510 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5511 const char* type_param,
5512 Test::SetUpTestCaseFunc set_up_tc,
5513 Test::TearDownTestCaseFunc tear_down_tc) {
5514 // Can we find a TestCase with the given name?
5515 const std::vector<TestCase*>::const_iterator test_case = std::find_if(
5516 test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name));
5517
5518 if (test_case != test_cases_.end()) return *test_case;
5519
5520 // No. Let's create one.
5521 TestCase* const new_test_case =
5522 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5523
5524 // Is this a death test case?
5525 if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5526 kDeathTestCaseFilter)) {
5527 // Yes. Inserts the test case after the last death test case
5528 // defined so far. This only works when the test cases haven't
5529 // been shuffled. Otherwise we may end up running a death test
5530 // after a non-death test.
5531 ++last_death_test_case_;
5532 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5533 new_test_case);
5534 } else {
5535 // No. Appends to the end of the list.
5536 test_cases_.push_back(new_test_case);
5537 }
5538
5539 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5540 return new_test_case;
5541 }
5542
5543 // Helpers for setting up / tearing down the given environment. They
5544 // are for use in the ForEach() function.
5545 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5546 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5547
5548 // Runs all tests in this UnitTest object, prints the result, and
5549 // returns true if all tests are successful. If any exception is
5550 // thrown during a test, the test is considered to be failed, but the
5551 // rest of the tests will still be run.
5552 //
5553 // When parameterized tests are enabled, it expands and registers
5554 // parameterized tests first in RegisterParameterizedTests().
5555 // All other functions called from RunAllTests() may safely assume that
5556 // parameterized tests are ready to be counted and run.
5557 bool UnitTestImpl::RunAllTests() {
5558 // Makes sure InitGoogleTest() was called.
5559 if (!GTestIsInitialized()) {
5560 printf("%s",
5561 "\nThis test program did NOT call ::testing::InitGoogleTest "
5562 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5563 return false;
5564 }
5565
5566 // Do not run any test if the --help flag was specified.
5567 if (g_help_flag) return true;
5568
5569 // Repeats the call to the post-flag parsing initialization in case the
5570 // user didn't call InitGoogleTest.
5571 PostFlagParsingInit();
5572
5573 // Even if sharding is not on, test runners may want to use the
5574 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5575 // protocol.
5576 internal::WriteToShardStatusFileIfNeeded();
5577
5578 // True iff we are in a subprocess for running a thread-safe-style
5579 // death test.
5580 bool in_subprocess_for_death_test = false;
5581
5582 #if GTEST_HAS_DEATH_TEST
5583 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5584 #endif // GTEST_HAS_DEATH_TEST
5585
5586 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5587 in_subprocess_for_death_test);
5588
5589 // Compares the full test names with the filter to decide which
5590 // tests to run.
5591 const bool has_tests_to_run =
5592 FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
5593 : IGNORE_SHARDING_PROTOCOL) > 0;
5594
5595 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5596 if (GTEST_FLAG(list_tests)) {
5597 // This must be called *after* FilterTests() has been called.
5598 ListTestsMatchingFilter();
5599 return true;
5600 }
5601
5602 random_seed_ =
5603 GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5604
5605 // True iff at least one test has failed.
5606 bool failed = false;
5607
5608 TestEventListener* repeater = listeners()->repeater();
5609
5610 start_timestamp_ = GetTimeInMillis();
5611 repeater->OnTestProgramStart(*parent_);
5612
5613 // How many times to repeat the tests? We don't want to repeat them
5614 // when we are inside the subprocess of a death test.
5615 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5616 // Repeats forever if the repeat count is negative.
5617 const bool forever = repeat < 0;
5618 for (int i = 0; forever || i != repeat; i++) {
5619 // We want to preserve failures generated by ad-hoc test
5620 // assertions executed before RUN_ALL_TESTS().
5621 ClearNonAdHocTestResult();
5622
5623 const TimeInMillis start = GetTimeInMillis();
5624
5625 // Shuffles test cases and tests if requested.
5626 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5627 random()->Reseed(random_seed_);
5628 // This should be done before calling OnTestIterationStart(),
5629 // such that a test event listener can see the actual test order
5630 // in the event.
5631 ShuffleTests();
5632 }
5633
5634 // Tells the unit test event listeners that the tests are about to start.
5635 repeater->OnTestIterationStart(*parent_, i);
5636
5637 // Runs each test case if there is at least one test to run.
5638 if (has_tests_to_run) {
5639 // Sets up all environments beforehand.
5640 repeater->OnEnvironmentsSetUpStart(*parent_);
5641 ForEach(environments_, SetUpEnvironment);
5642 repeater->OnEnvironmentsSetUpEnd(*parent_);
5643
5644 // Runs the tests only if there was no fatal failure during global
5645 // set-up.
5646 if (!Test::HasFatalFailure()) {
5647 for (int test_index = 0; test_index < total_test_case_count();
5648 test_index++) {
5649 GetMutableTestCase(test_index)->Run();
5650 }
5651 }
5652
5653 // Tears down all environments in reverse order afterwards.
5654 repeater->OnEnvironmentsTearDownStart(*parent_);
5655 std::for_each(environments_.rbegin(), environments_.rend(),
5656 TearDownEnvironment);
5657 repeater->OnEnvironmentsTearDownEnd(*parent_);
5658 }
5659
5660 elapsed_time_ = GetTimeInMillis() - start;
5661
5662 // Tells the unit test event listener that the tests have just finished.
5663 repeater->OnTestIterationEnd(*parent_, i);
5664
5665 // Gets the result and clears it.
5666 if (!Passed()) {
5667 failed = true;
5668 }
5669
5670 // Restores the original test order after the iteration. This
5671 // allows the user to quickly repro a failure that happens in the
5672 // N-th iteration without repeating the first (N - 1) iterations.
5673 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5674 // case the user somehow changes the value of the flag somewhere
5675 // (it's always safe to unshuffle the tests).
5676 UnshuffleTests();
5677
5678 if (GTEST_FLAG(shuffle)) {
5679 // Picks a new random seed for each iteration.
5680 random_seed_ = GetNextRandomSeed(random_seed_);
5681 }
5682 }
5683
5684 repeater->OnTestProgramEnd(*parent_);
5685
5686 return !failed;
5687 }
5688
5689 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5690 // if the variable is present. If a file already exists at this location, this
5691 // function will write over it. If the variable is present, but the file cannot
5692 // be created, prints an error and exits.
5693 void WriteToShardStatusFileIfNeeded() {
5694 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5695 if (test_shard_file != NULL) {
5696 FILE* const file = posix::FOpen(test_shard_file, "w");
5697 if (file == NULL) {
5698 ColoredPrintf(COLOR_RED,
5699 "Could not write to the test shard status file \"%s\" "
5700 "specified by the %s environment variable.\n",
5701 test_shard_file, kTestShardStatusFile);
5702 fflush(stdout);
5703 exit(EXIT_FAILURE);
5704 }
5705 fclose(file);
5706 }
5707 }
5708
5709 // Checks whether sharding is enabled by examining the relevant
5710 // environment variable values. If the variables are present,
5711 // but inconsistent (i.e., shard_index >= total_shards), prints
5712 // an error and exits. If in_subprocess_for_death_test, sharding is
5713 // disabled because it must only be applied to the original test
5714 // process. Otherwise, we could filter out death tests we intended to execute.
5715 bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
5716 bool in_subprocess_for_death_test) {
5717 if (in_subprocess_for_death_test) {
5718 return false;
5719 }
5720
5721 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5722 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5723
5724 if (total_shards == -1 && shard_index == -1) {
5725 return false;
5726 } else if (total_shards == -1 && shard_index != -1) {
5727 const Message msg = Message() << "Invalid environment variables: you have "
5728 << kTestShardIndex << " = " << shard_index
5729 << ", but have left " << kTestTotalShards
5730 << " unset.\n";
5731 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5732 fflush(stdout);
5733 exit(EXIT_FAILURE);
5734 } else if (total_shards != -1 && shard_index == -1) {
5735 const Message msg = Message()
5736 << "Invalid environment variables: you have "
5737 << kTestTotalShards << " = " << total_shards
5738 << ", but have left " << kTestShardIndex << " unset.\n";
5739 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5740 fflush(stdout);
5741 exit(EXIT_FAILURE);
5742 } else if (shard_index < 0 || shard_index >= total_shards) {
5743 const Message msg =
5744 Message() << "Invalid environment variables: we require 0 <= "
5745 << kTestShardIndex << " < " << kTestTotalShards
5746 << ", but you have " << kTestShardIndex << "=" << shard_index
5747 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5748 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5749 fflush(stdout);
5750 exit(EXIT_FAILURE);
5751 }
5752
5753 return total_shards > 1;
5754 }
5755
5756 // Parses the environment variable var as an Int32. If it is unset,
5757 // returns default_val. If it is not an Int32, prints an error
5758 // and aborts.
5759 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5760 const char* str_val = posix::GetEnv(var);
5761 if (str_val == NULL) {
5762 return default_val;
5763 }
5764
5765 Int32 result;
5766 if (!ParseInt32(Message() << "The value of environment variable " << var,
5767 str_val, &result)) {
5768 exit(EXIT_FAILURE);
5769 }
5770 return result;
5771 }
5772
5773 // Given the total number of shards, the shard index, and the test id,
5774 // returns true iff the test should be run on this shard. The test id is
5775 // some arbitrary but unique non-negative integer assigned to each test
5776 // method. Assumes that 0 <= shard_index < total_shards.
5777 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5778 return (test_id % total_shards) == shard_index;
5779 }
5780
5781 // Compares the name of each test with the user-specified filter to
5782 // decide whether the test should be run, then records the result in
5783 // each TestCase and TestInfo object.
5784 // If shard_tests == true, further filters tests based on sharding
5785 // variables in the environment - see
5786 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5787 // Returns the number of tests that should run.
5788 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5789 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
5790 ? Int32FromEnvOrDie(kTestTotalShards, -1)
5791 : -1;
5792 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
5793 ? Int32FromEnvOrDie(kTestShardIndex, -1)
5794 : -1;
5795
5796 // num_runnable_tests are the number of tests that will
5797 // run across all shards (i.e., match filter and are not disabled).
5798 // num_selected_tests are the number of tests to be run on
5799 // this shard.
5800 int num_runnable_tests = 0;
5801 int num_selected_tests = 0;
5802 for (size_t i = 0; i < test_cases_.size(); i++) {
5803 TestCase* const test_case = test_cases_[i];
5804 const std::string& test_case_name = test_case->name();
5805 test_case->set_should_run(false);
5806
5807 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5808 TestInfo* const test_info = test_case->test_info_list()[j];
5809 const std::string test_name(test_info->name());
5810 // A test is disabled if test case name or test name matches
5811 // kDisableTestFilter.
5812 const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
5813 test_case_name, kDisableTestFilter) ||
5814 internal::UnitTestOptions::MatchesFilter(
5815 test_name, kDisableTestFilter);
5816 test_info->is_disabled_ = is_disabled;
5817
5818 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
5819 test_case_name, test_name);
5820 test_info->matches_filter_ = matches_filter;
5821
5822 const bool is_runnable =
5823 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5824 matches_filter;
5825
5826 const bool is_selected =
5827 is_runnable &&
5828 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5829 ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests));
5830
5831 num_runnable_tests += is_runnable;
5832 num_selected_tests += is_selected;
5833
5834 test_info->should_run_ = is_selected;
5835 test_case->set_should_run(test_case->should_run() || is_selected);
5836 }
5837 }
5838 return num_selected_tests;
5839 }
5840
5841 // Prints the given C-string on a single line by replacing all '\n'
5842 // characters with string "\\n". If the output takes more than
5843 // max_length characters, only prints the first max_length characters
5844 // and "...".
5845 static void PrintOnOneLine(const char* str, int max_length) {
5846 if (str != NULL) {
5847 for (int i = 0; *str != '\0'; ++str) {
5848 if (i >= max_length) {
5849 printf("...");
5850 break;
5851 }
5852 if (*str == '\n') {
5853 printf("\\n");
5854 i += 2;
5855 } else {
5856 printf("%c", *str);
5857 ++i;
5858 }
5859 }
5860 }
5861 }
5862
5863 // Prints the names of the tests matching the user-specified filter flag.
5864 void UnitTestImpl::ListTestsMatchingFilter() {
5865 // Print at most this many characters for each type/value parameter.
5866 const int kMaxParamLength = 250;
5867
5868 for (size_t i = 0; i < test_cases_.size(); i++) {
5869 const TestCase* const test_case = test_cases_[i];
5870 bool printed_test_case_name = false;
5871
5872 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5873 const TestInfo* const test_info = test_case->test_info_list()[j];
5874 if (test_info->matches_filter_) {
5875 if (!printed_test_case_name) {
5876 printed_test_case_name = true;
5877 printf("%s.", test_case->name());
5878 if (test_case->type_param() != NULL) {
5879 printf(" # %s = ", kTypeParamLabel);
5880 // We print the type parameter on a single line to make
5881 // the output easy to parse by a program.
5882 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
5883 }
5884 printf("\n");
5885 }
5886 printf(" %s", test_info->name());
5887 if (test_info->value_param() != NULL) {
5888 printf(" # %s = ", kValueParamLabel);
5889 // We print the value parameter on a single line to make the
5890 // output easy to parse by a program.
5891 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
5892 }
5893 printf("\n");
5894 }
5895 }
5896 }
5897 fflush(stdout);
5898 }
5899
5900 // Sets the OS stack trace getter.
5901 //
5902 // Does nothing if the input and the current OS stack trace getter are
5903 // the same; otherwise, deletes the old getter and makes the input the
5904 // current getter.
5905 void UnitTestImpl::set_os_stack_trace_getter(
5906 OsStackTraceGetterInterface* getter) {
5907 if (os_stack_trace_getter_ != getter) {
5908 delete os_stack_trace_getter_;
5909 os_stack_trace_getter_ = getter;
5910 }
5911 }
5912
5913 // Returns the current OS stack trace getter if it is not NULL;
5914 // otherwise, creates an OsStackTraceGetter, makes it the current
5915 // getter, and returns it.
5916 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5917 if (os_stack_trace_getter_ == NULL) {
5918 os_stack_trace_getter_ = new OsStackTraceGetter;
5919 }
5920
5921 return os_stack_trace_getter_;
5922 }
5923
5924 // Returns the TestResult for the test that's currently running, or
5925 // the TestResult for the ad hoc test if no test is running.
5926 TestResult* UnitTestImpl::current_test_result() {
5927 return current_test_info_ ? &(current_test_info_->result_)
5928 : &ad_hoc_test_result_;
5929 }
5930
5931 // Shuffles all test cases, and the tests within each test case,
5932 // making sure that death tests are still run first.
5933 void UnitTestImpl::ShuffleTests() {
5934 // Shuffles the death test cases.
5935 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5936
5937 // Shuffles the non-death test cases.
5938 ShuffleRange(random(), last_death_test_case_ + 1,
5939 static_cast<int>(test_cases_.size()), &test_case_indices_);
5940
5941 // Shuffles the tests inside each test case.
5942 for (size_t i = 0; i < test_cases_.size(); i++) {
5943 test_cases_[i]->ShuffleTests(random());
5944 }
5945 }
5946
5947 // Restores the test cases and tests to their order before the first shuffle.
5948 void UnitTestImpl::UnshuffleTests() {
5949 for (size_t i = 0; i < test_cases_.size(); i++) {
5950 // Unshuffles the tests in each test case.
5951 test_cases_[i]->UnshuffleTests();
5952 // Resets the index of each test case.
5953 test_case_indices_[i] = static_cast<int>(i);
5954 }
5955 }
5956
5957 // Returns the current OS stack trace as an std::string.
5958 //
5959 // The maximum number of stack frames to be included is specified by
5960 // the gtest_stack_trace_depth flag. The skip_count parameter
5961 // specifies the number of top frames to be skipped, which doesn't
5962 // count against the number of frames to be included.
5963 //
5964 // For example, if Foo() calls Bar(), which in turn calls
5965 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5966 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5967 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5968 int skip_count) {
5969 // We pass skip_count + 1 to skip this wrapper function in addition
5970 // to what the user really wants to skip.
5971 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5972 }
5973
5974 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5975 // suppress unreachable code warnings.
5976 namespace {
5977 class ClassUniqueToAlwaysTrue {};
5978 } // namespace
5979
5980 bool IsTrue(bool condition) { return condition; }
5981
5982 bool AlwaysTrue() {
5983 #if GTEST_HAS_EXCEPTIONS
5984 // This condition is always false so AlwaysTrue() never actually throws,
5985 // but it makes the compiler think that it may throw.
5986 if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
5987 #endif // GTEST_HAS_EXCEPTIONS
5988 return true;
5989 }
5990
5991 // If *pstr starts with the given prefix, modifies *pstr to be right
5992 // past the prefix and returns true; otherwise leaves *pstr unchanged
5993 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5994 bool SkipPrefix(const char* prefix, const char** pstr) {
5995 const size_t prefix_len = strlen(prefix);
5996 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5997 *pstr += prefix_len;
5998 return true;
5999 }
6000 return false;
6001 }
6002
6003 // Parses a string as a command line flag. The string should have
6004 // the format "--flag=value". When def_optional is true, the "=value"
6005 // part can be omitted.
6006 //
6007 // Returns the value of the flag, or NULL if the parsing failed.
6008 const char* ParseFlagValue(const char* str, const char* flag,
6009 bool def_optional) {
6010 // str and flag must not be NULL.
6011 if (str == NULL || flag == NULL) return NULL;
6012
6013 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6014 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6015 const size_t flag_len = flag_str.length();
6016 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6017
6018 // Skips the flag name.
6019 const char* flag_end = str + flag_len;
6020
6021 // When def_optional is true, it's OK to not have a "=value" part.
6022 if (def_optional && (flag_end[0] == '\0')) {
6023 return flag_end;
6024 }
6025
6026 // If def_optional is true and there are more characters after the
6027 // flag name, or if def_optional is false, there must be a '=' after
6028 // the flag name.
6029 if (flag_end[0] != '=') return NULL;
6030
6031 // Returns the string after "=".
6032 return flag_end + 1;
6033 }
6034
6035 // Parses a string for a bool flag, in the form of either
6036 // "--flag=value" or "--flag".
6037 //
6038 // In the former case, the value is taken as true as long as it does
6039 // not start with '0', 'f', or 'F'.
6040 //
6041 // In the latter case, the value is taken as true.
6042 //
6043 // On success, stores the value of the flag in *value, and returns
6044 // true. On failure, returns false without changing *value.
6045 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6046 // Gets the value of the flag as a string.
6047 const char* const value_str = ParseFlagValue(str, flag, true);
6048
6049 // Aborts if the parsing failed.
6050 if (value_str == NULL) return false;
6051
6052 // Converts the string value to a bool.
6053 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6054 return true;
6055 }
6056
6057 // Parses a string for an Int32 flag, in the form of
6058 // "--flag=value".
6059 //
6060 // On success, stores the value of the flag in *value, and returns
6061 // true. On failure, returns false without changing *value.
6062 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6063 // Gets the value of the flag as a string.
6064 const char* const value_str = ParseFlagValue(str, flag, false);
6065
6066 // Aborts if the parsing failed.
6067 if (value_str == NULL) return false;
6068
6069 // Sets *value to the value of the flag.
6070 return ParseInt32(Message() << "The value of flag --" << flag, value_str,
6071 value);
6072 }
6073
6074 // Parses a string for a string flag, in the form of
6075 // "--flag=value".
6076 //
6077 // On success, stores the value of the flag in *value, and returns
6078 // true. On failure, returns false without changing *value.
6079 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6080 // Gets the value of the flag as a string.
6081 const char* const value_str = ParseFlagValue(str, flag, false);
6082
6083 // Aborts if the parsing failed.
6084 if (value_str == NULL) return false;
6085
6086 // Sets *value to the value of the flag.
6087 *value = value_str;
6088 return true;
6089 }
6090
6091 // Determines whether a string has a prefix that Google Test uses for its
6092 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6093 // If Google Test detects that a command line flag has its prefix but is not
6094 // recognized, it will print its help message. Flags starting with
6095 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6096 // internal flags and do not trigger the help message.
6097 static bool HasGoogleTestFlagPrefix(const char* str) {
6098 return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
6099 SkipPrefix("/", &str)) &&
6100 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6101 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6102 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6103 }
6104
6105 // Prints a string containing code-encoded text. The following escape
6106 // sequences can be used in the string to control the text color:
6107 //
6108 // @@ prints a single '@' character.
6109 // @R changes the color to red.
6110 // @G changes the color to green.
6111 // @Y changes the color to yellow.
6112 // @D changes to the default terminal text color.
6113 //
6114 // TODO(wan@google.com): Write tests for this once we add stdout
6115 // capturing to Google Test.
6116 static void PrintColorEncoded(const char* str) {
6117 GTestColor color = COLOR_DEFAULT; // The current color.
6118
6119 // Conceptually, we split the string into segments divided by escape
6120 // sequences. Then we print one segment at a time. At the end of
6121 // each iteration, the str pointer advances to the beginning of the
6122 // next segment.
6123 for (;;) {
6124 const char* p = strchr(str, '@');
6125 if (p == NULL) {
6126 ColoredPrintf(color, "%s", str);
6127 return;
6128 }
6129
6130 ColoredPrintf(color, "%s", std::string(str, p).c_str());
6131
6132 const char ch = p[1];
6133 str = p + 2;
6134 if (ch == '@') {
6135 ColoredPrintf(color, "@");
6136 } else if (ch == 'D') {
6137 color = COLOR_DEFAULT;
6138 } else if (ch == 'R') {
6139 color = COLOR_RED;
6140 } else if (ch == 'G') {
6141 color = COLOR_GREEN;
6142 } else if (ch == 'Y') {
6143 color = COLOR_YELLOW;
6144 } else {
6145 --str;
6146 }
6147 }
6148 }
6149
6150 static const char kColorEncodedHelpMessage[] =
6151 "This program contains tests written using " GTEST_NAME_
6152 ". You can use the\n"
6153 "following command line flags to control its behavior:\n"
6154 "\n"
6155 "Test Selection:\n"
6156 " @G--" GTEST_FLAG_PREFIX_
6157 "list_tests@D\n"
6158 " List the names of all tests instead of running them. The name of\n"
6159 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6160 " @G--" GTEST_FLAG_PREFIX_
6161 "filter=@YPOSTIVE_PATTERNS"
6162 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6163 " Run only the tests whose name matches one of the positive patterns "
6164 "but\n"
6165 " none of the negative patterns. '?' matches any single character; "
6166 "'*'\n"
6167 " matches any substring; ':' separates two patterns.\n"
6168 " @G--" GTEST_FLAG_PREFIX_
6169 "also_run_disabled_tests@D\n"
6170 " Run all disabled tests too.\n"
6171 "\n"
6172 "Test Execution:\n"
6173 " @G--" GTEST_FLAG_PREFIX_
6174 "repeat=@Y[COUNT]@D\n"
6175 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6176 " @G--" GTEST_FLAG_PREFIX_
6177 "shuffle@D\n"
6178 " Randomize tests' orders on every iteration.\n"
6179 " @G--" GTEST_FLAG_PREFIX_
6180 "random_seed=@Y[NUMBER]@D\n"
6181 " Random number seed to use for shuffling test orders (between 1 and\n"
6182 " 99999, or 0 to use a seed based on the current time).\n"
6183 "\n"
6184 "Test Output:\n"
6185 " @G--" GTEST_FLAG_PREFIX_
6186 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6187 " Enable/disable colored output. The default is @Gauto@D.\n"
6188 " -@G-" GTEST_FLAG_PREFIX_
6189 "print_time=0@D\n"
6190 " Don't print the elapsed time of each test.\n"
6191 " @G--" GTEST_FLAG_PREFIX_
6192 "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6193 "@Y|@G:@YFILE_PATH]@D\n"
6194 " Generate an XML report in the given directory or with the given "
6195 "file\n"
6196 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6197 #if GTEST_CAN_STREAM_RESULTS_
6198 " @G--" GTEST_FLAG_PREFIX_
6199 "stream_result_to=@YHOST@G:@YPORT@D\n"
6200 " Stream test results to the given server.\n"
6201 #endif // GTEST_CAN_STREAM_RESULTS_
6202 "\n"
6203 "Assertion Behavior:\n"
6204 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6205 " @G--" GTEST_FLAG_PREFIX_
6206 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6207 " Set the default death test style.\n"
6208 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6209 " @G--" GTEST_FLAG_PREFIX_
6210 "break_on_failure@D\n"
6211 " Turn assertion failures into debugger break-points.\n"
6212 " @G--" GTEST_FLAG_PREFIX_
6213 "throw_on_failure@D\n"
6214 " Turn assertion failures into C++ exceptions.\n"
6215 " @G--" GTEST_FLAG_PREFIX_
6216 "catch_exceptions=0@D\n"
6217 " Do not report exceptions as test failures. Instead, allow them\n"
6218 " to crash the program or throw a pop-up (on Windows).\n"
6219 "\n"
6220 "Except for @G--" GTEST_FLAG_PREFIX_
6221 "list_tests@D, you can alternatively set "
6222 "the corresponding\n"
6223 "environment variable of a flag (all letters in upper-case). For example, "
6224 "to\n"
6225 "disable colored text output, you can either specify "
6226 "@G--" GTEST_FLAG_PREFIX_
6227 "color=no@D or set\n"
6228 "the @G" GTEST_FLAG_PREFIX_UPPER_
6229 "COLOR@D environment variable to @Gno@D.\n"
6230 "\n"
6231 "For more information, please read the " GTEST_NAME_
6232 " documentation at\n"
6233 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
6234 "\n"
6235 "(not one in your own code or tests), please report it to\n"
6236 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6237
6238 // Parses the command line for Google Test flags, without initializing
6239 // other parts of Google Test. The type parameter CharType can be
6240 // instantiated to either char or wchar_t.
6241 template <typename CharType>
6242 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6243 for (int i = 1; i < *argc; i++) {
6244 const std::string arg_string = StreamableToString(argv[i]);
6245 const char* const arg = arg_string.c_str();
6246
6247 using internal::ParseBoolFlag;
6248 using internal::ParseInt32Flag;
6249 using internal::ParseStringFlag;
6250
6251 // Do we see a Google Test flag?
6252 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6253 &GTEST_FLAG(also_run_disabled_tests)) ||
6254 ParseBoolFlag(arg, kBreakOnFailureFlag,
6255 &GTEST_FLAG(break_on_failure)) ||
6256 ParseBoolFlag(arg, kCatchExceptionsFlag,
6257 &GTEST_FLAG(catch_exceptions)) ||
6258 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6259 ParseStringFlag(arg, kDeathTestStyleFlag,
6260 &GTEST_FLAG(death_test_style)) ||
6261 ParseBoolFlag(arg, kDeathTestUseFork,
6262 &GTEST_FLAG(death_test_use_fork)) ||
6263 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6264 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6265 &GTEST_FLAG(internal_run_death_test)) ||
6266 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6267 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6268 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6269 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6270 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6271 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6272 ParseInt32Flag(arg, kStackTraceDepthFlag,
6273 &GTEST_FLAG(stack_trace_depth)) ||
6274 ParseStringFlag(arg, kStreamResultToFlag,
6275 &GTEST_FLAG(stream_result_to)) ||
6276 ParseBoolFlag(arg, kThrowOnFailureFlag,
6277 &GTEST_FLAG(throw_on_failure))) {
6278 // Yes. Shift the remainder of the argv list left by one. Note
6279 // that argv has (*argc + 1) elements, the last one always being
6280 // NULL. The following loop moves the trailing NULL element as
6281 // well.
6282 for (int j = i; j != *argc; j++) {
6283 argv[j] = argv[j + 1];
6284 }
6285
6286 // Decrements the argument count.
6287 (*argc)--;
6288
6289 // We also need to decrement the iterator as we just removed
6290 // an element.
6291 i--;
6292 } else if (arg_string == "--help" || arg_string == "-h" ||
6293 arg_string == "-?" || arg_string == "/?" ||
6294 HasGoogleTestFlagPrefix(arg)) {
6295 // Both help flag and unrecognized Google Test flags (excluding
6296 // internal ones) trigger help display.
6297 g_help_flag = true;
6298 }
6299 }
6300
6301 if (g_help_flag) {
6302 // We print the help here instead of in RUN_ALL_TESTS(), as the
6303 // latter may not be called at all if the user is using Google
6304 // Test with another testing framework.
6305 PrintColorEncoded(kColorEncodedHelpMessage);
6306 }
6307 }
6308
6309 // Parses the command line for Google Test flags, without initializing
6310 // other parts of Google Test.
6311 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6312 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6313 }
6314 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6315 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6316 }
6317
6318 // The internal implementation of InitGoogleTest().
6319 //
6320 // The type parameter CharType can be instantiated to either char or
6321 // wchar_t.
6322 template <typename CharType>
6323 void InitGoogleTestImpl(int* argc, CharType** argv) {
6324 g_init_gtest_count++;
6325
6326 // We don't want to run the initialization code twice.
6327 if (g_init_gtest_count != 1) return;
6328
6329 if (*argc <= 0) return;
6330
6331 internal::g_executable_path = internal::StreamableToString(argv[0]);
6332
6333 #if GTEST_HAS_DEATH_TEST
6334
6335 g_argvs.clear();
6336 for (int i = 0; i != *argc; i++) {
6337 g_argvs.push_back(StreamableToString(argv[i]));
6338 }
6339
6340 #endif // GTEST_HAS_DEATH_TEST
6341
6342 ParseGoogleTestFlagsOnly(argc, argv);
6343 GetUnitTestImpl()->PostFlagParsingInit();
6344 }
6345
6346 } // namespace internal
6347
6348 // Initializes Google Test. This must be called before calling
6349 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6350 // flags that Google Test recognizes. Whenever a Google Test flag is
6351 // seen, it is removed from argv, and *argc is decremented.
6352 //
6353 // No value is returned. Instead, the Google Test flag variables are
6354 // updated.
6355 //
6356 // Calling the function for the second time has no user-visible effect.
6357 void InitGoogleTest(int* argc, char** argv) {
6358 internal::InitGoogleTestImpl(argc, argv);
6359 }
6360
6361 // This overloaded version can be used in Windows programs compiled in
6362 // UNICODE mode.
6363 void InitGoogleTest(int* argc, wchar_t** argv) {
6364 internal::InitGoogleTestImpl(argc, argv);
6365 }
6366
6367 } // namespace testing
6368 // Copyright 2005, Google Inc.
6369 // All rights reserved.
6370 //
6371 // Redistribution and use in source and binary forms, with or without
6372 // modification, are permitted provided that the following conditions are
6373 // met:
6374 //
6375 // * Redistributions of source code must retain the above copyright
6376 // notice, this list of conditions and the following disclaimer.
6377 // * Redistributions in binary form must reproduce the above
6378 // copyright notice, this list of conditions and the following disclaimer
6379 // in the documentation and/or other materials provided with the
6380 // distribution.
6381 // * Neither the name of Google Inc. nor the names of its
6382 // contributors may be used to endorse or promote products derived from
6383 // this software without specific prior written permission.
6384 //
6385 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6386 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6387 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6388 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6389 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6390 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6391 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6392 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6393 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6394 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6395 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6396 //
6397 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6398 //
6399 // This file implements death tests.
6400
6401 #if GTEST_HAS_DEATH_TEST
6402
6403 # if GTEST_OS_MAC
6404 # include <crt_externs.h>
6405 # endif // GTEST_OS_MAC
6406
6407 # include <errno.h>
6408 # include <fcntl.h>
6409 # include <limits.h>
6410
6411 # if GTEST_OS_LINUX
6412 # include <signal.h>
6413 # endif // GTEST_OS_LINUX
6414
6415 # include <stdarg.h>
6416
6417 # if GTEST_OS_WINDOWS
6418 # include <windows.h>
6419 # else
6420 # include <sys/mman.h>
6421 # include <sys/wait.h>
6422 # endif // GTEST_OS_WINDOWS
6423
6424 # if GTEST_OS_QNX
6425 # include <spawn.h>
6426 # endif // GTEST_OS_QNX
6427
6428 #endif // GTEST_HAS_DEATH_TEST
6429
6430 // Indicates that this translation unit is part of Google Test's
6431 // implementation. It must come before gtest-internal-inl.h is
6432 // included, or there will be a compiler error. This trick is to
6433 // prevent a user from accidentally including gtest-internal-inl.h in
6434 // his code.
6435 #define GTEST_IMPLEMENTATION_ 1
6436 #undef GTEST_IMPLEMENTATION_
6437
6438 namespace testing {
6439
6440 // Constants.
6441
6442 // The default death test style.
6443 static const char kDefaultDeathTestStyle[] = "fast";
6444
6445 GTEST_DEFINE_string_(
6446 death_test_style,
6447 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6448 "Indicates how to run a death test in a forked child process: "
6449 "\"threadsafe\" (child process re-executes the test binary "
6450 "from the beginning, running only the specific death test) or "
6451 "\"fast\" (child process runs the death test immediately "
6452 "after forking).");
6453
6454 GTEST_DEFINE_bool_(
6455 death_test_use_fork,
6456 internal::BoolFromGTestEnv("death_test_use_fork", false),
6457 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6458 "Ignored and always uses fork() on POSIX systems where clone() is not "
6459 "implemented. Useful when running under valgrind or similar tools if "
6460 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6461 "it sees an unsupported combination of clone() flags. "
6462 "It is not recommended to use this flag w/o valgrind though it will "
6463 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6464 "most likely be removed.");
6465
6466 namespace internal {
6467 GTEST_DEFINE_string_(
6468 internal_run_death_test, "",
6469 "Indicates the file, line number, temporal index of "
6470 "the single death test to run, and a file descriptor to "
6471 "which a success code may be sent, all separated by "
6472 "the '|' characters. This flag is specified if and only if the current "
6473 "process is a sub-process launched for running a thread-safe "
6474 "death test. FOR INTERNAL USE ONLY.");
6475 } // namespace internal
6476
6477 #if GTEST_HAS_DEATH_TEST
6478
6479 namespace internal {
6480
6481 // Valid only for fast death tests. Indicates the code is running in the
6482 // child process of a fast style death test.
6483 static bool g_in_fast_death_test_child = false;
6484
6485 // Returns a Boolean value indicating whether the caller is currently
6486 // executing in the context of the death test child process. Tools such as
6487 // Valgrind heap checkers may need this to modify their behavior in death
6488 // tests. IMPORTANT: This is an internal utility. Using it may break the
6489 // implementation of death tests. User code MUST NOT use it.
6490 bool InDeathTestChild() {
6491 # if GTEST_OS_WINDOWS
6492
6493 // On Windows, death tests are thread-safe regardless of the value of the
6494 // death_test_style flag.
6495 return !GTEST_FLAG(internal_run_death_test).empty();
6496
6497 # else
6498
6499 if (GTEST_FLAG(death_test_style) == "threadsafe")
6500 return !GTEST_FLAG(internal_run_death_test).empty();
6501 else
6502 return g_in_fast_death_test_child;
6503 # endif
6504 }
6505
6506 } // namespace internal
6507
6508 // ExitedWithCode constructor.
6509 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
6510
6511 // ExitedWithCode function-call operator.
6512 bool ExitedWithCode::operator()(int exit_status) const {
6513 # if GTEST_OS_WINDOWS
6514
6515 return exit_status == exit_code_;
6516
6517 # else
6518
6519 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6520
6521 # endif // GTEST_OS_WINDOWS
6522 }
6523
6524 # if !GTEST_OS_WINDOWS
6525 // KilledBySignal constructor.
6526 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
6527
6528 // KilledBySignal function-call operator.
6529 bool KilledBySignal::operator()(int exit_status) const {
6530 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6531 }
6532 # endif // !GTEST_OS_WINDOWS
6533
6534 namespace internal {
6535
6536 // Utilities needed for death tests.
6537
6538 // Generates a textual description of a given exit code, in the format
6539 // specified by wait(2).
6540 static std::string ExitSummary(int exit_code) {
6541 Message m;
6542
6543 # if GTEST_OS_WINDOWS
6544
6545 m << "Exited with exit status " << exit_code;
6546
6547 # else
6548
6549 if (WIFEXITED(exit_code)) {
6550 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6551 } else if (WIFSIGNALED(exit_code)) {
6552 m << "Terminated by signal " << WTERMSIG(exit_code);
6553 }
6554 # ifdef WCOREDUMP
6555 if (WCOREDUMP(exit_code)) {
6556 m << " (core dumped)";
6557 }
6558 # endif
6559 # endif // GTEST_OS_WINDOWS
6560
6561 return m.GetString();
6562 }
6563
6564 // Returns true if exit_status describes a process that was terminated
6565 // by a signal, or exited normally with a nonzero exit code.
6566 bool ExitedUnsuccessfully(int exit_status) {
6567 return !ExitedWithCode(0)(exit_status);
6568 }
6569
6570 # if !GTEST_OS_WINDOWS
6571 // Generates a textual failure message when a death test finds more than
6572 // one thread running, or cannot determine the number of threads, prior
6573 // to executing the given statement. It is the responsibility of the
6574 // caller not to pass a thread_count of 1.
6575 static std::string DeathTestThreadWarning(size_t thread_count) {
6576 Message msg;
6577 msg << "Death tests use fork(), which is unsafe particularly"
6578 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6579 if (thread_count == 0)
6580 msg << "couldn't detect the number of threads.";
6581 else
6582 msg << "detected " << thread_count << " threads.";
6583 return msg.GetString();
6584 }
6585 # endif // !GTEST_OS_WINDOWS
6586
6587 // Flag characters for reporting a death test that did not die.
6588 static const char kDeathTestLived = 'L';
6589 static const char kDeathTestReturned = 'R';
6590 static const char kDeathTestThrew = 'T';
6591 static const char kDeathTestInternalError = 'I';
6592
6593 // An enumeration describing all of the possible ways that a death test can
6594 // conclude. DIED means that the process died while executing the test
6595 // code; LIVED means that process lived beyond the end of the test code;
6596 // RETURNED means that the test statement attempted to execute a return
6597 // statement, which is not allowed; THREW means that the test statement
6598 // returned control by throwing an exception. IN_PROGRESS means the test
6599 // has not yet concluded.
6600 // TODO(vladl@google.com): Unify names and possibly values for
6601 // AbortReason, DeathTestOutcome, and flag characters above.
6602 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6603
6604 // Routine for aborting the program which is safe to call from an
6605 // exec-style death test child process, in which case the error
6606 // message is propagated back to the parent process. Otherwise, the
6607 // message is simply printed to stderr. In either case, the program
6608 // then exits with status 1.
6609 void DeathTestAbort(const std::string& message) {
6610 // On a POSIX system, this function may be called from a threadsafe-style
6611 // death test child process, which operates on a very small stack. Use
6612 // the heap for any additional non-minuscule memory requirements.
6613 const InternalRunDeathTestFlag* const flag =
6614 GetUnitTestImpl()->internal_run_death_test_flag();
6615 if (flag != NULL) {
6616 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6617 fputc(kDeathTestInternalError, parent);
6618 fprintf(parent, "%s", message.c_str());
6619 fflush(parent);
6620 _exit(1);
6621 } else {
6622 fprintf(stderr, "%s", message.c_str());
6623 fflush(stderr);
6624 posix::Abort();
6625 }
6626 }
6627
6628 // A replacement for CHECK that calls DeathTestAbort if the assertion
6629 // fails.
6630 # define GTEST_DEATH_TEST_CHECK_(expression) \
6631 do { \
6632 if (!::testing::internal::IsTrue(expression)) { \
6633 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
6634 ", line " + \
6635 ::testing::internal::StreamableToString(__LINE__) + \
6636 ": " + #expression); \
6637 } \
6638 } while (::testing::internal::AlwaysFalse())
6639
6640 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6641 // evaluating any system call that fulfills two conditions: it must return
6642 // -1 on failure, and set errno to EINTR when it is interrupted and
6643 // should be tried again. The macro expands to a loop that repeatedly
6644 // evaluates the expression as long as it evaluates to -1 and sets
6645 // errno to EINTR. If the expression evaluates to -1 but errno is
6646 // something other than EINTR, DeathTestAbort is called.
6647 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6648 do { \
6649 int gtest_retval; \
6650 do { \
6651 gtest_retval = (expression); \
6652 } while (gtest_retval == -1 && errno == EINTR); \
6653 if (gtest_retval == -1) { \
6654 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
6655 ", line " + \
6656 ::testing::internal::StreamableToString(__LINE__) + \
6657 ": " + #expression + " != -1"); \
6658 } \
6659 } while (::testing::internal::AlwaysFalse())
6660
6661 // Returns the message describing the last system error in errno.
6662 std::string GetLastErrnoDescription() {
6663 return errno == 0 ? "" : posix::StrError(errno);
6664 }
6665
6666 // This is called from a death test parent process to read a failure
6667 // message from the death test child process and log it with the FATAL
6668 // severity. On Windows, the message is read from a pipe handle. On other
6669 // platforms, it is read from a file descriptor.
6670 static void FailFromInternalError(int fd) {
6671 Message error;
6672 char buffer[256];
6673 int num_read;
6674
6675 do {
6676 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6677 buffer[num_read] = '\0';
6678 error << buffer;
6679 }
6680 } while (num_read == -1 && errno == EINTR);
6681
6682 if (num_read == 0) {
6683 GTEST_LOG_(FATAL) << error.GetString();
6684 } else {
6685 const int last_error = errno;
6686 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6687 << GetLastErrnoDescription() << " [" << last_error << "]";
6688 }
6689 }
6690
6691 // Death test constructor. Increments the running death test count
6692 // for the current test.
6693 DeathTest::DeathTest() {
6694 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6695 if (info == NULL) {
6696 DeathTestAbort(
6697 "Cannot run a death test outside of a TEST or "
6698 "TEST_F construct");
6699 }
6700 }
6701
6702 // Creates and returns a death test by dispatching to the current
6703 // death test factory.
6704 bool DeathTest::Create(const char* statement, const RE* regex, const char* file,
6705 int line, DeathTest** test) {
6706 return GetUnitTestImpl()->death_test_factory()->Create(statement, regex, file,
6707 line, test);
6708 }
6709
6710 const char* DeathTest::LastMessage() {
6711 return last_death_test_message_.c_str();
6712 }
6713
6714 void DeathTest::set_last_death_test_message(const std::string& message) {
6715 last_death_test_message_ = message;
6716 }
6717
6718 std::string DeathTest::last_death_test_message_;
6719
6720 // Provides cross platform implementation for some death functionality.
6721 class DeathTestImpl : public DeathTest {
6722 protected:
6723 DeathTestImpl(const char* a_statement, const RE* a_regex)
6724 : statement_(a_statement),
6725 regex_(a_regex),
6726 spawned_(false),
6727 status_(-1),
6728 outcome_(IN_PROGRESS),
6729 read_fd_(-1),
6730 write_fd_(-1) {}
6731
6732 // read_fd_ is expected to be closed and cleared by a derived class.
6733 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6734
6735 void Abort(AbortReason reason);
6736 virtual bool Passed(bool status_ok);
6737
6738 const char* statement() const { return statement_; }
6739 const RE* regex() const { return regex_; }
6740 bool spawned() const { return spawned_; }
6741 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6742 int status() const { return status_; }
6743 void set_status(int a_status) { status_ = a_status; }
6744 DeathTestOutcome outcome() const { return outcome_; }
6745 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6746 int read_fd() const { return read_fd_; }
6747 void set_read_fd(int fd) { read_fd_ = fd; }
6748 int write_fd() const { return write_fd_; }
6749 void set_write_fd(int fd) { write_fd_ = fd; }
6750
6751 // Called in the parent process only. Reads the result code of the death
6752 // test child process via a pipe, interprets it to set the outcome_
6753 // member, and closes read_fd_. Outputs diagnostics and terminates in
6754 // case of unexpected codes.
6755 void ReadAndInterpretStatusByte();
6756
6757 private:
6758 // The textual content of the code this object is testing. This class
6759 // doesn't own this string and should not attempt to delete it.
6760 const char* const statement_;
6761 // The regular expression which test output must match. DeathTestImpl
6762 // doesn't own this object and should not attempt to delete it.
6763 const RE* const regex_;
6764 // True if the death test child process has been successfully spawned.
6765 bool spawned_;
6766 // The exit status of the child process.
6767 int status_;
6768 // How the death test concluded.
6769 DeathTestOutcome outcome_;
6770 // Descriptor to the read end of the pipe to the child process. It is
6771 // always -1 in the child process. The child keeps its write end of the
6772 // pipe in write_fd_.
6773 int read_fd_;
6774 // Descriptor to the child's write end of the pipe to the parent process.
6775 // It is always -1 in the parent process. The parent keeps its end of the
6776 // pipe in read_fd_.
6777 int write_fd_;
6778 };
6779
6780 // Called in the parent process only. Reads the result code of the death
6781 // test child process via a pipe, interprets it to set the outcome_
6782 // member, and closes read_fd_. Outputs diagnostics and terminates in
6783 // case of unexpected codes.
6784 void DeathTestImpl::ReadAndInterpretStatusByte() {
6785 char flag;
6786 int bytes_read;
6787
6788 // The read() here blocks until data is available (signifying the
6789 // failure of the death test) or until the pipe is closed (signifying
6790 // its success), so it's okay to call this in the parent before
6791 // the child process has exited.
6792 do {
6793 bytes_read = posix::Read(read_fd(), &flag, 1);
6794 } while (bytes_read == -1 && errno == EINTR);
6795
6796 if (bytes_read == 0) {
6797 set_outcome(DIED);
6798 } else if (bytes_read == 1) {
6799 switch (flag) {
6800 case kDeathTestReturned:
6801 set_outcome(RETURNED);
6802 break;
6803 case kDeathTestThrew:
6804 set_outcome(THREW);
6805 break;
6806 case kDeathTestLived:
6807 set_outcome(LIVED);
6808 break;
6809 case kDeathTestInternalError:
6810 FailFromInternalError(read_fd()); // Does not return.
6811 break;
6812 default:
6813 GTEST_LOG_(FATAL) << "Death test child process reported "
6814 << "unexpected status byte ("
6815 << static_cast<unsigned int>(flag) << ")";
6816 }
6817 } else {
6818 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6819 << GetLastErrnoDescription();
6820 }
6821 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6822 set_read_fd(-1);
6823 }
6824
6825 // Signals that the death test code which should have exited, didn't.
6826 // Should be called only in a death test child process.
6827 // Writes a status byte to the child's status file descriptor, then
6828 // calls _exit(1).
6829 void DeathTestImpl::Abort(AbortReason reason) {
6830 // The parent process considers the death test to be a failure if
6831 // it finds any data in our pipe. So, here we write a single flag byte
6832 // to the pipe, then exit.
6833 const char status_ch = reason == TEST_DID_NOT_DIE
6834 ? kDeathTestLived
6835 : reason == TEST_THREW_EXCEPTION
6836 ? kDeathTestThrew
6837 : kDeathTestReturned;
6838
6839 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6840 // We are leaking the descriptor here because on some platforms (i.e.,
6841 // when built as Windows DLL), destructors of global objects will still
6842 // run after calling _exit(). On such systems, write_fd_ will be
6843 // indirectly closed from the destructor of UnitTestImpl, causing double
6844 // close if it is also closed here. On debug configurations, double close
6845 // may assert. As there are no in-process buffers to flush here, we are
6846 // relying on the OS to close the descriptor after the process terminates
6847 // when the destructors are not run.
6848 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6849 }
6850
6851 // Returns an indented copy of stderr output for a death test.
6852 // This makes distinguishing death test output lines from regular log lines
6853 // much easier.
6854 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6855 ::std::string ret;
6856 for (size_t at = 0;;) {
6857 const size_t line_end = output.find('\n', at);
6858 ret += "[ DEATH ] ";
6859 if (line_end == ::std::string::npos) {
6860 ret += output.substr(at);
6861 break;
6862 }
6863 ret += output.substr(at, line_end + 1 - at);
6864 at = line_end + 1;
6865 }
6866 return ret;
6867 }
6868
6869 // Assesses the success or failure of a death test, using both private
6870 // members which have previously been set, and one argument:
6871 //
6872 // Private data members:
6873 // outcome: An enumeration describing how the death test
6874 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
6875 // fails in the latter three cases.
6876 // status: The exit status of the child process. On *nix, it is in the
6877 // in the format specified by wait(2). On Windows, this is the
6878 // value supplied to the ExitProcess() API or a numeric code
6879 // of the exception that terminated the program.
6880 // regex: A regular expression object to be applied to
6881 // the test's captured standard error output; the death test
6882 // fails if it does not match.
6883 //
6884 // Argument:
6885 // status_ok: true if exit_status is acceptable in the context of
6886 // this particular death test, which fails if it is false
6887 //
6888 // Returns true iff all of the above conditions are met. Otherwise, the
6889 // first failing condition, in the order given above, is the one that is
6890 // reported. Also sets the last death test message string.
6891 bool DeathTestImpl::Passed(bool status_ok) {
6892 if (!spawned()) return false;
6893
6894 const std::string error_message = GetCapturedStderr();
6895
6896 bool success = false;
6897 Message buffer;
6898
6899 buffer << "Death test: " << statement() << "\n";
6900 switch (outcome()) {
6901 case LIVED:
6902 buffer << " Result: failed to die.\n"
6903 << " Error msg:\n"
6904 << FormatDeathTestOutput(error_message);
6905 break;
6906 case THREW:
6907 buffer << " Result: threw an exception.\n"
6908 << " Error msg:\n"
6909 << FormatDeathTestOutput(error_message);
6910 break;
6911 case RETURNED:
6912 buffer << " Result: illegal return in test statement.\n"
6913 << " Error msg:\n"
6914 << FormatDeathTestOutput(error_message);
6915 break;
6916 case DIED:
6917 if (status_ok) {
6918 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6919 if (matched) {
6920 success = true;
6921 } else {
6922 buffer << " Result: died but not with expected error.\n"
6923 << " Expected: " << regex()->pattern() << "\n"
6924 << "Actual msg:\n"
6925 << FormatDeathTestOutput(error_message);
6926 }
6927 } else {
6928 buffer << " Result: died but not with expected exit code:\n"
6929 << " " << ExitSummary(status()) << "\n"
6930 << "Actual msg:\n"
6931 << FormatDeathTestOutput(error_message);
6932 }
6933 break;
6934 case IN_PROGRESS:
6935 default:
6936 GTEST_LOG_(FATAL)
6937 << "DeathTest::Passed somehow called before conclusion of test";
6938 }
6939
6940 DeathTest::set_last_death_test_message(buffer.GetString());
6941 return success;
6942 }
6943
6944 # if GTEST_OS_WINDOWS
6945 // WindowsDeathTest implements death tests on Windows. Due to the
6946 // specifics of starting new processes on Windows, death tests there are
6947 // always threadsafe, and Google Test considers the
6948 // --gtest_death_test_style=fast setting to be equivalent to
6949 // --gtest_death_test_style=threadsafe there.
6950 //
6951 // A few implementation notes: Like the Linux version, the Windows
6952 // implementation uses pipes for child-to-parent communication. But due to
6953 // the specifics of pipes on Windows, some extra steps are required:
6954 //
6955 // 1. The parent creates a communication pipe and stores handles to both
6956 // ends of it.
6957 // 2. The parent starts the child and provides it with the information
6958 // necessary to acquire the handle to the write end of the pipe.
6959 // 3. The child acquires the write end of the pipe and signals the parent
6960 // using a Windows event.
6961 // 4. Now the parent can release the write end of the pipe on its side. If
6962 // this is done before step 3, the object's reference count goes down to
6963 // 0 and it is destroyed, preventing the child from acquiring it. The
6964 // parent now has to release it, or read operations on the read end of
6965 // the pipe will not return when the child terminates.
6966 // 5. The parent reads child's output through the pipe (outcome code and
6967 // any possible error messages) from the pipe, and its stderr and then
6968 // determines whether to fail the test.
6969 //
6970 // Note: to distinguish Win32 API calls from the local method and function
6971 // calls, the former are explicitly resolved in the global namespace.
6972 //
6973 class WindowsDeathTest : public DeathTestImpl {
6974 public:
6975 WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file,
6976 int line)
6977 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
6978
6979 // All of these virtual functions are inherited from DeathTest.
6980 virtual int Wait();
6981 virtual TestRole AssumeRole();
6982
6983 private:
6984 // The name of the file in which the death test is located.
6985 const char* const file_;
6986 // The line number on which the death test is located.
6987 const int line_;
6988 // Handle to the write end of the pipe to the child process.
6989 AutoHandle write_handle_;
6990 // Child process handle.
6991 AutoHandle child_handle_;
6992 // Event the child process uses to signal the parent that it has
6993 // acquired the handle to the write end of the pipe. After seeing this
6994 // event the parent can release its own handles to make sure its
6995 // ReadFile() calls return when the child terminates.
6996 AutoHandle event_handle_;
6997 };
6998
6999 // Waits for the child in a death test to exit, returning its exit
7000 // status, or 0 if no child process exists. As a side effect, sets the
7001 // outcome data member.
7002 int WindowsDeathTest::Wait() {
7003 if (!spawned()) return 0;
7004
7005 // Wait until the child either signals that it has acquired the write end
7006 // of the pipe or it dies.
7007 const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
7008 switch (::WaitForMultipleObjects(2, wait_handles,
7009 FALSE, // Waits for any of the handles.
7010 INFINITE)) {
7011 case WAIT_OBJECT_0:
7012 case WAIT_OBJECT_0 + 1:
7013 break;
7014 default:
7015 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7016 }
7017
7018 // The child has acquired the write end of the pipe or exited.
7019 // We release the handle on our side and continue.
7020 write_handle_.Reset();
7021 event_handle_.Reset();
7022
7023 ReadAndInterpretStatusByte();
7024
7025 // Waits for the child process to exit if it haven't already. This
7026 // returns immediately if the child has already exited, regardless of
7027 // whether previous calls to WaitForMultipleObjects synchronized on this
7028 // handle or not.
7029 GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
7030 ::WaitForSingleObject(child_handle_.Get(), INFINITE));
7031 DWORD status_code;
7032 GTEST_DEATH_TEST_CHECK_(
7033 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7034 child_handle_.Reset();
7035 set_status(static_cast<int>(status_code));
7036 return status();
7037 }
7038
7039 // The AssumeRole process for a Windows death test. It creates a child
7040 // process with the same executable as the current process to run the
7041 // death test. The child process is given the --gtest_filter and
7042 // --gtest_internal_run_death_test flags such that it knows to run the
7043 // current death test only.
7044 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7045 const UnitTestImpl* const impl = GetUnitTestImpl();
7046 const InternalRunDeathTestFlag* const flag =
7047 impl->internal_run_death_test_flag();
7048 const TestInfo* const info = impl->current_test_info();
7049 const int death_test_index = info->result()->death_test_count();
7050
7051 if (flag != NULL) {
7052 // ParseInternalRunDeathTestFlag() has performed all the necessary
7053 // processing.
7054 set_write_fd(flag->write_fd());
7055 return EXECUTE_TEST;
7056 }
7057
7058 // WindowsDeathTest uses an anonymous pipe to communicate results of
7059 // a death test.
7060 SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
7061 NULL, TRUE};
7062 HANDLE read_handle, write_handle;
7063 GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
7064 &handles_are_inheritable,
7065 0) // Default buffer size.
7066 != FALSE);
7067 set_read_fd(
7068 ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
7069 write_handle_.Reset(write_handle);
7070 event_handle_.Reset(::CreateEvent(
7071 &handles_are_inheritable,
7072 TRUE, // The event will automatically reset to non-signaled state.
7073 FALSE, // The initial state is non-signalled.
7074 NULL)); // The even is unnamed.
7075 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7076 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7077 kFilterFlag + "=" + info->test_case_name() +
7078 "." + info->name();
7079 const std::string internal_flag =
7080 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" +
7081 file_ + "|" + StreamableToString(line_) + "|" +
7082 StreamableToString(death_test_index) + "|" +
7083 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7084 // size_t has the same width as pointers on both 32-bit and 64-bit
7085 // Windows platforms.
7086 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7087 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +
7088 StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7089
7090 char executable_path[_MAX_PATH + 1]; // NOLINT
7091 GTEST_DEATH_TEST_CHECK_(
7092 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH));
7093
7094 std::string command_line = std::string(::GetCommandLineA()) + " " +
7095 filter_flag + " \"" + internal_flag + "\"";
7096
7097 DeathTest::set_last_death_test_message("");
7098
7099 CaptureStderr();
7100 // Flush the log buffers since the log streams are shared with the child.
7101 FlushInfoLog();
7102
7103 // The child process will share the standard handles with the parent.
7104 STARTUPINFOA startup_info;
7105 memset(&startup_info, 0, sizeof(STARTUPINFO));
7106 startup_info.dwFlags = STARTF_USESTDHANDLES;
7107 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7108 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7109 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7110
7111 PROCESS_INFORMATION process_info;
7112 GTEST_DEATH_TEST_CHECK_(
7113 ::CreateProcessA(
7114 executable_path, const_cast<char*>(command_line.c_str()),
7115 NULL, // Retuned process handle is not inheritable.
7116 NULL, // Retuned thread handle is not inheritable.
7117 TRUE, // Child inherits all inheritable handles (for write_handle_).
7118 0x0, // Default creation flags.
7119 NULL, // Inherit the parent's environment.
7120 UnitTest::GetInstance()->original_working_dir(), &startup_info,
7121 &process_info) != FALSE);
7122 child_handle_.Reset(process_info.hProcess);
7123 ::CloseHandle(process_info.hThread);
7124 set_spawned(true);
7125 return OVERSEE_TEST;
7126 }
7127 # else // We are not on Windows.
7128
7129 // ForkingDeathTest provides implementations for most of the abstract
7130 // methods of the DeathTest interface. Only the AssumeRole method is
7131 // left undefined.
7132 class ForkingDeathTest : public DeathTestImpl {
7133 public:
7134 ForkingDeathTest(const char* statement, const RE* regex);
7135
7136 // All of these virtual functions are inherited from DeathTest.
7137 virtual int Wait();
7138
7139 protected:
7140 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7141
7142 private:
7143 // PID of child process during death test; 0 in the child process itself.
7144 pid_t child_pid_;
7145 };
7146
7147 // Constructs a ForkingDeathTest.
7148 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7149 : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {}
7150
7151 // Waits for the child in a death test to exit, returning its exit
7152 // status, or 0 if no child process exists. As a side effect, sets the
7153 // outcome data member.
7154 int ForkingDeathTest::Wait() {
7155 if (!spawned()) return 0;
7156
7157 ReadAndInterpretStatusByte();
7158
7159 int status_value;
7160 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7161 set_status(status_value);
7162 return status_value;
7163 }
7164
7165 // A concrete death test class that forks, then immediately runs the test
7166 // in the child process.
7167 class NoExecDeathTest : public ForkingDeathTest {
7168 public:
7169 NoExecDeathTest(const char* a_statement, const RE* a_regex)
7170 : ForkingDeathTest(a_statement, a_regex) {}
7171 virtual TestRole AssumeRole();
7172 };
7173
7174 // The AssumeRole process for a fork-and-run death test. It implements a
7175 // straightforward fork, with a simple pipe to transmit the status byte.
7176 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7177 const size_t thread_count = GetThreadCount();
7178 if (thread_count != 1) {
7179 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7180 }
7181
7182 int pipe_fd[2];
7183 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7184
7185 DeathTest::set_last_death_test_message("");
7186 CaptureStderr();
7187 // When we fork the process below, the log file buffers are copied, but the
7188 // file descriptors are shared. We flush all log files here so that closing
7189 // the file descriptors in the child process doesn't throw off the
7190 // synchronization between descriptors and buffers in the parent process.
7191 // This is as close to the fork as possible to avoid a race condition in case
7192 // there are multiple threads running before the death test, and another
7193 // thread writes to the log file.
7194 FlushInfoLog();
7195
7196 const pid_t child_pid = fork();
7197 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7198 set_child_pid(child_pid);
7199 if (child_pid == 0) {
7200 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7201 set_write_fd(pipe_fd[1]);
7202 // Redirects all logging to stderr in the child process to prevent
7203 // concurrent writes to the log files. We capture stderr in the parent
7204 // process and append the child process' output to a log.
7205 LogToStderr();
7206 // Event forwarding to the listeners of event listener API mush be shut
7207 // down in death test subprocesses.
7208 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7209 g_in_fast_death_test_child = true;
7210 return EXECUTE_TEST;
7211 } else {
7212 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7213 set_read_fd(pipe_fd[0]);
7214 set_spawned(true);
7215 return OVERSEE_TEST;
7216 }
7217 }
7218
7219 // A concrete death test class that forks and re-executes the main
7220 // program from the beginning, with command-line flags set that cause
7221 // only this specific death test to be run.
7222 class ExecDeathTest : public ForkingDeathTest {
7223 public:
7224 ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file,
7225 int line)
7226 : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) {}
7227 virtual TestRole AssumeRole();
7228
7229 private:
7230 static ::std::vector<testing::internal::string>
7231 GetArgvsForDeathTestChildProcess() {
7232 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7233 return args;
7234 }
7235 // The name of the file in which the death test is located.
7236 const char* const file_;
7237 // The line number on which the death test is located.
7238 const int line_;
7239 };
7240
7241 // Utility class for accumulating command-line arguments.
7242 class Arguments {
7243 public:
7244 Arguments() { args_.push_back(NULL); }
7245
7246 ~Arguments() {
7247 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7248 ++i) {
7249 free(*i);
7250 }
7251 }
7252 void AddArgument(const char* argument) {
7253 args_.insert(args_.end() - 1, posix::StrDup(argument));
7254 }
7255
7256 template <typename Str>
7257 void AddArguments(const ::std::vector<Str>& arguments) {
7258 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7259 i != arguments.end(); ++i) {
7260 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7261 }
7262 }
7263 char* const* Argv() { return &args_[0]; }
7264
7265 private:
7266 std::vector<char*> args_;
7267 };
7268
7269 // A struct that encompasses the arguments to the child process of a
7270 // threadsafe-style death test process.
7271 struct ExecDeathTestArgs {
7272 char* const* argv; // Command-line arguments for the child's call to exec
7273 int close_fd; // File descriptor to close; the read end of a pipe
7274 };
7275
7276 # if GTEST_OS_MAC
7277 inline char** GetEnviron() {
7278 // When Google Test is built as a framework on MacOS X, the environ variable
7279 // is unavailable. Apple's documentation (man environ) recommends using
7280 // _NSGetEnviron() instead.
7281 return *_NSGetEnviron();
7282 }
7283 # else
7284 // Some POSIX platforms expect you to declare environ. extern "C" makes
7285 // it reside in the global namespace.
7286 extern "C" char** environ;
7287 inline char** GetEnviron() { return environ; }
7288 # endif // GTEST_OS_MAC
7289
7290 # if !GTEST_OS_QNX
7291 // The main function for a threadsafe-style death test child process.
7292 // This function is called in a clone()-ed process and thus must avoid
7293 // any potentially unsafe operations like malloc or libc functions.
7294 static int ExecDeathTestChildMain(void* child_arg) {
7295 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7296 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7297
7298 // We need to execute the test program in the same environment where
7299 // it was originally invoked. Therefore we change to the original
7300 // working directory first.
7301 const char* const original_dir =
7302 UnitTest::GetInstance()->original_working_dir();
7303 // We can safely call chdir() as it's a direct system call.
7304 if (chdir(original_dir) != 0) {
7305 DeathTestAbort(std::string("chdir(\"") + original_dir +
7306 "\") failed: " + GetLastErrnoDescription());
7307 return EXIT_FAILURE;
7308 }
7309
7310 // We can safely call execve() as it's a direct system call. We
7311 // cannot use execvp() as it's a libc function and thus potentially
7312 // unsafe. Since execve() doesn't search the PATH, the user must
7313 // invoke the test program via a valid path that contains at least
7314 // one path separator.
7315 execve(args->argv[0], args->argv, GetEnviron());
7316 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7317 original_dir + " failed: " + GetLastErrnoDescription());
7318 return EXIT_FAILURE;
7319 }
7320 # endif // !GTEST_OS_QNX
7321
7322 // Two utility routines that together determine the direction the stack
7323 // grows.
7324 // This could be accomplished more elegantly by a single recursive
7325 // function, but we want to guard against the unlikely possibility of
7326 // a smart compiler optimizing the recursion away.
7327 //
7328 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7329 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7330 // correct answer.
7331 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7332 void StackLowerThanAddress(const void* ptr, bool* result) {
7333 int dummy;
7334 *result = (&dummy < ptr);
7335 }
7336
7337 bool StackGrowsDown() {
7338 int dummy;
7339 bool result;
7340 StackLowerThanAddress(&dummy, &result);
7341 return result;
7342 }
7343
7344 // Spawns a child process with the same executable as the current process in
7345 // a thread-safe manner and instructs it to run the death test. The
7346 // implementation uses fork(2) + exec. On systems where clone(2) is
7347 // available, it is used instead, being slightly more thread-safe. On QNX,
7348 // fork supports only single-threaded environments, so this function uses
7349 // spawn(2) there instead. The function dies with an error message if
7350 // anything goes wrong.
7351 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7352 ExecDeathTestArgs args = {argv, close_fd};
7353 pid_t child_pid = -1;
7354
7355 # if GTEST_OS_QNX
7356 // Obtains the current directory and sets it to be closed in the child
7357 // process.
7358 const int cwd_fd = open(".", O_RDONLY);
7359 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7360 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7361 // We need to execute the test program in the same environment where
7362 // it was originally invoked. Therefore we change to the original
7363 // working directory first.
7364 const char* const original_dir =
7365 UnitTest::GetInstance()->original_working_dir();
7366 // We can safely call chdir() as it's a direct system call.
7367 if (chdir(original_dir) != 0) {
7368 DeathTestAbort(std::string("chdir(\"") + original_dir +
7369 "\") failed: " + GetLastErrnoDescription());
7370 return EXIT_FAILURE;
7371 }
7372
7373 int fd_flags;
7374 // Set close_fd to be closed after spawn.
7375 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7376 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7377 fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
7378 struct inheritance inherit = {0};
7379 // spawn is a system call.
7380 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7381 // Restores the current working directory.
7382 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7383 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7384
7385 # else // GTEST_OS_QNX
7386 # if GTEST_OS_LINUX
7387 // When a SIGPROF signal is received while fork() or clone() are executing,
7388 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7389 // it after the call to fork()/clone() is complete.
7390 struct sigaction saved_sigprof_action;
7391 struct sigaction ignore_sigprof_action;
7392 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7393 sigemptyset(&ignore_sigprof_action.sa_mask);
7394 ignore_sigprof_action.sa_handler = SIG_IGN;
7395 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7396 sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7397 # endif // GTEST_OS_LINUX
7398
7399 # if GTEST_HAS_CLONE
7400 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7401
7402 if (!use_fork) {
7403 static const bool stack_grows_down = StackGrowsDown();
7404 const size_t stack_size = getpagesize();
7405 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7406 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7407 MAP_ANON | MAP_PRIVATE, -1, 0);
7408 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7409
7410 // Maximum stack alignment in bytes: For a downward-growing stack, this
7411 // amount is subtracted from size of the stack space to get an address
7412 // that is within the stack space and is aligned on all systems we care
7413 // about. As far as I know there is no ABI with stack alignment greater
7414 // than 64. We assume stack and stack_size already have alignment of
7415 // kMaxStackAlignment.
7416 const size_t kMaxStackAlignment = 64;
7417 void* const stack_top =
7418 static_cast<char*>(stack) +
7419 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7420 GTEST_DEATH_TEST_CHECK_(
7421 stack_size > kMaxStackAlignment &&
7422 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7423
7424 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7425
7426 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7427 }
7428 # else
7429 const bool use_fork = true;
7430 # endif // GTEST_HAS_CLONE
7431
7432 if (use_fork && (child_pid = fork()) == 0) {
7433 ExecDeathTestChildMain(&args);
7434 _exit(0);
7435 }
7436 # endif // GTEST_OS_QNX
7437 # if GTEST_OS_LINUX
7438 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7439 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7440 # endif // GTEST_OS_LINUX
7441
7442 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7443 return child_pid;
7444 }
7445
7446 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7447 // main program from the beginning, setting the --gtest_filter
7448 // and --gtest_internal_run_death_test flags to cause only the current
7449 // death test to be re-run.
7450 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7451 const UnitTestImpl* const impl = GetUnitTestImpl();
7452 const InternalRunDeathTestFlag* const flag =
7453 impl->internal_run_death_test_flag();
7454 const TestInfo* const info = impl->current_test_info();
7455 const int death_test_index = info->result()->death_test_count();
7456
7457 if (flag != NULL) {
7458 set_write_fd(flag->write_fd());
7459 return EXECUTE_TEST;
7460 }
7461
7462 int pipe_fd[2];
7463 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7464 // Clear the close-on-exec flag on the write end of the pipe, lest
7465 // it be closed when the child process does an exec:
7466 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7467
7468 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7469 kFilterFlag + "=" + info->test_case_name() +
7470 "." + info->name();
7471 const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7472 kInternalRunDeathTestFlag + "=" + file_ +
7473 "|" + StreamableToString(line_) + "|" +
7474 StreamableToString(death_test_index) + "|" +
7475 StreamableToString(pipe_fd[1]);
7476 Arguments args;
7477 args.AddArguments(GetArgvsForDeathTestChildProcess());
7478 args.AddArgument(filter_flag.c_str());
7479 args.AddArgument(internal_flag.c_str());
7480
7481 DeathTest::set_last_death_test_message("");
7482
7483 CaptureStderr();
7484 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7485 // is necessary.
7486 FlushInfoLog();
7487
7488 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7489 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7490 set_child_pid(child_pid);
7491 set_read_fd(pipe_fd[0]);
7492 set_spawned(true);
7493 return OVERSEE_TEST;
7494 }
7495
7496 # endif // !GTEST_OS_WINDOWS
7497
7498 // Creates a concrete DeathTest-derived class that depends on the
7499 // --gtest_death_test_style flag, and sets the pointer pointed to
7500 // by the "test" argument to its address. If the test should be
7501 // skipped, sets that pointer to NULL. Returns true, unless the
7502 // flag is set to an invalid value.
7503 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7504 const char* file, int line,
7505 DeathTest** test) {
7506 UnitTestImpl* const impl = GetUnitTestImpl();
7507 const InternalRunDeathTestFlag* const flag =
7508 impl->internal_run_death_test_flag();
7509 const int death_test_index =
7510 impl->current_test_info()->increment_death_test_count();
7511
7512 if (flag != NULL) {
7513 if (death_test_index > flag->index()) {
7514 DeathTest::set_last_death_test_message(
7515 "Death test count (" + StreamableToString(death_test_index) +
7516 ") somehow exceeded expected maximum (" +
7517 StreamableToString(flag->index()) + ")");
7518 return false;
7519 }
7520
7521 if (!(flag->file() == file && flag->line() == line &&
7522 flag->index() == death_test_index)) {
7523 *test = NULL;
7524 return true;
7525 }
7526 }
7527
7528 # if GTEST_OS_WINDOWS
7529
7530 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7531 GTEST_FLAG(death_test_style) == "fast") {
7532 *test = new WindowsDeathTest(statement, regex, file, line);
7533 }
7534
7535 # else
7536
7537 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7538 *test = new ExecDeathTest(statement, regex, file, line);
7539 } else if (GTEST_FLAG(death_test_style) == "fast") {
7540 *test = new NoExecDeathTest(statement, regex);
7541 }
7542
7543 # endif // GTEST_OS_WINDOWS
7544
7545 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7546 DeathTest::set_last_death_test_message("Unknown death test style \"" +
7547 GTEST_FLAG(death_test_style) +
7548 "\" encountered");
7549 return false;
7550 }
7551
7552 return true;
7553 }
7554
7555 // Splits a given string on a given delimiter, populating a given
7556 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7557 // ::std::string, so we can use it here.
7558 static void SplitString(const ::std::string& str, char delimiter,
7559 ::std::vector< ::std::string>* dest) {
7560 ::std::vector< ::std::string> parsed;
7561 ::std::string::size_type pos = 0;
7562 while (::testing::internal::AlwaysTrue()) {
7563 const ::std::string::size_type colon = str.find(delimiter, pos);
7564 if (colon == ::std::string::npos) {
7565 parsed.push_back(str.substr(pos));
7566 break;
7567 } else {
7568 parsed.push_back(str.substr(pos, colon - pos));
7569 pos = colon + 1;
7570 }
7571 }
7572 dest->swap(parsed);
7573 }
7574
7575 # if GTEST_OS_WINDOWS
7576 // Recreates the pipe and event handles from the provided parameters,
7577 // signals the event, and returns a file descriptor wrapped around the pipe
7578 // handle. This function is called in the child process only.
7579 int GetStatusFileDescriptor(unsigned int parent_process_id,
7580 size_t write_handle_as_size_t,
7581 size_t event_handle_as_size_t) {
7582 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7583 FALSE, // Non-inheritable.
7584 parent_process_id));
7585 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7586 DeathTestAbort("Unable to open parent process " +
7587 StreamableToString(parent_process_id));
7588 }
7589
7590 // TODO(vladl@google.com): Replace the following check with a
7591 // compile-time assertion when available.
7592 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7593
7594 const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
7595 HANDLE dup_write_handle;
7596
7597 // The newly initialized handle is accessible only in in the parent
7598 // process. To obtain one accessible within the child, we need to use
7599 // DuplicateHandle.
7600 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7601 ::GetCurrentProcess(), &dup_write_handle,
7602 0x0, // Requested privileges ignored since
7603 // DUPLICATE_SAME_ACCESS is used.
7604 FALSE, // Request non-inheritable handler.
7605 DUPLICATE_SAME_ACCESS)) {
7606 DeathTestAbort("Unable to duplicate the pipe handle " +
7607 StreamableToString(write_handle_as_size_t) +
7608 " from the parent process " +
7609 StreamableToString(parent_process_id));
7610 }
7611
7612 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7613 HANDLE dup_event_handle;
7614
7615 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7616 ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
7617 DUPLICATE_SAME_ACCESS)) {
7618 DeathTestAbort("Unable to duplicate the event handle " +
7619 StreamableToString(event_handle_as_size_t) +
7620 " from the parent process " +
7621 StreamableToString(parent_process_id));
7622 }
7623
7624 const int write_fd =
7625 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7626 if (write_fd == -1) {
7627 DeathTestAbort("Unable to convert pipe handle " +
7628 StreamableToString(write_handle_as_size_t) +
7629 " to a file descriptor");
7630 }
7631
7632 // Signals the parent that the write end of the pipe has been acquired
7633 // so the parent can release its own write end.
7634 ::SetEvent(dup_event_handle);
7635
7636 return write_fd;
7637 }
7638 # endif // GTEST_OS_WINDOWS
7639
7640 // Returns a newly created InternalRunDeathTestFlag object with fields
7641 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7642 // the flag is specified; otherwise returns NULL.
7643 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7644 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7645
7646 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7647 // can use it here.
7648 int line = -1;
7649 int index = -1;
7650 ::std::vector< ::std::string> fields;
7651 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7652 int write_fd = -1;
7653
7654 # if GTEST_OS_WINDOWS
7655
7656 unsigned int parent_process_id = 0;
7657 size_t write_handle_as_size_t = 0;
7658 size_t event_handle_as_size_t = 0;
7659
7660 if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
7661 !ParseNaturalNumber(fields[2], &index) ||
7662 !ParseNaturalNumber(fields[3], &parent_process_id) ||
7663 !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
7664 !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7665 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7666 GTEST_FLAG(internal_run_death_test));
7667 }
7668 write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
7669 event_handle_as_size_t);
7670 # else
7671
7672 if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
7673 !ParseNaturalNumber(fields[2], &index) ||
7674 !ParseNaturalNumber(fields[3], &write_fd)) {
7675 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7676 GTEST_FLAG(internal_run_death_test));
7677 }
7678
7679 # endif // GTEST_OS_WINDOWS
7680
7681 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7682 }
7683
7684 } // namespace internal
7685
7686 #endif // GTEST_HAS_DEATH_TEST
7687
7688 } // namespace testing
7689 // Copyright 2008, Google Inc.
7690 // All rights reserved.
7691 //
7692 // Redistribution and use in source and binary forms, with or without
7693 // modification, are permitted provided that the following conditions are
7694 // met:
7695 //
7696 // * Redistributions of source code must retain the above copyright
7697 // notice, this list of conditions and the following disclaimer.
7698 // * Redistributions in binary form must reproduce the above
7699 // copyright notice, this list of conditions and the following disclaimer
7700 // in the documentation and/or other materials provided with the
7701 // distribution.
7702 // * Neither the name of Google Inc. nor the names of its
7703 // contributors may be used to endorse or promote products derived from
7704 // this software without specific prior written permission.
7705 //
7706 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7707 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7708 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7709 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7710 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7711 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7712 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7713 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7714 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7715 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7716 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7717 //
7718 // Authors: keith.ray@gmail.com (Keith Ray)
7719
7720 #include <stdlib.h>
7721
7722 #if GTEST_OS_WINDOWS_MOBILE
7723 # include <windows.h>
7724 #elif GTEST_OS_WINDOWS
7725 # include <direct.h>
7726 # include <io.h>
7727 #elif GTEST_OS_SYMBIAN
7728 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7729 # include <sys/syslimits.h>
7730 #else
7731 # include <limits.h>
7732
7733 # include <climits> // Some Linux distributions define PATH_MAX here.
7734 #endif // GTEST_OS_WINDOWS_MOBILE
7735
7736 #if GTEST_OS_WINDOWS
7737 # define GTEST_PATH_MAX_ _MAX_PATH
7738 #elif defined(PATH_MAX)
7739 # define GTEST_PATH_MAX_ PATH_MAX
7740 #elif defined(_XOPEN_PATH_MAX)
7741 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7742 #else
7743 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7744 #endif // GTEST_OS_WINDOWS
7745
7746 namespace testing {
7747 namespace internal {
7748
7749 #if GTEST_OS_WINDOWS
7750 // On Windows, '\\' is the standard path separator, but many tools and the
7751 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7752 // noted, a file path can contain either kind of path separators, or a mixture
7753 // of them.
7754 const char kPathSeparator = '\\';
7755 const char kAlternatePathSeparator = '/';
7756 const char kPathSeparatorString[] = "\\";
7757 const char kAlternatePathSeparatorString[] = "/";
7758 # if GTEST_OS_WINDOWS_MOBILE
7759 // Windows CE doesn't have a current directory. You should not use
7760 // the current directory in tests on Windows CE, but this at least
7761 // provides a reasonable fallback.
7762 const char kCurrentDirectoryString[] = "\\";
7763 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7764 const DWORD kInvalidFileAttributes = 0xffffffff;
7765 # else
7766 const char kCurrentDirectoryString[] = ".\\";
7767 # endif // GTEST_OS_WINDOWS_MOBILE
7768 #else
7769 const char kPathSeparator = '/';
7770 const char kPathSeparatorString[] = "/";
7771 const char kCurrentDirectoryString[] = "./";
7772 #endif // GTEST_OS_WINDOWS
7773
7774 // Returns whether the given character is a valid path separator.
7775 static bool IsPathSeparator(char c) {
7776 #if GTEST_HAS_ALT_PATH_SEP_
7777 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7778 #else
7779 return c == kPathSeparator;
7780 #endif
7781 }
7782
7783 // Returns the current working directory, or "" if unsuccessful.
7784 FilePath FilePath::GetCurrentDir() {
7785 #if GTEST_OS_WINDOWS_MOBILE
7786 // Windows CE doesn't have a current directory, so we just return
7787 // something reasonable.
7788 return FilePath(kCurrentDirectoryString);
7789 #elif GTEST_OS_WINDOWS
7790 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
7791 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7792 #else
7793 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
7794 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7795 #endif // GTEST_OS_WINDOWS_MOBILE
7796 }
7797
7798 // Returns a copy of the FilePath with the case-insensitive extension removed.
7799 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7800 // FilePath("dir/file"). If a case-insensitive extension is not
7801 // found, returns a copy of the original FilePath.
7802 FilePath FilePath::RemoveExtension(const char* extension) const {
7803 const std::string dot_extension = std::string(".") + extension;
7804 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7805 return FilePath(
7806 pathname_.substr(0, pathname_.length() - dot_extension.length()));
7807 }
7808 return *this;
7809 }
7810
7811 // Returns a pointer to the last occurence of a valid path separator in
7812 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7813 // separators. Returns NULL if no path separator was found.
7814 const char* FilePath::FindLastPathSeparator() const {
7815 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7816 #if GTEST_HAS_ALT_PATH_SEP_
7817 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7818 // Comparing two pointers of which only one is NULL is undefined.
7819 if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) {
7820 return last_alt_sep;
7821 }
7822 #endif
7823 return last_sep;
7824 }
7825
7826 // Returns a copy of the FilePath with the directory part removed.
7827 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7828 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7829 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7830 // returns an empty FilePath ("").
7831 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7832 FilePath FilePath::RemoveDirectoryName() const {
7833 const char* const last_sep = FindLastPathSeparator();
7834 return last_sep ? FilePath(last_sep + 1) : *this;
7835 }
7836
7837 // RemoveFileName returns the directory path with the filename removed.
7838 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7839 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7840 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7841 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7842 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7843 FilePath FilePath::RemoveFileName() const {
7844 const char* const last_sep = FindLastPathSeparator();
7845 std::string dir;
7846 if (last_sep) {
7847 dir = std::string(c_str(), last_sep + 1 - c_str());
7848 } else {
7849 dir = kCurrentDirectoryString;
7850 }
7851 return FilePath(dir);
7852 }
7853
7854 // Helper functions for naming files in a directory for xml output.
7855
7856 // Given directory = "dir", base_name = "test", number = 0,
7857 // extension = "xml", returns "dir/test.xml". If number is greater
7858 // than zero (e.g., 12), returns "dir/test_12.xml".
7859 // On Windows platform, uses \ as the separator rather than /.
7860 FilePath FilePath::MakeFileName(const FilePath& directory,
7861 const FilePath& base_name, int number,
7862 const char* extension) {
7863 std::string file;
7864 if (number == 0) {
7865 file = base_name.string() + "." + extension;
7866 } else {
7867 file =
7868 base_name.string() + "_" + StreamableToString(number) + "." + extension;
7869 }
7870 return ConcatPaths(directory, FilePath(file));
7871 }
7872
7873 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7874 // On Windows, uses \ as the separator rather than /.
7875 FilePath FilePath::ConcatPaths(const FilePath& directory,
7876 const FilePath& relative_path) {
7877 if (directory.IsEmpty()) return relative_path;
7878 const FilePath dir(directory.RemoveTrailingPathSeparator());
7879 return FilePath(dir.string() + kPathSeparator + relative_path.string());
7880 }
7881
7882 // Returns true if pathname describes something findable in the file-system,
7883 // either a file, directory, or whatever.
7884 bool FilePath::FileOrDirectoryExists() const {
7885 #if GTEST_OS_WINDOWS_MOBILE
7886 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7887 const DWORD attributes = GetFileAttributes(unicode);
7888 delete[] unicode;
7889 return attributes != kInvalidFileAttributes;
7890 #else
7891 posix::StatStruct file_stat;
7892 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7893 #endif // GTEST_OS_WINDOWS_MOBILE
7894 }
7895
7896 // Returns true if pathname describes a directory in the file-system
7897 // that exists.
7898 bool FilePath::DirectoryExists() const {
7899 bool result = false;
7900 #if GTEST_OS_WINDOWS
7901 // Don't strip off trailing separator if path is a root directory on
7902 // Windows (like "C:\\").
7903 const FilePath& path(IsRootDirectory() ? *this
7904 : RemoveTrailingPathSeparator());
7905 #else
7906 const FilePath& path(*this);
7907 #endif
7908
7909 #if GTEST_OS_WINDOWS_MOBILE
7910 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7911 const DWORD attributes = GetFileAttributes(unicode);
7912 delete[] unicode;
7913 if ((attributes != kInvalidFileAttributes) &&
7914 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7915 result = true;
7916 }
7917 #else
7918 posix::StatStruct file_stat;
7919 result =
7920 posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
7921 #endif // GTEST_OS_WINDOWS_MOBILE
7922
7923 return result;
7924 }
7925
7926 // Returns true if pathname describes a root directory. (Windows has one
7927 // root directory per disk drive.)
7928 bool FilePath::IsRootDirectory() const {
7929 #if GTEST_OS_WINDOWS
7930 // TODO(wan@google.com): on Windows a network share like
7931 // \\server\share can be a root directory, although it cannot be the
7932 // current directory. Handle this properly.
7933 return pathname_.length() == 3 && IsAbsolutePath();
7934 #else
7935 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7936 #endif
7937 }
7938
7939 // Returns true if pathname describes an absolute path.
7940 bool FilePath::IsAbsolutePath() const {
7941 const char* const name = pathname_.c_str();
7942 #if GTEST_OS_WINDOWS
7943 return pathname_.length() >= 3 &&
7944 ((name[0] >= 'a' && name[0] <= 'z') ||
7945 (name[0] >= 'A' && name[0] <= 'Z')) &&
7946 name[1] == ':' && IsPathSeparator(name[2]);
7947 #else
7948 return IsPathSeparator(name[0]);
7949 #endif
7950 }
7951
7952 // Returns a pathname for a file that does not currently exist. The pathname
7953 // will be directory/base_name.extension or
7954 // directory/base_name_<number>.extension if directory/base_name.extension
7955 // already exists. The number will be incremented until a pathname is found
7956 // that does not already exist.
7957 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7958 // There could be a race condition if two or more processes are calling this
7959 // function at the same time -- they could both pick the same filename.
7960 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7961 const FilePath& base_name,
7962 const char* extension) {
7963 FilePath full_pathname;
7964 int number = 0;
7965 do {
7966 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7967 } while (full_pathname.FileOrDirectoryExists());
7968 return full_pathname;
7969 }
7970
7971 // Returns true if FilePath ends with a path separator, which indicates that
7972 // it is intended to represent a directory. Returns false otherwise.
7973 // This does NOT check that a directory (or file) actually exists.
7974 bool FilePath::IsDirectory() const {
7975 return !pathname_.empty() &&
7976 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7977 }
7978
7979 // Create directories so that path exists. Returns true if successful or if
7980 // the directories already exist; returns false if unable to create directories
7981 // for any reason.
7982 bool FilePath::CreateDirectoriesRecursively() const {
7983 if (!this->IsDirectory()) {
7984 return false;
7985 }
7986
7987 if (pathname_.length() == 0 || this->DirectoryExists()) {
7988 return true;
7989 }
7990
7991 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7992 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7993 }
7994
7995 // Create the directory so that path exists. Returns true if successful or
7996 // if the directory already exists; returns false if unable to create the
7997 // directory for any reason, including if the parent directory does not
7998 // exist. Not named "CreateDirectory" because that's a macro on Windows.
7999 bool FilePath::CreateFolder() const {
8000 #if GTEST_OS_WINDOWS_MOBILE
8001 FilePath removed_sep(this->RemoveTrailingPathSeparator());
8002 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8003 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8004 delete[] unicode;
8005 #elif GTEST_OS_WINDOWS
8006 int result = _mkdir(pathname_.c_str());
8007 #else
8008 int result = mkdir(pathname_.c_str(), 0777);
8009 #endif // GTEST_OS_WINDOWS_MOBILE
8010
8011 if (result == -1) {
8012 return this->DirectoryExists(); // An error is OK if the directory exists.
8013 }
8014 return true; // No error.
8015 }
8016
8017 // If input name has a trailing separator character, remove it and return the
8018 // name, otherwise return the name string unmodified.
8019 // On Windows platform, uses \ as the separator, other platforms use /.
8020 FilePath FilePath::RemoveTrailingPathSeparator() const {
8021 return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8022 : *this;
8023 }
8024
8025 // Removes any redundant separators that might be in the pathname.
8026 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8027 // redundancies that might be in a pathname involving "." or "..".
8028 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8029 void FilePath::Normalize() {
8030 if (pathname_.c_str() == NULL) {
8031 pathname_ = "";
8032 return;
8033 }
8034 const char* src = pathname_.c_str();
8035 char* const dest = new char[pathname_.length() + 1];
8036 char* dest_ptr = dest;
8037 memset(dest_ptr, 0, pathname_.length() + 1);
8038
8039 while (*src != '\0') {
8040 *dest_ptr = *src;
8041 if (!IsPathSeparator(*src)) {
8042 src++;
8043 } else {
8044 #if GTEST_HAS_ALT_PATH_SEP_
8045 if (*dest_ptr == kAlternatePathSeparator) {
8046 *dest_ptr = kPathSeparator;
8047 }
8048 #endif
8049 while (IsPathSeparator(*src)) src++;
8050 }
8051 dest_ptr++;
8052 }
8053 *dest_ptr = '\0';
8054 pathname_ = dest;
8055 delete[] dest;
8056 }
8057
8058 } // namespace internal
8059 } // namespace testing
8060 // Copyright 2008, Google Inc.
8061 // All rights reserved.
8062 //
8063 // Redistribution and use in source and binary forms, with or without
8064 // modification, are permitted provided that the following conditions are
8065 // met:
8066 //
8067 // * Redistributions of source code must retain the above copyright
8068 // notice, this list of conditions and the following disclaimer.
8069 // * Redistributions in binary form must reproduce the above
8070 // copyright notice, this list of conditions and the following disclaimer
8071 // in the documentation and/or other materials provided with the
8072 // distribution.
8073 // * Neither the name of Google Inc. nor the names of its
8074 // contributors may be used to endorse or promote products derived from
8075 // this software without specific prior written permission.
8076 //
8077 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8078 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8079 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8080 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8081 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8082 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8083 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8084 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8085 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8086 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8087 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8088 //
8089 // Author: wan@google.com (Zhanyong Wan)
8090
8091 #include <limits.h>
8092 #include <stdio.h>
8093 #include <stdlib.h>
8094 #include <string.h>
8095
8096 #if GTEST_OS_WINDOWS_MOBILE
8097 # include <windows.h> // For TerminateProcess()
8098 #elif GTEST_OS_WINDOWS
8099 # include <io.h>
8100 # include <sys/stat.h>
8101 #else
8102 # include <unistd.h>
8103 #endif // GTEST_OS_WINDOWS_MOBILE
8104
8105 #if GTEST_OS_MAC
8106 # include <mach/mach_init.h>
8107 # include <mach/task.h>
8108 # include <mach/vm_map.h>
8109 #endif // GTEST_OS_MAC
8110
8111 #if GTEST_OS_QNX
8112 # include <devctl.h>
8113 # include <sys/procfs.h>
8114 #endif // GTEST_OS_QNX
8115
8116 // Indicates that this translation unit is part of Google Test's
8117 // implementation. It must come before gtest-internal-inl.h is
8118 // included, or there will be a compiler error. This trick is to
8119 // prevent a user from accidentally including gtest-internal-inl.h in
8120 // his code.
8121 #define GTEST_IMPLEMENTATION_ 1
8122 #undef GTEST_IMPLEMENTATION_
8123
8124 namespace testing {
8125 namespace internal {
8126
8127 #if defined(_MSC_VER) || defined(__BORLANDC__)
8128 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8129 const int kStdOutFileno = 1;
8130 const int kStdErrFileno = 2;
8131 #else
8132 const int kStdOutFileno = STDOUT_FILENO;
8133 const int kStdErrFileno = STDERR_FILENO;
8134 #endif // _MSC_VER
8135
8136 #if GTEST_OS_MAC
8137
8138 // Returns the number of threads running in the process, or 0 to indicate that
8139 // we cannot detect it.
8140 size_t GetThreadCount() {
8141 const task_t task = mach_task_self();
8142 mach_msg_type_number_t thread_count;
8143 thread_act_array_t thread_list;
8144 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8145 if (status == KERN_SUCCESS) {
8146 // task_threads allocates resources in thread_list and we need to free them
8147 // to avoid leaks.
8148 vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
8149 sizeof(thread_t) * thread_count);
8150 return static_cast<size_t>(thread_count);
8151 } else {
8152 return 0;
8153 }
8154 }
8155
8156 #elif GTEST_OS_QNX
8157
8158 // Returns the number of threads running in the process, or 0 to indicate that
8159 // we cannot detect it.
8160 size_t GetThreadCount() {
8161 const int fd = open("/proc/self/as", O_RDONLY);
8162 if (fd < 0) {
8163 return 0;
8164 }
8165 procfs_info process_info;
8166 const int status =
8167 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8168 close(fd);
8169 if (status == EOK) {
8170 return static_cast<size_t>(process_info.num_threads);
8171 } else {
8172 return 0;
8173 }
8174 }
8175
8176 #else
8177
8178 size_t GetThreadCount() {
8179 // There's no portable way to detect the number of threads, so we just
8180 // return 0 to indicate that we cannot detect it.
8181 return 0;
8182 }
8183
8184 #endif // GTEST_OS_MAC
8185
8186 #if GTEST_USES_POSIX_RE
8187
8188 // Implements RE. Currently only needed for death tests.
8189
8190 RE::~RE() {
8191 if (is_valid_) {
8192 // regfree'ing an invalid regex might crash because the content
8193 // of the regex is undefined. Since the regex's are essentially
8194 // the same, one cannot be valid (or invalid) without the other
8195 // being so too.
8196 regfree(&partial_regex_);
8197 regfree(&full_regex_);
8198 }
8199 free(const_cast<char*>(pattern_));
8200 }
8201
8202 // Returns true iff regular expression re matches the entire str.
8203 bool RE::FullMatch(const char* str, const RE& re) {
8204 if (!re.is_valid_) return false;
8205
8206 regmatch_t match;
8207 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8208 }
8209
8210 // Returns true iff regular expression re matches a substring of str
8211 // (including str itself).
8212 bool RE::PartialMatch(const char* str, const RE& re) {
8213 if (!re.is_valid_) return false;
8214
8215 regmatch_t match;
8216 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8217 }
8218
8219 // Initializes an RE from its string representation.
8220 void RE::Init(const char* regex) {
8221 pattern_ = posix::StrDup(regex);
8222
8223 // Reserves enough bytes to hold the regular expression used for a
8224 // full match.
8225 const size_t full_regex_len = strlen(regex) + 10;
8226 char* const full_pattern = new char[full_regex_len];
8227
8228 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8229 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8230 // We want to call regcomp(&partial_regex_, ...) even if the
8231 // previous expression returns false. Otherwise partial_regex_ may
8232 // not be properly initialized can may cause trouble when it's
8233 // freed.
8234 //
8235 // Some implementation of POSIX regex (e.g. on at least some
8236 // versions of Cygwin) doesn't accept the empty string as a valid
8237 // regex. We change it to an equivalent form "()" to be safe.
8238 if (is_valid_) {
8239 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8240 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8241 }
8242 EXPECT_TRUE(is_valid_)
8243 << "Regular expression \"" << regex
8244 << "\" is not a valid POSIX Extended regular expression.";
8245
8246 delete[] full_pattern;
8247 }
8248
8249 #elif GTEST_USES_SIMPLE_RE
8250
8251 // Returns true iff ch appears anywhere in str (excluding the
8252 // terminating '\0' character).
8253 bool IsInSet(char ch, const char* str) {
8254 return ch != '\0' && strchr(str, ch) != NULL;
8255 }
8256
8257 // Returns true iff ch belongs to the given classification. Unlike
8258 // similar functions in <ctype.h>, these aren't affected by the
8259 // current locale.
8260 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
8261 bool IsAsciiPunct(char ch) {
8262 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8263 }
8264 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
8265 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
8266 bool IsAsciiWordChar(char ch) {
8267 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8268 ('0' <= ch && ch <= '9') || ch == '_';
8269 }
8270
8271 // Returns true iff "\\c" is a supported escape sequence.
8272 bool IsValidEscape(char c) {
8273 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8274 }
8275
8276 // Returns true iff the given atom (specified by escaped and pattern)
8277 // matches ch. The result is undefined if the atom is invalid.
8278 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8279 if (escaped) { // "\\p" where p is pattern_char.
8280 switch (pattern_char) {
8281 case 'd':
8282 return IsAsciiDigit(ch);
8283 case 'D':
8284 return !IsAsciiDigit(ch);
8285 case 'f':
8286 return ch == '\f';
8287 case 'n':
8288 return ch == '\n';
8289 case 'r':
8290 return ch == '\r';
8291 case 's':
8292 return IsAsciiWhiteSpace(ch);
8293 case 'S':
8294 return !IsAsciiWhiteSpace(ch);
8295 case 't':
8296 return ch == '\t';
8297 case 'v':
8298 return ch == '\v';
8299 case 'w':
8300 return IsAsciiWordChar(ch);
8301 case 'W':
8302 return !IsAsciiWordChar(ch);
8303 }
8304 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8305 }
8306
8307 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8308 }
8309
8310 // Helper function used by ValidateRegex() to format error messages.
8311 std::string FormatRegexSyntaxError(const char* regex, int index) {
8312 return (Message() << "Syntax error at index " << index
8313 << " in simple regular expression \"" << regex << "\": ")
8314 .GetString();
8315 }
8316
8317 // Generates non-fatal failures and returns false if regex is invalid;
8318 // otherwise returns true.
8319 bool ValidateRegex(const char* regex) {
8320 if (regex == NULL) {
8321 // TODO(wan@google.com): fix the source file location in the
8322 // assertion failures to match where the regex is used in user
8323 // code.
8324 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8325 return false;
8326 }
8327
8328 bool is_valid = true;
8329
8330 // True iff ?, *, or + can follow the previous atom.
8331 bool prev_repeatable = false;
8332 for (int i = 0; regex[i]; i++) {
8333 if (regex[i] == '\\') { // An escape sequence
8334 i++;
8335 if (regex[i] == '\0') {
8336 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8337 << "'\\' cannot appear at the end.";
8338 return false;
8339 }
8340
8341 if (!IsValidEscape(regex[i])) {
8342 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8343 << "invalid escape sequence \"\\" << regex[i] << "\".";
8344 is_valid = false;
8345 }
8346 prev_repeatable = true;
8347 } else { // Not an escape sequence.
8348 const char ch = regex[i];
8349
8350 if (ch == '^' && i > 0) {
8351 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8352 << "'^' can only appear at the beginning.";
8353 is_valid = false;
8354 } else if (ch == '$' && regex[i + 1] != '\0') {
8355 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8356 << "'$' can only appear at the end.";
8357 is_valid = false;
8358 } else if (IsInSet(ch, "()[]{}|")) {
8359 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
8360 << "' is unsupported.";
8361 is_valid = false;
8362 } else if (IsRepeat(ch) && !prev_repeatable) {
8363 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
8364 << "' can only follow a repeatable token.";
8365 is_valid = false;
8366 }
8367
8368 prev_repeatable = !IsInSet(ch, "^$?*+");
8369 }
8370 }
8371
8372 return is_valid;
8373 }
8374
8375 // Matches a repeated regex atom followed by a valid simple regular
8376 // expression. The regex atom is defined as c if escaped is false,
8377 // or \c otherwise. repeat is the repetition meta character (?, *,
8378 // or +). The behavior is undefined if str contains too many
8379 // characters to be indexable by size_t, in which case the test will
8380 // probably time out anyway. We are fine with this limitation as
8381 // std::string has it too.
8382 bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
8383 const char* regex, const char* str) {
8384 const size_t min_count = (repeat == '+') ? 1 : 0;
8385 const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
8386 // We cannot call numeric_limits::max() as it conflicts with the
8387 // max() macro on Windows.
8388
8389 for (size_t i = 0; i <= max_count; ++i) {
8390 // We know that the atom matches each of the first i characters in str.
8391 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8392 // We have enough matches at the head, and the tail matches too.
8393 // Since we only care about *whether* the pattern matches str
8394 // (as opposed to *how* it matches), there is no need to find a
8395 // greedy match.
8396 return true;
8397 }
8398 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
8399 }
8400 return false;
8401 }
8402
8403 // Returns true iff regex matches a prefix of str. regex must be a
8404 // valid simple regular expression and not start with "^", or the
8405 // result is undefined.
8406 bool MatchRegexAtHead(const char* regex, const char* str) {
8407 if (*regex == '\0') // An empty regex matches a prefix of anything.
8408 return true;
8409
8410 // "$" only matches the end of a string. Note that regex being
8411 // valid guarantees that there's nothing after "$" in it.
8412 if (*regex == '$') return *str == '\0';
8413
8414 // Is the first thing in regex an escape sequence?
8415 const bool escaped = *regex == '\\';
8416 if (escaped) ++regex;
8417 if (IsRepeat(regex[1])) {
8418 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8419 // here's an indirect recursion. It terminates as the regex gets
8420 // shorter in each recursion.
8421 return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
8422 str);
8423 } else {
8424 // regex isn't empty, isn't "$", and doesn't start with a
8425 // repetition. We match the first atom of regex with the first
8426 // character of str and recurse.
8427 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8428 MatchRegexAtHead(regex + 1, str + 1);
8429 }
8430 }
8431
8432 // Returns true iff regex matches any substring of str. regex must be
8433 // a valid simple regular expression, or the result is undefined.
8434 //
8435 // The algorithm is recursive, but the recursion depth doesn't exceed
8436 // the regex length, so we won't need to worry about running out of
8437 // stack space normally. In rare cases the time complexity can be
8438 // exponential with respect to the regex length + the string length,
8439 // but usually it's must faster (often close to linear).
8440 bool MatchRegexAnywhere(const char* regex, const char* str) {
8441 if (regex == NULL || str == NULL) return false;
8442
8443 if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
8444
8445 // A successful match can be anywhere in str.
8446 do {
8447 if (MatchRegexAtHead(regex, str)) return true;
8448 } while (*str++ != '\0');
8449 return false;
8450 }
8451
8452 // Implements the RE class.
8453
8454 RE::~RE() {
8455 free(const_cast<char*>(pattern_));
8456 free(const_cast<char*>(full_pattern_));
8457 }
8458
8459 // Returns true iff regular expression re matches the entire str.
8460 bool RE::FullMatch(const char* str, const RE& re) {
8461 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8462 }
8463
8464 // Returns true iff regular expression re matches a substring of str
8465 // (including str itself).
8466 bool RE::PartialMatch(const char* str, const RE& re) {
8467 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8468 }
8469
8470 // Initializes an RE from its string representation.
8471 void RE::Init(const char* regex) {
8472 pattern_ = full_pattern_ = NULL;
8473 if (regex != NULL) {
8474 pattern_ = posix::StrDup(regex);
8475 }
8476
8477 is_valid_ = ValidateRegex(regex);
8478 if (!is_valid_) {
8479 // No need to calculate the full pattern when the regex is invalid.
8480 return;
8481 }
8482
8483 const size_t len = strlen(regex);
8484 // Reserves enough bytes to hold the regular expression used for a
8485 // full match: we need space to prepend a '^', append a '$', and
8486 // terminate the string with '\0'.
8487 char* buffer = static_cast<char*>(malloc(len + 3));
8488 full_pattern_ = buffer;
8489
8490 if (*regex != '^')
8491 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8492
8493 // We don't use snprintf or strncpy, as they trigger a warning when
8494 // compiled with VC++ 8.0.
8495 memcpy(buffer, regex, len);
8496 buffer += len;
8497
8498 if (len == 0 || regex[len - 1] != '$')
8499 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8500
8501 *buffer = '\0';
8502 }
8503
8504 #endif // GTEST_USES_POSIX_RE
8505
8506 const char kUnknownFile[] = "unknown file";
8507
8508 // Formats a source file path and a line number as they would appear
8509 // in an error message from the compiler used to compile this code.
8510 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8511 const std::string file_name(file == NULL ? kUnknownFile : file);
8512
8513 if (line < 0) {
8514 return file_name + ":";
8515 }
8516 #ifdef _MSC_VER
8517 return file_name + "(" + StreamableToString(line) + "):";
8518 #else
8519 return file_name + ":" + StreamableToString(line) + ":";
8520 #endif // _MSC_VER
8521 }
8522
8523 // Formats a file location for compiler-independent XML output.
8524 // Although this function is not platform dependent, we put it next to
8525 // FormatFileLocation in order to contrast the two functions.
8526 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8527 // to the file location it produces, unlike FormatFileLocation().
8528 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
8529 int line) {
8530 const std::string file_name(file == NULL ? kUnknownFile : file);
8531
8532 if (line < 0)
8533 return file_name;
8534 else
8535 return file_name + ":" + StreamableToString(line);
8536 }
8537
8538 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8539 : severity_(severity) {
8540 const char* const marker =
8541 severity == GTEST_INFO
8542 ? "[ INFO ]"
8543 : severity == GTEST_WARNING
8544 ? "[WARNING]"
8545 : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8546 GetStream() << ::std::endl
8547 << marker << " " << FormatFileLocation(file, line).c_str()
8548 << ": ";
8549 }
8550
8551 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8552 GTestLog::~GTestLog() {
8553 GetStream() << ::std::endl;
8554 if (severity_ == GTEST_FATAL) {
8555 fflush(stderr);
8556 posix::Abort();
8557 }
8558 }
8559 // Disable Microsoft deprecation warnings for POSIX functions called from
8560 // this class (creat, dup, dup2, and close)
8561 #ifdef _MSC_VER
8562 # pragma warning(push)
8563 # pragma warning(disable : 4996)
8564 #endif // _MSC_VER
8565
8566 #if GTEST_HAS_STREAM_REDIRECTION
8567
8568 // Object that captures an output stream (stdout/stderr).
8569 class CapturedStream {
8570 public:
8571 // The ctor redirects the stream to a temporary file.
8572 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8573 # if GTEST_OS_WINDOWS
8574 char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
8575 char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
8576
8577 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8578 const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
8579 0, // Generate unique file name.
8580 temp_file_path);
8581 GTEST_CHECK_(success != 0)
8582 << "Unable to create a temporary file in " << temp_dir_path;
8583 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8584 GTEST_CHECK_(captured_fd != -1)
8585 << "Unable to open temporary file " << temp_file_path;
8586 filename_ = temp_file_path;
8587 # else
8588 // There's no guarantee that a test has write access to the current
8589 // directory, so we create the temporary file in the /tmp directory
8590 // instead. We use /tmp on most systems, and /sdcard on Android.
8591 // That's because Android doesn't have /tmp.
8592 # if GTEST_OS_LINUX_ANDROID
8593 // Note: Android applications are expected to call the framework's
8594 // Context.getExternalStorageDirectory() method through JNI to get
8595 // the location of the world-writable SD Card directory. However,
8596 // this requires a Context handle, which cannot be retrieved
8597 // globally from native code. Doing so also precludes running the
8598 // code as part of a regular standalone executable, which doesn't
8599 // run in a Dalvik process (e.g. when running it through 'adb shell').
8600 //
8601 // The location /sdcard is directly accessible from native code
8602 // and is the only location (unofficially) supported by the Android
8603 // team. It's generally a symlink to the real SD Card mount point
8604 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8605 // other OEM-customized locations. Never rely on these, and always
8606 // use /sdcard.
8607 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8608 # else
8609 char name_template[] = "/tmp/captured_stream.XXXXXX";
8610 # endif // GTEST_OS_LINUX_ANDROID
8611 const int captured_fd = mkstemp(name_template);
8612 filename_ = name_template;
8613 # endif // GTEST_OS_WINDOWS
8614 fflush(NULL);
8615 dup2(captured_fd, fd_);
8616 close(captured_fd);
8617 }
8618
8619 ~CapturedStream() { remove(filename_.c_str()); }
8620
8621 std::string GetCapturedString() {
8622 if (uncaptured_fd_ != -1) {
8623 // Restores the original stream.
8624 fflush(NULL);
8625 dup2(uncaptured_fd_, fd_);
8626 close(uncaptured_fd_);
8627 uncaptured_fd_ = -1;
8628 }
8629
8630 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8631 const std::string content = ReadEntireFile(file);
8632 posix::FClose(file);
8633 return content;
8634 }
8635
8636 private:
8637 // Reads the entire content of a file as an std::string.
8638 static std::string ReadEntireFile(FILE* file);
8639
8640 // Returns the size (in bytes) of a file.
8641 static size_t GetFileSize(FILE* file);
8642
8643 const int fd_; // A stream to capture.
8644 int uncaptured_fd_;
8645 // Name of the temporary file holding the stderr output.
8646 ::std::string filename_;
8647
8648 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8649 };
8650
8651 // Returns the size (in bytes) of a file.
8652 size_t CapturedStream::GetFileSize(FILE* file) {
8653 fseek(file, 0, SEEK_END);
8654 return static_cast<size_t>(ftell(file));
8655 }
8656
8657 // Reads the entire content of a file as a string.
8658 std::string CapturedStream::ReadEntireFile(FILE* file) {
8659 const size_t file_size = GetFileSize(file);
8660 char* const buffer = new char[file_size];
8661
8662 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8663 size_t bytes_read = 0; // # of bytes read so far
8664
8665 fseek(file, 0, SEEK_SET);
8666
8667 // Keeps reading the file until we cannot read further or the
8668 // pre-determined file size is reached.
8669 do {
8670 bytes_last_read =
8671 fread(buffer + bytes_read, 1, file_size - bytes_read, file);
8672 bytes_read += bytes_last_read;
8673 } while (bytes_last_read > 0 && bytes_read < file_size);
8674
8675 const std::string content(buffer, bytes_read);
8676 delete[] buffer;
8677
8678 return content;
8679 }
8680
8681 # ifdef _MSC_VER
8682 # pragma warning(pop)
8683 # endif // _MSC_VER
8684
8685 static CapturedStream* g_captured_stderr = NULL;
8686 static CapturedStream* g_captured_stdout = NULL;
8687
8688 // Starts capturing an output stream (stdout/stderr).
8689 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8690 if (*stream != NULL) {
8691 GTEST_LOG_(FATAL) << "Only one " << stream_name
8692 << " capturer can exist at a time.";
8693 }
8694 *stream = new CapturedStream(fd);
8695 }
8696
8697 // Stops capturing the output stream and returns the captured string.
8698 std::string GetCapturedStream(CapturedStream** captured_stream) {
8699 const std::string content = (*captured_stream)->GetCapturedString();
8700
8701 delete *captured_stream;
8702 *captured_stream = NULL;
8703
8704 return content;
8705 }
8706
8707 // Starts capturing stdout.
8708 void CaptureStdout() {
8709 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8710 }
8711
8712 // Starts capturing stderr.
8713 void CaptureStderr() {
8714 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8715 }
8716
8717 // Stops capturing stdout and returns the captured string.
8718 std::string GetCapturedStdout() {
8719 return GetCapturedStream(&g_captured_stdout);
8720 }
8721
8722 // Stops capturing stderr and returns the captured string.
8723 std::string GetCapturedStderr() {
8724 return GetCapturedStream(&g_captured_stderr);
8725 }
8726
8727 #endif // GTEST_HAS_STREAM_REDIRECTION
8728
8729 #if GTEST_HAS_DEATH_TEST
8730
8731 // A copy of all command line arguments. Set by InitGoogleTest().
8732 ::std::vector<testing::internal::string> g_argvs;
8733
8734 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8735 NULL; // Owned.
8736
8737 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8738 if (g_injected_test_argvs != argvs) delete g_injected_test_argvs;
8739 g_injected_test_argvs = argvs;
8740 }
8741
8742 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8743 if (g_injected_test_argvs != NULL) {
8744 return *g_injected_test_argvs;
8745 }
8746 return g_argvs;
8747 }
8748 #endif // GTEST_HAS_DEATH_TEST
8749
8750 #if GTEST_OS_WINDOWS_MOBILE
8751 namespace posix {
8752 void Abort() {
8753 DebugBreak();
8754 TerminateProcess(GetCurrentProcess(), 1);
8755 }
8756 } // namespace posix
8757 #endif // GTEST_OS_WINDOWS_MOBILE
8758
8759 // Returns the name of the environment variable corresponding to the
8760 // given flag. For example, FlagToEnvVar("foo") will return
8761 // "GTEST_FOO" in the open-source version.
8762 static std::string FlagToEnvVar(const char* flag) {
8763 const std::string full_flag =
8764 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8765
8766 Message env_var;
8767 for (size_t i = 0; i != full_flag.length(); i++) {
8768 env_var << ToUpper(full_flag.c_str()[i]);
8769 }
8770
8771 return env_var.GetString();
8772 }
8773
8774 // Parses 'str' for a 32-bit signed integer. If successful, writes
8775 // the result to *value and returns true; otherwise leaves *value
8776 // unchanged and returns false.
8777 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8778 // Parses the environment variable as a decimal integer.
8779 char* end = NULL;
8780 const long long_value = strtol(str, &end, 10); // NOLINT
8781
8782 // Has strtol() consumed all characters in the string?
8783 if (*end != '\0') {
8784 // No - an invalid character was encountered.
8785 Message msg;
8786 msg << "WARNING: " << src_text
8787 << " is expected to be a 32-bit integer, but actually"
8788 << " has value \"" << str << "\".\n";
8789 printf("%s", msg.GetString().c_str());
8790 fflush(stdout);
8791 return false;
8792 }
8793
8794 // Is the parsed value in the range of an Int32?
8795 const Int32 result = static_cast<Int32>(long_value);
8796 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8797 // The parsed value overflows as a long. (strtol() returns
8798 // LONG_MAX or LONG_MIN when the input overflows.)
8799 result != long_value
8800 // The parsed value overflows as an Int32.
8801 ) {
8802 Message msg;
8803 msg << "WARNING: " << src_text
8804 << " is expected to be a 32-bit integer, but actually"
8805 << " has value " << str << ", which overflows.\n";
8806 printf("%s", msg.GetString().c_str());
8807 fflush(stdout);
8808 return false;
8809 }
8810
8811 *value = result;
8812 return true;
8813 }
8814
8815 // Reads and returns the Boolean environment variable corresponding to
8816 // the given flag; if it's not set, returns default_value.
8817 //
8818 // The value is considered true iff it's not "0".
8819 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8820 const std::string env_var = FlagToEnvVar(flag);
8821 const char* const string_value = posix::GetEnv(env_var.c_str());
8822 return string_value == NULL ? default_value : strcmp(string_value, "0") != 0;
8823 }
8824
8825 // Reads and returns a 32-bit integer stored in the environment
8826 // variable corresponding to the given flag; if it isn't set or
8827 // doesn't represent a valid 32-bit integer, returns default_value.
8828 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8829 const std::string env_var = FlagToEnvVar(flag);
8830 const char* const string_value = posix::GetEnv(env_var.c_str());
8831 if (string_value == NULL) {
8832 // The environment variable is not set.
8833 return default_value;
8834 }
8835
8836 Int32 result = default_value;
8837 if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
8838 &result)) {
8839 printf("The default value %s is used.\n",
8840 (Message() << default_value).GetString().c_str());
8841 fflush(stdout);
8842 return default_value;
8843 }
8844
8845 return result;
8846 }
8847
8848 // Reads and returns the string environment variable corresponding to
8849 // the given flag; if it's not set, returns default_value.
8850 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8851 const std::string env_var = FlagToEnvVar(flag);
8852 const char* const value = posix::GetEnv(env_var.c_str());
8853 return value == NULL ? default_value : value;
8854 }
8855
8856 } // namespace internal
8857 } // namespace testing
8858 // Copyright 2007, Google Inc.
8859 // All rights reserved.
8860 //
8861 // Redistribution and use in source and binary forms, with or without
8862 // modification, are permitted provided that the following conditions are
8863 // met:
8864 //
8865 // * Redistributions of source code must retain the above copyright
8866 // notice, this list of conditions and the following disclaimer.
8867 // * Redistributions in binary form must reproduce the above
8868 // copyright notice, this list of conditions and the following disclaimer
8869 // in the documentation and/or other materials provided with the
8870 // distribution.
8871 // * Neither the name of Google Inc. nor the names of its
8872 // contributors may be used to endorse or promote products derived from
8873 // this software without specific prior written permission.
8874 //
8875 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8876 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8877 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8878 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8879 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8880 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8881 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8882 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8883 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8884 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8885 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8886 //
8887 // Author: wan@google.com (Zhanyong Wan)
8888
8889 // Google Test - The Google C++ Testing Framework
8890 //
8891 // This file implements a universal value printer that can print a
8892 // value of any type T:
8893 //
8894 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8895 //
8896 // It uses the << operator when possible, and prints the bytes in the
8897 // object otherwise. A user can override its behavior for a class
8898 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8899 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8900 // defines Foo.
8901
8902 #include <ctype.h>
8903 #include <stdio.h>
8904
8905 #include <ostream> // NOLINT
8906 #include <string>
8907
8908 namespace testing {
8909
8910 namespace {
8911
8912 using ::std::ostream;
8913
8914 // Prints a segment of bytes in the given object.
8915 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8916 size_t count, ostream* os) {
8917 char text[5] = "";
8918 for (size_t i = 0; i != count; i++) {
8919 const size_t j = start + i;
8920 if (i != 0) {
8921 // Organizes the bytes into groups of 2 for easy parsing by
8922 // human.
8923 if ((j % 2) == 0)
8924 *os << ' ';
8925 else
8926 *os << '-';
8927 }
8928 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
8929 *os << text;
8930 }
8931 }
8932
8933 // Prints the bytes in the given value to the given ostream.
8934 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
8935 ostream* os) {
8936 // Tells the user how big the object is.
8937 *os << count << "-byte object <";
8938
8939 const size_t kThreshold = 132;
8940 const size_t kChunkSize = 64;
8941 // If the object size is bigger than kThreshold, we'll have to omit
8942 // some details by printing only the first and the last kChunkSize
8943 // bytes.
8944 // TODO(wan): let the user control the threshold using a flag.
8945 if (count < kThreshold) {
8946 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
8947 } else {
8948 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
8949 *os << " ... ";
8950 // Rounds up to 2-byte boundary.
8951 const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
8952 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
8953 }
8954 *os << ">";
8955 }
8956
8957 } // namespace
8958
8959 namespace internal2 {
8960
8961 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8962 // given object. The delegation simplifies the implementation, which
8963 // uses the << operator and thus is easier done outside of the
8964 // ::testing::internal namespace, which contains a << operator that
8965 // sometimes conflicts with the one in STL.
8966 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
8967 ostream* os) {
8968 PrintBytesInObjectToImpl(obj_bytes, count, os);
8969 }
8970
8971 } // namespace internal2
8972
8973 namespace internal {
8974
8975 // Depending on the value of a char (or wchar_t), we print it in one
8976 // of three formats:
8977 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8978 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
8979 // - as a special escape sequence (e.g. '\r', '\n').
8980 enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
8981
8982 // Returns true if c is a printable ASCII character. We test the
8983 // value of c directly instead of calling isprint(), which is buggy on
8984 // Windows Mobile.
8985 inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; }
8986
8987 // Prints a wide or narrow char c as a character literal without the
8988 // quotes, escaping it when necessary; returns how c was formatted.
8989 // The template argument UnsignedChar is the unsigned version of Char,
8990 // which is the type of c.
8991 template <typename UnsignedChar, typename Char>
8992 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
8993 switch (static_cast<wchar_t>(c)) {
8994 case L'\0':
8995 *os << "\\0";
8996 break;
8997 case L'\'':
8998 *os << "\\'";
8999 break;
9000 case L'\\':
9001 *os << "\\\\";
9002 break;
9003 case L'\a':
9004 *os << "\\a";
9005 break;
9006 case L'\b':
9007 *os << "\\b";
9008 break;
9009 case L'\f':
9010 *os << "\\f";
9011 break;
9012 case L'\n':
9013 *os << "\\n";
9014 break;
9015 case L'\r':
9016 *os << "\\r";
9017 break;
9018 case L'\t':
9019 *os << "\\t";
9020 break;
9021 case L'\v':
9022 *os << "\\v";
9023 break;
9024 default:
9025 if (IsPrintableAscii(c)) {
9026 *os << static_cast<char>(c);
9027 return kAsIs;
9028 } else {
9029 *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9030 return kHexEscape;
9031 }
9032 }
9033 return kSpecialEscape;
9034 }
9035
9036 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9037 // necessary; returns how c was formatted.
9038 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9039 switch (c) {
9040 case L'\'':
9041 *os << "'";
9042 return kAsIs;
9043 case L'"':
9044 *os << "\\\"";
9045 return kSpecialEscape;
9046 default:
9047 return PrintAsCharLiteralTo<wchar_t>(c, os);
9048 }
9049 }
9050
9051 // Prints a char c as if it's part of a string literal, escaping it when
9052 // necessary; returns how c was formatted.
9053 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9054 return PrintAsStringLiteralTo(
9055 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9056 }
9057
9058 // Prints a wide or narrow character c and its code. '\0' is printed
9059 // as "'\\0'", other unprintable characters are also properly escaped
9060 // using the standard C++ escape sequence. The template argument
9061 // UnsignedChar is the unsigned version of Char, which is the type of c.
9062 template <typename UnsignedChar, typename Char>
9063 void PrintCharAndCodeTo(Char c, ostream* os) {
9064 // First, print c as a literal in the most readable form we can find.
9065 *os << ((sizeof(c) > 1) ? "L'" : "'");
9066 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9067 *os << "'";
9068
9069 // To aid user debugging, we also print c's code in decimal, unless
9070 // it's 0 (in which case c was printed as '\\0', making the code
9071 // obvious).
9072 if (c == 0) return;
9073 *os << " (" << static_cast<int>(c);
9074
9075 // For more convenience, we print c's code again in hexidecimal,
9076 // unless c was already printed in the form '\x##' or the code is in
9077 // [1, 9].
9078 if (format == kHexEscape || (1 <= c && c <= 9)) {
9079 // Do nothing.
9080 } else {
9081 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
9082 }
9083 *os << ")";
9084 }
9085
9086 void PrintTo(unsigned char c, ::std::ostream* os) {
9087 PrintCharAndCodeTo<unsigned char>(c, os);
9088 }
9089 void PrintTo(signed char c, ::std::ostream* os) {
9090 PrintCharAndCodeTo<unsigned char>(c, os);
9091 }
9092
9093 // Prints a wchar_t as a symbol if it is printable or as its internal
9094 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9095 void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); }
9096
9097 // Prints the given array of characters to the ostream. CharType must be either
9098 // char or wchar_t.
9099 // The array starts at begin, the length is len, it may include '\0' characters
9100 // and may not be NUL-terminated.
9101 template <typename CharType>
9102 static void PrintCharsAsStringTo(const CharType* begin, size_t len,
9103 ostream* os) {
9104 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9105 *os << kQuoteBegin;
9106 bool is_previous_hex = false;
9107 for (size_t index = 0; index < len; ++index) {
9108 const CharType cur = begin[index];
9109 if (is_previous_hex && IsXDigit(cur)) {
9110 // Previous character is of '\x..' form and this character can be
9111 // interpreted as another hexadecimal digit in its number. Break string to
9112 // disambiguate.
9113 *os << "\" " << kQuoteBegin;
9114 }
9115 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9116 }
9117 *os << "\"";
9118 }
9119
9120 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9121 // 'begin'. CharType must be either char or wchar_t.
9122 template <typename CharType>
9123 static void UniversalPrintCharArray(const CharType* begin, size_t len,
9124 ostream* os) {
9125 // The code
9126 // const char kFoo[] = "foo";
9127 // generates an array of 4, not 3, elements, with the last one being '\0'.
9128 //
9129 // Therefore when printing a char array, we don't print the last element if
9130 // it's '\0', such that the output matches the string literal as it's
9131 // written in the source code.
9132 if (len > 0 && begin[len - 1] == '\0') {
9133 PrintCharsAsStringTo(begin, len - 1, os);
9134 return;
9135 }
9136
9137 // If, however, the last element in the array is not '\0', e.g.
9138 // const char kFoo[] = { 'f', 'o', 'o' };
9139 // we must print the entire array. We also print a message to indicate
9140 // that the array is not NUL-terminated.
9141 PrintCharsAsStringTo(begin, len, os);
9142 *os << " (no terminating NUL)";
9143 }
9144
9145 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9146 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9147 UniversalPrintCharArray(begin, len, os);
9148 }
9149
9150 // Prints a (const) wchar_t array of 'len' elements, starting at address
9151 // 'begin'.
9152 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9153 UniversalPrintCharArray(begin, len, os);
9154 }
9155
9156 // Prints the given C string to the ostream.
9157 void PrintTo(const char* s, ostream* os) {
9158 if (s == NULL) {
9159 *os << "NULL";
9160 } else {
9161 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9162 PrintCharsAsStringTo(s, strlen(s), os);
9163 }
9164 }
9165
9166 // MSVC compiler can be configured to define whar_t as a typedef
9167 // of unsigned short. Defining an overload for const wchar_t* in that case
9168 // would cause pointers to unsigned shorts be printed as wide strings,
9169 // possibly accessing more memory than intended and causing invalid
9170 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9171 // wchar_t is implemented as a native type.
9172 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9173 // Prints the given wide C string to the ostream.
9174 void PrintTo(const wchar_t* s, ostream* os) {
9175 if (s == NULL) {
9176 *os << "NULL";
9177 } else {
9178 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9179 PrintCharsAsStringTo(s, wcslen(s), os);
9180 }
9181 }
9182 #endif // wchar_t is native
9183
9184 // Prints a ::string object.
9185 #if GTEST_HAS_GLOBAL_STRING
9186 void PrintStringTo(const ::string& s, ostream* os) {
9187 PrintCharsAsStringTo(s.data(), s.size(), os);
9188 }
9189 #endif // GTEST_HAS_GLOBAL_STRING
9190
9191 void PrintStringTo(const ::std::string& s, ostream* os) {
9192 PrintCharsAsStringTo(s.data(), s.size(), os);
9193 }
9194
9195 // Prints a ::wstring object.
9196 #if GTEST_HAS_GLOBAL_WSTRING
9197 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9198 PrintCharsAsStringTo(s.data(), s.size(), os);
9199 }
9200 #endif // GTEST_HAS_GLOBAL_WSTRING
9201
9202 #if GTEST_HAS_STD_WSTRING
9203 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
9204 PrintCharsAsStringTo(s.data(), s.size(), os);
9205 }
9206 #endif // GTEST_HAS_STD_WSTRING
9207
9208 } // namespace internal
9209
9210 } // namespace testing
9211 // Copyright 2008, Google Inc.
9212 // All rights reserved.
9213 //
9214 // Redistribution and use in source and binary forms, with or without
9215 // modification, are permitted provided that the following conditions are
9216 // met:
9217 //
9218 // * Redistributions of source code must retain the above copyright
9219 // notice, this list of conditions and the following disclaimer.
9220 // * Redistributions in binary form must reproduce the above
9221 // copyright notice, this list of conditions and the following disclaimer
9222 // in the documentation and/or other materials provided with the
9223 // distribution.
9224 // * Neither the name of Google Inc. nor the names of its
9225 // contributors may be used to endorse or promote products derived from
9226 // this software without specific prior written permission.
9227 //
9228 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9229 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9230 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9231 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9232 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9233 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9234 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9235 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9236 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9237 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9238 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9239 //
9240 // Author: mheule@google.com (Markus Heule)
9241 //
9242 // The Google C++ Testing Framework (Google Test)
9243
9244 // Indicates that this translation unit is part of Google Test's
9245 // implementation. It must come before gtest-internal-inl.h is
9246 // included, or there will be a compiler error. This trick is to
9247 // prevent a user from accidentally including gtest-internal-inl.h in
9248 // his code.
9249 #define GTEST_IMPLEMENTATION_ 1
9250 #undef GTEST_IMPLEMENTATION_
9251
9252 namespace testing {
9253
9254 using internal::GetUnitTestImpl;
9255
9256 // Gets the summary of the failure message by omitting the stack trace
9257 // in it.
9258 std::string TestPartResult::ExtractSummary(const char* message) {
9259 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9260 return stack_trace == NULL ? message : std::string(message, stack_trace);
9261 }
9262
9263 // Prints a TestPartResult object.
9264 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9265 return os << result.file_name() << ":" << result.line_number() << ": "
9266 << (result.type() == TestPartResult::kSuccess
9267 ? "Success"
9268 : result.type() == TestPartResult::kFatalFailure
9269 ? "Fatal failure"
9270 : "Non-fatal failure")
9271 << ":\n"
9272 << result.message() << std::endl;
9273 }
9274
9275 // Appends a TestPartResult to the array.
9276 void TestPartResultArray::Append(const TestPartResult& result) {
9277 array_.push_back(result);
9278 }
9279
9280 // Returns the TestPartResult at the given index (0-based).
9281 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9282 if (index < 0 || index >= size()) {
9283 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9284 internal::posix::Abort();
9285 }
9286
9287 return array_[index];
9288 }
9289
9290 // Returns the number of TestPartResult objects in the array.
9291 int TestPartResultArray::size() const {
9292 return static_cast<int>(array_.size());
9293 }
9294
9295 namespace internal {
9296
9297 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9298 : has_new_fatal_failure_(false),
9299 original_reporter_(
9300 GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
9301 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9302 }
9303
9304 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9305 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9306 original_reporter_);
9307 }
9308
9309 void HasNewFatalFailureHelper::ReportTestPartResult(
9310 const TestPartResult& result) {
9311 if (result.fatally_failed()) has_new_fatal_failure_ = true;
9312 original_reporter_->ReportTestPartResult(result);
9313 }
9314
9315 } // namespace internal
9316
9317 } // namespace testing
9318 // Copyright 2008 Google Inc.
9319 // All Rights Reserved.
9320 //
9321 // Redistribution and use in source and binary forms, with or without
9322 // modification, are permitted provided that the following conditions are
9323 // met:
9324 //
9325 // * Redistributions of source code must retain the above copyright
9326 // notice, this list of conditions and the following disclaimer.
9327 // * Redistributions in binary form must reproduce the above
9328 // copyright notice, this list of conditions and the following disclaimer
9329 // in the documentation and/or other materials provided with the
9330 // distribution.
9331 // * Neither the name of Google Inc. nor the names of its
9332 // contributors may be used to endorse or promote products derived from
9333 // this software without specific prior written permission.
9334 //
9335 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9336 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9337 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9338 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9339 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9340 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9341 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9342 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9343 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9344 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9345 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9346 //
9347 // Author: wan@google.com (Zhanyong Wan)
9348
9349 namespace testing {
9350 namespace internal {
9351
9352 #if GTEST_HAS_TYPED_TEST_P
9353
9354 // Skips to the first non-space char in str. Returns an empty string if str
9355 // contains only whitespace characters.
9356 static const char* SkipSpaces(const char* str) {
9357 while (IsSpace(*str)) str++;
9358 return str;
9359 }
9360
9361 // Verifies that registered_tests match the test names in
9362 // defined_test_names_; returns registered_tests if successful, or
9363 // aborts the program otherwise.
9364 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9365 const char* file, int line, const char* registered_tests) {
9366 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9367 registered_ = true;
9368
9369 // Skip initial whitespace in registered_tests since some
9370 // preprocessors prefix stringizied literals with whitespace.
9371 registered_tests = SkipSpaces(registered_tests);
9372
9373 Message errors;
9374 ::std::set<std::string> tests;
9375 for (const char* names = registered_tests; names != NULL;
9376 names = SkipComma(names)) {
9377 const std::string name = GetPrefixUntilComma(names);
9378 if (tests.count(name) != 0) {
9379 errors << "Test " << name << " is listed more than once.\n";
9380 continue;
9381 }
9382
9383 bool found = false;
9384 for (DefinedTestIter it = defined_test_names_.begin();
9385 it != defined_test_names_.end(); ++it) {
9386 if (name == *it) {
9387 found = true;
9388 break;
9389 }
9390 }
9391
9392 if (found) {
9393 tests.insert(name);
9394 } else {
9395 errors << "No test named " << name
9396 << " can be found in this test case.\n";
9397 }
9398 }
9399
9400 for (DefinedTestIter it = defined_test_names_.begin();
9401 it != defined_test_names_.end(); ++it) {
9402 if (tests.count(*it) == 0) {
9403 errors << "You forgot to list test " << *it << ".\n";
9404 }
9405 }
9406
9407 const std::string& errors_str = errors.GetString();
9408 if (errors_str != "") {
9409 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9410 errors_str.c_str());
9411 fflush(stderr);
9412 posix::Abort();
9413 }
9414
9415 return registered_tests;
9416 }
9417
9418 #endif // GTEST_HAS_TYPED_TEST_P
9419
9420 } // namespace internal
9421 } // namespace testing
9422 // Copyright 2008, Google Inc.
9423 // All rights reserved.
9424 //
9425 // Redistribution and use in source and binary forms, with or without
9426 // modification, are permitted provided that the following conditions are
9427 // met:
9428 //
9429 // * Redistributions of source code must retain the above copyright
9430 // notice, this list of conditions and the following disclaimer.
9431 // * Redistributions in binary form must reproduce the above
9432 // copyright notice, this list of conditions and the following disclaimer
9433 // in the documentation and/or other materials provided with the
9434 // distribution.
9435 // * Neither the name of Google Inc. nor the names of its
9436 // contributors may be used to endorse or promote products derived from
9437 // this software without specific prior written permission.
9438 //
9439 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9440 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9441 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9442 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9443 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9444 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9445 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9446 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9447 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9448 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9449 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9450 //
9451 // Author: wan@google.com (Zhanyong Wan)
9452 //
9453 // Google C++ Mocking Framework (Google Mock)
9454 //
9455 // This file #includes all Google Mock implementation .cc files. The
9456 // purpose is to allow a user to build Google Mock by compiling this
9457 // file alone.
9458
9459 // This line ensures that gmock.h can be compiled on its own, even
9460 // when it's fused.
9461 #include "gmock/gmock.h"
9462
9463 // The following lines pull in the real gmock *.cc files.
9464 // Copyright 2007, Google Inc.
9465 // All rights reserved.
9466 //
9467 // Redistribution and use in source and binary forms, with or without
9468 // modification, are permitted provided that the following conditions are
9469 // met:
9470 //
9471 // * Redistributions of source code must retain the above copyright
9472 // notice, this list of conditions and the following disclaimer.
9473 // * Redistributions in binary form must reproduce the above
9474 // copyright notice, this list of conditions and the following disclaimer
9475 // in the documentation and/or other materials provided with the
9476 // distribution.
9477 // * Neither the name of Google Inc. nor the names of its
9478 // contributors may be used to endorse or promote products derived from
9479 // this software without specific prior written permission.
9480 //
9481 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9482 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9483 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9484 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9485 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9486 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9487 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9488 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9489 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9490 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9491 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9492 //
9493 // Author: wan@google.com (Zhanyong Wan)
9494
9495 // Google Mock - a framework for writing C++ mock classes.
9496 //
9497 // This file implements cardinalities.
9498
9499 #include <limits.h>
9500
9501 #include <ostream> // NOLINT
9502 #include <sstream>
9503 #include <string>
9504
9505 namespace testing {
9506
9507 namespace {
9508
9509 // Implements the Between(m, n) cardinality.
9510 class BetweenCardinalityImpl : public CardinalityInterface {
9511 public:
9512 BetweenCardinalityImpl(int min, int max)
9513 : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
9514 std::stringstream ss;
9515 if (min < 0) {
9516 ss << "The invocation lower bound must be >= 0, "
9517 << "but is actually " << min << ".";
9518 internal::Expect(false, __FILE__, __LINE__, ss.str());
9519 } else if (max < 0) {
9520 ss << "The invocation upper bound must be >= 0, "
9521 << "but is actually " << max << ".";
9522 internal::Expect(false, __FILE__, __LINE__, ss.str());
9523 } else if (min > max) {
9524 ss << "The invocation upper bound (" << max
9525 << ") must be >= the invocation lower bound (" << min << ").";
9526 internal::Expect(false, __FILE__, __LINE__, ss.str());
9527 }
9528 }
9529
9530 // Conservative estimate on the lower/upper bound of the number of
9531 // calls allowed.
9532 virtual int ConservativeLowerBound() const { return min_; }
9533 virtual int ConservativeUpperBound() const { return max_; }
9534
9535 virtual bool IsSatisfiedByCallCount(int call_count) const {
9536 return min_ <= call_count && call_count <= max_;
9537 }
9538
9539 virtual bool IsSaturatedByCallCount(int call_count) const {
9540 return call_count >= max_;
9541 }
9542
9543 virtual void DescribeTo(::std::ostream* os) const;
9544
9545 private:
9546 const int min_;
9547 const int max_;
9548
9549 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
9550 };
9551
9552 // Formats "n times" in a human-friendly way.
9553 inline internal::string FormatTimes(int n) {
9554 if (n == 1) {
9555 return "once";
9556 } else if (n == 2) {
9557 return "twice";
9558 } else {
9559 std::stringstream ss;
9560 ss << n << " times";
9561 return ss.str();
9562 }
9563 }
9564
9565 // Describes the Between(m, n) cardinality in human-friendly text.
9566 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
9567 if (min_ == 0) {
9568 if (max_ == 0) {
9569 *os << "never called";
9570 } else if (max_ == INT_MAX) {
9571 *os << "called any number of times";
9572 } else {
9573 *os << "called at most " << FormatTimes(max_);
9574 }
9575 } else if (min_ == max_) {
9576 *os << "called " << FormatTimes(min_);
9577 } else if (max_ == INT_MAX) {
9578 *os << "called at least " << FormatTimes(min_);
9579 } else {
9580 // 0 < min_ < max_ < INT_MAX
9581 *os << "called between " << min_ << " and " << max_ << " times";
9582 }
9583 }
9584
9585 } // Unnamed namespace
9586
9587 // Describes the given call count to an ostream.
9588 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
9589 ::std::ostream* os) {
9590 if (actual_call_count > 0) {
9591 *os << "called " << FormatTimes(actual_call_count);
9592 } else {
9593 *os << "never called";
9594 }
9595 }
9596
9597 // Creates a cardinality that allows at least n calls.
9598 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
9599
9600 // Creates a cardinality that allows at most n calls.
9601 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
9602
9603 // Creates a cardinality that allows any number of calls.
9604 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
9605
9606 // Creates a cardinality that allows between min and max calls.
9607 GTEST_API_ Cardinality Between(int min, int max) {
9608 return Cardinality(new BetweenCardinalityImpl(min, max));
9609 }
9610
9611 // Creates a cardinality that allows exactly n calls.
9612 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
9613
9614 } // namespace testing
9615 // Copyright 2007, Google Inc.
9616 // All rights reserved.
9617 //
9618 // Redistribution and use in source and binary forms, with or without
9619 // modification, are permitted provided that the following conditions are
9620 // met:
9621 //
9622 // * Redistributions of source code must retain the above copyright
9623 // notice, this list of conditions and the following disclaimer.
9624 // * Redistributions in binary form must reproduce the above
9625 // copyright notice, this list of conditions and the following disclaimer
9626 // in the documentation and/or other materials provided with the
9627 // distribution.
9628 // * Neither the name of Google Inc. nor the names of its
9629 // contributors may be used to endorse or promote products derived from
9630 // this software without specific prior written permission.
9631 //
9632 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9633 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9634 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9635 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9636 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9637 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9638 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9639 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9640 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9641 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9642 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9643 //
9644 // Author: wan@google.com (Zhanyong Wan)
9645
9646 // Google Mock - a framework for writing C++ mock classes.
9647 //
9648 // This file defines some utilities useful for implementing Google
9649 // Mock. They are subject to change without notice, so please DO NOT
9650 // USE THEM IN USER CODE.
9651
9652 #include <ctype.h>
9653
9654 #include <ostream> // NOLINT
9655 #include <string>
9656
9657 namespace testing {
9658 namespace internal {
9659
9660 // Converts an identifier name to a space-separated list of lower-case
9661 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9662 // treated as one word. For example, both "FooBar123" and
9663 // "foo_bar_123" are converted to "foo bar 123".
9664 GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
9665 string result;
9666 char prev_char = '\0';
9667 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
9668 // We don't care about the current locale as the input is
9669 // guaranteed to be a valid C++ identifier name.
9670 const bool starts_new_word = IsUpper(*p) ||
9671 (!IsAlpha(prev_char) && IsLower(*p)) ||
9672 (!IsDigit(prev_char) && IsDigit(*p));
9673
9674 if (IsAlNum(*p)) {
9675 if (starts_new_word && result != "") result += ' ';
9676 result += ToLower(*p);
9677 }
9678 }
9679 return result;
9680 }
9681
9682 // This class reports Google Mock failures as Google Test failures. A
9683 // user can define another class in a similar fashion if he intends to
9684 // use Google Mock with a testing framework other than Google Test.
9685 class GoogleTestFailureReporter : public FailureReporterInterface {
9686 public:
9687 virtual void ReportFailure(FailureType type, const char* file, int line,
9688 const string& message) {
9689 AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
9690 : TestPartResult::kNonFatalFailure,
9691 file, line, message.c_str()) = Message();
9692 if (type == kFatal) {
9693 posix::Abort();
9694 }
9695 }
9696 };
9697
9698 // Returns the global failure reporter. Will create a
9699 // GoogleTestFailureReporter and return it the first time called.
9700 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
9701 // Points to the global failure reporter used by Google Mock. gcc
9702 // guarantees that the following use of failure_reporter is
9703 // thread-safe. We may need to add additional synchronization to
9704 // protect failure_reporter if we port Google Mock to other
9705 // compilers.
9706 static FailureReporterInterface* const failure_reporter =
9707 new GoogleTestFailureReporter();
9708 return failure_reporter;
9709 }
9710
9711 // Protects global resources (stdout in particular) used by Log().
9712 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
9713
9714 // Returns true iff a log with the given severity is visible according
9715 // to the --gmock_verbose flag.
9716 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
9717 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
9718 // Always show the log if --gmock_verbose=info.
9719 return true;
9720 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
9721 // Always hide it if --gmock_verbose=error.
9722 return false;
9723 } else {
9724 // If --gmock_verbose is neither "info" nor "error", we treat it
9725 // as "warning" (its default value).
9726 return severity == kWarning;
9727 }
9728 }
9729
9730 // Prints the given message to stdout iff 'severity' >= the level
9731 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
9732 // 0, also prints the stack trace excluding the top
9733 // stack_frames_to_skip frames. In opt mode, any positive
9734 // stack_frames_to_skip is treated as 0, since we don't know which
9735 // function calls will be inlined by the compiler and need to be
9736 // conservative.
9737 GTEST_API_ void Log(LogSeverity severity, const string& message,
9738 int stack_frames_to_skip) {
9739 if (!LogIsVisible(severity)) return;
9740
9741 // Ensures that logs from different threads don't interleave.
9742 MutexLock l(&g_log_mutex);
9743
9744 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9745 // macro.
9746
9747 if (severity == kWarning) {
9748 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9749 std::cout << "\nGMOCK WARNING:";
9750 }
9751 // Pre-pends a new-line to message if it doesn't start with one.
9752 if (message.empty() || message[0] != '\n') {
9753 std::cout << "\n";
9754 }
9755 std::cout << message;
9756 if (stack_frames_to_skip >= 0) {
9757 #ifdef NDEBUG
9758 // In opt mode, we have to be conservative and skip no stack frame.
9759 const int actual_to_skip = 0;
9760 #else
9761 // In dbg mode, we can do what the caller tell us to do (plus one
9762 // for skipping this function's stack frame).
9763 const int actual_to_skip = stack_frames_to_skip + 1;
9764 #endif // NDEBUG
9765
9766 // Appends a new-line to message if it doesn't end with one.
9767 if (!message.empty() && *message.rbegin() != '\n') {
9768 std::cout << "\n";
9769 }
9770 std::cout << "Stack trace:\n"
9771 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
9772 ::testing::UnitTest::GetInstance(), actual_to_skip);
9773 }
9774 std::cout << ::std::flush;
9775 }
9776
9777 } // namespace internal
9778 } // namespace testing
9779 // Copyright 2007, Google Inc.
9780 // All rights reserved.
9781 //
9782 // Redistribution and use in source and binary forms, with or without
9783 // modification, are permitted provided that the following conditions are
9784 // met:
9785 //
9786 // * Redistributions of source code must retain the above copyright
9787 // notice, this list of conditions and the following disclaimer.
9788 // * Redistributions in binary form must reproduce the above
9789 // copyright notice, this list of conditions and the following disclaimer
9790 // in the documentation and/or other materials provided with the
9791 // distribution.
9792 // * Neither the name of Google Inc. nor the names of its
9793 // contributors may be used to endorse or promote products derived from
9794 // this software without specific prior written permission.
9795 //
9796 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9797 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9798 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9799 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9800 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9801 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9802 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9803 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9804 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9805 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9806 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9807 //
9808 // Author: wan@google.com (Zhanyong Wan)
9809
9810 // Google Mock - a framework for writing C++ mock classes.
9811 //
9812 // This file implements Matcher<const string&>, Matcher<string>, and
9813 // utilities for defining matchers.
9814
9815 #include <string.h>
9816
9817 #include <sstream>
9818 #include <string>
9819
9820 namespace testing {
9821
9822 // Constructs a matcher that matches a const string& whose value is
9823 // equal to s.
9824 Matcher<const internal::string&>::Matcher(const internal::string& s) {
9825 *this = Eq(s);
9826 }
9827
9828 // Constructs a matcher that matches a const string& whose value is
9829 // equal to s.
9830 Matcher<const internal::string&>::Matcher(const char* s) {
9831 *this = Eq(internal::string(s));
9832 }
9833
9834 // Constructs a matcher that matches a string whose value is equal to s.
9835 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
9836
9837 // Constructs a matcher that matches a string whose value is equal to s.
9838 Matcher<internal::string>::Matcher(const char* s) {
9839 *this = Eq(internal::string(s));
9840 }
9841
9842 #if GTEST_HAS_STRING_PIECE_
9843 // Constructs a matcher that matches a const StringPiece& whose value is
9844 // equal to s.
9845 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
9846 *this = Eq(s);
9847 }
9848
9849 // Constructs a matcher that matches a const StringPiece& whose value is
9850 // equal to s.
9851 Matcher<const StringPiece&>::Matcher(const char* s) {
9852 *this = Eq(internal::string(s));
9853 }
9854
9855 // Constructs a matcher that matches a const StringPiece& whose value is
9856 // equal to s.
9857 Matcher<const StringPiece&>::Matcher(StringPiece s) {
9858 *this = Eq(s.ToString());
9859 }
9860
9861 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9862 Matcher<StringPiece>::Matcher(const internal::string& s) { *this = Eq(s); }
9863
9864 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9865 Matcher<StringPiece>::Matcher(const char* s) {
9866 *this = Eq(internal::string(s));
9867 }
9868
9869 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9870 Matcher<StringPiece>::Matcher(StringPiece s) { *this = Eq(s.ToString()); }
9871 #endif // GTEST_HAS_STRING_PIECE_
9872
9873 namespace internal {
9874
9875 // Joins a vector of strings as if they are fields of a tuple; returns
9876 // the joined string.
9877 GTEST_API_ string JoinAsTuple(const Strings& fields) {
9878 switch (fields.size()) {
9879 case 0:
9880 return "";
9881 case 1:
9882 return fields[0];
9883 default:
9884 string result = "(" + fields[0];
9885 for (size_t i = 1; i < fields.size(); i++) {
9886 result += ", ";
9887 result += fields[i];
9888 }
9889 result += ")";
9890 return result;
9891 }
9892 }
9893
9894 // Returns the description for a matcher defined using the MATCHER*()
9895 // macro where the user-supplied description string is "", if
9896 // 'negation' is false; otherwise returns the description of the
9897 // negation of the matcher. 'param_values' contains a list of strings
9898 // that are the print-out of the matcher's parameters.
9899 GTEST_API_ string FormatMatcherDescription(bool negation,
9900 const char* matcher_name,
9901 const Strings& param_values) {
9902 string result = ConvertIdentifierNameToWords(matcher_name);
9903 if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
9904 return negation ? "not (" + result + ")" : result;
9905 }
9906
9907 // FindMaxBipartiteMatching and its helper class.
9908 //
9909 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
9910 // bipartite matching. Flow is considered to be from left to right.
9911 // There is an implicit source node that is connected to all of the left
9912 // nodes, and an implicit sink node that is connected to all of the
9913 // right nodes. All edges have unit capacity.
9914 //
9915 // Neither the flow graph nor the residual flow graph are represented
9916 // explicitly. Instead, they are implied by the information in 'graph' and
9917 // a vector<int> called 'left_' whose elements are initialized to the
9918 // value kUnused. This represents the initial state of the algorithm,
9919 // where the flow graph is empty, and the residual flow graph has the
9920 // following edges:
9921 // - An edge from source to each left_ node
9922 // - An edge from each right_ node to sink
9923 // - An edge from each left_ node to each right_ node, if the
9924 // corresponding edge exists in 'graph'.
9925 //
9926 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
9927 // nodes l and r. This induces the following changes:
9928 // - The edges (source, l), (l, r), and (r, sink) are added to the
9929 // flow graph.
9930 // - The same three edges are removed from the residual flow graph.
9931 // - The reverse edges (l, source), (r, l), and (sink, r) are added
9932 // to the residual flow graph, which is a directional graph
9933 // representing unused flow capacity.
9934 //
9935 // When the method augments a flow (moving left_[l] from some r1 to some
9936 // other r2), this can be thought of as "undoing" the above steps with
9937 // respect to r1 and "redoing" them with respect to r2.
9938 //
9939 // It bears repeating that the flow graph and residual flow graph are
9940 // never represented explicitly, but can be derived by looking at the
9941 // information in 'graph' and in left_.
9942 //
9943 // As an optimization, there is a second vector<int> called right_ which
9944 // does not provide any new information. Instead, it enables more
9945 // efficient queries about edges entering or leaving the right-side nodes
9946 // of the flow or residual flow graphs. The following invariants are
9947 // maintained:
9948 //
9949 // left[l] == kUnused or right[left[l]] == l
9950 // right[r] == kUnused or left[right[r]] == r
9951 //
9952 // . [ source ] .
9953 // . ||| .
9954 // . ||| .
9955 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
9956 // . || | | .
9957 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
9958 // . | || .
9959 // . \----> left[2]=2 ------> right[2]=2 --\|| .
9960 // . ||| .
9961 // . elements matchers vvv .
9962 // . [ sink ] .
9963 //
9964 // See Also:
9965 // [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
9966 // "Introduction to Algorithms (Second ed.)", pp. 651–664.
9967 // [2] "Ford–Fulkerson algorithm", Wikipedia,
9968 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
9969 class MaxBipartiteMatchState {
9970 public:
9971 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
9972 : graph_(&graph),
9973 left_(graph_->LhsSize(), kUnused),
9974 right_(graph_->RhsSize(), kUnused) {}
9975
9976 // Returns the edges of a maximal match, each in the form {left, right}.
9977 ElementMatcherPairs Compute() {
9978 // 'seen' is used for path finding { 0: unseen, 1: seen }.
9979 ::std::vector<char> seen;
9980 // Searches the residual flow graph for a path from each left node to
9981 // the sink in the residual flow graph, and if one is found, add flow
9982 // to the graph. It's okay to search through the left nodes once. The
9983 // edge from the implicit source node to each previously-visited left
9984 // node will have flow if that left node has any path to the sink
9985 // whatsoever. Subsequent augmentations can only add flow to the
9986 // network, and cannot take away that previous flow unit from the source.
9987 // Since the source-to-left edge can only carry one flow unit (or,
9988 // each element can be matched to only one matcher), there is no need
9989 // to visit the left nodes more than once looking for augmented paths.
9990 // The flow is known to be possible or impossible by looking at the
9991 // node once.
9992 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
9993 // Reset the path-marking vector and try to find a path from
9994 // source to sink starting at the left_[ilhs] node.
9995 GTEST_CHECK_(left_[ilhs] == kUnused)
9996 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
9997 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
9998 seen.assign(graph_->RhsSize(), 0);
9999 TryAugment(ilhs, &seen);
10000 }
10001 ElementMatcherPairs result;
10002 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10003 size_t irhs = left_[ilhs];
10004 if (irhs == kUnused) continue;
10005 result.push_back(ElementMatcherPair(ilhs, irhs));
10006 }
10007 return result;
10008 }
10009
10010 private:
10011 static const size_t kUnused = static_cast<size_t>(-1);
10012
10013 // Perform a depth-first search from left node ilhs to the sink. If a
10014 // path is found, flow is added to the network by linking the left and
10015 // right vector elements corresponding each segment of the path.
10016 // Returns true if a path to sink was found, which means that a unit of
10017 // flow was added to the network. The 'seen' vector elements correspond
10018 // to right nodes and are marked to eliminate cycles from the search.
10019 //
10020 // Left nodes will only be explored at most once because they
10021 // are accessible from at most one right node in the residual flow
10022 // graph.
10023 //
10024 // Note that left_[ilhs] is the only element of left_ that TryAugment will
10025 // potentially transition from kUnused to another value. Any other
10026 // left_ element holding kUnused before TryAugment will be holding it
10027 // when TryAugment returns.
10028 //
10029 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
10030 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
10031 if ((*seen)[irhs]) continue;
10032 if (!graph_->HasEdge(ilhs, irhs)) continue;
10033 // There's an available edge from ilhs to irhs.
10034 (*seen)[irhs] = 1;
10035 // Next a search is performed to determine whether
10036 // this edge is a dead end or leads to the sink.
10037 //
10038 // right_[irhs] == kUnused means that there is residual flow from
10039 // right node irhs to the sink, so we can use that to finish this
10040 // flow path and return success.
10041 //
10042 // Otherwise there is residual flow to some ilhs. We push flow
10043 // along that path and call ourselves recursively to see if this
10044 // ultimately leads to sink.
10045 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
10046 // Add flow from left_[ilhs] to right_[irhs].
10047 left_[ilhs] = irhs;
10048 right_[irhs] = ilhs;
10049 return true;
10050 }
10051 }
10052 return false;
10053 }
10054
10055 const MatchMatrix* graph_; // not owned
10056 // Each element of the left_ vector represents a left hand side node
10057 // (i.e. an element) and each element of right_ is a right hand side
10058 // node (i.e. a matcher). The values in the left_ vector indicate
10059 // outflow from that node to a node on the the right_ side. The values
10060 // in the right_ indicate inflow, and specify which left_ node is
10061 // feeding that right_ node, if any. For example, left_[3] == 1 means
10062 // there's a flow from element #3 to matcher #1. Such a flow would also
10063 // be redundantly represented in the right_ vector as right_[1] == 3.
10064 // Elements of left_ and right_ are either kUnused or mutually
10065 // referent. Mutually referent means that left_[right_[i]] = i and
10066 // right_[left_[i]] = i.
10067 ::std::vector<size_t> left_;
10068 ::std::vector<size_t> right_;
10069
10070 GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
10071 };
10072
10073 const size_t MaxBipartiteMatchState::kUnused;
10074
10075 GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
10076 return MaxBipartiteMatchState(g).Compute();
10077 }
10078
10079 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
10080 ::std::ostream* stream) {
10081 typedef ElementMatcherPairs::const_iterator Iter;
10082 ::std::ostream& os = *stream;
10083 os << "{";
10084 const char* sep = "";
10085 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
10086 os << sep << "\n ("
10087 << "element #" << it->first << ", "
10088 << "matcher #" << it->second << ")";
10089 sep = ",";
10090 }
10091 os << "\n}";
10092 }
10093
10094 // Tries to find a pairing, and explains the result.
10095 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
10096 MatchResultListener* listener) {
10097 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
10098
10099 size_t max_flow = matches.size();
10100 bool result = (max_flow == matrix.RhsSize());
10101
10102 if (!result) {
10103 if (listener->IsInterested()) {
10104 *listener << "where no permutation of the elements can "
10105 "satisfy all matchers, and the closest match is "
10106 << max_flow << " of " << matrix.RhsSize()
10107 << " matchers with the pairings:\n";
10108 LogElementMatcherPairVec(matches, listener->stream());
10109 }
10110 return false;
10111 }
10112
10113 if (matches.size() > 1) {
10114 if (listener->IsInterested()) {
10115 const char* sep = "where:\n";
10116 for (size_t mi = 0; mi < matches.size(); ++mi) {
10117 *listener << sep << " - element #" << matches[mi].first
10118 << " is matched by matcher #" << matches[mi].second;
10119 sep = ",\n";
10120 }
10121 }
10122 }
10123 return true;
10124 }
10125
10126 bool MatchMatrix::NextGraph() {
10127 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10128 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10129 char& b = matched_[SpaceIndex(ilhs, irhs)];
10130 if (!b) {
10131 b = 1;
10132 return true;
10133 }
10134 b = 0;
10135 }
10136 }
10137 return false;
10138 }
10139
10140 void MatchMatrix::Randomize() {
10141 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10142 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10143 char& b = matched_[SpaceIndex(ilhs, irhs)];
10144 b = static_cast<char>(rand() & 1); // NOLINT
10145 }
10146 }
10147 }
10148
10149 string MatchMatrix::DebugString() const {
10150 ::std::stringstream ss;
10151 const char* sep = "";
10152 for (size_t i = 0; i < LhsSize(); ++i) {
10153 ss << sep;
10154 for (size_t j = 0; j < RhsSize(); ++j) {
10155 ss << HasEdge(i, j);
10156 }
10157 sep = ";";
10158 }
10159 return ss.str();
10160 }
10161
10162 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
10163 ::std::ostream* os) const {
10164 if (matcher_describers_.empty()) {
10165 *os << "is empty";
10166 return;
10167 }
10168 if (matcher_describers_.size() == 1) {
10169 *os << "has " << Elements(1) << " and that element ";
10170 matcher_describers_[0]->DescribeTo(os);
10171 return;
10172 }
10173 *os << "has " << Elements(matcher_describers_.size())
10174 << " and there exists some permutation of elements such that:\n";
10175 const char* sep = "";
10176 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10177 *os << sep << " - element #" << i << " ";
10178 matcher_describers_[i]->DescribeTo(os);
10179 sep = ", and\n";
10180 }
10181 }
10182
10183 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
10184 ::std::ostream* os) const {
10185 if (matcher_describers_.empty()) {
10186 *os << "isn't empty";
10187 return;
10188 }
10189 if (matcher_describers_.size() == 1) {
10190 *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
10191 << " that ";
10192 matcher_describers_[0]->DescribeNegationTo(os);
10193 return;
10194 }
10195 *os << "doesn't have " << Elements(matcher_describers_.size())
10196 << ", or there exists no permutation of elements such that:\n";
10197 const char* sep = "";
10198 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10199 *os << sep << " - element #" << i << " ";
10200 matcher_describers_[i]->DescribeTo(os);
10201 sep = ", and\n";
10202 }
10203 }
10204
10205 // Checks that all matchers match at least one element, and that all
10206 // elements match at least one matcher. This enables faster matching
10207 // and better error reporting.
10208 // Returns false, writing an explanation to 'listener', if and only
10209 // if the success criteria are not met.
10210 bool UnorderedElementsAreMatcherImplBase::
10211 VerifyAllElementsAndMatchersAreMatched(
10212 const ::std::vector<string>& element_printouts,
10213 const MatchMatrix& matrix, MatchResultListener* listener) const {
10214 bool result = true;
10215 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
10216 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
10217
10218 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
10219 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
10220 char matched = matrix.HasEdge(ilhs, irhs);
10221 element_matched[ilhs] |= matched;
10222 matcher_matched[irhs] |= matched;
10223 }
10224 }
10225
10226 {
10227 const char* sep =
10228 "where the following matchers don't match any elements:\n";
10229 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
10230 if (matcher_matched[mi]) continue;
10231 result = false;
10232 if (listener->IsInterested()) {
10233 *listener << sep << "matcher #" << mi << ": ";
10234 matcher_describers_[mi]->DescribeTo(listener->stream());
10235 sep = ",\n";
10236 }
10237 }
10238 }
10239
10240 {
10241 const char* sep =
10242 "where the following elements don't match any matchers:\n";
10243 const char* outer_sep = "";
10244 if (!result) {
10245 outer_sep = "\nand ";
10246 }
10247 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
10248 if (element_matched[ei]) continue;
10249 result = false;
10250 if (listener->IsInterested()) {
10251 *listener << outer_sep << sep << "element #" << ei << ": "
10252 << element_printouts[ei];
10253 sep = ",\n";
10254 outer_sep = "";
10255 }
10256 }
10257 }
10258 return result;
10259 }
10260
10261 } // namespace internal
10262 } // namespace testing
10263 // Copyright 2007, Google Inc.
10264 // All rights reserved.
10265 //
10266 // Redistribution and use in source and binary forms, with or without
10267 // modification, are permitted provided that the following conditions are
10268 // met:
10269 //
10270 // * Redistributions of source code must retain the above copyright
10271 // notice, this list of conditions and the following disclaimer.
10272 // * Redistributions in binary form must reproduce the above
10273 // copyright notice, this list of conditions and the following disclaimer
10274 // in the documentation and/or other materials provided with the
10275 // distribution.
10276 // * Neither the name of Google Inc. nor the names of its
10277 // contributors may be used to endorse or promote products derived from
10278 // this software without specific prior written permission.
10279 //
10280 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10281 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10282 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10283 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10284 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10285 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10286 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10287 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10288 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10289 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10290 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10291 //
10292 // Author: wan@google.com (Zhanyong Wan)
10293
10294 // Google Mock - a framework for writing C++ mock classes.
10295 //
10296 // This file implements the spec builder syntax (ON_CALL and
10297 // EXPECT_CALL).
10298
10299 #include <stdlib.h>
10300
10301 #include <iostream> // NOLINT
10302 #include <map>
10303 #include <set>
10304 #include <string>
10305
10306 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
10307 # include <unistd.h> // NOLINT
10308 #endif
10309
10310 namespace testing {
10311 namespace internal {
10312
10313 // Protects the mock object registry (in class Mock), all function
10314 // mockers, and all expectations.
10315 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
10316
10317 // Logs a message including file and line number information.
10318 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
10319 const char* file, int line,
10320 const string& message) {
10321 ::std::ostringstream s;
10322 s << file << ":" << line << ": " << message << ::std::endl;
10323 Log(severity, s.str(), 0);
10324 }
10325
10326 // Constructs an ExpectationBase object.
10327 ExpectationBase::ExpectationBase(const char* a_file, int a_line,
10328 const string& a_source_text)
10329 : file_(a_file),
10330 line_(a_line),
10331 source_text_(a_source_text),
10332 cardinality_specified_(false),
10333 cardinality_(Exactly(1)),
10334 call_count_(0),
10335 retired_(false),
10336 extra_matcher_specified_(false),
10337 repeated_action_specified_(false),
10338 retires_on_saturation_(false),
10339 last_clause_(kNone),
10340 action_count_checked_(false) {}
10341
10342 // Destructs an ExpectationBase object.
10343 ExpectationBase::~ExpectationBase() {}
10344
10345 // Explicitly specifies the cardinality of this expectation. Used by
10346 // the subclasses to implement the .Times() clause.
10347 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
10348 cardinality_specified_ = true;
10349 cardinality_ = a_cardinality;
10350 }
10351
10352 // Retires all pre-requisites of this expectation.
10353 void ExpectationBase::RetireAllPreRequisites()
10354 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10355 if (is_retired()) {
10356 // We can take this short-cut as we never retire an expectation
10357 // until we have retired all its pre-requisites.
10358 return;
10359 }
10360
10361 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10362 it != immediate_prerequisites_.end(); ++it) {
10363 ExpectationBase* const prerequisite = it->expectation_base().get();
10364 if (!prerequisite->is_retired()) {
10365 prerequisite->RetireAllPreRequisites();
10366 prerequisite->Retire();
10367 }
10368 }
10369 }
10370
10371 // Returns true iff all pre-requisites of this expectation have been
10372 // satisfied.
10373 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
10374 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10375 g_gmock_mutex.AssertHeld();
10376 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10377 it != immediate_prerequisites_.end(); ++it) {
10378 if (!(it->expectation_base()->IsSatisfied()) ||
10379 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
10380 return false;
10381 }
10382 return true;
10383 }
10384
10385 // Adds unsatisfied pre-requisites of this expectation to 'result'.
10386 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
10387 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10388 g_gmock_mutex.AssertHeld();
10389 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10390 it != immediate_prerequisites_.end(); ++it) {
10391 if (it->expectation_base()->IsSatisfied()) {
10392 // If *it is satisfied and has a call count of 0, some of its
10393 // pre-requisites may not be satisfied yet.
10394 if (it->expectation_base()->call_count_ == 0) {
10395 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
10396 }
10397 } else {
10398 // Now that we know *it is unsatisfied, we are not so interested
10399 // in whether its pre-requisites are satisfied. Therefore we
10400 // don't recursively call FindUnsatisfiedPrerequisites() here.
10401 *result += *it;
10402 }
10403 }
10404 }
10405
10406 // Describes how many times a function call matching this
10407 // expectation has occurred.
10408 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
10409 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10410 g_gmock_mutex.AssertHeld();
10411
10412 // Describes how many times the function is expected to be called.
10413 *os << " Expected: to be ";
10414 cardinality().DescribeTo(os);
10415 *os << "\n Actual: ";
10416 Cardinality::DescribeActualCallCountTo(call_count(), os);
10417
10418 // Describes the state of the expectation (e.g. is it satisfied?
10419 // is it active?).
10420 *os << " - "
10421 << (IsOverSaturated()
10422 ? "over-saturated"
10423 : IsSaturated() ? "saturated"
10424 : IsSatisfied() ? "satisfied" : "unsatisfied")
10425 << " and " << (is_retired() ? "retired" : "active");
10426 }
10427
10428 // Checks the action count (i.e. the number of WillOnce() and
10429 // WillRepeatedly() clauses) against the cardinality if this hasn't
10430 // been done before. Prints a warning if there are too many or too
10431 // few actions.
10432 void ExpectationBase::CheckActionCountIfNotDone() const
10433 GTEST_LOCK_EXCLUDED_(mutex_) {
10434 bool should_check = false;
10435 {
10436 MutexLock l(&mutex_);
10437 if (!action_count_checked_) {
10438 action_count_checked_ = true;
10439 should_check = true;
10440 }
10441 }
10442
10443 if (should_check) {
10444 if (!cardinality_specified_) {
10445 // The cardinality was inferred - no need to check the action
10446 // count against it.
10447 return;
10448 }
10449
10450 // The cardinality was explicitly specified.
10451 const int action_count = static_cast<int>(untyped_actions_.size());
10452 const int upper_bound = cardinality().ConservativeUpperBound();
10453 const int lower_bound = cardinality().ConservativeLowerBound();
10454 bool too_many; // True if there are too many actions, or false
10455 // if there are too few.
10456 if (action_count > upper_bound ||
10457 (action_count == upper_bound && repeated_action_specified_)) {
10458 too_many = true;
10459 } else if (0 < action_count && action_count < lower_bound &&
10460 !repeated_action_specified_) {
10461 too_many = false;
10462 } else {
10463 return;
10464 }
10465
10466 ::std::stringstream ss;
10467 DescribeLocationTo(&ss);
10468 ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
10469 << source_text() << "...\n"
10470 << "Expected to be ";
10471 cardinality().DescribeTo(&ss);
10472 ss << ", but has " << (too_many ? "" : "only ") << action_count
10473 << " WillOnce()" << (action_count == 1 ? "" : "s");
10474 if (repeated_action_specified_) {
10475 ss << " and a WillRepeatedly()";
10476 }
10477 ss << ".";
10478 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
10479 }
10480 }
10481
10482 // Implements the .Times() clause.
10483 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
10484 if (last_clause_ == kTimes) {
10485 ExpectSpecProperty(false,
10486 ".Times() cannot appear "
10487 "more than once in an EXPECT_CALL().");
10488 } else {
10489 ExpectSpecProperty(last_clause_ < kTimes,
10490 ".Times() cannot appear after "
10491 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
10492 "or .RetiresOnSaturation().");
10493 }
10494 last_clause_ = kTimes;
10495
10496 SpecifyCardinality(a_cardinality);
10497 }
10498
10499 // Points to the implicit sequence introduced by a living InSequence
10500 // object (if any) in the current thread or NULL.
10501 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
10502
10503 // Reports an uninteresting call (whose description is in msg) in the
10504 // manner specified by 'reaction'.
10505 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
10506 switch (reaction) {
10507 case kAllow:
10508 Log(kInfo, msg, 3);
10509 break;
10510 case kWarn:
10511 Log(kWarning, msg, 3);
10512 break;
10513 default: // FAIL
10514 Expect(false, NULL, -1, msg);
10515 }
10516 }
10517
10518 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
10519 : mock_obj_(NULL), name_("") {}
10520
10521 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
10522
10523 // Sets the mock object this mock method belongs to, and registers
10524 // this information in the global mock registry. Will be called
10525 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
10526 // method.
10527 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
10528 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10529 {
10530 MutexLock l(&g_gmock_mutex);
10531 mock_obj_ = mock_obj;
10532 }
10533 Mock::Register(mock_obj, this);
10534 }
10535
10536 // Sets the mock object this mock method belongs to, and sets the name
10537 // of the mock function. Will be called upon each invocation of this
10538 // mock function.
10539 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
10540 const char* name)
10541 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10542 // We protect name_ under g_gmock_mutex in case this mock function
10543 // is called from two threads concurrently.
10544 MutexLock l(&g_gmock_mutex);
10545 mock_obj_ = mock_obj;
10546 name_ = name;
10547 }
10548
10549 // Returns the name of the function being mocked. Must be called
10550 // after RegisterOwner() or SetOwnerAndName() has been called.
10551 const void* UntypedFunctionMockerBase::MockObject() const
10552 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10553 const void* mock_obj;
10554 {
10555 // We protect mock_obj_ under g_gmock_mutex in case this mock
10556 // function is called from two threads concurrently.
10557 MutexLock l(&g_gmock_mutex);
10558 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
10559 "MockObject() must not be called before RegisterOwner() or "
10560 "SetOwnerAndName() has been called.");
10561 mock_obj = mock_obj_;
10562 }
10563 return mock_obj;
10564 }
10565
10566 // Returns the name of this mock method. Must be called after
10567 // SetOwnerAndName() has been called.
10568 const char* UntypedFunctionMockerBase::Name() const
10569 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10570 const char* name;
10571 {
10572 // We protect name_ under g_gmock_mutex in case this mock
10573 // function is called from two threads concurrently.
10574 MutexLock l(&g_gmock_mutex);
10575 Assert(name_ != NULL, __FILE__, __LINE__,
10576 "Name() must not be called before SetOwnerAndName() has "
10577 "been called.");
10578 name = name_;
10579 }
10580 return name;
10581 }
10582
10583 // Calculates the result of invoking this mock function with the given
10584 // arguments, prints it, and returns it. The caller is responsible
10585 // for deleting the result.
10586 const UntypedActionResultHolderBase*
10587 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
10588 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10589 if (untyped_expectations_.size() == 0) {
10590 // No expectation is set on this mock method - we have an
10591 // uninteresting call.
10592
10593 // We must get Google Mock's reaction on uninteresting calls
10594 // made on this mock object BEFORE performing the action,
10595 // because the action may DELETE the mock object and make the
10596 // following expression meaningless.
10597 const CallReaction reaction =
10598 Mock::GetReactionOnUninterestingCalls(MockObject());
10599
10600 // True iff we need to print this call's arguments and return
10601 // value. This definition must be kept in sync with
10602 // the behavior of ReportUninterestingCall().
10603 const bool need_to_report_uninteresting_call =
10604 // If the user allows this uninteresting call, we print it
10605 // only when he wants informational messages.
10606 reaction == kAllow ? LogIsVisible(kInfo) :
10607 // If the user wants this to be a warning, we print
10608 // it only when he wants to see warnings.
10609 reaction == kWarn
10610 ? LogIsVisible(kWarning)
10611 :
10612 // Otherwise, the user wants this to be an error, and we
10613 // should always print detailed information in the error.
10614 true;
10615
10616 if (!need_to_report_uninteresting_call) {
10617 // Perform the action without printing the call information.
10618 return this->UntypedPerformDefaultAction(untyped_args, "");
10619 }
10620
10621 // Warns about the uninteresting call.
10622 ::std::stringstream ss;
10623 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
10624
10625 // Calculates the function result.
10626 const UntypedActionResultHolderBase* const result =
10627 this->UntypedPerformDefaultAction(untyped_args, ss.str());
10628
10629 // Prints the function result.
10630 if (result != NULL) result->PrintAsActionResult(&ss);
10631
10632 ReportUninterestingCall(reaction, ss.str());
10633 return result;
10634 }
10635
10636 bool is_excessive = false;
10637 ::std::stringstream ss;
10638 ::std::stringstream why;
10639 ::std::stringstream loc;
10640 const void* untyped_action = NULL;
10641
10642 // The UntypedFindMatchingExpectation() function acquires and
10643 // releases g_gmock_mutex.
10644 const ExpectationBase* const untyped_expectation =
10645 this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
10646 &is_excessive, &ss, &why);
10647 const bool found = untyped_expectation != NULL;
10648
10649 // True iff we need to print the call's arguments and return value.
10650 // This definition must be kept in sync with the uses of Expect()
10651 // and Log() in this function.
10652 const bool need_to_report_call =
10653 !found || is_excessive || LogIsVisible(kInfo);
10654 if (!need_to_report_call) {
10655 // Perform the action without printing the call information.
10656 return untyped_action == NULL
10657 ? this->UntypedPerformDefaultAction(untyped_args, "")
10658 : this->UntypedPerformAction(untyped_action, untyped_args);
10659 }
10660
10661 ss << " Function call: " << Name();
10662 this->UntypedPrintArgs(untyped_args, &ss);
10663
10664 // In case the action deletes a piece of the expectation, we
10665 // generate the message beforehand.
10666 if (found && !is_excessive) {
10667 untyped_expectation->DescribeLocationTo(&loc);
10668 }
10669
10670 const UntypedActionResultHolderBase* const result =
10671 untyped_action == NULL
10672 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
10673 : this->UntypedPerformAction(untyped_action, untyped_args);
10674 if (result != NULL) result->PrintAsActionResult(&ss);
10675 ss << "\n" << why.str();
10676
10677 if (!found) {
10678 // No expectation matches this call - reports a failure.
10679 Expect(false, NULL, -1, ss.str());
10680 } else if (is_excessive) {
10681 // We had an upper-bound violation and the failure message is in ss.
10682 Expect(false, untyped_expectation->file(), untyped_expectation->line(),
10683 ss.str());
10684 } else {
10685 // We had an expected call and the matching expectation is
10686 // described in ss.
10687 Log(kInfo, loc.str() + ss.str(), 2);
10688 }
10689
10690 return result;
10691 }
10692
10693 // Returns an Expectation object that references and co-owns exp,
10694 // which must be an expectation on this mock function.
10695 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
10696 for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
10697 it != untyped_expectations_.end(); ++it) {
10698 if (it->get() == exp) {
10699 return Expectation(*it);
10700 }
10701 }
10702
10703 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
10704 return Expectation();
10705 // The above statement is just to make the code compile, and will
10706 // never be executed.
10707 }
10708
10709 // Verifies that all expectations on this mock function have been
10710 // satisfied. Reports one or more Google Test non-fatal failures
10711 // and returns false if not.
10712 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
10713 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10714 g_gmock_mutex.AssertHeld();
10715 bool expectations_met = true;
10716 for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
10717 it != untyped_expectations_.end(); ++it) {
10718 ExpectationBase* const untyped_expectation = it->get();
10719 if (untyped_expectation->IsOverSaturated()) {
10720 // There was an upper-bound violation. Since the error was
10721 // already reported when it occurred, there is no need to do
10722 // anything here.
10723 expectations_met = false;
10724 } else if (!untyped_expectation->IsSatisfied()) {
10725 expectations_met = false;
10726 ::std::stringstream ss;
10727 ss << "Actual function call count doesn't match "
10728 << untyped_expectation->source_text() << "...\n";
10729 // No need to show the source file location of the expectation
10730 // in the description, as the Expect() call that follows already
10731 // takes care of it.
10732 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
10733 untyped_expectation->DescribeCallCountTo(&ss);
10734 Expect(false, untyped_expectation->file(), untyped_expectation->line(),
10735 ss.str());
10736 }
10737 }
10738
10739 // Deleting our expectations may trigger other mock objects to be deleted, for
10740 // example if an action contains a reference counted smart pointer to that
10741 // mock object, and that is the last reference. So if we delete our
10742 // expectations within the context of the global mutex we may deadlock when
10743 // this method is called again. Instead, make a copy of the set of
10744 // expectations to delete, clear our set within the mutex, and then clear the
10745 // copied set outside of it.
10746 UntypedExpectations expectations_to_delete;
10747 untyped_expectations_.swap(expectations_to_delete);
10748
10749 g_gmock_mutex.Unlock();
10750 expectations_to_delete.clear();
10751 g_gmock_mutex.Lock();
10752
10753 return expectations_met;
10754 }
10755
10756 } // namespace internal
10757
10758 // Class Mock.
10759
10760 namespace {
10761
10762 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10763
10764 // The current state of a mock object. Such information is needed for
10765 // detecting leaked mock objects and explicitly verifying a mock's
10766 // expectations.
10767 struct MockObjectState {
10768 MockObjectState()
10769 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
10770
10771 // Where in the source file an ON_CALL or EXPECT_CALL is first
10772 // invoked on this mock object.
10773 const char* first_used_file;
10774 int first_used_line;
10775 ::std::string first_used_test_case;
10776 ::std::string first_used_test;
10777 bool leakable; // true iff it's OK to leak the object.
10778 FunctionMockers function_mockers; // All registered methods of the object.
10779 };
10780
10781 // A global registry holding the state of all mock objects that are
10782 // alive. A mock object is added to this registry the first time
10783 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
10784 // is removed from the registry in the mock object's destructor.
10785 class MockObjectRegistry {
10786 public:
10787 // Maps a mock object (identified by its address) to its state.
10788 typedef std::map<const void*, MockObjectState> StateMap;
10789
10790 // This destructor will be called when a program exits, after all
10791 // tests in it have been run. By then, there should be no mock
10792 // object alive. Therefore we report any living object as test
10793 // failure, unless the user explicitly asked us to ignore it.
10794 ~MockObjectRegistry() {
10795 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
10796 // a macro.
10797
10798 if (!GMOCK_FLAG(catch_leaked_mocks)) return;
10799
10800 int leaked_count = 0;
10801 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
10802 ++it) {
10803 if (it->second.leakable) // The user said it's fine to leak this object.
10804 continue;
10805
10806 // TODO(wan@google.com): Print the type of the leaked object.
10807 // This can help the user identify the leaked object.
10808 std::cout << "\n";
10809 const MockObjectState& state = it->second;
10810 std::cout << internal::FormatFileLocation(state.first_used_file,
10811 state.first_used_line);
10812 std::cout << " ERROR: this mock object";
10813 if (state.first_used_test != "") {
10814 std::cout << " (used in test " << state.first_used_test_case << "."
10815 << state.first_used_test << ")";
10816 }
10817 std::cout << " should be deleted but never is. Its address is @"
10818 << it->first << ".";
10819 leaked_count++;
10820 }
10821 if (leaked_count > 0) {
10822 std::cout << "\nERROR: " << leaked_count << " leaked mock "
10823 << (leaked_count == 1 ? "object" : "objects")
10824 << " found at program exit.\n";
10825 std::cout.flush();
10826 ::std::cerr.flush();
10827 // RUN_ALL_TESTS() has already returned when this destructor is
10828 // called. Therefore we cannot use the normal Google Test
10829 // failure reporting mechanism.
10830 _exit(1); // We cannot call exit() as it is not reentrant and
10831 // may already have been called.
10832 }
10833 }
10834
10835 StateMap& states() { return states_; }
10836
10837 private:
10838 StateMap states_;
10839 };
10840
10841 // Protected by g_gmock_mutex.
10842 MockObjectRegistry g_mock_object_registry;
10843
10844 // Maps a mock object to the reaction Google Mock should have when an
10845 // uninteresting method is called. Protected by g_gmock_mutex.
10846 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
10847
10848 // Sets the reaction Google Mock should have when an uninteresting
10849 // method of the given mock object is called.
10850 void SetReactionOnUninterestingCalls(const void* mock_obj,
10851 internal::CallReaction reaction)
10852 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10853 internal::MutexLock l(&internal::g_gmock_mutex);
10854 g_uninteresting_call_reaction[mock_obj] = reaction;
10855 }
10856
10857 } // namespace
10858
10859 // Tells Google Mock to allow uninteresting calls on the given mock
10860 // object.
10861 void Mock::AllowUninterestingCalls(const void* mock_obj)
10862 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10863 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
10864 }
10865
10866 // Tells Google Mock to warn the user about uninteresting calls on the
10867 // given mock object.
10868 void Mock::WarnUninterestingCalls(const void* mock_obj)
10869 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10870 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
10871 }
10872
10873 // Tells Google Mock to fail uninteresting calls on the given mock
10874 // object.
10875 void Mock::FailUninterestingCalls(const void* mock_obj)
10876 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10877 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
10878 }
10879
10880 // Tells Google Mock the given mock object is being destroyed and its
10881 // entry in the call-reaction table should be removed.
10882 void Mock::UnregisterCallReaction(const void* mock_obj)
10883 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10884 internal::MutexLock l(&internal::g_gmock_mutex);
10885 g_uninteresting_call_reaction.erase(mock_obj);
10886 }
10887
10888 // Returns the reaction Google Mock will have on uninteresting calls
10889 // made on the given mock object.
10890 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
10891 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10892 internal::MutexLock l(&internal::g_gmock_mutex);
10893 return (g_uninteresting_call_reaction.count(mock_obj) == 0)
10894 ? internal::kDefault
10895 : g_uninteresting_call_reaction[mock_obj];
10896 }
10897
10898 // Tells Google Mock to ignore mock_obj when checking for leaked mock
10899 // objects.
10900 void Mock::AllowLeak(const void* mock_obj)
10901 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10902 internal::MutexLock l(&internal::g_gmock_mutex);
10903 g_mock_object_registry.states()[mock_obj].leakable = true;
10904 }
10905
10906 // Verifies and clears all expectations on the given mock object. If
10907 // the expectations aren't satisfied, generates one or more Google
10908 // Test non-fatal failures and returns false.
10909 bool Mock::VerifyAndClearExpectations(void* mock_obj)
10910 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10911 internal::MutexLock l(&internal::g_gmock_mutex);
10912 return VerifyAndClearExpectationsLocked(mock_obj);
10913 }
10914
10915 // Verifies all expectations on the given mock object and clears its
10916 // default actions and expectations. Returns true iff the
10917 // verification was successful.
10918 bool Mock::VerifyAndClear(void* mock_obj)
10919 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10920 internal::MutexLock l(&internal::g_gmock_mutex);
10921 ClearDefaultActionsLocked(mock_obj);
10922 return VerifyAndClearExpectationsLocked(mock_obj);
10923 }
10924
10925 // Verifies and clears all expectations on the given mock object. If
10926 // the expectations aren't satisfied, generates one or more Google
10927 // Test non-fatal failures and returns false.
10928 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
10929 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
10930 internal::g_gmock_mutex.AssertHeld();
10931 if (g_mock_object_registry.states().count(mock_obj) == 0) {
10932 // No EXPECT_CALL() was set on the given mock object.
10933 return true;
10934 }
10935
10936 // Verifies and clears the expectations on each mock method in the
10937 // given mock object.
10938 bool expectations_met = true;
10939 FunctionMockers& mockers =
10940 g_mock_object_registry.states()[mock_obj].function_mockers;
10941 for (FunctionMockers::const_iterator it = mockers.begin();
10942 it != mockers.end(); ++it) {
10943 if (!(*it)->VerifyAndClearExpectationsLocked()) {
10944 expectations_met = false;
10945 }
10946 }
10947
10948 // We don't clear the content of mockers, as they may still be
10949 // needed by ClearDefaultActionsLocked().
10950 return expectations_met;
10951 }
10952
10953 // Registers a mock object and a mock method it owns.
10954 void Mock::Register(const void* mock_obj,
10955 internal::UntypedFunctionMockerBase* mocker)
10956 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10957 internal::MutexLock l(&internal::g_gmock_mutex);
10958 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
10959 }
10960
10961 // Tells Google Mock where in the source code mock_obj is used in an
10962 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
10963 // information helps the user identify which object it is.
10964 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
10965 const char* file, int line)
10966 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10967 internal::MutexLock l(&internal::g_gmock_mutex);
10968 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
10969 if (state.first_used_file == NULL) {
10970 state.first_used_file = file;
10971 state.first_used_line = line;
10972 const TestInfo* const test_info =
10973 UnitTest::GetInstance()->current_test_info();
10974 if (test_info != NULL) {
10975 // TODO(wan@google.com): record the test case name when the
10976 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
10977 // TearDownTestCase().
10978 state.first_used_test_case = test_info->test_case_name();
10979 state.first_used_test = test_info->name();
10980 }
10981 }
10982 }
10983
10984 // Unregisters a mock method; removes the owning mock object from the
10985 // registry when the last mock method associated with it has been
10986 // unregistered. This is called only in the destructor of
10987 // FunctionMockerBase.
10988 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
10989 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
10990 internal::g_gmock_mutex.AssertHeld();
10991 for (MockObjectRegistry::StateMap::iterator it =
10992 g_mock_object_registry.states().begin();
10993 it != g_mock_object_registry.states().end(); ++it) {
10994 FunctionMockers& mockers = it->second.function_mockers;
10995 if (mockers.erase(mocker) > 0) {
10996 // mocker was in mockers and has been just removed.
10997 if (mockers.empty()) {
10998 g_mock_object_registry.states().erase(it);
10999 }
11000 return;
11001 }
11002 }
11003 }
11004
11005 // Clears all ON_CALL()s set on the given mock object.
11006 void Mock::ClearDefaultActionsLocked(void* mock_obj)
11007 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11008 internal::g_gmock_mutex.AssertHeld();
11009
11010 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11011 // No ON_CALL() was set on the given mock object.
11012 return;
11013 }
11014
11015 // Clears the default actions for each mock method in the given mock
11016 // object.
11017 FunctionMockers& mockers =
11018 g_mock_object_registry.states()[mock_obj].function_mockers;
11019 for (FunctionMockers::const_iterator it = mockers.begin();
11020 it != mockers.end(); ++it) {
11021 (*it)->ClearDefaultActionsLocked();
11022 }
11023
11024 // We don't clear the content of mockers, as they may still be
11025 // needed by VerifyAndClearExpectationsLocked().
11026 }
11027
11028 Expectation::Expectation() {}
11029
11030 Expectation::Expectation(
11031 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
11032 : expectation_base_(an_expectation_base) {}
11033
11034 Expectation::~Expectation() {}
11035
11036 // Adds an expectation to a sequence.
11037 void Sequence::AddExpectation(const Expectation& expectation) const {
11038 if (*last_expectation_ != expectation) {
11039 if (last_expectation_->expectation_base() != NULL) {
11040 expectation.expectation_base()->immediate_prerequisites_ +=
11041 *last_expectation_;
11042 }
11043 *last_expectation_ = expectation;
11044 }
11045 }
11046
11047 // Creates the implicit sequence if there isn't one.
11048 InSequence::InSequence() {
11049 if (internal::g_gmock_implicit_sequence.get() == NULL) {
11050 internal::g_gmock_implicit_sequence.set(new Sequence);
11051 sequence_created_ = true;
11052 } else {
11053 sequence_created_ = false;
11054 }
11055 }
11056
11057 // Deletes the implicit sequence if it was created by the constructor
11058 // of this object.
11059 InSequence::~InSequence() {
11060 if (sequence_created_) {
11061 delete internal::g_gmock_implicit_sequence.get();
11062 internal::g_gmock_implicit_sequence.set(NULL);
11063 }
11064 }
11065
11066 } // namespace testing
11067 // Copyright 2008, Google Inc.
11068 // All rights reserved.
11069 //
11070 // Redistribution and use in source and binary forms, with or without
11071 // modification, are permitted provided that the following conditions are
11072 // met:
11073 //
11074 // * Redistributions of source code must retain the above copyright
11075 // notice, this list of conditions and the following disclaimer.
11076 // * Redistributions in binary form must reproduce the above
11077 // copyright notice, this list of conditions and the following disclaimer
11078 // in the documentation and/or other materials provided with the
11079 // distribution.
11080 // * Neither the name of Google Inc. nor the names of its
11081 // contributors may be used to endorse or promote products derived from
11082 // this software without specific prior written permission.
11083 //
11084 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11085 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11086 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11087 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11088 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11089 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11090 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11091 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11092 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11093 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11094 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11095 //
11096 // Author: wan@google.com (Zhanyong Wan)
11097
11098 namespace testing {
11099
11100 // TODO(wan@google.com): support using environment variables to
11101 // control the flag values, like what Google Test does.
11102
11103 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
11104 "true iff Google Mock should report leaked mock objects "
11105 "as failures.");
11106
11107 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
11108 "Controls how verbose Google Mock's output is."
11109 " Valid values:\n"
11110 " info - prints all messages.\n"
11111 " warning - prints warnings and errors.\n"
11112 " error - prints errors only.");
11113
11114 namespace internal {
11115
11116 // Parses a string as a command line flag. The string should have the
11117 // format "--gmock_flag=value". When def_optional is true, the
11118 // "=value" part can be omitted.
11119 //
11120 // Returns the value of the flag, or NULL if the parsing failed.
11121 static const char* ParseGoogleMockFlagValue(const char* str, const char* flag,
11122 bool def_optional) {
11123 // str and flag must not be NULL.
11124 if (str == NULL || flag == NULL) return NULL;
11125
11126 // The flag must start with "--gmock_".
11127 const std::string flag_str = std::string("--gmock_") + flag;
11128 const size_t flag_len = flag_str.length();
11129 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
11130
11131 // Skips the flag name.
11132 const char* flag_end = str + flag_len;
11133
11134 // When def_optional is true, it's OK to not have a "=value" part.
11135 if (def_optional && (flag_end[0] == '\0')) {
11136 return flag_end;
11137 }
11138
11139 // If def_optional is true and there are more characters after the
11140 // flag name, or if def_optional is false, there must be a '=' after
11141 // the flag name.
11142 if (flag_end[0] != '=') return NULL;
11143
11144 // Returns the string after "=".
11145 return flag_end + 1;
11146 }
11147
11148 // Parses a string for a Google Mock bool flag, in the form of
11149 // "--gmock_flag=value".
11150 //
11151 // On success, stores the value of the flag in *value, and returns
11152 // true. On failure, returns false without changing *value.
11153 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
11154 bool* value) {
11155 // Gets the value of the flag as a string.
11156 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
11157
11158 // Aborts if the parsing failed.
11159 if (value_str == NULL) return false;
11160
11161 // Converts the string value to a bool.
11162 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
11163 return true;
11164 }
11165
11166 // Parses a string for a Google Mock string flag, in the form of
11167 // "--gmock_flag=value".
11168 //
11169 // On success, stores the value of the flag in *value, and returns
11170 // true. On failure, returns false without changing *value.
11171 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
11172 std::string* value) {
11173 // Gets the value of the flag as a string.
11174 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
11175
11176 // Aborts if the parsing failed.
11177 if (value_str == NULL) return false;
11178
11179 // Sets *value to the value of the flag.
11180 *value = value_str;
11181 return true;
11182 }
11183
11184 // The internal implementation of InitGoogleMock().
11185 //
11186 // The type parameter CharType can be instantiated to either char or
11187 // wchar_t.
11188 template <typename CharType>
11189 void InitGoogleMockImpl(int* argc, CharType** argv) {
11190 // Makes sure Google Test is initialized. InitGoogleTest() is
11191 // idempotent, so it's fine if the user has already called it.
11192 InitGoogleTest(argc, argv);
11193 if (*argc <= 0) return;
11194
11195 for (int i = 1; i != *argc; i++) {
11196 const std::string arg_string = StreamableToString(argv[i]);
11197 const char* const arg = arg_string.c_str();
11198
11199 // Do we see a Google Mock flag?
11200 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
11201 &GMOCK_FLAG(catch_leaked_mocks)) ||
11202 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
11203 // Yes. Shift the remainder of the argv list left by one. Note
11204 // that argv has (*argc + 1) elements, the last one always being
11205 // NULL. The following loop moves the trailing NULL element as
11206 // well.
11207 for (int j = i; j != *argc; j++) {
11208 argv[j] = argv[j + 1];
11209 }
11210
11211 // Decrements the argument count.
11212 (*argc)--;
11213
11214 // We also need to decrement the iterator as we just removed
11215 // an element.
11216 i--;
11217 }
11218 }
11219 }
11220
11221 } // namespace internal
11222
11223 // Initializes Google Mock. This must be called before running the
11224 // tests. In particular, it parses a command line for the flags that
11225 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
11226 // removed from argv, and *argc is decremented.
11227 //
11228 // No value is returned. Instead, the Google Mock flag variables are
11229 // updated.
11230 //
11231 // Since Google Test is needed for Google Mock to work, this function
11232 // also initializes Google Test and parses its flags, if that hasn't
11233 // been done.
11234 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
11235 internal::InitGoogleMockImpl(argc, argv);
11236 }
11237
11238 // This overloaded version can be used in Windows programs compiled in
11239 // UNICODE mode.
11240 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
11241 internal::InitGoogleMockImpl(argc, argv);
11242 }
11243
11244 } // namespace testing