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