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 //
31 // Google C++ Testing and Mocking Framework (Google Test)
32 //
33 // Sometimes it's desirable to build Google Test by compiling a single file.
34 // This file serves this purpose.
35
36 // This line ensures that gtest.h can be compiled on its own, even
37 // when it's fused.
38 #include "gtest/gtest.h"
39
40 // The following lines pull in the real gtest *.cc files.
41 // Copyright 2005, Google Inc.
42 // All rights reserved.
43 //
44 // Redistribution and use in source and binary forms, with or without
45 // modification, are permitted provided that the following conditions are
46 // met:
47 //
48 // * Redistributions of source code must retain the above copyright
49 // notice, this list of conditions and the following disclaimer.
50 // * Redistributions in binary form must reproduce the above
51 // copyright notice, this list of conditions and the following disclaimer
52 // in the documentation and/or other materials provided with the
53 // distribution.
54 // * Neither the name of Google Inc. nor the names of its
55 // contributors may be used to endorse or promote products derived from
56 // this software without specific prior written permission.
57 //
58 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
59 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
60 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
61 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
62 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
63 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
64 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
65 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
66 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
67 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
68 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69
70 //
71 // The Google C++ Testing and Mocking Framework (Google Test)
72
73 // Copyright 2007, Google Inc.
74 // All rights reserved.
75 //
76 // Redistribution and use in source and binary forms, with or without
77 // modification, are permitted provided that the following conditions are
78 // met:
79 //
80 // * Redistributions of source code must retain the above copyright
81 // notice, this list of conditions and the following disclaimer.
82 // * Redistributions in binary form must reproduce the above
83 // copyright notice, this list of conditions and the following disclaimer
84 // in the documentation and/or other materials provided with the
85 // distribution.
86 // * Neither the name of Google Inc. nor the names of its
87 // contributors may be used to endorse or promote products derived from
88 // this software without specific prior written permission.
89 //
90 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
91 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
92 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
93 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
94 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
95 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
96 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
97 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
98 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
99 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
100 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
101
102 //
103 // Utilities for testing Google Test itself and code that uses Google Test
104 // (e.g. frameworks built on top of Google Test).
105
106 // GOOGLETEST_CM0004 DO NOT DELETE
107
108 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
109 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110
111
112 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
113 /* class A needs to have dll-interface to be used by clients of class B */)
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 ~ScopedFakeTestPartResultReporter() override;
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 void ReportTestPartResult(const TestPartResult& result) override;
154
155 private:
156 void Init();
157
158 const InterceptMode intercept_mode_;
159 TestPartResultReporterInterface* old_reporter_;
160 TestPartResultArray* const result_;
161
162 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
163 };
164
165 namespace internal {
166
167 // A helper class for implementing EXPECT_FATAL_FAILURE() and
168 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
169 // TestPartResultArray contains exactly one failure that has the given
170 // type and contains the given substring. If that's not the case, a
171 // non-fatal failure will be generated.
172 class GTEST_API_ SingleFailureChecker {
173 public:
174 // The constructor remembers the arguments.
175 SingleFailureChecker(const TestPartResultArray* results,
176 TestPartResult::Type type, const std::string& substr);
177 ~SingleFailureChecker();
178 private:
179 const TestPartResultArray* const results_;
180 const TestPartResult::Type type_;
181 const std::string substr_;
182
183 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184 };
185
186 } // namespace internal
187
188 } // namespace testing
189
190 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
191
192 // A set of macros for testing Google Test assertions or code that's expected
193 // to generate Google Test fatal failures. It verifies that the given
194 // statement will cause exactly one fatal Google Test failure with 'substr'
195 // being part of the failure message.
196 //
197 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
198 // affects and considers failures generated in the current thread and
199 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
200 //
201 // The verification of the assertion is done correctly even when the statement
202 // throws an exception or aborts the current function.
203 //
204 // Known restrictions:
205 // - 'statement' cannot reference local non-static variables or
206 // non-static members of the current object.
207 // - 'statement' cannot return a value.
208 // - You cannot stream a failure message to this macro.
209 //
210 // Note that even though the implementations of the following two
211 // macros are much alike, we cannot refactor them to use a common
212 // helper macro, due to some peculiarity in how the preprocessor
213 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
214 // gtest_unittest.cc will fail to compile if we do that.
215 #define EXPECT_FATAL_FAILURE(statement, substr) \
216 do { \
217 class GTestExpectFatalFailureHelper {\
218 public:\
219 static void Execute() { statement; }\
220 };\
221 ::testing::TestPartResultArray gtest_failures;\
222 ::testing::internal::SingleFailureChecker gtest_checker(\
223 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
224 {\
225 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
226 ::testing::ScopedFakeTestPartResultReporter:: \
227 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
228 GTestExpectFatalFailureHelper::Execute();\
229 }\
230 } while (::testing::internal::AlwaysFalse())
231
232 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
233 do { \
234 class GTestExpectFatalFailureHelper {\
235 public:\
236 static void Execute() { statement; }\
237 };\
238 ::testing::TestPartResultArray gtest_failures;\
239 ::testing::internal::SingleFailureChecker gtest_checker(\
240 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
241 {\
242 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
243 ::testing::ScopedFakeTestPartResultReporter:: \
244 INTERCEPT_ALL_THREADS, >est_failures);\
245 GTestExpectFatalFailureHelper::Execute();\
246 }\
247 } while (::testing::internal::AlwaysFalse())
248
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures. It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
253 //
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257 //
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
260 //
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
263 //
264 // Known restrictions:
265 // - You cannot stream a failure message to this macro.
266 //
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works. If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma. The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274 // catches that.
275 //
276 // For the same reason, we have to write
277 // if (::testing::internal::AlwaysTrue()) { statement; }
278 // instead of
279 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
282 do {\
283 ::testing::TestPartResultArray gtest_failures;\
284 ::testing::internal::SingleFailureChecker gtest_checker(\
285 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
286 (substr));\
287 {\
288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
289 ::testing::ScopedFakeTestPartResultReporter:: \
290 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
291 if (::testing::internal::AlwaysTrue()) { statement; }\
292 }\
293 } while (::testing::internal::AlwaysFalse())
294
295 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
296 do {\
297 ::testing::TestPartResultArray gtest_failures;\
298 ::testing::internal::SingleFailureChecker gtest_checker(\
299 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
300 (substr));\
301 {\
302 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
303 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
304 >est_failures);\
305 if (::testing::internal::AlwaysTrue()) { statement; }\
306 }\
307 } while (::testing::internal::AlwaysFalse())
308
309 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
310
311 #include <ctype.h>
312 #include <math.h>
313 #include <stdarg.h>
314 #include <stdio.h>
315 #include <stdlib.h>
316 #include <time.h>
317 #include <wchar.h>
318 #include <wctype.h>
319
320 #include <algorithm>
321 #include <iomanip>
322 #include <limits>
323 #include <list>
324 #include <map>
325 #include <ostream> // NOLINT
326 #include <sstream>
327 #include <vector>
328
329 #if GTEST_OS_LINUX
330
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_ZOS
344 # define GTEST_HAS_GETTIMEOFDAY_ 1
345 # include <sys/time.h> // NOLINT
346
347 // On z/OS we additionally need strings.h for strcasecmp.
348 # include <strings.h> // NOLINT
349
350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
351
352 # include <windows.h> // NOLINT
353 # undef min
354
355 #elif GTEST_OS_WINDOWS // We are on Windows proper.
356
357 # include <io.h> // NOLINT
358 # include <sys/timeb.h> // NOLINT
359 # include <sys/types.h> // NOLINT
360 # include <sys/stat.h> // NOLINT
361
362 # if GTEST_OS_WINDOWS_MINGW
363 // MinGW has gettimeofday() but not _ftime64().
364 # define GTEST_HAS_GETTIMEOFDAY_ 1
365 # include <sys/time.h> // NOLINT
366 # endif // GTEST_OS_WINDOWS_MINGW
367
368 // cpplint thinks that the header is already included, so we want to
369 // silence it.
370 # include <windows.h> // NOLINT
371 # undef min
372
373 #else
374
375 // Assume other platforms have gettimeofday().
376 # define GTEST_HAS_GETTIMEOFDAY_ 1
377
378 // cpplint thinks that the header is already included, so we want to
379 // silence it.
380 # include <sys/time.h> // NOLINT
381 # include <unistd.h> // NOLINT
382
383 #endif // GTEST_OS_LINUX
384
385 #if GTEST_HAS_EXCEPTIONS
386 # include <stdexcept>
387 #endif
388
389 #if GTEST_CAN_STREAM_RESULTS_
390 # include <arpa/inet.h> // NOLINT
391 # include <netdb.h> // NOLINT
392 # include <sys/socket.h> // NOLINT
393 # include <sys/types.h> // NOLINT
394 #endif
395
396 // Copyright 2005, Google Inc.
397 // All rights reserved.
398 //
399 // Redistribution and use in source and binary forms, with or without
400 // modification, are permitted provided that the following conditions are
401 // met:
402 //
403 // * Redistributions of source code must retain the above copyright
404 // notice, this list of conditions and the following disclaimer.
405 // * Redistributions in binary form must reproduce the above
406 // copyright notice, this list of conditions and the following disclaimer
407 // in the documentation and/or other materials provided with the
408 // distribution.
409 // * Neither the name of Google Inc. nor the names of its
410 // contributors may be used to endorse or promote products derived from
411 // this software without specific prior written permission.
412 //
413 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
414 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
415 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
416 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
417 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
418 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
419 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
420 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
421 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
422 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
423 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
424
425 // Utility functions and classes used by the Google C++ testing framework.//
426 // This file contains purely Google Test's internal implementation. Please
427 // DO NOT #INCLUDE IT IN A USER PROGRAM.
428
429 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
430 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
431
432 #ifndef _WIN32_WCE
433 # include <errno.h>
434 #endif // !_WIN32_WCE
435 #include <stddef.h>
436 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
437 #include <string.h> // For memmove.
438
439 #include <algorithm>
440 #include <memory>
441 #include <string>
442 #include <vector>
443
444
445 #if GTEST_CAN_STREAM_RESULTS_
446 # include <arpa/inet.h> // NOLINT
447 # include <netdb.h> // NOLINT
448 #endif
449
450 #if GTEST_OS_WINDOWS
451 # include <windows.h> // NOLINT
452 #endif // GTEST_OS_WINDOWS
453
454
455 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
456 /* class A needs to have dll-interface to be used by clients of class B */)
457
458 namespace testing {
459
460 // Declares the flags.
461 //
462 // We don't want the users to modify this flag in the code, but want
463 // Google Test's own unit tests to be able to access it. Therefore we
464 // declare it here as opposed to in gtest.h.
465 GTEST_DECLARE_bool_(death_test_use_fork);
466
467 namespace internal {
468
469 // The value of GetTestTypeId() as seen from within the Google Test
470 // library. This is solely for testing GetTestTypeId().
471 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
472
473 // Names of the flags (needed for parsing Google Test flags).
474 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
475 const char kBreakOnFailureFlag[] = "break_on_failure";
476 const char kCatchExceptionsFlag[] = "catch_exceptions";
477 const char kColorFlag[] = "color";
478 const char kFilterFlag[] = "filter";
479 const char kListTestsFlag[] = "list_tests";
480 const char kOutputFlag[] = "output";
481 const char kPrintTimeFlag[] = "print_time";
482 const char kPrintUTF8Flag[] = "print_utf8";
483 const char kRandomSeedFlag[] = "random_seed";
484 const char kRepeatFlag[] = "repeat";
485 const char kShuffleFlag[] = "shuffle";
486 const char kStackTraceDepthFlag[] = "stack_trace_depth";
487 const char kStreamResultToFlag[] = "stream_result_to";
488 const char kThrowOnFailureFlag[] = "throw_on_failure";
489 const char kFlagfileFlag[] = "flagfile";
490
491 // A valid random seed must be in [1, kMaxRandomSeed].
492 const int kMaxRandomSeed = 99999;
493
494 // g_help_flag is true iff the --help flag or an equivalent form is
495 // specified on the command line.
496 GTEST_API_ extern bool g_help_flag;
497
498 // Returns the current time in milliseconds.
499 GTEST_API_ TimeInMillis GetTimeInMillis();
500
501 // Returns true iff Google Test should use colors in the output.
502 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
503
504 // Formats the given time in milliseconds as seconds.
505 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
506
507 // Converts the given time in milliseconds to a date string in the ISO 8601
508 // format, without the timezone information. N.B.: due to the use the
509 // non-reentrant localtime() function, this function is not thread safe. Do
510 // not use it in any code that can be called from multiple threads.
511 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
512
513 // Parses a string for an Int32 flag, in the form of "--flag=value".
514 //
515 // On success, stores the value of the flag in *value, and returns
516 // true. On failure, returns false without changing *value.
517 GTEST_API_ bool ParseInt32Flag(
518 const char* str, const char* flag, Int32* value);
519
520 // Returns a random seed in range [1, kMaxRandomSeed] based on the
521 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(Int32 random_seed_flag)522 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
523 const unsigned int raw_seed = (random_seed_flag == 0) ?
524 static_cast<unsigned int>(GetTimeInMillis()) :
525 static_cast<unsigned int>(random_seed_flag);
526
527 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
528 // it's easy to type.
529 const int normalized_seed =
530 static_cast<int>((raw_seed - 1U) %
531 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
532 return normalized_seed;
533 }
534
535 // Returns the first valid random seed after 'seed'. The behavior is
536 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
537 // considered to be 1.
GetNextRandomSeed(int seed)538 inline int GetNextRandomSeed(int seed) {
539 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
540 << "Invalid random seed " << seed << " - must be in [1, "
541 << kMaxRandomSeed << "].";
542 const int next_seed = seed + 1;
543 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
544 }
545
546 // This class saves the values of all Google Test flags in its c'tor, and
547 // restores them in its d'tor.
548 class GTestFlagSaver {
549 public:
550 // The c'tor.
GTestFlagSaver()551 GTestFlagSaver() {
552 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
553 break_on_failure_ = GTEST_FLAG(break_on_failure);
554 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
555 color_ = GTEST_FLAG(color);
556 death_test_style_ = GTEST_FLAG(death_test_style);
557 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
558 filter_ = GTEST_FLAG(filter);
559 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
560 list_tests_ = GTEST_FLAG(list_tests);
561 output_ = GTEST_FLAG(output);
562 print_time_ = GTEST_FLAG(print_time);
563 print_utf8_ = GTEST_FLAG(print_utf8);
564 random_seed_ = GTEST_FLAG(random_seed);
565 repeat_ = GTEST_FLAG(repeat);
566 shuffle_ = GTEST_FLAG(shuffle);
567 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
568 stream_result_to_ = GTEST_FLAG(stream_result_to);
569 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
570 }
571
572 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()573 ~GTestFlagSaver() {
574 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
575 GTEST_FLAG(break_on_failure) = break_on_failure_;
576 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
577 GTEST_FLAG(color) = color_;
578 GTEST_FLAG(death_test_style) = death_test_style_;
579 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
580 GTEST_FLAG(filter) = filter_;
581 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
582 GTEST_FLAG(list_tests) = list_tests_;
583 GTEST_FLAG(output) = output_;
584 GTEST_FLAG(print_time) = print_time_;
585 GTEST_FLAG(print_utf8) = print_utf8_;
586 GTEST_FLAG(random_seed) = random_seed_;
587 GTEST_FLAG(repeat) = repeat_;
588 GTEST_FLAG(shuffle) = shuffle_;
589 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
590 GTEST_FLAG(stream_result_to) = stream_result_to_;
591 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
592 }
593
594 private:
595 // Fields for saving the original values of flags.
596 bool also_run_disabled_tests_;
597 bool break_on_failure_;
598 bool catch_exceptions_;
599 std::string color_;
600 std::string death_test_style_;
601 bool death_test_use_fork_;
602 std::string filter_;
603 std::string internal_run_death_test_;
604 bool list_tests_;
605 std::string output_;
606 bool print_time_;
607 bool print_utf8_;
608 internal::Int32 random_seed_;
609 internal::Int32 repeat_;
610 bool shuffle_;
611 internal::Int32 stack_trace_depth_;
612 std::string stream_result_to_;
613 bool throw_on_failure_;
614 } GTEST_ATTRIBUTE_UNUSED_;
615
616 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
617 // code_point parameter is of type UInt32 because wchar_t may not be
618 // wide enough to contain a code point.
619 // If the code_point is not a valid Unicode code point
620 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
621 // to "(Invalid Unicode 0xXXXXXXXX)".
622 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
623
624 // Converts a wide string to a narrow string in UTF-8 encoding.
625 // The wide string is assumed to have the following encoding:
626 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
627 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
628 // Parameter str points to a null-terminated wide string.
629 // Parameter num_chars may additionally limit the number
630 // of wchar_t characters processed. -1 is used when the entire string
631 // should be processed.
632 // If the string contains code points that are not valid Unicode code points
633 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
634 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
635 // and contains invalid UTF-16 surrogate pairs, values in those pairs
636 // will be encoded as individual Unicode characters from Basic Normal Plane.
637 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
638
639 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
640 // if the variable is present. If a file already exists at this location, this
641 // function will write over it. If the variable is present, but the file cannot
642 // be created, prints an error and exits.
643 void WriteToShardStatusFileIfNeeded();
644
645 // Checks whether sharding is enabled by examining the relevant
646 // environment variable values. If the variables are present,
647 // but inconsistent (e.g., shard_index >= total_shards), prints
648 // an error and exits. If in_subprocess_for_death_test, sharding is
649 // disabled because it must only be applied to the original test
650 // process. Otherwise, we could filter out death tests we intended to execute.
651 GTEST_API_ bool ShouldShard(const char* total_shards_str,
652 const char* shard_index_str,
653 bool in_subprocess_for_death_test);
654
655 // Parses the environment variable var as an Int32. If it is unset,
656 // returns default_val. If it is not an Int32, prints an error and
657 // and aborts.
658 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
659
660 // Given the total number of shards, the shard index, and the test id,
661 // returns true iff the test should be run on this shard. The test id is
662 // some arbitrary but unique non-negative integer assigned to each test
663 // method. Assumes that 0 <= shard_index < total_shards.
664 GTEST_API_ bool ShouldRunTestOnShard(
665 int total_shards, int shard_index, int test_id);
666
667 // STL container utilities.
668
669 // Returns the number of elements in the given container that satisfy
670 // the given predicate.
671 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)672 inline int CountIf(const Container& c, Predicate predicate) {
673 // Implemented as an explicit loop since std::count_if() in libCstd on
674 // Solaris has a non-standard signature.
675 int count = 0;
676 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
677 if (predicate(*it))
678 ++count;
679 }
680 return count;
681 }
682
683 // Applies a function/functor to each element in the container.
684 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)685 void ForEach(const Container& c, Functor functor) {
686 std::for_each(c.begin(), c.end(), functor);
687 }
688
689 // Returns the i-th element of the vector, or default_value if i is not
690 // in range [0, v.size()).
691 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)692 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
693 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
694 }
695
696 // Performs an in-place shuffle of a range of the vector's elements.
697 // 'begin' and 'end' are element indices as an STL-style range;
698 // i.e. [begin, end) are shuffled, where 'end' == size() means to
699 // shuffle to the end of the vector.
700 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)701 void ShuffleRange(internal::Random* random, int begin, int end,
702 std::vector<E>* v) {
703 const int size = static_cast<int>(v->size());
704 GTEST_CHECK_(0 <= begin && begin <= size)
705 << "Invalid shuffle range start " << begin << ": must be in range [0, "
706 << size << "].";
707 GTEST_CHECK_(begin <= end && end <= size)
708 << "Invalid shuffle range finish " << end << ": must be in range ["
709 << begin << ", " << size << "].";
710
711 // Fisher-Yates shuffle, from
712 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
713 for (int range_width = end - begin; range_width >= 2; range_width--) {
714 const int last_in_range = begin + range_width - 1;
715 const int selected = begin + random->Generate(range_width);
716 std::swap((*v)[selected], (*v)[last_in_range]);
717 }
718 }
719
720 // Performs an in-place shuffle of the vector's elements.
721 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)722 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
723 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
724 }
725
726 // A function for deleting an object. Handy for being used as a
727 // functor.
728 template <typename T>
Delete(T * x)729 static void Delete(T* x) {
730 delete x;
731 }
732
733 // A predicate that checks the key of a TestProperty against a known key.
734 //
735 // TestPropertyKeyIs is copyable.
736 class TestPropertyKeyIs {
737 public:
738 // Constructor.
739 //
740 // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)741 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
742
743 // Returns true iff the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const744 bool operator()(const TestProperty& test_property) const {
745 return test_property.key() == key_;
746 }
747
748 private:
749 std::string key_;
750 };
751
752 // Class UnitTestOptions.
753 //
754 // This class contains functions for processing options the user
755 // specifies when running the tests. It has only static members.
756 //
757 // In most cases, the user can specify an option using either an
758 // environment variable or a command line flag. E.g. you can set the
759 // test filter using either GTEST_FILTER or --gtest_filter. If both
760 // the variable and the flag are present, the latter overrides the
761 // former.
762 class GTEST_API_ UnitTestOptions {
763 public:
764 // Functions for processing the gtest_output flag.
765
766 // Returns the output format, or "" for normal printed output.
767 static std::string GetOutputFormat();
768
769 // Returns the absolute path of the requested output file, or the
770 // default (test_detail.xml in the original working directory) if
771 // none was explicitly specified.
772 static std::string GetAbsolutePathToOutputFile();
773
774 // Functions for processing the gtest_filter flag.
775
776 // Returns true iff the wildcard pattern matches the string. The
777 // first ':' or '\0' character in pattern marks the end of it.
778 //
779 // This recursive algorithm isn't very efficient, but is clear and
780 // works well enough for matching test names, which are short.
781 static bool PatternMatchesString(const char *pattern, const char *str);
782
783 // Returns true iff the user-specified filter matches the test suite
784 // name and the test name.
785 static bool FilterMatchesTest(const std::string& test_suite_name,
786 const std::string& test_name);
787
788 #if GTEST_OS_WINDOWS
789 // Function for supporting the gtest_catch_exception flag.
790
791 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
792 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
793 // This function is useful as an __except condition.
794 static int GTestShouldProcessSEH(DWORD exception_code);
795 #endif // GTEST_OS_WINDOWS
796
797 // Returns true if "name" matches the ':' separated list of glob-style
798 // filters in "filter".
799 static bool MatchesFilter(const std::string& name, const char* filter);
800 };
801
802 // Returns the current application's name, removing directory path if that
803 // is present. Used by UnitTestOptions::GetOutputFile.
804 GTEST_API_ FilePath GetCurrentExecutableName();
805
806 // The role interface for getting the OS stack trace as a string.
807 class OsStackTraceGetterInterface {
808 public:
OsStackTraceGetterInterface()809 OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()810 virtual ~OsStackTraceGetterInterface() {}
811
812 // Returns the current OS stack trace as an std::string. Parameters:
813 //
814 // max_depth - the maximum number of stack frames to be included
815 // in the trace.
816 // skip_count - the number of top frames to be skipped; doesn't count
817 // against max_depth.
818 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
819
820 // UponLeavingGTest() should be called immediately before Google Test calls
821 // user code. It saves some information about the current stack that
822 // CurrentStackTrace() will use to find and hide Google Test stack frames.
823 virtual void UponLeavingGTest() = 0;
824
825 // This string is inserted in place of stack frames that are part of
826 // Google Test's implementation.
827 static const char* const kElidedFramesMarker;
828
829 private:
830 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
831 };
832
833 // A working implementation of the OsStackTraceGetterInterface interface.
834 class OsStackTraceGetter : public OsStackTraceGetterInterface {
835 public:
OsStackTraceGetter()836 OsStackTraceGetter() {}
837
838 std::string CurrentStackTrace(int max_depth, int skip_count) override;
839 void UponLeavingGTest() override;
840
841 private:
842 #if GTEST_HAS_ABSL
843 Mutex mutex_; // Protects all internal state.
844
845 // We save the stack frame below the frame that calls user code.
846 // We do this because the address of the frame immediately below
847 // the user code changes between the call to UponLeavingGTest()
848 // and any calls to the stack trace code from within the user code.
849 void* caller_frame_ = nullptr;
850 #endif // GTEST_HAS_ABSL
851
852 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
853 };
854
855 // Information about a Google Test trace point.
856 struct TraceInfo {
857 const char* file;
858 int line;
859 std::string message;
860 };
861
862 // This is the default global test part result reporter used in UnitTestImpl.
863 // This class should only be used by UnitTestImpl.
864 class DefaultGlobalTestPartResultReporter
865 : public TestPartResultReporterInterface {
866 public:
867 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
868 // Implements the TestPartResultReporterInterface. Reports the test part
869 // result in the current test.
870 void ReportTestPartResult(const TestPartResult& result) override;
871
872 private:
873 UnitTestImpl* const unit_test_;
874
875 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
876 };
877
878 // This is the default per thread test part result reporter used in
879 // UnitTestImpl. This class should only be used by UnitTestImpl.
880 class DefaultPerThreadTestPartResultReporter
881 : public TestPartResultReporterInterface {
882 public:
883 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
884 // Implements the TestPartResultReporterInterface. The implementation just
885 // delegates to the current global test part result reporter of *unit_test_.
886 void ReportTestPartResult(const TestPartResult& result) override;
887
888 private:
889 UnitTestImpl* const unit_test_;
890
891 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
892 };
893
894 // The private implementation of the UnitTest class. We don't protect
895 // the methods under a mutex, as this class is not accessible by a
896 // user and the UnitTest class that delegates work to this class does
897 // proper locking.
898 class GTEST_API_ UnitTestImpl {
899 public:
900 explicit UnitTestImpl(UnitTest* parent);
901 virtual ~UnitTestImpl();
902
903 // There are two different ways to register your own TestPartResultReporter.
904 // You can register your own repoter to listen either only for test results
905 // from the current thread or for results from all threads.
906 // By default, each per-thread test result repoter just passes a new
907 // TestPartResult to the global test result reporter, which registers the
908 // test part result for the currently running test.
909
910 // Returns the global test part result reporter.
911 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
912
913 // Sets the global test part result reporter.
914 void SetGlobalTestPartResultReporter(
915 TestPartResultReporterInterface* reporter);
916
917 // Returns the test part result reporter for the current thread.
918 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
919
920 // Sets the test part result reporter for the current thread.
921 void SetTestPartResultReporterForCurrentThread(
922 TestPartResultReporterInterface* reporter);
923
924 // Gets the number of successful test suites.
925 int successful_test_suite_count() const;
926
927 // Gets the number of failed test suites.
928 int failed_test_suite_count() const;
929
930 // Gets the number of all test suites.
931 int total_test_suite_count() const;
932
933 // Gets the number of all test suites that contain at least one test
934 // that should run.
935 int test_suite_to_run_count() const;
936
937 // Gets the number of successful tests.
938 int successful_test_count() const;
939
940 // Gets the number of skipped tests.
941 int skipped_test_count() const;
942
943 // Gets the number of failed tests.
944 int failed_test_count() const;
945
946 // Gets the number of disabled tests that will be reported in the XML report.
947 int reportable_disabled_test_count() const;
948
949 // Gets the number of disabled tests.
950 int disabled_test_count() const;
951
952 // Gets the number of tests to be printed in the XML report.
953 int reportable_test_count() const;
954
955 // Gets the number of all tests.
956 int total_test_count() const;
957
958 // Gets the number of tests that should run.
959 int test_to_run_count() const;
960
961 // Gets the time of the test program start, in ms from the start of the
962 // UNIX epoch.
start_timestamp() const963 TimeInMillis start_timestamp() const { return start_timestamp_; }
964
965 // Gets the elapsed time, in milliseconds.
elapsed_time() const966 TimeInMillis elapsed_time() const { return elapsed_time_; }
967
968 // Returns true iff the unit test passed (i.e. all test suites passed).
Passed() const969 bool Passed() const { return !Failed(); }
970
971 // Returns true iff the unit test failed (i.e. some test suite failed
972 // or something outside of all tests failed).
Failed() const973 bool Failed() const {
974 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
975 }
976
977 // Gets the i-th test suite among all the test suites. i can range from 0 to
978 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i) const979 const TestSuite* GetTestSuite(int i) const {
980 const int index = GetElementOr(test_suite_indices_, i, -1);
981 return index < 0 ? nullptr : test_suites_[i];
982 }
983
984 // Legacy API is deprecated but still available
985 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i) const986 const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
987 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
988
989 // Gets the i-th test suite among all the test suites. i can range from 0 to
990 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableSuiteCase(int i)991 TestSuite* GetMutableSuiteCase(int i) {
992 const int index = GetElementOr(test_suite_indices_, i, -1);
993 return index < 0 ? nullptr : test_suites_[index];
994 }
995
996 // Provides access to the event listener list.
listeners()997 TestEventListeners* listeners() { return &listeners_; }
998
999 // Returns the TestResult for the test that's currently running, or
1000 // the TestResult for the ad hoc test if no test is running.
1001 TestResult* current_test_result();
1002
1003 // Returns the TestResult for the ad hoc test.
ad_hoc_test_result() const1004 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1005
1006 // Sets the OS stack trace getter.
1007 //
1008 // Does nothing if the input and the current OS stack trace getter
1009 // are the same; otherwise, deletes the old getter and makes the
1010 // input the current getter.
1011 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1012
1013 // Returns the current OS stack trace getter if it is not NULL;
1014 // otherwise, creates an OsStackTraceGetter, makes it the current
1015 // getter, and returns it.
1016 OsStackTraceGetterInterface* os_stack_trace_getter();
1017
1018 // Returns the current OS stack trace as an std::string.
1019 //
1020 // The maximum number of stack frames to be included is specified by
1021 // the gtest_stack_trace_depth flag. The skip_count parameter
1022 // specifies the number of top frames to be skipped, which doesn't
1023 // count against the number of frames to be included.
1024 //
1025 // For example, if Foo() calls Bar(), which in turn calls
1026 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1027 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1028 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1029
1030 // Finds and returns a TestSuite with the given name. If one doesn't
1031 // exist, creates one and returns it.
1032 //
1033 // Arguments:
1034 //
1035 // test_suite_name: name of the test suite
1036 // type_param: the name of the test's type parameter, or NULL if
1037 // this is not a typed or a type-parameterized test.
1038 // set_up_tc: pointer to the function that sets up the test suite
1039 // tear_down_tc: pointer to the function that tears down the test suite
1040 TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
1041 internal::SetUpTestSuiteFunc set_up_tc,
1042 internal::TearDownTestSuiteFunc tear_down_tc);
1043
1044 // Legacy API is deprecated but still available
1045 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(const char * test_case_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)1046 TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1047 internal::SetUpTestSuiteFunc set_up_tc,
1048 internal::TearDownTestSuiteFunc tear_down_tc) {
1049 return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
1050 }
1051 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1052
1053 // Adds a TestInfo to the unit test.
1054 //
1055 // Arguments:
1056 //
1057 // set_up_tc: pointer to the function that sets up the test suite
1058 // tear_down_tc: pointer to the function that tears down the test suite
1059 // test_info: the TestInfo object
AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc,TestInfo * test_info)1060 void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
1061 internal::TearDownTestSuiteFunc tear_down_tc,
1062 TestInfo* test_info) {
1063 // In order to support thread-safe death tests, we need to
1064 // remember the original working directory when the test program
1065 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1066 // the user may have changed the current directory before calling
1067 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1068 // AddTestInfo(), which is called to register a TEST or TEST_F
1069 // before main() is reached.
1070 if (original_working_dir_.IsEmpty()) {
1071 original_working_dir_.Set(FilePath::GetCurrentDir());
1072 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1073 << "Failed to get the current working directory.";
1074 }
1075
1076 GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1077 set_up_tc, tear_down_tc)
1078 ->AddTestInfo(test_info);
1079 }
1080
1081 // Returns ParameterizedTestSuiteRegistry object used to keep track of
1082 // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1083 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
1084 return parameterized_test_registry_;
1085 }
1086
1087 // Sets the TestSuite object for the test that's currently running.
set_current_test_suite(TestSuite * a_current_test_suite)1088 void set_current_test_suite(TestSuite* a_current_test_suite) {
1089 current_test_suite_ = a_current_test_suite;
1090 }
1091
1092 // Sets the TestInfo object for the test that's currently running. If
1093 // current_test_info is NULL, the assertion results will be stored in
1094 // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1095 void set_current_test_info(TestInfo* a_current_test_info) {
1096 current_test_info_ = a_current_test_info;
1097 }
1098
1099 // Registers all parameterized tests defined using TEST_P and
1100 // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
1101 // combination. This method can be called more then once; it has guards
1102 // protecting from registering the tests more then once. If
1103 // value-parameterized tests are disabled, RegisterParameterizedTests is
1104 // present but does nothing.
1105 void RegisterParameterizedTests();
1106
1107 // Runs all tests in this UnitTest object, prints the result, and
1108 // returns true if all tests are successful. If any exception is
1109 // thrown during a test, this test is considered to be failed, but
1110 // the rest of the tests will still be run.
1111 bool RunAllTests();
1112
1113 // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1114 void ClearNonAdHocTestResult() {
1115 ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
1116 }
1117
1118 // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1119 void ClearAdHocTestResult() {
1120 ad_hoc_test_result_.Clear();
1121 }
1122
1123 // Adds a TestProperty to the current TestResult object when invoked in a
1124 // context of a test or a test suite, or to the global property set. If the
1125 // result already contains a property with the same key, the value will be
1126 // updated.
1127 void RecordProperty(const TestProperty& test_property);
1128
1129 enum ReactionToSharding {
1130 HONOR_SHARDING_PROTOCOL,
1131 IGNORE_SHARDING_PROTOCOL
1132 };
1133
1134 // Matches the full name of each test against the user-specified
1135 // filter to decide whether the test should run, then records the
1136 // result in each TestSuite and TestInfo object.
1137 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1138 // based on sharding variables in the environment.
1139 // Returns the number of tests that should run.
1140 int FilterTests(ReactionToSharding shard_tests);
1141
1142 // Prints the names of the tests matching the user-specified filter flag.
1143 void ListTestsMatchingFilter();
1144
current_test_suite() const1145 const TestSuite* current_test_suite() const { return current_test_suite_; }
current_test_info()1146 TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1147 const TestInfo* current_test_info() const { return current_test_info_; }
1148
1149 // Returns the vector of environments that need to be set-up/torn-down
1150 // before/after the tests are run.
environments()1151 std::vector<Environment*>& environments() { return environments_; }
1152
1153 // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1154 std::vector<TraceInfo>& gtest_trace_stack() {
1155 return *(gtest_trace_stack_.pointer());
1156 }
gtest_trace_stack() const1157 const std::vector<TraceInfo>& gtest_trace_stack() const {
1158 return gtest_trace_stack_.get();
1159 }
1160
1161 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1162 void InitDeathTestSubprocessControlInfo() {
1163 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1164 }
1165 // Returns a pointer to the parsed --gtest_internal_run_death_test
1166 // flag, or NULL if that flag was not specified.
1167 // This information is useful only in a death test child process.
1168 // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1169 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1170 return internal_run_death_test_flag_.get();
1171 }
1172
1173 // Returns a pointer to the current death test factory.
death_test_factory()1174 internal::DeathTestFactory* death_test_factory() {
1175 return death_test_factory_.get();
1176 }
1177
1178 void SuppressTestEventsIfInSubprocess();
1179
1180 friend class ReplaceDeathTestFactory;
1181 #endif // GTEST_HAS_DEATH_TEST
1182
1183 // Initializes the event listener performing XML output as specified by
1184 // UnitTestOptions. Must not be called before InitGoogleTest.
1185 void ConfigureXmlOutput();
1186
1187 #if GTEST_CAN_STREAM_RESULTS_
1188 // Initializes the event listener for streaming test results to a socket.
1189 // Must not be called before InitGoogleTest.
1190 void ConfigureStreamingOutput();
1191 #endif
1192
1193 // Performs initialization dependent upon flag values obtained in
1194 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1195 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1196 // this function is also called from RunAllTests. Since this function can be
1197 // called more than once, it has to be idempotent.
1198 void PostFlagParsingInit();
1199
1200 // Gets the random seed used at the start of the current test iteration.
random_seed() const1201 int random_seed() const { return random_seed_; }
1202
1203 // Gets the random number generator.
random()1204 internal::Random* random() { return &random_; }
1205
1206 // Shuffles all test suites, and the tests within each test suite,
1207 // making sure that death tests are still run first.
1208 void ShuffleTests();
1209
1210 // Restores the test suites and tests to their order before the first shuffle.
1211 void UnshuffleTests();
1212
1213 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1214 // UnitTest::Run() starts.
catch_exceptions() const1215 bool catch_exceptions() const { return catch_exceptions_; }
1216
1217 private:
1218 friend class ::testing::UnitTest;
1219
1220 // Used by UnitTest::Run() to capture the state of
1221 // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1222 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1223
1224 // The UnitTest object that owns this implementation object.
1225 UnitTest* const parent_;
1226
1227 // The working directory when the first TEST() or TEST_F() was
1228 // executed.
1229 internal::FilePath original_working_dir_;
1230
1231 // The default test part result reporters.
1232 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1233 DefaultPerThreadTestPartResultReporter
1234 default_per_thread_test_part_result_reporter_;
1235
1236 // Points to (but doesn't own) the global test part result reporter.
1237 TestPartResultReporterInterface* global_test_part_result_repoter_;
1238
1239 // Protects read and write access to global_test_part_result_reporter_.
1240 internal::Mutex global_test_part_result_reporter_mutex_;
1241
1242 // Points to (but doesn't own) the per-thread test part result reporter.
1243 internal::ThreadLocal<TestPartResultReporterInterface*>
1244 per_thread_test_part_result_reporter_;
1245
1246 // The vector of environments that need to be set-up/torn-down
1247 // before/after the tests are run.
1248 std::vector<Environment*> environments_;
1249
1250 // The vector of TestSuites in their original order. It owns the
1251 // elements in the vector.
1252 std::vector<TestSuite*> test_suites_;
1253
1254 // Provides a level of indirection for the test suite list to allow
1255 // easy shuffling and restoring the test suite order. The i-th
1256 // element of this vector is the index of the i-th test suite in the
1257 // shuffled order.
1258 std::vector<int> test_suite_indices_;
1259
1260 // ParameterizedTestRegistry object used to register value-parameterized
1261 // tests.
1262 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
1263
1264 // Indicates whether RegisterParameterizedTests() has been called already.
1265 bool parameterized_tests_registered_;
1266
1267 // Index of the last death test suite registered. Initially -1.
1268 int last_death_test_suite_;
1269
1270 // This points to the TestSuite for the currently running test. It
1271 // changes as Google Test goes through one test suite after another.
1272 // When no test is running, this is set to NULL and Google Test
1273 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1274 TestSuite* current_test_suite_;
1275
1276 // This points to the TestInfo for the currently running test. It
1277 // changes as Google Test goes through one test after another. When
1278 // no test is running, this is set to NULL and Google Test stores
1279 // assertion results in ad_hoc_test_result_. Initially NULL.
1280 TestInfo* current_test_info_;
1281
1282 // Normally, a user only writes assertions inside a TEST or TEST_F,
1283 // or inside a function called by a TEST or TEST_F. Since Google
1284 // Test keeps track of which test is current running, it can
1285 // associate such an assertion with the test it belongs to.
1286 //
1287 // If an assertion is encountered when no TEST or TEST_F is running,
1288 // Google Test attributes the assertion result to an imaginary "ad hoc"
1289 // test, and records the result in ad_hoc_test_result_.
1290 TestResult ad_hoc_test_result_;
1291
1292 // The list of event listeners that can be used to track events inside
1293 // Google Test.
1294 TestEventListeners listeners_;
1295
1296 // The OS stack trace getter. Will be deleted when the UnitTest
1297 // object is destructed. By default, an OsStackTraceGetter is used,
1298 // but the user can set this field to use a custom getter if that is
1299 // desired.
1300 OsStackTraceGetterInterface* os_stack_trace_getter_;
1301
1302 // True iff PostFlagParsingInit() has been called.
1303 bool post_flag_parse_init_performed_;
1304
1305 // The random number seed used at the beginning of the test run.
1306 int random_seed_;
1307
1308 // Our random number generator.
1309 internal::Random random_;
1310
1311 // The time of the test program start, in ms from the start of the
1312 // UNIX epoch.
1313 TimeInMillis start_timestamp_;
1314
1315 // How long the test took to run, in milliseconds.
1316 TimeInMillis elapsed_time_;
1317
1318 #if GTEST_HAS_DEATH_TEST
1319 // The decomposed components of the gtest_internal_run_death_test flag,
1320 // parsed when RUN_ALL_TESTS is called.
1321 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322 std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
1323 #endif // GTEST_HAS_DEATH_TEST
1324
1325 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1326 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1327
1328 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329 // starts.
1330 bool catch_exceptions_;
1331
1332 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1333 }; // class UnitTestImpl
1334
1335 // Convenience function for accessing the global UnitTest
1336 // implementation object.
GetUnitTestImpl()1337 inline UnitTestImpl* GetUnitTestImpl() {
1338 return UnitTest::GetInstance()->impl();
1339 }
1340
1341 #if GTEST_USES_SIMPLE_RE
1342
1343 // Internal helper functions for implementing the simple regular
1344 // expression matcher.
1345 GTEST_API_ bool IsInSet(char ch, const char* str);
1346 GTEST_API_ bool IsAsciiDigit(char ch);
1347 GTEST_API_ bool IsAsciiPunct(char ch);
1348 GTEST_API_ bool IsRepeat(char ch);
1349 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1350 GTEST_API_ bool IsAsciiWordChar(char ch);
1351 GTEST_API_ bool IsValidEscape(char ch);
1352 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1353 GTEST_API_ bool ValidateRegex(const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped, char ch, char repeat, const char* regex, const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1358
1359 #endif // GTEST_USES_SIMPLE_RE
1360
1361 // Parses the command line for Google Test flags, without initializing
1362 // other parts of Google Test.
1363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1365
1366 #if GTEST_HAS_DEATH_TEST
1367
1368 // Returns the message describing the last system error, regardless of the
1369 // platform.
1370 GTEST_API_ std::string GetLastErrnoDescription();
1371
1372 // Attempts to parse a string into a positive integer pointed to by the
1373 // number parameter. Returns true if that is possible.
1374 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1375 // it here.
1376 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1377 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1378 // Fail fast if the given string does not begin with a digit;
1379 // this bypasses strtoXXX's "optional leading whitespace and plus
1380 // or minus sign" semantics, which are undesirable here.
1381 if (str.empty() || !IsDigit(str[0])) {
1382 return false;
1383 }
1384 errno = 0;
1385
1386 char* end;
1387 // BiggestConvertible is the largest integer type that system-provided
1388 // string-to-number conversion routines can return.
1389
1390 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1391
1392 // MSVC and C++ Builder define __int64 instead of the standard long long.
1393 typedef unsigned __int64 BiggestConvertible;
1394 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1395
1396 # else
1397
1398 typedef unsigned long long BiggestConvertible; // NOLINT
1399 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1400
1401 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1402
1403 const bool parse_success = *end == '\0' && errno == 0;
1404
1405 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1406
1407 const Integer result = static_cast<Integer>(parsed);
1408 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1409 *number = result;
1410 return true;
1411 }
1412 return false;
1413 }
1414 #endif // GTEST_HAS_DEATH_TEST
1415
1416 // TestResult contains some private methods that should be hidden from
1417 // Google Test user but are required for testing. This class allow our tests
1418 // to access them.
1419 //
1420 // This class is supplied only for the purpose of testing Google Test's own
1421 // constructs. Do not use it in user tests, either directly or indirectly.
1422 class TestResultAccessor {
1423 public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1424 static void RecordProperty(TestResult* test_result,
1425 const std::string& xml_element,
1426 const TestProperty& property) {
1427 test_result->RecordProperty(xml_element, property);
1428 }
1429
ClearTestPartResults(TestResult * test_result)1430 static void ClearTestPartResults(TestResult* test_result) {
1431 test_result->ClearTestPartResults();
1432 }
1433
test_part_results(const TestResult & test_result)1434 static const std::vector<testing::TestPartResult>& test_part_results(
1435 const TestResult& test_result) {
1436 return test_result.test_part_results();
1437 }
1438 };
1439
1440 #if GTEST_CAN_STREAM_RESULTS_
1441
1442 // Streams test results to the given port on the given host machine.
1443 class StreamingListener : public EmptyTestEventListener {
1444 public:
1445 // Abstract base class for writing strings to a socket.
1446 class AbstractSocketWriter {
1447 public:
~AbstractSocketWriter()1448 virtual ~AbstractSocketWriter() {}
1449
1450 // Sends a string to the socket.
1451 virtual void Send(const std::string& message) = 0;
1452
1453 // Closes the socket.
CloseConnection()1454 virtual void CloseConnection() {}
1455
1456 // Sends a string and a newline to the socket.
SendLn(const std::string & message)1457 void SendLn(const std::string& message) { Send(message + "\n"); }
1458 };
1459
1460 // Concrete class for actually writing strings to a socket.
1461 class SocketWriter : public AbstractSocketWriter {
1462 public:
SocketWriter(const std::string & host,const std::string & port)1463 SocketWriter(const std::string& host, const std::string& port)
1464 : sockfd_(-1), host_name_(host), port_num_(port) {
1465 MakeConnection();
1466 }
1467
~SocketWriter()1468 ~SocketWriter() override {
1469 if (sockfd_ != -1)
1470 CloseConnection();
1471 }
1472
1473 // Sends a string to the socket.
Send(const std::string & message)1474 void Send(const std::string& message) override {
1475 GTEST_CHECK_(sockfd_ != -1)
1476 << "Send() can be called only when there is a connection.";
1477
1478 const int len = static_cast<int>(message.length());
1479 if (write(sockfd_, message.c_str(), len) != len) {
1480 GTEST_LOG_(WARNING)
1481 << "stream_result_to: failed to stream to "
1482 << host_name_ << ":" << port_num_;
1483 }
1484 }
1485
1486 private:
1487 // Creates a client socket and connects to the server.
1488 void MakeConnection();
1489
1490 // Closes the socket.
CloseConnection()1491 void CloseConnection() override {
1492 GTEST_CHECK_(sockfd_ != -1)
1493 << "CloseConnection() can be called only when there is a connection.";
1494
1495 close(sockfd_);
1496 sockfd_ = -1;
1497 }
1498
1499 int sockfd_; // socket file descriptor
1500 const std::string host_name_;
1501 const std::string port_num_;
1502
1503 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1504 }; // class SocketWriter
1505
1506 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1507 static std::string UrlEncode(const char* str);
1508
StreamingListener(const std::string & host,const std::string & port)1509 StreamingListener(const std::string& host, const std::string& port)
1510 : socket_writer_(new SocketWriter(host, port)) {
1511 Start();
1512 }
1513
StreamingListener(AbstractSocketWriter * socket_writer)1514 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1515 : socket_writer_(socket_writer) { Start(); }
1516
OnTestProgramStart(const UnitTest &)1517 void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1518 SendLn("event=TestProgramStart");
1519 }
1520
OnTestProgramEnd(const UnitTest & unit_test)1521 void OnTestProgramEnd(const UnitTest& unit_test) override {
1522 // Note that Google Test current only report elapsed time for each
1523 // test iteration, not for the entire test program.
1524 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1525
1526 // Notify the streaming server to stop.
1527 socket_writer_->CloseConnection();
1528 }
1529
OnTestIterationStart(const UnitTest &,int iteration)1530 void OnTestIterationStart(const UnitTest& /* unit_test */,
1531 int iteration) override {
1532 SendLn("event=TestIterationStart&iteration=" +
1533 StreamableToString(iteration));
1534 }
1535
OnTestIterationEnd(const UnitTest & unit_test,int)1536 void OnTestIterationEnd(const UnitTest& unit_test,
1537 int /* iteration */) override {
1538 SendLn("event=TestIterationEnd&passed=" +
1539 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1540 StreamableToString(unit_test.elapsed_time()) + "ms");
1541 }
1542
1543 // Note that "event=TestCaseStart" is a wire format and has to remain
1544 // "case" for compatibilty
OnTestCaseStart(const TestCase & test_case)1545 void OnTestCaseStart(const TestCase& test_case) override {
1546 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1547 }
1548
1549 // Note that "event=TestCaseEnd" is a wire format and has to remain
1550 // "case" for compatibilty
OnTestCaseEnd(const TestCase & test_case)1551 void OnTestCaseEnd(const TestCase& test_case) override {
1552 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1553 "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1554 "ms");
1555 }
1556
OnTestStart(const TestInfo & test_info)1557 void OnTestStart(const TestInfo& test_info) override {
1558 SendLn(std::string("event=TestStart&name=") + test_info.name());
1559 }
1560
OnTestEnd(const TestInfo & test_info)1561 void OnTestEnd(const TestInfo& test_info) override {
1562 SendLn("event=TestEnd&passed=" +
1563 FormatBool((test_info.result())->Passed()) +
1564 "&elapsed_time=" +
1565 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1566 }
1567
OnTestPartResult(const TestPartResult & test_part_result)1568 void OnTestPartResult(const TestPartResult& test_part_result) override {
1569 const char* file_name = test_part_result.file_name();
1570 if (file_name == nullptr) file_name = "";
1571 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1572 "&line=" + StreamableToString(test_part_result.line_number()) +
1573 "&message=" + UrlEncode(test_part_result.message()));
1574 }
1575
1576 private:
1577 // Sends the given message and a newline to the socket.
SendLn(const std::string & message)1578 void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1579
1580 // Called at the start of streaming to notify the receiver what
1581 // protocol we are using.
Start()1582 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1583
FormatBool(bool value)1584 std::string FormatBool(bool value) { return value ? "1" : "0"; }
1585
1586 const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1587
1588 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1589 }; // class StreamingListener
1590
1591 #endif // GTEST_CAN_STREAM_RESULTS_
1592
1593 } // namespace internal
1594 } // namespace testing
1595
1596 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1597
1598 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1599
1600 #if GTEST_OS_WINDOWS
1601 # define vsnprintf _vsnprintf
1602 #endif // GTEST_OS_WINDOWS
1603
1604 #if GTEST_OS_MAC
1605 #ifndef GTEST_OS_IOS
1606 #include <crt_externs.h>
1607 #endif
1608 #endif
1609
1610 #if GTEST_HAS_ABSL
1611 #include "absl/debugging/failure_signal_handler.h"
1612 #include "absl/debugging/stacktrace.h"
1613 #include "absl/debugging/symbolize.h"
1614 #include "absl/strings/str_cat.h"
1615 #endif // GTEST_HAS_ABSL
1616
1617 namespace testing {
1618
1619 using internal::CountIf;
1620 using internal::ForEach;
1621 using internal::GetElementOr;
1622 using internal::Shuffle;
1623
1624 // Constants.
1625
1626 // A test whose test suite name or test name matches this filter is
1627 // disabled and not run.
1628 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1629
1630 // A test suite whose name matches this filter is considered a death
1631 // test suite and will be run before test suites whose name doesn't
1632 // match this filter.
1633 static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
1634
1635 // A test filter that matches everything.
1636 static const char kUniversalFilter[] = "*";
1637
1638 // The default output format.
1639 static const char kDefaultOutputFormat[] = "xml";
1640 // The default output file.
1641 static const char kDefaultOutputFile[] = "test_detail";
1642
1643 // The environment variable name for the test shard index.
1644 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1645 // The environment variable name for the total number of test shards.
1646 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1647 // The environment variable name for the test shard status file.
1648 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1649
1650 namespace internal {
1651
1652 // The text used in failure messages to indicate the start of the
1653 // stack trace.
1654 const char kStackTraceMarker[] = "\nStack trace:\n";
1655
1656 // g_help_flag is true iff the --help flag or an equivalent form is
1657 // specified on the command line.
1658 bool g_help_flag = false;
1659
1660 // Utilty function to Open File for Writing
OpenFileForWriting(const std::string & output_file)1661 static FILE* OpenFileForWriting(const std::string& output_file) {
1662 FILE* fileout = nullptr;
1663 FilePath output_file_path(output_file);
1664 FilePath output_dir(output_file_path.RemoveFileName());
1665
1666 if (output_dir.CreateDirectoriesRecursively()) {
1667 fileout = posix::FOpen(output_file.c_str(), "w");
1668 }
1669 if (fileout == nullptr) {
1670 GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1671 }
1672 return fileout;
1673 }
1674
1675 } // namespace internal
1676
1677 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1678 // environment variable.
GetDefaultFilter()1679 static const char* GetDefaultFilter() {
1680 const char* const testbridge_test_only =
1681 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1682 if (testbridge_test_only != nullptr) {
1683 return testbridge_test_only;
1684 }
1685 return kUniversalFilter;
1686 }
1687
1688 GTEST_DEFINE_bool_(
1689 also_run_disabled_tests,
1690 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1691 "Run disabled tests too, in addition to the tests normally being run.");
1692
1693 GTEST_DEFINE_bool_(
1694 break_on_failure,
1695 internal::BoolFromGTestEnv("break_on_failure", false),
1696 "True iff a failed assertion should be a debugger break-point.");
1697
1698 GTEST_DEFINE_bool_(
1699 catch_exceptions,
1700 internal::BoolFromGTestEnv("catch_exceptions", true),
1701 "True iff " GTEST_NAME_
1702 " should catch exceptions and treat them as test failures.");
1703
1704 GTEST_DEFINE_string_(
1705 color,
1706 internal::StringFromGTestEnv("color", "auto"),
1707 "Whether to use colors in the output. Valid values: yes, no, "
1708 "and auto. 'auto' means to use colors if the output is "
1709 "being sent to a terminal and the TERM environment variable "
1710 "is set to a terminal type that supports colors.");
1711
1712 GTEST_DEFINE_string_(
1713 filter,
1714 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1715 "A colon-separated list of glob (not regex) patterns "
1716 "for filtering the tests to run, optionally followed by a "
1717 "'-' and a : separated list of negative patterns (tests to "
1718 "exclude). A test is run if it matches one of the positive "
1719 "patterns and does not match any of the negative patterns.");
1720
1721 GTEST_DEFINE_bool_(
1722 install_failure_signal_handler,
1723 internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1724 "If true and supported on the current platform, " GTEST_NAME_ " should "
1725 "install a signal handler that dumps debugging information when fatal "
1726 "signals are raised.");
1727
1728 GTEST_DEFINE_bool_(list_tests, false,
1729 "List all tests without running them.");
1730
1731 // The net priority order after flag processing is thus:
1732 // --gtest_output command line flag
1733 // GTEST_OUTPUT environment variable
1734 // XML_OUTPUT_FILE environment variable
1735 // ''
1736 GTEST_DEFINE_string_(
1737 output,
1738 internal::StringFromGTestEnv("output",
1739 internal::OutputFlagAlsoCheckEnvVar().c_str()),
1740 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
1741 "optionally followed by a colon and an output file name or directory. "
1742 "A directory is indicated by a trailing pathname separator. "
1743 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1744 "If a directory is specified, output files will be created "
1745 "within that directory, with file-names based on the test "
1746 "executable's name and, if necessary, made unique by adding "
1747 "digits.");
1748
1749 GTEST_DEFINE_bool_(
1750 print_time,
1751 internal::BoolFromGTestEnv("print_time", true),
1752 "True iff " GTEST_NAME_
1753 " should display elapsed time in text output.");
1754
1755 GTEST_DEFINE_bool_(
1756 print_utf8,
1757 internal::BoolFromGTestEnv("print_utf8", true),
1758 "True iff " GTEST_NAME_
1759 " prints UTF8 characters as text.");
1760
1761 GTEST_DEFINE_int32_(
1762 random_seed,
1763 internal::Int32FromGTestEnv("random_seed", 0),
1764 "Random number seed to use when shuffling test orders. Must be in range "
1765 "[1, 99999], or 0 to use a seed based on the current time.");
1766
1767 GTEST_DEFINE_int32_(
1768 repeat,
1769 internal::Int32FromGTestEnv("repeat", 1),
1770 "How many times to repeat each test. Specify a negative number "
1771 "for repeating forever. Useful for shaking out flaky tests.");
1772
1773 GTEST_DEFINE_bool_(
1774 show_internal_stack_frames, false,
1775 "True iff " GTEST_NAME_ " should include internal stack frames when "
1776 "printing test failure stack traces.");
1777
1778 GTEST_DEFINE_bool_(
1779 shuffle,
1780 internal::BoolFromGTestEnv("shuffle", false),
1781 "True iff " GTEST_NAME_
1782 " should randomize tests' order on every run.");
1783
1784 GTEST_DEFINE_int32_(
1785 stack_trace_depth,
1786 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1787 "The maximum number of stack frames to print when an "
1788 "assertion fails. The valid range is 0 through 100, inclusive.");
1789
1790 GTEST_DEFINE_string_(
1791 stream_result_to,
1792 internal::StringFromGTestEnv("stream_result_to", ""),
1793 "This flag specifies the host name and the port number on which to stream "
1794 "test results. Example: \"localhost:555\". The flag is effective only on "
1795 "Linux.");
1796
1797 GTEST_DEFINE_bool_(
1798 throw_on_failure,
1799 internal::BoolFromGTestEnv("throw_on_failure", false),
1800 "When this flag is specified, a failed assertion will throw an exception "
1801 "if exceptions are enabled or exit the program with a non-zero code "
1802 "otherwise. For use with an external test framework.");
1803
1804 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1805 GTEST_DEFINE_string_(
1806 flagfile,
1807 internal::StringFromGTestEnv("flagfile", ""),
1808 "This flag specifies the flagfile to read command-line flags from.");
1809 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1810
1811 namespace internal {
1812
1813 // Generates a random number from [0, range), using a Linear
1814 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1815 // than kMaxRange.
Generate(UInt32 range)1816 UInt32 Random::Generate(UInt32 range) {
1817 // These constants are the same as are used in glibc's rand(3).
1818 // Use wider types than necessary to prevent unsigned overflow diagnostics.
1819 state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
1820
1821 GTEST_CHECK_(range > 0)
1822 << "Cannot generate a number in the range [0, 0).";
1823 GTEST_CHECK_(range <= kMaxRange)
1824 << "Generation of a number in [0, " << range << ") was requested, "
1825 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1826
1827 // Converting via modulus introduces a bit of downward bias, but
1828 // it's simple, and a linear congruential generator isn't too good
1829 // to begin with.
1830 return state_ % range;
1831 }
1832
1833 // GTestIsInitialized() returns true iff the user has initialized
1834 // Google Test. Useful for catching the user mistake of not initializing
1835 // Google Test before calling RUN_ALL_TESTS().
GTestIsInitialized()1836 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1837
1838 // Iterates over a vector of TestSuites, keeping a running sum of the
1839 // results of calling a given int-returning method on each.
1840 // Returns the sum.
SumOverTestSuiteList(const std::vector<TestSuite * > & case_list,int (TestSuite::* method)()const)1841 static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
1842 int (TestSuite::*method)() const) {
1843 int sum = 0;
1844 for (size_t i = 0; i < case_list.size(); i++) {
1845 sum += (case_list[i]->*method)();
1846 }
1847 return sum;
1848 }
1849
1850 // Returns true iff the test suite passed.
TestSuitePassed(const TestSuite * test_suite)1851 static bool TestSuitePassed(const TestSuite* test_suite) {
1852 return test_suite->should_run() && test_suite->Passed();
1853 }
1854
1855 // Returns true iff the test suite failed.
TestSuiteFailed(const TestSuite * test_suite)1856 static bool TestSuiteFailed(const TestSuite* test_suite) {
1857 return test_suite->should_run() && test_suite->Failed();
1858 }
1859
1860 // Returns true iff test_suite contains at least one test that should
1861 // run.
ShouldRunTestSuite(const TestSuite * test_suite)1862 static bool ShouldRunTestSuite(const TestSuite* test_suite) {
1863 return test_suite->should_run();
1864 }
1865
1866 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1867 AssertHelper::AssertHelper(TestPartResult::Type type,
1868 const char* file,
1869 int line,
1870 const char* message)
1871 : data_(new AssertHelperData(type, file, line, message)) {
1872 }
1873
~AssertHelper()1874 AssertHelper::~AssertHelper() {
1875 delete data_;
1876 }
1877
1878 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1879 void AssertHelper::operator=(const Message& message) const {
1880 UnitTest::GetInstance()->
1881 AddTestPartResult(data_->type, data_->file, data_->line,
1882 AppendUserMessage(data_->message, message),
1883 UnitTest::GetInstance()->impl()
1884 ->CurrentOsStackTraceExceptTop(1)
1885 // Skips the stack frame for this function itself.
1886 ); // NOLINT
1887 }
1888
1889 // A copy of all command line arguments. Set by InitGoogleTest().
1890 static ::std::vector<std::string> g_argvs;
1891
GetArgvs()1892 ::std::vector<std::string> GetArgvs() {
1893 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1894 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
1895 // ::string. This code converts it to the appropriate type.
1896 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
1897 return ::std::vector<std::string>(custom.begin(), custom.end());
1898 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
1899 return g_argvs;
1900 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
1901 }
1902
1903 // Returns the current application's name, removing directory path if that
1904 // is present.
GetCurrentExecutableName()1905 FilePath GetCurrentExecutableName() {
1906 FilePath result;
1907
1908 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
1909 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1910 #else
1911 result.Set(FilePath(GetArgvs()[0]));
1912 #endif // GTEST_OS_WINDOWS
1913
1914 return result.RemoveDirectoryName();
1915 }
1916
1917 // Functions for processing the gtest_output flag.
1918
1919 // Returns the output format, or "" for normal printed output.
GetOutputFormat()1920 std::string UnitTestOptions::GetOutputFormat() {
1921 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1922 const char* const colon = strchr(gtest_output_flag, ':');
1923 return (colon == nullptr)
1924 ? std::string(gtest_output_flag)
1925 : std::string(gtest_output_flag, colon - gtest_output_flag);
1926 }
1927
1928 // Returns the name of the requested output file, or the default if none
1929 // was explicitly specified.
GetAbsolutePathToOutputFile()1930 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1931 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1932
1933 std::string format = GetOutputFormat();
1934 if (format.empty())
1935 format = std::string(kDefaultOutputFormat);
1936
1937 const char* const colon = strchr(gtest_output_flag, ':');
1938 if (colon == nullptr)
1939 return internal::FilePath::MakeFileName(
1940 internal::FilePath(
1941 UnitTest::GetInstance()->original_working_dir()),
1942 internal::FilePath(kDefaultOutputFile), 0,
1943 format.c_str()).string();
1944
1945 internal::FilePath output_name(colon + 1);
1946 if (!output_name.IsAbsolutePath())
1947 output_name = internal::FilePath::ConcatPaths(
1948 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1949 internal::FilePath(colon + 1));
1950
1951 if (!output_name.IsDirectory())
1952 return output_name.string();
1953
1954 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1955 output_name, internal::GetCurrentExecutableName(),
1956 GetOutputFormat().c_str()));
1957 return result.string();
1958 }
1959
1960 // Returns true iff the wildcard pattern matches the string. The
1961 // first ':' or '\0' character in pattern marks the end of it.
1962 //
1963 // This recursive algorithm isn't very efficient, but is clear and
1964 // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)1965 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1966 const char *str) {
1967 switch (*pattern) {
1968 case '\0':
1969 case ':': // Either ':' or '\0' marks the end of the pattern.
1970 return *str == '\0';
1971 case '?': // Matches any single character.
1972 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1973 case '*': // Matches any string (possibly empty) of characters.
1974 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1975 PatternMatchesString(pattern + 1, str);
1976 default: // Non-special character. Matches itself.
1977 return *pattern == *str &&
1978 PatternMatchesString(pattern + 1, str + 1);
1979 }
1980 }
1981
MatchesFilter(const std::string & name,const char * filter)1982 bool UnitTestOptions::MatchesFilter(
1983 const std::string& name, const char* filter) {
1984 const char *cur_pattern = filter;
1985 for (;;) {
1986 if (PatternMatchesString(cur_pattern, name.c_str())) {
1987 return true;
1988 }
1989
1990 // Finds the next pattern in the filter.
1991 cur_pattern = strchr(cur_pattern, ':');
1992
1993 // Returns if no more pattern can be found.
1994 if (cur_pattern == nullptr) {
1995 return false;
1996 }
1997
1998 // Skips the pattern separater (the ':' character).
1999 cur_pattern++;
2000 }
2001 }
2002
2003 // Returns true iff the user-specified filter matches the test suite
2004 // name and the test name.
FilterMatchesTest(const std::string & test_suite_name,const std::string & test_name)2005 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
2006 const std::string& test_name) {
2007 const std::string& full_name = test_suite_name + "." + test_name.c_str();
2008
2009 // Split --gtest_filter at '-', if there is one, to separate into
2010 // positive filter and negative filter portions
2011 const char* const p = GTEST_FLAG(filter).c_str();
2012 const char* const dash = strchr(p, '-');
2013 std::string positive;
2014 std::string negative;
2015 if (dash == nullptr) {
2016 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
2017 negative = "";
2018 } else {
2019 positive = std::string(p, dash); // Everything up to the dash
2020 negative = std::string(dash + 1); // Everything after the dash
2021 if (positive.empty()) {
2022 // Treat '-test1' as the same as '*-test1'
2023 positive = kUniversalFilter;
2024 }
2025 }
2026
2027 // A filter is a colon-separated list of patterns. It matches a
2028 // test if any pattern in it matches the test.
2029 return (MatchesFilter(full_name, positive.c_str()) &&
2030 !MatchesFilter(full_name, negative.c_str()));
2031 }
2032
2033 #if GTEST_HAS_SEH
2034 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2035 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2036 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)2037 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2038 // Google Test should handle a SEH exception if:
2039 // 1. the user wants it to, AND
2040 // 2. this is not a breakpoint exception, AND
2041 // 3. this is not a C++ exception (VC++ implements them via SEH,
2042 // apparently).
2043 //
2044 // SEH exception code for C++ exceptions.
2045 // (see http://support.microsoft.com/kb/185294 for more information).
2046 const DWORD kCxxExceptionCode = 0xe06d7363;
2047
2048 bool should_handle = true;
2049
2050 if (!GTEST_FLAG(catch_exceptions))
2051 should_handle = false;
2052 else if (exception_code == EXCEPTION_BREAKPOINT)
2053 should_handle = false;
2054 else if (exception_code == kCxxExceptionCode)
2055 should_handle = false;
2056
2057 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2058 }
2059 #endif // GTEST_HAS_SEH
2060
2061 } // namespace internal
2062
2063 // The c'tor sets this object as the test part result reporter used by
2064 // Google Test. The 'result' parameter specifies where to report the
2065 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)2066 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2067 TestPartResultArray* result)
2068 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2069 result_(result) {
2070 Init();
2071 }
2072
2073 // The c'tor sets this object as the test part result reporter used by
2074 // Google Test. The 'result' parameter specifies where to report the
2075 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2076 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2077 InterceptMode intercept_mode, TestPartResultArray* result)
2078 : intercept_mode_(intercept_mode),
2079 result_(result) {
2080 Init();
2081 }
2082
Init()2083 void ScopedFakeTestPartResultReporter::Init() {
2084 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2085 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2086 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2087 impl->SetGlobalTestPartResultReporter(this);
2088 } else {
2089 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2090 impl->SetTestPartResultReporterForCurrentThread(this);
2091 }
2092 }
2093
2094 // The d'tor restores the test part result reporter used by Google Test
2095 // before.
~ScopedFakeTestPartResultReporter()2096 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2097 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2098 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2099 impl->SetGlobalTestPartResultReporter(old_reporter_);
2100 } else {
2101 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2102 }
2103 }
2104
2105 // Increments the test part result count and remembers the result.
2106 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2107 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2108 const TestPartResult& result) {
2109 result_->Append(result);
2110 }
2111
2112 namespace internal {
2113
2114 // Returns the type ID of ::testing::Test. We should always call this
2115 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2116 // testing::Test. This is to work around a suspected linker bug when
2117 // using Google Test as a framework on Mac OS X. The bug causes
2118 // GetTypeId< ::testing::Test>() to return different values depending
2119 // on whether the call is from the Google Test framework itself or
2120 // from user test code. GetTestTypeId() is guaranteed to always
2121 // return the same value, as it always calls GetTypeId<>() from the
2122 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2123 TypeId GetTestTypeId() {
2124 return GetTypeId<Test>();
2125 }
2126
2127 // The value of GetTestTypeId() as seen from within the Google Test
2128 // library. This is solely for testing GetTestTypeId().
2129 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2130
2131 // This predicate-formatter checks that 'results' contains a test part
2132 // failure of the given type and that the failure message contains the
2133 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const std::string & substr)2134 static AssertionResult HasOneFailure(const char* /* results_expr */,
2135 const char* /* type_expr */,
2136 const char* /* substr_expr */,
2137 const TestPartResultArray& results,
2138 TestPartResult::Type type,
2139 const std::string& substr) {
2140 const std::string expected(type == TestPartResult::kFatalFailure ?
2141 "1 fatal failure" :
2142 "1 non-fatal failure");
2143 Message msg;
2144 if (results.size() != 1) {
2145 msg << "Expected: " << expected << "\n"
2146 << " Actual: " << results.size() << " failures";
2147 for (int i = 0; i < results.size(); i++) {
2148 msg << "\n" << results.GetTestPartResult(i);
2149 }
2150 return AssertionFailure() << msg;
2151 }
2152
2153 const TestPartResult& r = results.GetTestPartResult(0);
2154 if (r.type() != type) {
2155 return AssertionFailure() << "Expected: " << expected << "\n"
2156 << " Actual:\n"
2157 << r;
2158 }
2159
2160 if (strstr(r.message(), substr.c_str()) == nullptr) {
2161 return AssertionFailure() << "Expected: " << expected << " containing \""
2162 << substr << "\"\n"
2163 << " Actual:\n"
2164 << r;
2165 }
2166
2167 return AssertionSuccess();
2168 }
2169
2170 // The constructor of SingleFailureChecker remembers where to look up
2171 // test part results, what type of failure we expect, and what
2172 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const std::string & substr)2173 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2174 TestPartResult::Type type,
2175 const std::string& substr)
2176 : results_(results), type_(type), substr_(substr) {}
2177
2178 // The destructor of SingleFailureChecker verifies that the given
2179 // TestPartResultArray contains exactly one failure that has the given
2180 // type and contains the given substring. If that's not the case, a
2181 // non-fatal failure will be generated.
~SingleFailureChecker()2182 SingleFailureChecker::~SingleFailureChecker() {
2183 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2184 }
2185
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2186 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2187 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2188
ReportTestPartResult(const TestPartResult & result)2189 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2190 const TestPartResult& result) {
2191 unit_test_->current_test_result()->AddTestPartResult(result);
2192 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2193 }
2194
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2195 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2196 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2197
ReportTestPartResult(const TestPartResult & result)2198 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2199 const TestPartResult& result) {
2200 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2201 }
2202
2203 // Returns the global test part result reporter.
2204 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2205 UnitTestImpl::GetGlobalTestPartResultReporter() {
2206 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2207 return global_test_part_result_repoter_;
2208 }
2209
2210 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2211 void UnitTestImpl::SetGlobalTestPartResultReporter(
2212 TestPartResultReporterInterface* reporter) {
2213 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2214 global_test_part_result_repoter_ = reporter;
2215 }
2216
2217 // Returns the test part result reporter for the current thread.
2218 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2219 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2220 return per_thread_test_part_result_reporter_.get();
2221 }
2222
2223 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2224 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2225 TestPartResultReporterInterface* reporter) {
2226 per_thread_test_part_result_reporter_.set(reporter);
2227 }
2228
2229 // Gets the number of successful test suites.
successful_test_suite_count() const2230 int UnitTestImpl::successful_test_suite_count() const {
2231 return CountIf(test_suites_, TestSuitePassed);
2232 }
2233
2234 // Gets the number of failed test suites.
failed_test_suite_count() const2235 int UnitTestImpl::failed_test_suite_count() const {
2236 return CountIf(test_suites_, TestSuiteFailed);
2237 }
2238
2239 // Gets the number of all test suites.
total_test_suite_count() const2240 int UnitTestImpl::total_test_suite_count() const {
2241 return static_cast<int>(test_suites_.size());
2242 }
2243
2244 // Gets the number of all test suites that contain at least one test
2245 // that should run.
test_suite_to_run_count() const2246 int UnitTestImpl::test_suite_to_run_count() const {
2247 return CountIf(test_suites_, ShouldRunTestSuite);
2248 }
2249
2250 // Gets the number of successful tests.
successful_test_count() const2251 int UnitTestImpl::successful_test_count() const {
2252 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2253 }
2254
2255 // Gets the number of skipped tests.
skipped_test_count() const2256 int UnitTestImpl::skipped_test_count() const {
2257 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
2258 }
2259
2260 // Gets the number of failed tests.
failed_test_count() const2261 int UnitTestImpl::failed_test_count() const {
2262 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
2263 }
2264
2265 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2266 int UnitTestImpl::reportable_disabled_test_count() const {
2267 return SumOverTestSuiteList(test_suites_,
2268 &TestSuite::reportable_disabled_test_count);
2269 }
2270
2271 // Gets the number of disabled tests.
disabled_test_count() const2272 int UnitTestImpl::disabled_test_count() const {
2273 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
2274 }
2275
2276 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2277 int UnitTestImpl::reportable_test_count() const {
2278 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
2279 }
2280
2281 // Gets the number of all tests.
total_test_count() const2282 int UnitTestImpl::total_test_count() const {
2283 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
2284 }
2285
2286 // Gets the number of tests that should run.
test_to_run_count() const2287 int UnitTestImpl::test_to_run_count() const {
2288 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
2289 }
2290
2291 // Returns the current OS stack trace as an std::string.
2292 //
2293 // The maximum number of stack frames to be included is specified by
2294 // the gtest_stack_trace_depth flag. The skip_count parameter
2295 // specifies the number of top frames to be skipped, which doesn't
2296 // count against the number of frames to be included.
2297 //
2298 // For example, if Foo() calls Bar(), which in turn calls
2299 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2300 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2301 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2302 return os_stack_trace_getter()->CurrentStackTrace(
2303 static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2304 skip_count + 1
2305 // Skips the user-specified number of frames plus this function
2306 // itself.
2307 ); // NOLINT
2308 }
2309
2310 // Returns the current time in milliseconds.
GetTimeInMillis()2311 TimeInMillis GetTimeInMillis() {
2312 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2313 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2314 // http://analogous.blogspot.com/2005/04/epoch.html
2315 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2316 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2317 const DWORD kTenthMicrosInMilliSecond = 10000;
2318
2319 SYSTEMTIME now_systime;
2320 FILETIME now_filetime;
2321 ULARGE_INTEGER now_int64;
2322 GetSystemTime(&now_systime);
2323 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2324 now_int64.LowPart = now_filetime.dwLowDateTime;
2325 now_int64.HighPart = now_filetime.dwHighDateTime;
2326 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2327 kJavaEpochToWinFileTimeDelta;
2328 return now_int64.QuadPart;
2329 }
2330 return 0;
2331 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2332 __timeb64 now;
2333
2334 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2335 // (deprecated function) there.
2336 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2337 _ftime64(&now);
2338 GTEST_DISABLE_MSC_DEPRECATED_POP_()
2339
2340 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2341 #elif GTEST_HAS_GETTIMEOFDAY_
2342 struct timeval now;
2343 gettimeofday(&now, nullptr);
2344 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2345 #else
2346 # error "Don't know how to get the current time on your system."
2347 #endif
2348 }
2349
2350 // Utilities
2351
2352 // class String.
2353
2354 #if GTEST_OS_WINDOWS_MOBILE
2355 // Creates a UTF-16 wide string from the given ANSI string, allocating
2356 // memory using new. The caller is responsible for deleting the return
2357 // value using delete[]. Returns the wide string, or NULL if the
2358 // input is NULL.
AnsiToUtf16(const char * ansi)2359 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2360 if (!ansi) return nullptr;
2361 const int length = strlen(ansi);
2362 const int unicode_length =
2363 MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
2364 WCHAR* unicode = new WCHAR[unicode_length + 1];
2365 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2366 unicode, unicode_length);
2367 unicode[unicode_length] = 0;
2368 return unicode;
2369 }
2370
2371 // Creates an ANSI string from the given wide string, allocating
2372 // memory using new. The caller is responsible for deleting the return
2373 // value using delete[]. Returns the ANSI string, or NULL if the
2374 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2375 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2376 if (!utf16_str) return nullptr;
2377 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
2378 0, nullptr, nullptr);
2379 char* ansi = new char[ansi_length + 1];
2380 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
2381 nullptr);
2382 ansi[ansi_length] = 0;
2383 return ansi;
2384 }
2385
2386 #endif // GTEST_OS_WINDOWS_MOBILE
2387
2388 // Compares two C strings. Returns true iff they have the same content.
2389 //
2390 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2391 // C string is considered different to any non-NULL C string,
2392 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2393 bool String::CStringEquals(const char * lhs, const char * rhs) {
2394 if (lhs == nullptr) return rhs == nullptr;
2395
2396 if (rhs == nullptr) return false;
2397
2398 return strcmp(lhs, rhs) == 0;
2399 }
2400
2401 #if GTEST_HAS_STD_WSTRING
2402
2403 // Converts an array of wide chars to a narrow string using the UTF-8
2404 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2405 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2406 Message* msg) {
2407 for (size_t i = 0; i != length; ) { // NOLINT
2408 if (wstr[i] != L'\0') {
2409 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2410 while (i != length && wstr[i] != L'\0')
2411 i++;
2412 } else {
2413 *msg << '\0';
2414 i++;
2415 }
2416 }
2417 }
2418
2419 #endif // GTEST_HAS_STD_WSTRING
2420
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)2421 void SplitString(const ::std::string& str, char delimiter,
2422 ::std::vector< ::std::string>* dest) {
2423 ::std::vector< ::std::string> parsed;
2424 ::std::string::size_type pos = 0;
2425 while (::testing::internal::AlwaysTrue()) {
2426 const ::std::string::size_type colon = str.find(delimiter, pos);
2427 if (colon == ::std::string::npos) {
2428 parsed.push_back(str.substr(pos));
2429 break;
2430 } else {
2431 parsed.push_back(str.substr(pos, colon - pos));
2432 pos = colon + 1;
2433 }
2434 }
2435 dest->swap(parsed);
2436 }
2437
2438 } // namespace internal
2439
2440 // Constructs an empty Message.
2441 // We allocate the stringstream separately because otherwise each use of
2442 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2443 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2444 // the stack space.
Message()2445 Message::Message() : ss_(new ::std::stringstream) {
2446 // By default, we want there to be enough precision when printing
2447 // a double to a Message.
2448 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2449 }
2450
2451 // These two overloads allow streaming a wide C string to a Message
2452 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2453 Message& Message::operator <<(const wchar_t* wide_c_str) {
2454 return *this << internal::String::ShowWideCString(wide_c_str);
2455 }
operator <<(wchar_t * wide_c_str)2456 Message& Message::operator <<(wchar_t* wide_c_str) {
2457 return *this << internal::String::ShowWideCString(wide_c_str);
2458 }
2459
2460 #if GTEST_HAS_STD_WSTRING
2461 // Converts the given wide string to a narrow string using the UTF-8
2462 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2463 Message& Message::operator <<(const ::std::wstring& wstr) {
2464 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2465 return *this;
2466 }
2467 #endif // GTEST_HAS_STD_WSTRING
2468
2469 // Gets the text streamed to this object so far as an std::string.
2470 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2471 std::string Message::GetString() const {
2472 return internal::StringStreamToString(ss_.get());
2473 }
2474
2475 // AssertionResult constructors.
2476 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2477 AssertionResult::AssertionResult(const AssertionResult& other)
2478 : success_(other.success_),
2479 message_(other.message_.get() != nullptr
2480 ? new ::std::string(*other.message_)
2481 : static_cast< ::std::string*>(nullptr)) {}
2482
2483 // Swaps two AssertionResults.
swap(AssertionResult & other)2484 void AssertionResult::swap(AssertionResult& other) {
2485 using std::swap;
2486 swap(success_, other.success_);
2487 swap(message_, other.message_);
2488 }
2489
2490 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2491 AssertionResult AssertionResult::operator!() const {
2492 AssertionResult negation(!success_);
2493 if (message_.get() != nullptr) negation << *message_;
2494 return negation;
2495 }
2496
2497 // Makes a successful assertion result.
AssertionSuccess()2498 AssertionResult AssertionSuccess() {
2499 return AssertionResult(true);
2500 }
2501
2502 // Makes a failed assertion result.
AssertionFailure()2503 AssertionResult AssertionFailure() {
2504 return AssertionResult(false);
2505 }
2506
2507 // Makes a failed assertion result with the given failure message.
2508 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2509 AssertionResult AssertionFailure(const Message& message) {
2510 return AssertionFailure() << message;
2511 }
2512
2513 namespace internal {
2514
2515 namespace edit_distance {
CalculateOptimalEdits(const std::vector<size_t> & left,const std::vector<size_t> & right)2516 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2517 const std::vector<size_t>& right) {
2518 std::vector<std::vector<double> > costs(
2519 left.size() + 1, std::vector<double>(right.size() + 1));
2520 std::vector<std::vector<EditType> > best_move(
2521 left.size() + 1, std::vector<EditType>(right.size() + 1));
2522
2523 // Populate for empty right.
2524 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2525 costs[l_i][0] = static_cast<double>(l_i);
2526 best_move[l_i][0] = kRemove;
2527 }
2528 // Populate for empty left.
2529 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2530 costs[0][r_i] = static_cast<double>(r_i);
2531 best_move[0][r_i] = kAdd;
2532 }
2533
2534 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2535 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2536 if (left[l_i] == right[r_i]) {
2537 // Found a match. Consume it.
2538 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2539 best_move[l_i + 1][r_i + 1] = kMatch;
2540 continue;
2541 }
2542
2543 const double add = costs[l_i + 1][r_i];
2544 const double remove = costs[l_i][r_i + 1];
2545 const double replace = costs[l_i][r_i];
2546 if (add < remove && add < replace) {
2547 costs[l_i + 1][r_i + 1] = add + 1;
2548 best_move[l_i + 1][r_i + 1] = kAdd;
2549 } else if (remove < add && remove < replace) {
2550 costs[l_i + 1][r_i + 1] = remove + 1;
2551 best_move[l_i + 1][r_i + 1] = kRemove;
2552 } else {
2553 // We make replace a little more expensive than add/remove to lower
2554 // their priority.
2555 costs[l_i + 1][r_i + 1] = replace + 1.00001;
2556 best_move[l_i + 1][r_i + 1] = kReplace;
2557 }
2558 }
2559 }
2560
2561 // Reconstruct the best path. We do it in reverse order.
2562 std::vector<EditType> best_path;
2563 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2564 EditType move = best_move[l_i][r_i];
2565 best_path.push_back(move);
2566 l_i -= move != kAdd;
2567 r_i -= move != kRemove;
2568 }
2569 std::reverse(best_path.begin(), best_path.end());
2570 return best_path;
2571 }
2572
2573 namespace {
2574
2575 // Helper class to convert string into ids with deduplication.
2576 class InternalStrings {
2577 public:
GetId(const std::string & str)2578 size_t GetId(const std::string& str) {
2579 IdMap::iterator it = ids_.find(str);
2580 if (it != ids_.end()) return it->second;
2581 size_t id = ids_.size();
2582 return ids_[str] = id;
2583 }
2584
2585 private:
2586 typedef std::map<std::string, size_t> IdMap;
2587 IdMap ids_;
2588 };
2589
2590 } // namespace
2591
CalculateOptimalEdits(const std::vector<std::string> & left,const std::vector<std::string> & right)2592 std::vector<EditType> CalculateOptimalEdits(
2593 const std::vector<std::string>& left,
2594 const std::vector<std::string>& right) {
2595 std::vector<size_t> left_ids, right_ids;
2596 {
2597 InternalStrings intern_table;
2598 for (size_t i = 0; i < left.size(); ++i) {
2599 left_ids.push_back(intern_table.GetId(left[i]));
2600 }
2601 for (size_t i = 0; i < right.size(); ++i) {
2602 right_ids.push_back(intern_table.GetId(right[i]));
2603 }
2604 }
2605 return CalculateOptimalEdits(left_ids, right_ids);
2606 }
2607
2608 namespace {
2609
2610 // Helper class that holds the state for one hunk and prints it out to the
2611 // stream.
2612 // It reorders adds/removes when possible to group all removes before all
2613 // adds. It also adds the hunk header before printint into the stream.
2614 class Hunk {
2615 public:
Hunk(size_t left_start,size_t right_start)2616 Hunk(size_t left_start, size_t right_start)
2617 : left_start_(left_start),
2618 right_start_(right_start),
2619 adds_(),
2620 removes_(),
2621 common_() {}
2622
PushLine(char edit,const char * line)2623 void PushLine(char edit, const char* line) {
2624 switch (edit) {
2625 case ' ':
2626 ++common_;
2627 FlushEdits();
2628 hunk_.push_back(std::make_pair(' ', line));
2629 break;
2630 case '-':
2631 ++removes_;
2632 hunk_removes_.push_back(std::make_pair('-', line));
2633 break;
2634 case '+':
2635 ++adds_;
2636 hunk_adds_.push_back(std::make_pair('+', line));
2637 break;
2638 }
2639 }
2640
PrintTo(std::ostream * os)2641 void PrintTo(std::ostream* os) {
2642 PrintHeader(os);
2643 FlushEdits();
2644 for (std::list<std::pair<char, const char*> >::const_iterator it =
2645 hunk_.begin();
2646 it != hunk_.end(); ++it) {
2647 *os << it->first << it->second << "\n";
2648 }
2649 }
2650
has_edits() const2651 bool has_edits() const { return adds_ || removes_; }
2652
2653 private:
FlushEdits()2654 void FlushEdits() {
2655 hunk_.splice(hunk_.end(), hunk_removes_);
2656 hunk_.splice(hunk_.end(), hunk_adds_);
2657 }
2658
2659 // Print a unified diff header for one hunk.
2660 // The format is
2661 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2662 // where the left/right parts are omitted if unnecessary.
PrintHeader(std::ostream * ss) const2663 void PrintHeader(std::ostream* ss) const {
2664 *ss << "@@ ";
2665 if (removes_) {
2666 *ss << "-" << left_start_ << "," << (removes_ + common_);
2667 }
2668 if (removes_ && adds_) {
2669 *ss << " ";
2670 }
2671 if (adds_) {
2672 *ss << "+" << right_start_ << "," << (adds_ + common_);
2673 }
2674 *ss << " @@\n";
2675 }
2676
2677 size_t left_start_, right_start_;
2678 size_t adds_, removes_, common_;
2679 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2680 };
2681
2682 } // namespace
2683
2684 // Create a list of diff hunks in Unified diff format.
2685 // Each hunk has a header generated by PrintHeader above plus a body with
2686 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2687 // addition.
2688 // 'context' represents the desired unchanged prefix/suffix around the diff.
2689 // If two hunks are close enough that their contexts overlap, then they are
2690 // joined into one hunk.
CreateUnifiedDiff(const std::vector<std::string> & left,const std::vector<std::string> & right,size_t context)2691 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2692 const std::vector<std::string>& right,
2693 size_t context) {
2694 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2695
2696 size_t l_i = 0, r_i = 0, edit_i = 0;
2697 std::stringstream ss;
2698 while (edit_i < edits.size()) {
2699 // Find first edit.
2700 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2701 ++l_i;
2702 ++r_i;
2703 ++edit_i;
2704 }
2705
2706 // Find the first line to include in the hunk.
2707 const size_t prefix_context = std::min(l_i, context);
2708 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2709 for (size_t i = prefix_context; i > 0; --i) {
2710 hunk.PushLine(' ', left[l_i - i].c_str());
2711 }
2712
2713 // Iterate the edits until we found enough suffix for the hunk or the input
2714 // is over.
2715 size_t n_suffix = 0;
2716 for (; edit_i < edits.size(); ++edit_i) {
2717 if (n_suffix >= context) {
2718 // Continue only if the next hunk is very close.
2719 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2720 while (it != edits.end() && *it == kMatch) ++it;
2721 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2722 // There is no next edit or it is too far away.
2723 break;
2724 }
2725 }
2726
2727 EditType edit = edits[edit_i];
2728 // Reset count when a non match is found.
2729 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2730
2731 if (edit == kMatch || edit == kRemove || edit == kReplace) {
2732 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2733 }
2734 if (edit == kAdd || edit == kReplace) {
2735 hunk.PushLine('+', right[r_i].c_str());
2736 }
2737
2738 // Advance indices, depending on edit type.
2739 l_i += edit != kAdd;
2740 r_i += edit != kRemove;
2741 }
2742
2743 if (!hunk.has_edits()) {
2744 // We are done. We don't want this hunk.
2745 break;
2746 }
2747
2748 hunk.PrintTo(&ss);
2749 }
2750 return ss.str();
2751 }
2752
2753 } // namespace edit_distance
2754
2755 namespace {
2756
2757 // The string representation of the values received in EqFailure() are already
2758 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2759 // characters the same.
SplitEscapedString(const std::string & str)2760 std::vector<std::string> SplitEscapedString(const std::string& str) {
2761 std::vector<std::string> lines;
2762 size_t start = 0, end = str.size();
2763 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2764 ++start;
2765 --end;
2766 }
2767 bool escaped = false;
2768 for (size_t i = start; i + 1 < end; ++i) {
2769 if (escaped) {
2770 escaped = false;
2771 if (str[i] == 'n') {
2772 lines.push_back(str.substr(start, i - start - 1));
2773 start = i + 1;
2774 }
2775 } else {
2776 escaped = str[i] == '\\';
2777 }
2778 }
2779 lines.push_back(str.substr(start, end - start));
2780 return lines;
2781 }
2782
2783 } // namespace
2784
2785 // Constructs and returns the message for an equality assertion
2786 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2787 //
2788 // The first four parameters are the expressions used in the assertion
2789 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2790 // where foo is 5 and bar is 6, we have:
2791 //
2792 // lhs_expression: "foo"
2793 // rhs_expression: "bar"
2794 // lhs_value: "5"
2795 // rhs_value: "6"
2796 //
2797 // The ignoring_case parameter is true iff the assertion is a
2798 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
2799 // be inserted into the message.
EqFailure(const char * lhs_expression,const char * rhs_expression,const std::string & lhs_value,const std::string & rhs_value,bool ignoring_case)2800 AssertionResult EqFailure(const char* lhs_expression,
2801 const char* rhs_expression,
2802 const std::string& lhs_value,
2803 const std::string& rhs_value,
2804 bool ignoring_case) {
2805 Message msg;
2806 msg << "Expected equality of these values:";
2807 msg << "\n " << lhs_expression;
2808 if (lhs_value != lhs_expression) {
2809 msg << "\n Which is: " << lhs_value;
2810 }
2811 msg << "\n " << rhs_expression;
2812 if (rhs_value != rhs_expression) {
2813 msg << "\n Which is: " << rhs_value;
2814 }
2815
2816 if (ignoring_case) {
2817 msg << "\nIgnoring case";
2818 }
2819
2820 if (!lhs_value.empty() && !rhs_value.empty()) {
2821 const std::vector<std::string> lhs_lines =
2822 SplitEscapedString(lhs_value);
2823 const std::vector<std::string> rhs_lines =
2824 SplitEscapedString(rhs_value);
2825 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2826 msg << "\nWith diff:\n"
2827 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2828 }
2829 }
2830
2831 return AssertionFailure() << msg;
2832 }
2833
2834 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GetBoolAssertionFailureMessage(const AssertionResult & assertion_result,const char * expression_text,const char * actual_predicate_value,const char * expected_predicate_value)2835 std::string GetBoolAssertionFailureMessage(
2836 const AssertionResult& assertion_result,
2837 const char* expression_text,
2838 const char* actual_predicate_value,
2839 const char* expected_predicate_value) {
2840 const char* actual_message = assertion_result.message();
2841 Message msg;
2842 msg << "Value of: " << expression_text
2843 << "\n Actual: " << actual_predicate_value;
2844 if (actual_message[0] != '\0')
2845 msg << " (" << actual_message << ")";
2846 msg << "\nExpected: " << expected_predicate_value;
2847 return msg.GetString();
2848 }
2849
2850 // Helper function for implementing ASSERT_NEAR.
DoubleNearPredFormat(const char * expr1,const char * expr2,const char * abs_error_expr,double val1,double val2,double abs_error)2851 AssertionResult DoubleNearPredFormat(const char* expr1,
2852 const char* expr2,
2853 const char* abs_error_expr,
2854 double val1,
2855 double val2,
2856 double abs_error) {
2857 const double diff = fabs(val1 - val2);
2858 if (diff <= abs_error) return AssertionSuccess();
2859
2860 return AssertionFailure()
2861 << "The difference between " << expr1 << " and " << expr2
2862 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2863 << expr1 << " evaluates to " << val1 << ",\n"
2864 << expr2 << " evaluates to " << val2 << ", and\n"
2865 << abs_error_expr << " evaluates to " << abs_error << ".";
2866 }
2867
2868
2869 // Helper template for implementing FloatLE() and DoubleLE().
2870 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)2871 AssertionResult FloatingPointLE(const char* expr1,
2872 const char* expr2,
2873 RawType val1,
2874 RawType val2) {
2875 // Returns success if val1 is less than val2,
2876 if (val1 < val2) {
2877 return AssertionSuccess();
2878 }
2879
2880 // or if val1 is almost equal to val2.
2881 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2882 if (lhs.AlmostEquals(rhs)) {
2883 return AssertionSuccess();
2884 }
2885
2886 // Note that the above two checks will both fail if either val1 or
2887 // val2 is NaN, as the IEEE floating-point standard requires that
2888 // any predicate involving a NaN must return false.
2889
2890 ::std::stringstream val1_ss;
2891 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2892 << val1;
2893
2894 ::std::stringstream val2_ss;
2895 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2896 << val2;
2897
2898 return AssertionFailure()
2899 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2900 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2901 << StringStreamToString(&val2_ss);
2902 }
2903
2904 } // namespace internal
2905
2906 // Asserts that val1 is less than, or almost equal to, val2. Fails
2907 // otherwise. In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)2908 AssertionResult FloatLE(const char* expr1, const char* expr2,
2909 float val1, float val2) {
2910 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2911 }
2912
2913 // Asserts that val1 is less than, or almost equal to, val2. Fails
2914 // otherwise. In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)2915 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2916 double val1, double val2) {
2917 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2918 }
2919
2920 namespace internal {
2921
2922 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2923 // arguments.
CmpHelperEQ(const char * lhs_expression,const char * rhs_expression,BiggestInt lhs,BiggestInt rhs)2924 AssertionResult CmpHelperEQ(const char* lhs_expression,
2925 const char* rhs_expression,
2926 BiggestInt lhs,
2927 BiggestInt rhs) {
2928 if (lhs == rhs) {
2929 return AssertionSuccess();
2930 }
2931
2932 return EqFailure(lhs_expression,
2933 rhs_expression,
2934 FormatForComparisonFailureMessage(lhs, rhs),
2935 FormatForComparisonFailureMessage(rhs, lhs),
2936 false);
2937 }
2938
2939 // A macro for implementing the helper functions needed to implement
2940 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2941 // just to avoid copy-and-paste of similar code.
2942 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2943 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2944 BiggestInt val1, BiggestInt val2) {\
2945 if (val1 op val2) {\
2946 return AssertionSuccess();\
2947 } else {\
2948 return AssertionFailure() \
2949 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2950 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2951 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2952 }\
2953 }
2954
2955 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2956 // enum arguments.
2957 GTEST_IMPL_CMP_HELPER_(NE, !=)
2958 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2959 // enum arguments.
2960 GTEST_IMPL_CMP_HELPER_(LE, <=)
2961 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2962 // enum arguments.
2963 GTEST_IMPL_CMP_HELPER_(LT, < )
2964 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2965 // enum arguments.
2966 GTEST_IMPL_CMP_HELPER_(GE, >=)
2967 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2968 // enum arguments.
2969 GTEST_IMPL_CMP_HELPER_(GT, > )
2970
2971 #undef GTEST_IMPL_CMP_HELPER_
2972
2973 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)2974 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2975 const char* rhs_expression,
2976 const char* lhs,
2977 const char* rhs) {
2978 if (String::CStringEquals(lhs, rhs)) {
2979 return AssertionSuccess();
2980 }
2981
2982 return EqFailure(lhs_expression,
2983 rhs_expression,
2984 PrintToString(lhs),
2985 PrintToString(rhs),
2986 false);
2987 }
2988
2989 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)2990 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
2991 const char* rhs_expression,
2992 const char* lhs,
2993 const char* rhs) {
2994 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
2995 return AssertionSuccess();
2996 }
2997
2998 return EqFailure(lhs_expression,
2999 rhs_expression,
3000 PrintToString(lhs),
3001 PrintToString(rhs),
3002 true);
3003 }
3004
3005 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3006 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3007 const char* s2_expression,
3008 const char* s1,
3009 const char* s2) {
3010 if (!String::CStringEquals(s1, s2)) {
3011 return AssertionSuccess();
3012 } else {
3013 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3014 << s2_expression << "), actual: \""
3015 << s1 << "\" vs \"" << s2 << "\"";
3016 }
3017 }
3018
3019 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3020 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3021 const char* s2_expression,
3022 const char* s1,
3023 const char* s2) {
3024 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3025 return AssertionSuccess();
3026 } else {
3027 return AssertionFailure()
3028 << "Expected: (" << s1_expression << ") != ("
3029 << s2_expression << ") (ignoring case), actual: \""
3030 << s1 << "\" vs \"" << s2 << "\"";
3031 }
3032 }
3033
3034 } // namespace internal
3035
3036 namespace {
3037
3038 // Helper functions for implementing IsSubString() and IsNotSubstring().
3039
3040 // This group of overloaded functions return true iff needle is a
3041 // substring of haystack. NULL is considered a substring of itself
3042 // only.
3043
IsSubstringPred(const char * needle,const char * haystack)3044 bool IsSubstringPred(const char* needle, const char* haystack) {
3045 if (needle == nullptr || haystack == nullptr) return needle == haystack;
3046
3047 return strstr(haystack, needle) != nullptr;
3048 }
3049
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)3050 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3051 if (needle == nullptr || haystack == nullptr) return needle == haystack;
3052
3053 return wcsstr(haystack, needle) != nullptr;
3054 }
3055
3056 // StringType here can be either ::std::string or ::std::wstring.
3057 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)3058 bool IsSubstringPred(const StringType& needle,
3059 const StringType& haystack) {
3060 return haystack.find(needle) != StringType::npos;
3061 }
3062
3063 // This function implements either IsSubstring() or IsNotSubstring(),
3064 // depending on the value of the expected_to_be_substring parameter.
3065 // StringType here can be const char*, const wchar_t*, ::std::string,
3066 // or ::std::wstring.
3067 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)3068 AssertionResult IsSubstringImpl(
3069 bool expected_to_be_substring,
3070 const char* needle_expr, const char* haystack_expr,
3071 const StringType& needle, const StringType& haystack) {
3072 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3073 return AssertionSuccess();
3074
3075 const bool is_wide_string = sizeof(needle[0]) > 1;
3076 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3077 return AssertionFailure()
3078 << "Value of: " << needle_expr << "\n"
3079 << " Actual: " << begin_string_quote << needle << "\"\n"
3080 << "Expected: " << (expected_to_be_substring ? "" : "not ")
3081 << "a substring of " << haystack_expr << "\n"
3082 << "Which is: " << begin_string_quote << haystack << "\"";
3083 }
3084
3085 } // namespace
3086
3087 // IsSubstring() and IsNotSubstring() check whether needle is a
3088 // substring of haystack (NULL is considered a substring of itself
3089 // only), and return an appropriate error message when they fail.
3090
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3091 AssertionResult IsSubstring(
3092 const char* needle_expr, const char* haystack_expr,
3093 const char* needle, const char* haystack) {
3094 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3095 }
3096
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3097 AssertionResult IsSubstring(
3098 const char* needle_expr, const char* haystack_expr,
3099 const wchar_t* needle, const wchar_t* haystack) {
3100 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3101 }
3102
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3103 AssertionResult IsNotSubstring(
3104 const char* needle_expr, const char* haystack_expr,
3105 const char* needle, const char* haystack) {
3106 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3107 }
3108
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3109 AssertionResult IsNotSubstring(
3110 const char* needle_expr, const char* haystack_expr,
3111 const wchar_t* needle, const wchar_t* haystack) {
3112 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3113 }
3114
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3115 AssertionResult IsSubstring(
3116 const char* needle_expr, const char* haystack_expr,
3117 const ::std::string& needle, const ::std::string& haystack) {
3118 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3119 }
3120
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3121 AssertionResult IsNotSubstring(
3122 const char* needle_expr, const char* haystack_expr,
3123 const ::std::string& needle, const ::std::string& haystack) {
3124 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3125 }
3126
3127 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3128 AssertionResult IsSubstring(
3129 const char* needle_expr, const char* haystack_expr,
3130 const ::std::wstring& needle, const ::std::wstring& haystack) {
3131 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3132 }
3133
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3134 AssertionResult IsNotSubstring(
3135 const char* needle_expr, const char* haystack_expr,
3136 const ::std::wstring& needle, const ::std::wstring& haystack) {
3137 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3138 }
3139 #endif // GTEST_HAS_STD_WSTRING
3140
3141 namespace internal {
3142
3143 #if GTEST_OS_WINDOWS
3144
3145 namespace {
3146
3147 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)3148 AssertionResult HRESULTFailureHelper(const char* expr,
3149 const char* expected,
3150 long hr) { // NOLINT
3151 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3152
3153 // Windows CE doesn't support FormatMessage.
3154 const char error_text[] = "";
3155
3156 # else
3157
3158 // Looks up the human-readable system message for the HRESULT code
3159 // and since we're not passing any params to FormatMessage, we don't
3160 // want inserts expanded.
3161 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3162 FORMAT_MESSAGE_IGNORE_INSERTS;
3163 const DWORD kBufSize = 4096;
3164 // Gets the system's human readable message string for this HRESULT.
3165 char error_text[kBufSize] = { '\0' };
3166 DWORD message_length = ::FormatMessageA(kFlags,
3167 0, // no source, we're asking system
3168 hr, // the error
3169 0, // no line width restrictions
3170 error_text, // output buffer
3171 kBufSize, // buf size
3172 nullptr); // no arguments for inserts
3173 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3174 for (; message_length && IsSpace(error_text[message_length - 1]);
3175 --message_length) {
3176 error_text[message_length - 1] = '\0';
3177 }
3178
3179 # endif // GTEST_OS_WINDOWS_MOBILE
3180
3181 const std::string error_hex("0x" + String::FormatHexInt(hr));
3182 return ::testing::AssertionFailure()
3183 << "Expected: " << expr << " " << expected << ".\n"
3184 << " Actual: " << error_hex << " " << error_text << "\n";
3185 }
3186
3187 } // namespace
3188
IsHRESULTSuccess(const char * expr,long hr)3189 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3190 if (SUCCEEDED(hr)) {
3191 return AssertionSuccess();
3192 }
3193 return HRESULTFailureHelper(expr, "succeeds", hr);
3194 }
3195
IsHRESULTFailure(const char * expr,long hr)3196 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3197 if (FAILED(hr)) {
3198 return AssertionSuccess();
3199 }
3200 return HRESULTFailureHelper(expr, "fails", hr);
3201 }
3202
3203 #endif // GTEST_OS_WINDOWS
3204
3205 // Utility functions for encoding Unicode text (wide strings) in
3206 // UTF-8.
3207
3208 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3209 // like this:
3210 //
3211 // Code-point length Encoding
3212 // 0 - 7 bits 0xxxxxxx
3213 // 8 - 11 bits 110xxxxx 10xxxxxx
3214 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3215 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3216
3217 // The maximum code-point a one-byte UTF-8 sequence can represent.
3218 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
3219
3220 // The maximum code-point a two-byte UTF-8 sequence can represent.
3221 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3222
3223 // The maximum code-point a three-byte UTF-8 sequence can represent.
3224 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3225
3226 // The maximum code-point a four-byte UTF-8 sequence can represent.
3227 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3228
3229 // Chops off the n lowest bits from a bit pattern. Returns the n
3230 // lowest bits. As a side effect, the original bit pattern will be
3231 // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)3232 inline UInt32 ChopLowBits(UInt32* bits, int n) {
3233 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3234 *bits >>= n;
3235 return low_bits;
3236 }
3237
3238 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3239 // code_point parameter is of type UInt32 because wchar_t may not be
3240 // wide enough to contain a code point.
3241 // If the code_point is not a valid Unicode code point
3242 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3243 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)3244 std::string CodePointToUtf8(UInt32 code_point) {
3245 if (code_point > kMaxCodePoint4) {
3246 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3247 }
3248
3249 char str[5]; // Big enough for the largest valid code point.
3250 if (code_point <= kMaxCodePoint1) {
3251 str[1] = '\0';
3252 str[0] = static_cast<char>(code_point); // 0xxxxxxx
3253 } else if (code_point <= kMaxCodePoint2) {
3254 str[2] = '\0';
3255 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3256 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3257 } else if (code_point <= kMaxCodePoint3) {
3258 str[3] = '\0';
3259 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3260 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3261 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3262 } else { // code_point <= kMaxCodePoint4
3263 str[4] = '\0';
3264 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3265 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3266 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3267 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3268 }
3269 return str;
3270 }
3271
3272 // The following two functions only make sense if the system
3273 // uses UTF-16 for wide string encoding. All supported systems
3274 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
3275
3276 // Determines if the arguments constitute UTF-16 surrogate pair
3277 // and thus should be combined into a single Unicode code point
3278 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)3279 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3280 return sizeof(wchar_t) == 2 &&
3281 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3282 }
3283
3284 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)3285 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3286 wchar_t second) {
3287 const UInt32 mask = (1 << 10) - 1;
3288 return (sizeof(wchar_t) == 2) ?
3289 (((first & mask) << 10) | (second & mask)) + 0x10000 :
3290 // This function should not be called when the condition is
3291 // false, but we provide a sensible default in case it is.
3292 static_cast<UInt32>(first);
3293 }
3294
3295 // Converts a wide string to a narrow string in UTF-8 encoding.
3296 // The wide string is assumed to have the following encoding:
3297 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
3298 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3299 // Parameter str points to a null-terminated wide string.
3300 // Parameter num_chars may additionally limit the number
3301 // of wchar_t characters processed. -1 is used when the entire string
3302 // should be processed.
3303 // If the string contains code points that are not valid Unicode code points
3304 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3305 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3306 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3307 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)3308 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3309 if (num_chars == -1)
3310 num_chars = static_cast<int>(wcslen(str));
3311
3312 ::std::stringstream stream;
3313 for (int i = 0; i < num_chars; ++i) {
3314 UInt32 unicode_code_point;
3315
3316 if (str[i] == L'\0') {
3317 break;
3318 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3319 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3320 str[i + 1]);
3321 i++;
3322 } else {
3323 unicode_code_point = static_cast<UInt32>(str[i]);
3324 }
3325
3326 stream << CodePointToUtf8(unicode_code_point);
3327 }
3328 return StringStreamToString(&stream);
3329 }
3330
3331 // Converts a wide C string to an std::string using the UTF-8 encoding.
3332 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)3333 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3334 if (wide_c_str == nullptr) return "(null)";
3335
3336 return internal::WideStringToUtf8(wide_c_str, -1);
3337 }
3338
3339 // Compares two wide C strings. Returns true iff they have the same
3340 // content.
3341 //
3342 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3343 // C string is considered different to any non-NULL C string,
3344 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3345 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3346 if (lhs == nullptr) return rhs == nullptr;
3347
3348 if (rhs == nullptr) return false;
3349
3350 return wcscmp(lhs, rhs) == 0;
3351 }
3352
3353 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const wchar_t * lhs,const wchar_t * rhs)3354 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3355 const char* rhs_expression,
3356 const wchar_t* lhs,
3357 const wchar_t* rhs) {
3358 if (String::WideCStringEquals(lhs, rhs)) {
3359 return AssertionSuccess();
3360 }
3361
3362 return EqFailure(lhs_expression,
3363 rhs_expression,
3364 PrintToString(lhs),
3365 PrintToString(rhs),
3366 false);
3367 }
3368
3369 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)3370 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3371 const char* s2_expression,
3372 const wchar_t* s1,
3373 const wchar_t* s2) {
3374 if (!String::WideCStringEquals(s1, s2)) {
3375 return AssertionSuccess();
3376 }
3377
3378 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3379 << s2_expression << "), actual: "
3380 << PrintToString(s1)
3381 << " vs " << PrintToString(s2);
3382 }
3383
3384 // Compares two C strings, ignoring case. Returns true iff they have
3385 // the same content.
3386 //
3387 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3388 // NULL C string is considered different to any non-NULL C string,
3389 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)3390 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3391 if (lhs == nullptr) return rhs == nullptr;
3392 if (rhs == nullptr) return false;
3393 return posix::StrCaseCmp(lhs, rhs) == 0;
3394 }
3395
3396 // Compares two wide C strings, ignoring case. Returns true iff they
3397 // have the same content.
3398 //
3399 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3400 // A NULL C string is considered different to any non-NULL wide C string,
3401 // including the empty string.
3402 // NB: The implementations on different platforms slightly differ.
3403 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3404 // environment variable. On GNU platform this method uses wcscasecmp
3405 // which compares according to LC_CTYPE category of the current locale.
3406 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3407 // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3408 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3409 const wchar_t* rhs) {
3410 if (lhs == nullptr) return rhs == nullptr;
3411
3412 if (rhs == nullptr) return false;
3413
3414 #if GTEST_OS_WINDOWS
3415 return _wcsicmp(lhs, rhs) == 0;
3416 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3417 return wcscasecmp(lhs, rhs) == 0;
3418 #else
3419 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3420 // Other unknown OSes may not define it either.
3421 wint_t left, right;
3422 do {
3423 left = towlower(*lhs++);
3424 right = towlower(*rhs++);
3425 } while (left && left == right);
3426 return left == right;
3427 #endif // OS selector
3428 }
3429
3430 // Returns true iff str ends with the given suffix, ignoring case.
3431 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3432 bool String::EndsWithCaseInsensitive(
3433 const std::string& str, const std::string& suffix) {
3434 const size_t str_len = str.length();
3435 const size_t suffix_len = suffix.length();
3436 return (str_len >= suffix_len) &&
3437 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3438 suffix.c_str());
3439 }
3440
3441 // Formats an int value as "%02d".
FormatIntWidth2(int value)3442 std::string String::FormatIntWidth2(int value) {
3443 std::stringstream ss;
3444 ss << std::setfill('0') << std::setw(2) << value;
3445 return ss.str();
3446 }
3447
3448 // Formats an int value as "%X".
FormatHexInt(int value)3449 std::string String::FormatHexInt(int value) {
3450 std::stringstream ss;
3451 ss << std::hex << std::uppercase << value;
3452 return ss.str();
3453 }
3454
3455 // Formats a byte as "%02X".
FormatByte(unsigned char value)3456 std::string String::FormatByte(unsigned char value) {
3457 std::stringstream ss;
3458 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3459 << static_cast<unsigned int>(value);
3460 return ss.str();
3461 }
3462
3463 // Converts the buffer in a stringstream to an std::string, converting NUL
3464 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3465 std::string StringStreamToString(::std::stringstream* ss) {
3466 const ::std::string& str = ss->str();
3467 const char* const start = str.c_str();
3468 const char* const end = start + str.length();
3469
3470 std::string result;
3471 result.reserve(2 * (end - start));
3472 for (const char* ch = start; ch != end; ++ch) {
3473 if (*ch == '\0') {
3474 result += "\\0"; // Replaces NUL with "\\0";
3475 } else {
3476 result += *ch;
3477 }
3478 }
3479
3480 return result;
3481 }
3482
3483 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3484 std::string AppendUserMessage(const std::string& gtest_msg,
3485 const Message& user_msg) {
3486 // Appends the user message if it's non-empty.
3487 const std::string user_msg_string = user_msg.GetString();
3488 if (user_msg_string.empty()) {
3489 return gtest_msg;
3490 }
3491
3492 return gtest_msg + "\n" + user_msg_string;
3493 }
3494
3495 } // namespace internal
3496
3497 // class TestResult
3498
3499 // Creates an empty TestResult.
TestResult()3500 TestResult::TestResult()
3501 : death_test_count_(0),
3502 elapsed_time_(0) {
3503 }
3504
3505 // D'tor.
~TestResult()3506 TestResult::~TestResult() {
3507 }
3508
3509 // Returns the i-th test part result among all the results. i can
3510 // range from 0 to total_part_count() - 1. If i is not in that range,
3511 // aborts the program.
GetTestPartResult(int i) const3512 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3513 if (i < 0 || i >= total_part_count())
3514 internal::posix::Abort();
3515 return test_part_results_.at(i);
3516 }
3517
3518 // Returns the i-th test property. i can range from 0 to
3519 // test_property_count() - 1. If i is not in that range, aborts the
3520 // program.
GetTestProperty(int i) const3521 const TestProperty& TestResult::GetTestProperty(int i) const {
3522 if (i < 0 || i >= test_property_count())
3523 internal::posix::Abort();
3524 return test_properties_.at(i);
3525 }
3526
3527 // Clears the test part results.
ClearTestPartResults()3528 void TestResult::ClearTestPartResults() {
3529 test_part_results_.clear();
3530 }
3531
3532 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3533 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3534 test_part_results_.push_back(test_part_result);
3535 }
3536
3537 // Adds a test property to the list. If a property with the same key as the
3538 // supplied property is already represented, the value of this test_property
3539 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3540 void TestResult::RecordProperty(const std::string& xml_element,
3541 const TestProperty& test_property) {
3542 if (!ValidateTestProperty(xml_element, test_property)) {
3543 return;
3544 }
3545 internal::MutexLock lock(&test_properites_mutex_);
3546 const std::vector<TestProperty>::iterator property_with_matching_key =
3547 std::find_if(test_properties_.begin(), test_properties_.end(),
3548 internal::TestPropertyKeyIs(test_property.key()));
3549 if (property_with_matching_key == test_properties_.end()) {
3550 test_properties_.push_back(test_property);
3551 return;
3552 }
3553 property_with_matching_key->SetValue(test_property.value());
3554 }
3555
3556 // The list of reserved attributes used in the <testsuites> element of XML
3557 // output.
3558 static const char* const kReservedTestSuitesAttributes[] = {
3559 "disabled",
3560 "errors",
3561 "failures",
3562 "name",
3563 "random_seed",
3564 "tests",
3565 "time",
3566 "timestamp"
3567 };
3568
3569 // The list of reserved attributes used in the <testsuite> element of XML
3570 // output.
3571 static const char* const kReservedTestSuiteAttributes[] = {
3572 "disabled",
3573 "errors",
3574 "failures",
3575 "name",
3576 "tests",
3577 "time"
3578 };
3579
3580 // The list of reserved attributes used in the <testcase> element of XML output.
3581 static const char* const kReservedTestCaseAttributes[] = {
3582 "classname", "name", "status", "time", "type_param",
3583 "value_param", "file", "line"};
3584
3585 // Use a slightly different set for allowed output to ensure existing tests can
3586 // still RecordProperty("result")
3587 static const char* const kReservedOutputTestCaseAttributes[] = {
3588 "classname", "name", "status", "time", "type_param",
3589 "value_param", "file", "line", "result"};
3590
3591 template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])3592 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3593 return std::vector<std::string>(array, array + kSize);
3594 }
3595
GetReservedAttributesForElement(const std::string & xml_element)3596 static std::vector<std::string> GetReservedAttributesForElement(
3597 const std::string& xml_element) {
3598 if (xml_element == "testsuites") {
3599 return ArrayAsVector(kReservedTestSuitesAttributes);
3600 } else if (xml_element == "testsuite") {
3601 return ArrayAsVector(kReservedTestSuiteAttributes);
3602 } else if (xml_element == "testcase") {
3603 return ArrayAsVector(kReservedTestCaseAttributes);
3604 } else {
3605 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3606 }
3607 // This code is unreachable but some compilers may not realizes that.
3608 return std::vector<std::string>();
3609 }
3610
3611 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
GetReservedOutputAttributesForElement(const std::string & xml_element)3612 static std::vector<std::string> GetReservedOutputAttributesForElement(
3613 const std::string& xml_element) {
3614 if (xml_element == "testsuites") {
3615 return ArrayAsVector(kReservedTestSuitesAttributes);
3616 } else if (xml_element == "testsuite") {
3617 return ArrayAsVector(kReservedTestSuiteAttributes);
3618 } else if (xml_element == "testcase") {
3619 return ArrayAsVector(kReservedOutputTestCaseAttributes);
3620 } else {
3621 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3622 }
3623 // This code is unreachable but some compilers may not realizes that.
3624 return std::vector<std::string>();
3625 }
3626
FormatWordList(const std::vector<std::string> & words)3627 static std::string FormatWordList(const std::vector<std::string>& words) {
3628 Message word_list;
3629 for (size_t i = 0; i < words.size(); ++i) {
3630 if (i > 0 && words.size() > 2) {
3631 word_list << ", ";
3632 }
3633 if (i == words.size() - 1) {
3634 word_list << "and ";
3635 }
3636 word_list << "'" << words[i] << "'";
3637 }
3638 return word_list.GetString();
3639 }
3640
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3641 static bool ValidateTestPropertyName(
3642 const std::string& property_name,
3643 const std::vector<std::string>& reserved_names) {
3644 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3645 reserved_names.end()) {
3646 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3647 << " (" << FormatWordList(reserved_names)
3648 << " are reserved by " << GTEST_NAME_ << ")";
3649 return false;
3650 }
3651 return true;
3652 }
3653
3654 // Adds a failure if the key is a reserved attribute of the element named
3655 // xml_element. Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3656 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3657 const TestProperty& test_property) {
3658 return ValidateTestPropertyName(test_property.key(),
3659 GetReservedAttributesForElement(xml_element));
3660 }
3661
3662 // Clears the object.
Clear()3663 void TestResult::Clear() {
3664 test_part_results_.clear();
3665 test_properties_.clear();
3666 death_test_count_ = 0;
3667 elapsed_time_ = 0;
3668 }
3669
3670 // Returns true off the test part was skipped.
TestPartSkipped(const TestPartResult & result)3671 static bool TestPartSkipped(const TestPartResult& result) {
3672 return result.skipped();
3673 }
3674
3675 // Returns true iff the test was skipped.
Skipped() const3676 bool TestResult::Skipped() const {
3677 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3678 }
3679
3680 // Returns true iff the test failed.
Failed() const3681 bool TestResult::Failed() const {
3682 for (int i = 0; i < total_part_count(); ++i) {
3683 if (GetTestPartResult(i).failed())
3684 return true;
3685 }
3686 return false;
3687 }
3688
3689 // Returns true iff the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3690 static bool TestPartFatallyFailed(const TestPartResult& result) {
3691 return result.fatally_failed();
3692 }
3693
3694 // Returns true iff the test fatally failed.
HasFatalFailure() const3695 bool TestResult::HasFatalFailure() const {
3696 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3697 }
3698
3699 // Returns true iff the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3700 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3701 return result.nonfatally_failed();
3702 }
3703
3704 // Returns true iff the test has a non-fatal failure.
HasNonfatalFailure() const3705 bool TestResult::HasNonfatalFailure() const {
3706 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3707 }
3708
3709 // Gets the number of all test parts. This is the sum of the number
3710 // of successful test parts and the number of failed test parts.
total_part_count() const3711 int TestResult::total_part_count() const {
3712 return static_cast<int>(test_part_results_.size());
3713 }
3714
3715 // Returns the number of the test properties.
test_property_count() const3716 int TestResult::test_property_count() const {
3717 return static_cast<int>(test_properties_.size());
3718 }
3719
3720 // class Test
3721
3722 // Creates a Test object.
3723
3724 // The c'tor saves the states of all flags.
Test()3725 Test::Test()
3726 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3727 }
3728
3729 // The d'tor restores the states of all flags. The actual work is
3730 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3731 // visible here.
~Test()3732 Test::~Test() {
3733 }
3734
3735 // Sets up the test fixture.
3736 //
3737 // A sub-class may override this.
SetUp()3738 void Test::SetUp() {
3739 }
3740
3741 // Tears down the test fixture.
3742 //
3743 // A sub-class may override this.
TearDown()3744 void Test::TearDown() {
3745 }
3746
3747 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3748 void Test::RecordProperty(const std::string& key, const std::string& value) {
3749 UnitTest::GetInstance()->RecordProperty(key, value);
3750 }
3751
3752 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3753 void Test::RecordProperty(const std::string& key, int value) {
3754 Message value_message;
3755 value_message << value;
3756 RecordProperty(key, value_message.GetString().c_str());
3757 }
3758
3759 namespace internal {
3760
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3761 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3762 const std::string& message) {
3763 // This function is a friend of UnitTest and as such has access to
3764 // AddTestPartResult.
3765 UnitTest::GetInstance()->AddTestPartResult(
3766 result_type,
3767 nullptr, // No info about the source file where the exception occurred.
3768 -1, // We have no info on which line caused the exception.
3769 message,
3770 ""); // No stack trace, either.
3771 }
3772
3773 } // namespace internal
3774
3775 // Google Test requires all tests in the same test suite to use the same test
3776 // fixture class. This function checks if the current test has the
3777 // same fixture class as the first test in the current test suite. If
3778 // yes, it returns true; otherwise it generates a Google Test failure and
3779 // returns false.
HasSameFixtureClass()3780 bool Test::HasSameFixtureClass() {
3781 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3782 const TestSuite* const test_suite = impl->current_test_suite();
3783
3784 // Info about the first test in the current test suite.
3785 const TestInfo* const first_test_info = test_suite->test_info_list()[0];
3786 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3787 const char* const first_test_name = first_test_info->name();
3788
3789 // Info about the current test.
3790 const TestInfo* const this_test_info = impl->current_test_info();
3791 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3792 const char* const this_test_name = this_test_info->name();
3793
3794 if (this_fixture_id != first_fixture_id) {
3795 // Is the first test defined using TEST?
3796 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3797 // Is this test defined using TEST?
3798 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3799
3800 if (first_is_TEST || this_is_TEST) {
3801 // Both TEST and TEST_F appear in same test suite, which is incorrect.
3802 // Tell the user how to fix this.
3803
3804 // Gets the name of the TEST and the name of the TEST_F. Note
3805 // that first_is_TEST and this_is_TEST cannot both be true, as
3806 // the fixture IDs are different for the two tests.
3807 const char* const TEST_name =
3808 first_is_TEST ? first_test_name : this_test_name;
3809 const char* const TEST_F_name =
3810 first_is_TEST ? this_test_name : first_test_name;
3811
3812 ADD_FAILURE()
3813 << "All tests in the same test suite must use the same test fixture\n"
3814 << "class, so mixing TEST_F and TEST in the same test suite is\n"
3815 << "illegal. In test suite " << this_test_info->test_suite_name()
3816 << ",\n"
3817 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3818 << "test " << TEST_name << " is defined using TEST. You probably\n"
3819 << "want to change the TEST to TEST_F or move it to another test\n"
3820 << "case.";
3821 } else {
3822 // Two fixture classes with the same name appear in two different
3823 // namespaces, which is not allowed. Tell the user how to fix this.
3824 ADD_FAILURE()
3825 << "All tests in the same test suite must use the same test fixture\n"
3826 << "class. However, in test suite "
3827 << this_test_info->test_suite_name() << ",\n"
3828 << "you defined test " << first_test_name << " and test "
3829 << this_test_name << "\n"
3830 << "using two different test fixture classes. This can happen if\n"
3831 << "the two classes are from different namespaces or translation\n"
3832 << "units and have the same name. You should probably rename one\n"
3833 << "of the classes to put the tests into different test suites.";
3834 }
3835 return false;
3836 }
3837
3838 return true;
3839 }
3840
3841 #if GTEST_HAS_SEH
3842
3843 // Adds an "exception thrown" fatal failure to the current test. This
3844 // function returns its result via an output parameter pointer because VC++
3845 // prohibits creation of objects with destructors on stack in functions
3846 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)3847 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3848 const char* location) {
3849 Message message;
3850 message << "SEH exception with code 0x" << std::setbase(16) <<
3851 exception_code << std::setbase(10) << " thrown in " << location << ".";
3852
3853 return new std::string(message.GetString());
3854 }
3855
3856 #endif // GTEST_HAS_SEH
3857
3858 namespace internal {
3859
3860 #if GTEST_HAS_EXCEPTIONS
3861
3862 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)3863 static std::string FormatCxxExceptionMessage(const char* description,
3864 const char* location) {
3865 Message message;
3866 if (description != nullptr) {
3867 message << "C++ exception with description \"" << description << "\"";
3868 } else {
3869 message << "Unknown C++ exception";
3870 }
3871 message << " thrown in " << location << ".";
3872
3873 return message.GetString();
3874 }
3875
3876 static std::string PrintTestPartResultToString(
3877 const TestPartResult& test_part_result);
3878
GoogleTestFailureException(const TestPartResult & failure)3879 GoogleTestFailureException::GoogleTestFailureException(
3880 const TestPartResult& failure)
3881 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3882
3883 #endif // GTEST_HAS_EXCEPTIONS
3884
3885 // We put these helper functions in the internal namespace as IBM's xlC
3886 // compiler rejects the code if they were declared static.
3887
3888 // Runs the given method and handles SEH exceptions it throws, when
3889 // SEH is supported; returns the 0-value for type Result in case of an
3890 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3891 // exceptions in the same function. Therefore, we provide a separate
3892 // wrapper function for handling SEH exceptions.)
3893 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3894 Result HandleSehExceptionsInMethodIfSupported(
3895 T* object, Result (T::*method)(), const char* location) {
3896 #if GTEST_HAS_SEH
3897 __try {
3898 return (object->*method)();
3899 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3900 GetExceptionCode())) {
3901 // We create the exception message on the heap because VC++ prohibits
3902 // creation of objects with destructors on stack in functions using __try
3903 // (see error C2712).
3904 std::string* exception_message = FormatSehExceptionMessage(
3905 GetExceptionCode(), location);
3906 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3907 *exception_message);
3908 delete exception_message;
3909 return static_cast<Result>(0);
3910 }
3911 #else
3912 (void)location;
3913 return (object->*method)();
3914 #endif // GTEST_HAS_SEH
3915 }
3916
3917 // Runs the given method and catches and reports C++ and/or SEH-style
3918 // exceptions, if they are supported; returns the 0-value for type
3919 // Result in case of an SEH exception.
3920 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3921 Result HandleExceptionsInMethodIfSupported(
3922 T* object, Result (T::*method)(), const char* location) {
3923 // NOTE: The user code can affect the way in which Google Test handles
3924 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3925 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3926 // after the exception is caught and either report or re-throw the
3927 // exception based on the flag's value:
3928 //
3929 // try {
3930 // // Perform the test method.
3931 // } catch (...) {
3932 // if (GTEST_FLAG(catch_exceptions))
3933 // // Report the exception as failure.
3934 // else
3935 // throw; // Re-throws the original exception.
3936 // }
3937 //
3938 // However, the purpose of this flag is to allow the program to drop into
3939 // the debugger when the exception is thrown. On most platforms, once the
3940 // control enters the catch block, the exception origin information is
3941 // lost and the debugger will stop the program at the point of the
3942 // re-throw in this function -- instead of at the point of the original
3943 // throw statement in the code under test. For this reason, we perform
3944 // the check early, sacrificing the ability to affect Google Test's
3945 // exception handling in the method where the exception is thrown.
3946 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3947 #if GTEST_HAS_EXCEPTIONS
3948 try {
3949 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3950 } catch (const AssertionException&) { // NOLINT
3951 // This failure was reported already.
3952 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3953 // This exception type can only be thrown by a failed Google
3954 // Test assertion with the intention of letting another testing
3955 // framework catch it. Therefore we just re-throw it.
3956 throw;
3957 } catch (const std::exception& e) { // NOLINT
3958 internal::ReportFailureInUnknownLocation(
3959 TestPartResult::kFatalFailure,
3960 FormatCxxExceptionMessage(e.what(), location));
3961 } catch (...) { // NOLINT
3962 internal::ReportFailureInUnknownLocation(
3963 TestPartResult::kFatalFailure,
3964 FormatCxxExceptionMessage(nullptr, location));
3965 }
3966 return static_cast<Result>(0);
3967 #else
3968 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3969 #endif // GTEST_HAS_EXCEPTIONS
3970 } else {
3971 return (object->*method)();
3972 }
3973 }
3974
3975 } // namespace internal
3976
3977 // Runs the test and updates the test result.
Run()3978 void Test::Run() {
3979 if (!HasSameFixtureClass()) return;
3980
3981 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3982 impl->os_stack_trace_getter()->UponLeavingGTest();
3983 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3984 // We will run the test only if SetUp() was successful and didn't call
3985 // GTEST_SKIP().
3986 if (!HasFatalFailure() && !IsSkipped()) {
3987 impl->os_stack_trace_getter()->UponLeavingGTest();
3988 internal::HandleExceptionsInMethodIfSupported(
3989 this, &Test::TestBody, "the test body");
3990 }
3991
3992 // However, we want to clean up as much as possible. Hence we will
3993 // always call TearDown(), even if SetUp() or the test body has
3994 // failed.
3995 impl->os_stack_trace_getter()->UponLeavingGTest();
3996 internal::HandleExceptionsInMethodIfSupported(
3997 this, &Test::TearDown, "TearDown()");
3998 }
3999
4000 // Returns true iff the current test has a fatal failure.
HasFatalFailure()4001 bool Test::HasFatalFailure() {
4002 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
4003 }
4004
4005 // Returns true iff the current test has a non-fatal failure.
HasNonfatalFailure()4006 bool Test::HasNonfatalFailure() {
4007 return internal::GetUnitTestImpl()->current_test_result()->
4008 HasNonfatalFailure();
4009 }
4010
4011 // Returns true iff the current test was skipped.
IsSkipped()4012 bool Test::IsSkipped() {
4013 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4014 }
4015
4016 // class TestInfo
4017
4018 // Constructs a TestInfo object. It assumes ownership of the test factory
4019 // object.
TestInfo(const std::string & a_test_suite_name,const std::string & a_name,const char * a_type_param,const char * a_value_param,internal::CodeLocation a_code_location,internal::TypeId fixture_class_id,internal::TestFactoryBase * factory)4020 TestInfo::TestInfo(const std::string& a_test_suite_name,
4021 const std::string& a_name, const char* a_type_param,
4022 const char* a_value_param,
4023 internal::CodeLocation a_code_location,
4024 internal::TypeId fixture_class_id,
4025 internal::TestFactoryBase* factory)
4026 : test_suite_name_(a_test_suite_name),
4027 name_(a_name),
4028 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4029 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
4030 location_(a_code_location),
4031 fixture_class_id_(fixture_class_id),
4032 should_run_(false),
4033 is_disabled_(false),
4034 matches_filter_(false),
4035 factory_(factory),
4036 result_() {}
4037
4038 // Destructs a TestInfo object.
~TestInfo()4039 TestInfo::~TestInfo() { delete factory_; }
4040
4041 namespace internal {
4042
4043 // Creates a new TestInfo object and registers it with Google Test;
4044 // returns the created object.
4045 //
4046 // Arguments:
4047 //
4048 // test_suite_name: name of the test suite
4049 // name: name of the test
4050 // type_param: the name of the test's type parameter, or NULL if
4051 // this is not a typed or a type-parameterized test.
4052 // value_param: text representation of the test's value parameter,
4053 // or NULL if this is not a value-parameterized test.
4054 // code_location: code location where the test is defined
4055 // fixture_class_id: ID of the test fixture class
4056 // set_up_tc: pointer to the function that sets up the test suite
4057 // tear_down_tc: pointer to the function that tears down the test suite
4058 // factory: pointer to the factory that creates a test object.
4059 // The newly created TestInfo instance will assume
4060 // ownership of the factory object.
MakeAndRegisterTestInfo(const char * test_suite_name,const char * name,const char * type_param,const char * value_param,CodeLocation code_location,TypeId fixture_class_id,SetUpTestSuiteFunc set_up_tc,TearDownTestSuiteFunc tear_down_tc,TestFactoryBase * factory)4061 TestInfo* MakeAndRegisterTestInfo(
4062 const char* test_suite_name, const char* name, const char* type_param,
4063 const char* value_param, CodeLocation code_location,
4064 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
4065 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
4066 TestInfo* const test_info =
4067 new TestInfo(test_suite_name, name, type_param, value_param,
4068 code_location, fixture_class_id, factory);
4069 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4070 return test_info;
4071 }
4072
ReportInvalidTestSuiteType(const char * test_suite_name,CodeLocation code_location)4073 void ReportInvalidTestSuiteType(const char* test_suite_name,
4074 CodeLocation code_location) {
4075 Message errors;
4076 errors
4077 << "Attempted redefinition of test suite " << test_suite_name << ".\n"
4078 << "All tests in the same test suite must use the same test fixture\n"
4079 << "class. However, in test suite " << test_suite_name << ", you tried\n"
4080 << "to define a test using a fixture class different from the one\n"
4081 << "used earlier. This can happen if the two fixture classes are\n"
4082 << "from different namespaces and have the same name. You should\n"
4083 << "probably rename one of the classes to put the tests into different\n"
4084 << "test suites.";
4085
4086 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4087 code_location.line)
4088 << " " << errors.GetString();
4089 }
4090 } // namespace internal
4091
4092 namespace {
4093
4094 // A predicate that checks the test name of a TestInfo against a known
4095 // value.
4096 //
4097 // This is used for implementation of the TestSuite class only. We put
4098 // it in the anonymous namespace to prevent polluting the outer
4099 // namespace.
4100 //
4101 // TestNameIs is copyable.
4102 class TestNameIs {
4103 public:
4104 // Constructor.
4105 //
4106 // TestNameIs has NO default constructor.
TestNameIs(const char * name)4107 explicit TestNameIs(const char* name)
4108 : name_(name) {}
4109
4110 // Returns true iff the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const4111 bool operator()(const TestInfo * test_info) const {
4112 return test_info && test_info->name() == name_;
4113 }
4114
4115 private:
4116 std::string name_;
4117 };
4118
4119 } // namespace
4120
4121 namespace internal {
4122
4123 // This method expands all parameterized tests registered with macros TEST_P
4124 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
4125 // This will be done just once during the program runtime.
RegisterParameterizedTests()4126 void UnitTestImpl::RegisterParameterizedTests() {
4127 if (!parameterized_tests_registered_) {
4128 parameterized_test_registry_.RegisterTests();
4129 parameterized_tests_registered_ = true;
4130 }
4131 }
4132
4133 } // namespace internal
4134
4135 // Creates the test object, runs it, records its result, and then
4136 // deletes it.
Run()4137 void TestInfo::Run() {
4138 if (!should_run_) return;
4139
4140 // Tells UnitTest where to store test result.
4141 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4142 impl->set_current_test_info(this);
4143
4144 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4145
4146 // Notifies the unit test event listeners that a test is about to start.
4147 repeater->OnTestStart(*this);
4148
4149 const TimeInMillis start = internal::GetTimeInMillis();
4150
4151 impl->os_stack_trace_getter()->UponLeavingGTest();
4152
4153 // Creates the test object.
4154 Test* const test = internal::HandleExceptionsInMethodIfSupported(
4155 factory_, &internal::TestFactoryBase::CreateTest,
4156 "the test fixture's constructor");
4157
4158 // Runs the test if the constructor didn't generate a fatal failure or invoke
4159 // GTEST_SKIP().
4160 // Note that the object will not be null
4161 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
4162 // This doesn't throw as all user code that can throw are wrapped into
4163 // exception handling code.
4164 test->Run();
4165 }
4166
4167 if (test != nullptr) {
4168 // Deletes the test object.
4169 impl->os_stack_trace_getter()->UponLeavingGTest();
4170 internal::HandleExceptionsInMethodIfSupported(
4171 test, &Test::DeleteSelf_, "the test fixture's destructor");
4172 }
4173
4174 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4175
4176 // Notifies the unit test event listener that a test has just finished.
4177 repeater->OnTestEnd(*this);
4178
4179 // Tells UnitTest to stop associating assertion results to this
4180 // test.
4181 impl->set_current_test_info(nullptr);
4182 }
4183
4184 // class TestSuite
4185
4186 // Gets the number of successful tests in this test suite.
successful_test_count() const4187 int TestSuite::successful_test_count() const {
4188 return CountIf(test_info_list_, TestPassed);
4189 }
4190
4191 // Gets the number of successful tests in this test suite.
skipped_test_count() const4192 int TestSuite::skipped_test_count() const {
4193 return CountIf(test_info_list_, TestSkipped);
4194 }
4195
4196 // Gets the number of failed tests in this test suite.
failed_test_count() const4197 int TestSuite::failed_test_count() const {
4198 return CountIf(test_info_list_, TestFailed);
4199 }
4200
4201 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const4202 int TestSuite::reportable_disabled_test_count() const {
4203 return CountIf(test_info_list_, TestReportableDisabled);
4204 }
4205
4206 // Gets the number of disabled tests in this test suite.
disabled_test_count() const4207 int TestSuite::disabled_test_count() const {
4208 return CountIf(test_info_list_, TestDisabled);
4209 }
4210
4211 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const4212 int TestSuite::reportable_test_count() const {
4213 return CountIf(test_info_list_, TestReportable);
4214 }
4215
4216 // Get the number of tests in this test suite that should run.
test_to_run_count() const4217 int TestSuite::test_to_run_count() const {
4218 return CountIf(test_info_list_, ShouldRunTest);
4219 }
4220
4221 // Gets the number of all tests.
total_test_count() const4222 int TestSuite::total_test_count() const {
4223 return static_cast<int>(test_info_list_.size());
4224 }
4225
4226 // Creates a TestSuite with the given name.
4227 //
4228 // Arguments:
4229 //
4230 // name: name of the test suite
4231 // a_type_param: the name of the test suite's type parameter, or NULL if
4232 // this is not a typed or a type-parameterized test suite.
4233 // set_up_tc: pointer to the function that sets up the test suite
4234 // tear_down_tc: pointer to the function that tears down the test suite
TestSuite(const char * a_name,const char * a_type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)4235 TestSuite::TestSuite(const char* a_name, const char* a_type_param,
4236 internal::SetUpTestSuiteFunc set_up_tc,
4237 internal::TearDownTestSuiteFunc tear_down_tc)
4238 : name_(a_name),
4239 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4240 set_up_tc_(set_up_tc),
4241 tear_down_tc_(tear_down_tc),
4242 should_run_(false),
4243 elapsed_time_(0) {}
4244
4245 // Destructor of TestSuite.
~TestSuite()4246 TestSuite::~TestSuite() {
4247 // Deletes every Test in the collection.
4248 ForEach(test_info_list_, internal::Delete<TestInfo>);
4249 }
4250
4251 // Returns the i-th test among all the tests. i can range from 0 to
4252 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const4253 const TestInfo* TestSuite::GetTestInfo(int i) const {
4254 const int index = GetElementOr(test_indices_, i, -1);
4255 return index < 0 ? nullptr : test_info_list_[index];
4256 }
4257
4258 // Returns the i-th test among all the tests. i can range from 0 to
4259 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)4260 TestInfo* TestSuite::GetMutableTestInfo(int i) {
4261 const int index = GetElementOr(test_indices_, i, -1);
4262 return index < 0 ? nullptr : test_info_list_[index];
4263 }
4264
4265 // Adds a test to this test suite. Will delete the test upon
4266 // destruction of the TestSuite object.
AddTestInfo(TestInfo * test_info)4267 void TestSuite::AddTestInfo(TestInfo* test_info) {
4268 test_info_list_.push_back(test_info);
4269 test_indices_.push_back(static_cast<int>(test_indices_.size()));
4270 }
4271
4272 // Runs every test in this TestSuite.
Run()4273 void TestSuite::Run() {
4274 if (!should_run_) return;
4275
4276 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4277 impl->set_current_test_suite(this);
4278
4279 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4280
4281 // Call both legacy and the new API
4282 repeater->OnTestSuiteStart(*this);
4283 // Legacy API is deprecated but still available
4284 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4285 repeater->OnTestCaseStart(*this);
4286 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4287
4288 impl->os_stack_trace_getter()->UponLeavingGTest();
4289 internal::HandleExceptionsInMethodIfSupported(
4290 this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
4291
4292 const internal::TimeInMillis start = internal::GetTimeInMillis();
4293 for (int i = 0; i < total_test_count(); i++) {
4294 GetMutableTestInfo(i)->Run();
4295 }
4296 elapsed_time_ = internal::GetTimeInMillis() - start;
4297
4298 impl->os_stack_trace_getter()->UponLeavingGTest();
4299 internal::HandleExceptionsInMethodIfSupported(
4300 this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
4301
4302 // Call both legacy and the new API
4303 repeater->OnTestSuiteEnd(*this);
4304 // Legacy API is deprecated but still available
4305 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4306 repeater->OnTestCaseEnd(*this);
4307 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4308
4309 impl->set_current_test_suite(nullptr);
4310 }
4311
4312 // Clears the results of all tests in this test suite.
ClearResult()4313 void TestSuite::ClearResult() {
4314 ad_hoc_test_result_.Clear();
4315 ForEach(test_info_list_, TestInfo::ClearTestResult);
4316 }
4317
4318 // Shuffles the tests in this test suite.
ShuffleTests(internal::Random * random)4319 void TestSuite::ShuffleTests(internal::Random* random) {
4320 Shuffle(random, &test_indices_);
4321 }
4322
4323 // Restores the test order to before the first shuffle.
UnshuffleTests()4324 void TestSuite::UnshuffleTests() {
4325 for (size_t i = 0; i < test_indices_.size(); i++) {
4326 test_indices_[i] = static_cast<int>(i);
4327 }
4328 }
4329
4330 // Formats a countable noun. Depending on its quantity, either the
4331 // singular form or the plural form is used. e.g.
4332 //
4333 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4334 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)4335 static std::string FormatCountableNoun(int count,
4336 const char * singular_form,
4337 const char * plural_form) {
4338 return internal::StreamableToString(count) + " " +
4339 (count == 1 ? singular_form : plural_form);
4340 }
4341
4342 // Formats the count of tests.
FormatTestCount(int test_count)4343 static std::string FormatTestCount(int test_count) {
4344 return FormatCountableNoun(test_count, "test", "tests");
4345 }
4346
4347 // Formats the count of test suites.
FormatTestSuiteCount(int test_suite_count)4348 static std::string FormatTestSuiteCount(int test_suite_count) {
4349 return FormatCountableNoun(test_suite_count, "test suite", "test suites");
4350 }
4351
4352 // Converts a TestPartResult::Type enum to human-friendly string
4353 // representation. Both kNonFatalFailure and kFatalFailure are translated
4354 // to "Failure", as the user usually doesn't care about the difference
4355 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)4356 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4357 switch (type) {
4358 case TestPartResult::kSkip:
4359 return "Skipped";
4360 case TestPartResult::kSuccess:
4361 return "Success";
4362
4363 case TestPartResult::kNonFatalFailure:
4364 case TestPartResult::kFatalFailure:
4365 #ifdef _MSC_VER
4366 return "error: ";
4367 #else
4368 return "Failure\n";
4369 #endif
4370 default:
4371 return "Unknown result type";
4372 }
4373 }
4374
4375 namespace internal {
4376
4377 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4378 static std::string PrintTestPartResultToString(
4379 const TestPartResult& test_part_result) {
4380 return (Message()
4381 << internal::FormatFileLocation(test_part_result.file_name(),
4382 test_part_result.line_number())
4383 << " " << TestPartResultTypeToString(test_part_result.type())
4384 << test_part_result.message()).GetString();
4385 }
4386
4387 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4388 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4389 const std::string& result =
4390 PrintTestPartResultToString(test_part_result);
4391 printf("%s\n", result.c_str());
4392 fflush(stdout);
4393 // If the test program runs in Visual Studio or a debugger, the
4394 // following statements add the test part result message to the Output
4395 // window such that the user can double-click on it to jump to the
4396 // corresponding source code location; otherwise they do nothing.
4397 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4398 // We don't call OutputDebugString*() on Windows Mobile, as printing
4399 // to stdout is done by OutputDebugString() there already - we don't
4400 // want the same message printed twice.
4401 ::OutputDebugStringA(result.c_str());
4402 ::OutputDebugStringA("\n");
4403 #endif
4404 }
4405
4406 // class PrettyUnitTestResultPrinter
4407 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4408 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4409
4410 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4411 static WORD GetColorAttribute(GTestColor color) {
4412 switch (color) {
4413 case COLOR_RED: return FOREGROUND_RED;
4414 case COLOR_GREEN: return FOREGROUND_GREEN;
4415 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4416 default: return 0;
4417 }
4418 }
4419
GetBitOffset(WORD color_mask)4420 static int GetBitOffset(WORD color_mask) {
4421 if (color_mask == 0) return 0;
4422
4423 int bitOffset = 0;
4424 while ((color_mask & 1) == 0) {
4425 color_mask >>= 1;
4426 ++bitOffset;
4427 }
4428 return bitOffset;
4429 }
4430
GetNewColor(GTestColor color,WORD old_color_attrs)4431 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4432 // Let's reuse the BG
4433 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4434 BACKGROUND_RED | BACKGROUND_INTENSITY;
4435 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4436 FOREGROUND_RED | FOREGROUND_INTENSITY;
4437 const WORD existing_bg = old_color_attrs & background_mask;
4438
4439 WORD new_color =
4440 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4441 static const int bg_bitOffset = GetBitOffset(background_mask);
4442 static const int fg_bitOffset = GetBitOffset(foreground_mask);
4443
4444 if (((new_color & background_mask) >> bg_bitOffset) ==
4445 ((new_color & foreground_mask) >> fg_bitOffset)) {
4446 new_color ^= FOREGROUND_INTENSITY; // invert intensity
4447 }
4448 return new_color;
4449 }
4450
4451 #else
4452
4453 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4454 // an invalid input.
GetAnsiColorCode(GTestColor color)4455 static const char* GetAnsiColorCode(GTestColor color) {
4456 switch (color) {
4457 case COLOR_RED: return "1";
4458 case COLOR_GREEN: return "2";
4459 case COLOR_YELLOW: return "3";
4460 default:
4461 return nullptr;
4462 }
4463 }
4464
4465 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4466
4467 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4468 bool ShouldUseColor(bool stdout_is_tty) {
4469 const char* const gtest_color = GTEST_FLAG(color).c_str();
4470
4471 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4472 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4473 // On Windows the TERM variable is usually not set, but the
4474 // console there does support colors.
4475 return stdout_is_tty;
4476 #else
4477 // On non-Windows platforms, we rely on the TERM variable.
4478 const char* const term = posix::GetEnv("TERM");
4479 const bool term_supports_color =
4480 String::CStringEquals(term, "xterm") ||
4481 String::CStringEquals(term, "xterm-color") ||
4482 String::CStringEquals(term, "xterm-256color") ||
4483 String::CStringEquals(term, "screen") ||
4484 String::CStringEquals(term, "screen-256color") ||
4485 String::CStringEquals(term, "tmux") ||
4486 String::CStringEquals(term, "tmux-256color") ||
4487 String::CStringEquals(term, "rxvt-unicode") ||
4488 String::CStringEquals(term, "rxvt-unicode-256color") ||
4489 String::CStringEquals(term, "linux") ||
4490 String::CStringEquals(term, "cygwin");
4491 return stdout_is_tty && term_supports_color;
4492 #endif // GTEST_OS_WINDOWS
4493 }
4494
4495 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4496 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4497 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4498 String::CStringEquals(gtest_color, "1");
4499 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4500 // value is neither one of these nor "auto", we treat it as "no" to
4501 // be conservative.
4502 }
4503
4504 // Helpers for printing colored strings to stdout. Note that on Windows, we
4505 // cannot simply emit special characters and have the terminal change colors.
4506 // This routine must actually emit the characters rather than return a string
4507 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)4508 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4509 va_list args;
4510 va_start(args, fmt);
4511
4512 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
4513 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4514 const bool use_color = AlwaysFalse();
4515 #else
4516 static const bool in_color_mode =
4517 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4518 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4519 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
4520
4521 if (!use_color) {
4522 vprintf(fmt, args);
4523 va_end(args);
4524 return;
4525 }
4526
4527 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4528 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4529 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4530
4531 // Gets the current text color.
4532 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4533 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4534 const WORD old_color_attrs = buffer_info.wAttributes;
4535 const WORD new_color = GetNewColor(color, old_color_attrs);
4536
4537 // We need to flush the stream buffers into the console before each
4538 // SetConsoleTextAttribute call lest it affect the text that is already
4539 // printed but has not yet reached the console.
4540 fflush(stdout);
4541 SetConsoleTextAttribute(stdout_handle, new_color);
4542
4543 vprintf(fmt, args);
4544
4545 fflush(stdout);
4546 // Restores the text color.
4547 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4548 #else
4549 printf("\033[0;3%sm", GetAnsiColorCode(color));
4550 vprintf(fmt, args);
4551 printf("\033[m"); // Resets the terminal to default.
4552 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4553 va_end(args);
4554 }
4555
4556 // Text printed in Google Test's text output and --gtest_list_tests
4557 // output to label the type parameter and value parameter for a test.
4558 static const char kTypeParamLabel[] = "TypeParam";
4559 static const char kValueParamLabel[] = "GetParam()";
4560
PrintFullTestCommentIfPresent(const TestInfo & test_info)4561 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4562 const char* const type_param = test_info.type_param();
4563 const char* const value_param = test_info.value_param();
4564
4565 if (type_param != nullptr || value_param != nullptr) {
4566 printf(", where ");
4567 if (type_param != nullptr) {
4568 printf("%s = %s", kTypeParamLabel, type_param);
4569 if (value_param != nullptr) printf(" and ");
4570 }
4571 if (value_param != nullptr) {
4572 printf("%s = %s", kValueParamLabel, value_param);
4573 }
4574 }
4575 }
4576
4577 // This class implements the TestEventListener interface.
4578 //
4579 // Class PrettyUnitTestResultPrinter is copyable.
4580 class PrettyUnitTestResultPrinter : public TestEventListener {
4581 public:
PrettyUnitTestResultPrinter()4582 PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_suite,const char * test)4583 static void PrintTestName(const char* test_suite, const char* test) {
4584 printf("%s.%s", test_suite, test);
4585 }
4586
4587 // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4588 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
4589 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4590 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
OnEnvironmentsSetUpEnd(const UnitTest &)4591 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
4592 void OnTestCaseStart(const TestSuite& test_suite) override;
4593 void OnTestStart(const TestInfo& test_info) override;
4594 void OnTestPartResult(const TestPartResult& result) override;
4595 void OnTestEnd(const TestInfo& test_info) override;
4596 void OnTestCaseEnd(const TestSuite& test_suite) override;
4597 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
OnEnvironmentsTearDownEnd(const UnitTest &)4598 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
4599 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
OnTestProgramEnd(const UnitTest &)4600 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
4601
4602 private:
4603 static void PrintFailedTests(const UnitTest& unit_test);
4604 static void PrintSkippedTests(const UnitTest& unit_test);
4605 };
4606
4607 // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4608 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4609 const UnitTest& unit_test, int iteration) {
4610 if (GTEST_FLAG(repeat) != 1)
4611 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4612
4613 const char* const filter = GTEST_FLAG(filter).c_str();
4614
4615 // Prints the filter if it's not *. This reminds the user that some
4616 // tests may be skipped.
4617 if (!String::CStringEquals(filter, kUniversalFilter)) {
4618 ColoredPrintf(COLOR_YELLOW,
4619 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4620 }
4621
4622 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4623 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4624 ColoredPrintf(COLOR_YELLOW,
4625 "Note: This is test shard %d of %s.\n",
4626 static_cast<int>(shard_index) + 1,
4627 internal::posix::GetEnv(kTestTotalShards));
4628 }
4629
4630 if (GTEST_FLAG(shuffle)) {
4631 ColoredPrintf(COLOR_YELLOW,
4632 "Note: Randomizing tests' orders with a seed of %d .\n",
4633 unit_test.random_seed());
4634 }
4635
4636 ColoredPrintf(COLOR_GREEN, "[==========] ");
4637 printf("Running %s from %s.\n",
4638 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4639 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4640 fflush(stdout);
4641 }
4642
OnEnvironmentsSetUpStart(const UnitTest &)4643 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4644 const UnitTest& /*unit_test*/) {
4645 ColoredPrintf(COLOR_GREEN, "[----------] ");
4646 printf("Global test environment set-up.\n");
4647 fflush(stdout);
4648 }
4649
OnTestCaseStart(const TestSuite & test_suite)4650 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) {
4651 const std::string counts =
4652 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4653 ColoredPrintf(COLOR_GREEN, "[----------] ");
4654 printf("%s from %s", counts.c_str(), test_suite.name());
4655 if (test_suite.type_param() == nullptr) {
4656 printf("\n");
4657 } else {
4658 printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
4659 }
4660 fflush(stdout);
4661 }
4662
OnTestStart(const TestInfo & test_info)4663 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4664 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4665 PrintTestName(test_info.test_suite_name(), test_info.name());
4666 printf("\n");
4667 fflush(stdout);
4668 }
4669
4670 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4671 void PrettyUnitTestResultPrinter::OnTestPartResult(
4672 const TestPartResult& result) {
4673 switch (result.type()) {
4674 // If the test part succeeded, or was skipped,
4675 // we don't need to do anything.
4676 case TestPartResult::kSkip:
4677 case TestPartResult::kSuccess:
4678 return;
4679 default:
4680 // Print failure message from the assertion
4681 // (e.g. expected this and got that).
4682 PrintTestPartResult(result);
4683 fflush(stdout);
4684 }
4685 }
4686
OnTestEnd(const TestInfo & test_info)4687 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4688 if (test_info.result()->Passed()) {
4689 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4690 } else if (test_info.result()->Skipped()) {
4691 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4692 } else {
4693 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4694 }
4695 PrintTestName(test_info.test_suite_name(), test_info.name());
4696 if (test_info.result()->Failed())
4697 PrintFullTestCommentIfPresent(test_info);
4698
4699 if (GTEST_FLAG(print_time)) {
4700 printf(" (%s ms)\n", internal::StreamableToString(
4701 test_info.result()->elapsed_time()).c_str());
4702 } else {
4703 printf("\n");
4704 }
4705 fflush(stdout);
4706 }
4707
OnTestCaseEnd(const TestSuite & test_suite)4708 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) {
4709 if (!GTEST_FLAG(print_time)) return;
4710
4711 const std::string counts =
4712 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4713 ColoredPrintf(COLOR_GREEN, "[----------] ");
4714 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
4715 internal::StreamableToString(test_suite.elapsed_time()).c_str());
4716 fflush(stdout);
4717 }
4718
OnEnvironmentsTearDownStart(const UnitTest &)4719 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4720 const UnitTest& /*unit_test*/) {
4721 ColoredPrintf(COLOR_GREEN, "[----------] ");
4722 printf("Global test environment tear-down\n");
4723 fflush(stdout);
4724 }
4725
4726 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4727 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4728 const int failed_test_count = unit_test.failed_test_count();
4729 if (failed_test_count == 0) {
4730 return;
4731 }
4732
4733 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4734 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4735 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
4736 continue;
4737 }
4738 for (int j = 0; j < test_suite.total_test_count(); ++j) {
4739 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4740 if (!test_info.should_run() || !test_info.result()->Failed()) {
4741 continue;
4742 }
4743 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4744 printf("%s.%s", test_suite.name(), test_info.name());
4745 PrintFullTestCommentIfPresent(test_info);
4746 printf("\n");
4747 }
4748 }
4749 }
4750
4751 // Internal helper for printing the list of skipped tests.
PrintSkippedTests(const UnitTest & unit_test)4752 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
4753 const int skipped_test_count = unit_test.skipped_test_count();
4754 if (skipped_test_count == 0) {
4755 return;
4756 }
4757
4758 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4759 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4760 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
4761 continue;
4762 }
4763 for (int j = 0; j < test_suite.total_test_count(); ++j) {
4764 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4765 if (!test_info.should_run() || !test_info.result()->Skipped()) {
4766 continue;
4767 }
4768 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4769 printf("%s.%s", test_suite.name(), test_info.name());
4770 printf("\n");
4771 }
4772 }
4773 }
4774
OnTestIterationEnd(const UnitTest & unit_test,int)4775 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4776 int /*iteration*/) {
4777 ColoredPrintf(COLOR_GREEN, "[==========] ");
4778 printf("%s from %s ran.",
4779 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4780 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4781 if (GTEST_FLAG(print_time)) {
4782 printf(" (%s ms total)",
4783 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4784 }
4785 printf("\n");
4786 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4787 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4788
4789 const int skipped_test_count = unit_test.skipped_test_count();
4790 if (skipped_test_count > 0) {
4791 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4792 printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
4793 PrintSkippedTests(unit_test);
4794 }
4795
4796 int num_failures = unit_test.failed_test_count();
4797 if (!unit_test.Passed()) {
4798 const int failed_test_count = unit_test.failed_test_count();
4799 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4800 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4801 PrintFailedTests(unit_test);
4802 printf("\n%2d FAILED %s\n", num_failures,
4803 num_failures == 1 ? "TEST" : "TESTS");
4804 }
4805
4806 int num_disabled = unit_test.reportable_disabled_test_count();
4807 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4808 if (!num_failures) {
4809 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4810 }
4811 ColoredPrintf(COLOR_YELLOW,
4812 " YOU HAVE %d DISABLED %s\n\n",
4813 num_disabled,
4814 num_disabled == 1 ? "TEST" : "TESTS");
4815 }
4816 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4817 fflush(stdout);
4818 }
4819
4820 // End PrettyUnitTestResultPrinter
4821
4822 // class TestEventRepeater
4823 //
4824 // This class forwards events to other event listeners.
4825 class TestEventRepeater : public TestEventListener {
4826 public:
TestEventRepeater()4827 TestEventRepeater() : forwarding_enabled_(true) {}
4828 ~TestEventRepeater() override;
4829 void Append(TestEventListener *listener);
4830 TestEventListener* Release(TestEventListener* listener);
4831
4832 // Controls whether events will be forwarded to listeners_. Set to false
4833 // in death test child processes.
forwarding_enabled() const4834 bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4835 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4836
4837 void OnTestProgramStart(const UnitTest& unit_test) override;
4838 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4839 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4840 void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
4841 // Legacy API is deprecated but still available
4842 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4843 void OnTestCaseStart(const TestSuite& parameter) override;
4844 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4845 void OnTestSuiteStart(const TestSuite& parameter) override;
4846 void OnTestStart(const TestInfo& test_info) override;
4847 void OnTestPartResult(const TestPartResult& result) override;
4848 void OnTestEnd(const TestInfo& test_info) override;
4849 // Legacy API is deprecated but still available
4850 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4851 void OnTestCaseEnd(const TestSuite& parameter) override;
4852 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4853 void OnTestSuiteEnd(const TestSuite& parameter) override;
4854 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4855 void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
4856 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4857 void OnTestProgramEnd(const UnitTest& unit_test) override;
4858
4859 private:
4860 // Controls whether events will be forwarded to listeners_. Set to false
4861 // in death test child processes.
4862 bool forwarding_enabled_;
4863 // The list of listeners that receive events.
4864 std::vector<TestEventListener*> listeners_;
4865
4866 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4867 };
4868
~TestEventRepeater()4869 TestEventRepeater::~TestEventRepeater() {
4870 ForEach(listeners_, Delete<TestEventListener>);
4871 }
4872
Append(TestEventListener * listener)4873 void TestEventRepeater::Append(TestEventListener *listener) {
4874 listeners_.push_back(listener);
4875 }
4876
Release(TestEventListener * listener)4877 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4878 for (size_t i = 0; i < listeners_.size(); ++i) {
4879 if (listeners_[i] == listener) {
4880 listeners_.erase(listeners_.begin() + i);
4881 return listener;
4882 }
4883 }
4884
4885 return nullptr;
4886 }
4887
4888 // Since most methods are very similar, use macros to reduce boilerplate.
4889 // This defines a member that forwards the call to all listeners.
4890 #define GTEST_REPEATER_METHOD_(Name, Type) \
4891 void TestEventRepeater::Name(const Type& parameter) { \
4892 if (forwarding_enabled_) { \
4893 for (size_t i = 0; i < listeners_.size(); i++) { \
4894 listeners_[i]->Name(parameter); \
4895 } \
4896 } \
4897 }
4898 // This defines a member that forwards the call to all listeners in reverse
4899 // order.
4900 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4901 void TestEventRepeater::Name(const Type& parameter) { \
4902 if (forwarding_enabled_) { \
4903 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4904 listeners_[i]->Name(parameter); \
4905 } \
4906 } \
4907 }
4908
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4909 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4910 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4911 // Legacy API is deprecated but still available
4912 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4913 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
4914 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4915 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
4916 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4917 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4918 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4919 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4920 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4921 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4922 // Legacy API is deprecated but still available
4923 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4924 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
4925 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4926 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
4927 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4928
4929 #undef GTEST_REPEATER_METHOD_
4930 #undef GTEST_REVERSE_REPEATER_METHOD_
4931
4932 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4933 int iteration) {
4934 if (forwarding_enabled_) {
4935 for (size_t i = 0; i < listeners_.size(); i++) {
4936 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4937 }
4938 }
4939 }
4940
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4941 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4942 int iteration) {
4943 if (forwarding_enabled_) {
4944 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4945 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4946 }
4947 }
4948 }
4949
4950 // End TestEventRepeater
4951
4952 // This class generates an XML output file.
4953 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4954 public:
4955 explicit XmlUnitTestResultPrinter(const char* output_file);
4956
4957 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4958 void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
4959
4960 // Prints an XML summary of all unit tests.
4961 static void PrintXmlTestsList(std::ostream* stream,
4962 const std::vector<TestSuite*>& test_suites);
4963
4964 private:
4965 // Is c a whitespace character that is normalized to a space character
4966 // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4967 static bool IsNormalizableWhitespace(char c) {
4968 return c == 0x9 || c == 0xA || c == 0xD;
4969 }
4970
4971 // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4972 static bool IsValidXmlCharacter(char c) {
4973 return IsNormalizableWhitespace(c) || c >= 0x20;
4974 }
4975
4976 // Returns an XML-escaped copy of the input string str. If
4977 // is_attribute is true, the text is meant to appear as an attribute
4978 // value, and normalizable whitespace is preserved by replacing it
4979 // with character references.
4980 static std::string EscapeXml(const std::string& str, bool is_attribute);
4981
4982 // Returns the given string with all characters invalid in XML removed.
4983 static std::string RemoveInvalidXmlCharacters(const std::string& str);
4984
4985 // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4986 static std::string EscapeXmlAttribute(const std::string& str) {
4987 return EscapeXml(str, true);
4988 }
4989
4990 // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4991 static std::string EscapeXmlText(const char* str) {
4992 return EscapeXml(str, false);
4993 }
4994
4995 // Verifies that the given attribute belongs to the given element and
4996 // streams the attribute as XML.
4997 static void OutputXmlAttribute(std::ostream* stream,
4998 const std::string& element_name,
4999 const std::string& name,
5000 const std::string& value);
5001
5002 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5003 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
5004
5005 // Streams an XML representation of a TestInfo object.
5006 static void OutputXmlTestInfo(::std::ostream* stream,
5007 const char* test_suite_name,
5008 const TestInfo& test_info);
5009
5010 // Prints an XML representation of a TestSuite object
5011 static void PrintXmlTestSuite(::std::ostream* stream,
5012 const TestSuite& test_suite);
5013
5014 // Prints an XML summary of unit_test to output stream out.
5015 static void PrintXmlUnitTest(::std::ostream* stream,
5016 const UnitTest& unit_test);
5017
5018 // Produces a string representing the test properties in a result as space
5019 // delimited XML attributes based on the property key="value" pairs.
5020 // When the std::string is not empty, it includes a space at the beginning,
5021 // to delimit this attribute from prior attributes.
5022 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
5023
5024 // Streams an XML representation of the test properties of a TestResult
5025 // object.
5026 static void OutputXmlTestProperties(std::ostream* stream,
5027 const TestResult& result);
5028
5029 // The output file.
5030 const std::string output_file_;
5031
5032 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
5033 };
5034
5035 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)5036 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
5037 : output_file_(output_file) {
5038 if (output_file_.empty()) {
5039 GTEST_LOG_(FATAL) << "XML output file may not be null";
5040 }
5041 }
5042
5043 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)5044 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5045 int /*iteration*/) {
5046 FILE* xmlout = OpenFileForWriting(output_file_);
5047 std::stringstream stream;
5048 PrintXmlUnitTest(&stream, unit_test);
5049 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5050 fclose(xmlout);
5051 }
5052
ListTestsMatchingFilter(const std::vector<TestSuite * > & test_suites)5053 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5054 const std::vector<TestSuite*>& test_suites) {
5055 FILE* xmlout = OpenFileForWriting(output_file_);
5056 std::stringstream stream;
5057 PrintXmlTestsList(&stream, test_suites);
5058 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5059 fclose(xmlout);
5060 }
5061
5062 // Returns an XML-escaped copy of the input string str. If is_attribute
5063 // is true, the text is meant to appear as an attribute value, and
5064 // normalizable whitespace is preserved by replacing it with character
5065 // references.
5066 //
5067 // Invalid XML characters in str, if any, are stripped from the output.
5068 // It is expected that most, if not all, of the text processed by this
5069 // module will consist of ordinary English text.
5070 // If this module is ever modified to produce version 1.1 XML output,
5071 // most invalid characters can be retained using character references.
EscapeXml(const std::string & str,bool is_attribute)5072 std::string XmlUnitTestResultPrinter::EscapeXml(
5073 const std::string& str, bool is_attribute) {
5074 Message m;
5075
5076 for (size_t i = 0; i < str.size(); ++i) {
5077 const char ch = str[i];
5078 switch (ch) {
5079 case '<':
5080 m << "<";
5081 break;
5082 case '>':
5083 m << ">";
5084 break;
5085 case '&':
5086 m << "&";
5087 break;
5088 case '\'':
5089 if (is_attribute)
5090 m << "'";
5091 else
5092 m << '\'';
5093 break;
5094 case '"':
5095 if (is_attribute)
5096 m << """;
5097 else
5098 m << '"';
5099 break;
5100 default:
5101 if (IsValidXmlCharacter(ch)) {
5102 if (is_attribute && IsNormalizableWhitespace(ch))
5103 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5104 << ";";
5105 else
5106 m << ch;
5107 }
5108 break;
5109 }
5110 }
5111
5112 return m.GetString();
5113 }
5114
5115 // Returns the given string with all characters invalid in XML removed.
5116 // Currently invalid characters are dropped from the string. An
5117 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)5118 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5119 const std::string& str) {
5120 std::string output;
5121 output.reserve(str.size());
5122 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5123 if (IsValidXmlCharacter(*it))
5124 output.push_back(*it);
5125
5126 return output;
5127 }
5128
5129 // The following routines generate an XML representation of a UnitTest
5130 // object.
5131 // GOOGLETEST_CM0009 DO NOT DELETE
5132 //
5133 // This is how Google Test concepts map to the DTD:
5134 //
5135 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
5136 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
5137 // <testcase name="test-name"> <-- corresponds to a TestInfo object
5138 // <failure message="...">...</failure>
5139 // <failure message="...">...</failure>
5140 // <failure message="...">...</failure>
5141 // <-- individual assertion failures
5142 // </testcase>
5143 // </testsuite>
5144 // </testsuites>
5145
5146 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)5147 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5148 ::std::stringstream ss;
5149 ss << (static_cast<double>(ms) * 1e-3);
5150 return ss.str();
5151 }
5152
PortableLocaltime(time_t seconds,struct tm * out)5153 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5154 #if defined(_MSC_VER)
5155 return localtime_s(out, &seconds) == 0;
5156 #elif defined(__MINGW32__) || defined(__MINGW64__)
5157 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5158 // Windows' localtime(), which has a thread-local tm buffer.
5159 struct tm* tm_ptr = localtime(&seconds); // NOLINT
5160 if (tm_ptr == nullptr) return false;
5161 *out = *tm_ptr;
5162 return true;
5163 #else
5164 return localtime_r(&seconds, out) != nullptr;
5165 #endif
5166 }
5167
5168 // Converts the given epoch time in milliseconds to a date string in the ISO
5169 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)5170 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5171 struct tm time_struct;
5172 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5173 return "";
5174 // YYYY-MM-DDThh:mm:ss
5175 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5176 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5177 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5178 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5179 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5180 String::FormatIntWidth2(time_struct.tm_sec);
5181 }
5182
5183 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)5184 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5185 const char* data) {
5186 const char* segment = data;
5187 *stream << "<![CDATA[";
5188 for (;;) {
5189 const char* const next_segment = strstr(segment, "]]>");
5190 if (next_segment != nullptr) {
5191 stream->write(
5192 segment, static_cast<std::streamsize>(next_segment - segment));
5193 *stream << "]]>]]><![CDATA[";
5194 segment = next_segment + strlen("]]>");
5195 } else {
5196 *stream << segment;
5197 break;
5198 }
5199 }
5200 *stream << "]]>";
5201 }
5202
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)5203 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5204 std::ostream* stream,
5205 const std::string& element_name,
5206 const std::string& name,
5207 const std::string& value) {
5208 const std::vector<std::string>& allowed_names =
5209 GetReservedOutputAttributesForElement(element_name);
5210
5211 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5212 allowed_names.end())
5213 << "Attribute " << name << " is not allowed for element <" << element_name
5214 << ">.";
5215
5216 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5217 }
5218
5219 // Prints an XML representation of a TestInfo object.
OutputXmlTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)5220 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5221 const char* test_suite_name,
5222 const TestInfo& test_info) {
5223 const TestResult& result = *test_info.result();
5224 const std::string kTestsuite = "testcase";
5225
5226 if (test_info.is_in_another_shard()) {
5227 return;
5228 }
5229
5230 *stream << " <testcase";
5231 OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
5232
5233 if (test_info.value_param() != nullptr) {
5234 OutputXmlAttribute(stream, kTestsuite, "value_param",
5235 test_info.value_param());
5236 }
5237 if (test_info.type_param() != nullptr) {
5238 OutputXmlAttribute(stream, kTestsuite, "type_param",
5239 test_info.type_param());
5240 }
5241 if (GTEST_FLAG(list_tests)) {
5242 OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
5243 OutputXmlAttribute(stream, kTestsuite, "line",
5244 StreamableToString(test_info.line()));
5245 *stream << " />\n";
5246 return;
5247 }
5248
5249 OutputXmlAttribute(stream, kTestsuite, "status",
5250 test_info.should_run() ? "run" : "notrun");
5251 OutputXmlAttribute(stream, kTestsuite, "result",
5252 test_info.should_run()
5253 ? (result.Skipped() ? "skipped" : "completed")
5254 : "suppressed");
5255 OutputXmlAttribute(stream, kTestsuite, "time",
5256 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5257 OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
5258
5259 int failures = 0;
5260 for (int i = 0; i < result.total_part_count(); ++i) {
5261 const TestPartResult& part = result.GetTestPartResult(i);
5262 if (part.failed()) {
5263 if (++failures == 1) {
5264 *stream << ">\n";
5265 }
5266 const std::string location =
5267 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5268 part.line_number());
5269 const std::string summary = location + "\n" + part.summary();
5270 *stream << " <failure message=\""
5271 << EscapeXmlAttribute(summary.c_str())
5272 << "\" type=\"\">";
5273 const std::string detail = location + "\n" + part.message();
5274 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5275 *stream << "</failure>\n";
5276 }
5277 }
5278
5279 if (failures == 0 && result.test_property_count() == 0) {
5280 *stream << " />\n";
5281 } else {
5282 if (failures == 0) {
5283 *stream << ">\n";
5284 }
5285 OutputXmlTestProperties(stream, result);
5286 *stream << " </testcase>\n";
5287 }
5288 }
5289
5290 // Prints an XML representation of a TestSuite object
PrintXmlTestSuite(std::ostream * stream,const TestSuite & test_suite)5291 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5292 const TestSuite& test_suite) {
5293 const std::string kTestsuite = "testsuite";
5294 *stream << " <" << kTestsuite;
5295 OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
5296 OutputXmlAttribute(stream, kTestsuite, "tests",
5297 StreamableToString(test_suite.reportable_test_count()));
5298 if (!GTEST_FLAG(list_tests)) {
5299 OutputXmlAttribute(stream, kTestsuite, "failures",
5300 StreamableToString(test_suite.failed_test_count()));
5301 OutputXmlAttribute(
5302 stream, kTestsuite, "disabled",
5303 StreamableToString(test_suite.reportable_disabled_test_count()));
5304 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5305 OutputXmlAttribute(stream, kTestsuite, "time",
5306 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5307 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5308 }
5309 *stream << ">\n";
5310 for (int i = 0; i < test_suite.total_test_count(); ++i) {
5311 if (test_suite.GetTestInfo(i)->is_reportable())
5312 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5313 }
5314 *stream << " </" << kTestsuite << ">\n";
5315 }
5316
5317 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)5318 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5319 const UnitTest& unit_test) {
5320 const std::string kTestsuites = "testsuites";
5321
5322 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5323 *stream << "<" << kTestsuites;
5324
5325 OutputXmlAttribute(stream, kTestsuites, "tests",
5326 StreamableToString(unit_test.reportable_test_count()));
5327 OutputXmlAttribute(stream, kTestsuites, "failures",
5328 StreamableToString(unit_test.failed_test_count()));
5329 OutputXmlAttribute(
5330 stream, kTestsuites, "disabled",
5331 StreamableToString(unit_test.reportable_disabled_test_count()));
5332 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5333 OutputXmlAttribute(
5334 stream, kTestsuites, "timestamp",
5335 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5336 OutputXmlAttribute(stream, kTestsuites, "time",
5337 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5338
5339 if (GTEST_FLAG(shuffle)) {
5340 OutputXmlAttribute(stream, kTestsuites, "random_seed",
5341 StreamableToString(unit_test.random_seed()));
5342 }
5343 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5344
5345 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5346 *stream << ">\n";
5347
5348 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5349 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5350 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5351 }
5352 *stream << "</" << kTestsuites << ">\n";
5353 }
5354
PrintXmlTestsList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)5355 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5356 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5357 const std::string kTestsuites = "testsuites";
5358
5359 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5360 *stream << "<" << kTestsuites;
5361
5362 int total_tests = 0;
5363 for (auto test_suite : test_suites) {
5364 total_tests += test_suite->total_test_count();
5365 }
5366 OutputXmlAttribute(stream, kTestsuites, "tests",
5367 StreamableToString(total_tests));
5368 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5369 *stream << ">\n";
5370
5371 for (auto test_suite : test_suites) {
5372 PrintXmlTestSuite(stream, *test_suite);
5373 }
5374 *stream << "</" << kTestsuites << ">\n";
5375 }
5376
5377 // Produces a string representing the test properties in a result as space
5378 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)5379 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5380 const TestResult& result) {
5381 Message attributes;
5382 for (int i = 0; i < result.test_property_count(); ++i) {
5383 const TestProperty& property = result.GetTestProperty(i);
5384 attributes << " " << property.key() << "="
5385 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5386 }
5387 return attributes.GetString();
5388 }
5389
OutputXmlTestProperties(std::ostream * stream,const TestResult & result)5390 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5391 std::ostream* stream, const TestResult& result) {
5392 const std::string kProperties = "properties";
5393 const std::string kProperty = "property";
5394
5395 if (result.test_property_count() <= 0) {
5396 return;
5397 }
5398
5399 *stream << "<" << kProperties << ">\n";
5400 for (int i = 0; i < result.test_property_count(); ++i) {
5401 const TestProperty& property = result.GetTestProperty(i);
5402 *stream << "<" << kProperty;
5403 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5404 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5405 *stream << "/>\n";
5406 }
5407 *stream << "</" << kProperties << ">\n";
5408 }
5409
5410 // End XmlUnitTestResultPrinter
5411
5412 // This class generates an JSON output file.
5413 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5414 public:
5415 explicit JsonUnitTestResultPrinter(const char* output_file);
5416
5417 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5418
5419 // Prints an JSON summary of all unit tests.
5420 static void PrintJsonTestList(::std::ostream* stream,
5421 const std::vector<TestSuite*>& test_suites);
5422
5423 private:
5424 // Returns an JSON-escaped copy of the input string str.
5425 static std::string EscapeJson(const std::string& str);
5426
5427 //// Verifies that the given attribute belongs to the given element and
5428 //// streams the attribute as JSON.
5429 static void OutputJsonKey(std::ostream* stream,
5430 const std::string& element_name,
5431 const std::string& name,
5432 const std::string& value,
5433 const std::string& indent,
5434 bool comma = true);
5435 static void OutputJsonKey(std::ostream* stream,
5436 const std::string& element_name,
5437 const std::string& name,
5438 int value,
5439 const std::string& indent,
5440 bool comma = true);
5441
5442 // Streams a JSON representation of a TestInfo object.
5443 static void OutputJsonTestInfo(::std::ostream* stream,
5444 const char* test_suite_name,
5445 const TestInfo& test_info);
5446
5447 // Prints a JSON representation of a TestSuite object
5448 static void PrintJsonTestSuite(::std::ostream* stream,
5449 const TestSuite& test_suite);
5450
5451 // Prints a JSON summary of unit_test to output stream out.
5452 static void PrintJsonUnitTest(::std::ostream* stream,
5453 const UnitTest& unit_test);
5454
5455 // Produces a string representing the test properties in a result as
5456 // a JSON dictionary.
5457 static std::string TestPropertiesAsJson(const TestResult& result,
5458 const std::string& indent);
5459
5460 // The output file.
5461 const std::string output_file_;
5462
5463 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5464 };
5465
5466 // Creates a new JsonUnitTestResultPrinter.
JsonUnitTestResultPrinter(const char * output_file)5467 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5468 : output_file_(output_file) {
5469 if (output_file_.empty()) {
5470 GTEST_LOG_(FATAL) << "JSON output file may not be null";
5471 }
5472 }
5473
OnTestIterationEnd(const UnitTest & unit_test,int)5474 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5475 int /*iteration*/) {
5476 FILE* jsonout = OpenFileForWriting(output_file_);
5477 std::stringstream stream;
5478 PrintJsonUnitTest(&stream, unit_test);
5479 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5480 fclose(jsonout);
5481 }
5482
5483 // Returns an JSON-escaped copy of the input string str.
EscapeJson(const std::string & str)5484 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5485 Message m;
5486
5487 for (size_t i = 0; i < str.size(); ++i) {
5488 const char ch = str[i];
5489 switch (ch) {
5490 case '\\':
5491 case '"':
5492 case '/':
5493 m << '\\' << ch;
5494 break;
5495 case '\b':
5496 m << "\\b";
5497 break;
5498 case '\t':
5499 m << "\\t";
5500 break;
5501 case '\n':
5502 m << "\\n";
5503 break;
5504 case '\f':
5505 m << "\\f";
5506 break;
5507 case '\r':
5508 m << "\\r";
5509 break;
5510 default:
5511 if (ch < ' ') {
5512 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5513 } else {
5514 m << ch;
5515 }
5516 break;
5517 }
5518 }
5519
5520 return m.GetString();
5521 }
5522
5523 // The following routines generate an JSON representation of a UnitTest
5524 // object.
5525
5526 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsDuration(TimeInMillis ms)5527 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
5528 ::std::stringstream ss;
5529 ss << (static_cast<double>(ms) * 1e-3) << "s";
5530 return ss.str();
5531 }
5532
5533 // Converts the given epoch time in milliseconds to a date string in the
5534 // RFC3339 format, without the timezone information.
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)5535 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
5536 struct tm time_struct;
5537 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5538 return "";
5539 // YYYY-MM-DDThh:mm:ss
5540 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5541 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5542 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5543 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5544 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5545 String::FormatIntWidth2(time_struct.tm_sec) + "Z";
5546 }
5547
Indent(int width)5548 static inline std::string Indent(int width) {
5549 return std::string(width, ' ');
5550 }
5551
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value,const std::string & indent,bool comma)5552 void JsonUnitTestResultPrinter::OutputJsonKey(
5553 std::ostream* stream,
5554 const std::string& element_name,
5555 const std::string& name,
5556 const std::string& value,
5557 const std::string& indent,
5558 bool comma) {
5559 const std::vector<std::string>& allowed_names =
5560 GetReservedOutputAttributesForElement(element_name);
5561
5562 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5563 allowed_names.end())
5564 << "Key \"" << name << "\" is not allowed for value \"" << element_name
5565 << "\".";
5566
5567 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
5568 if (comma)
5569 *stream << ",\n";
5570 }
5571
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,int value,const std::string & indent,bool comma)5572 void JsonUnitTestResultPrinter::OutputJsonKey(
5573 std::ostream* stream,
5574 const std::string& element_name,
5575 const std::string& name,
5576 int value,
5577 const std::string& indent,
5578 bool comma) {
5579 const std::vector<std::string>& allowed_names =
5580 GetReservedOutputAttributesForElement(element_name);
5581
5582 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5583 allowed_names.end())
5584 << "Key \"" << name << "\" is not allowed for value \"" << element_name
5585 << "\".";
5586
5587 *stream << indent << "\"" << name << "\": " << StreamableToString(value);
5588 if (comma)
5589 *stream << ",\n";
5590 }
5591
5592 // Prints a JSON representation of a TestInfo object.
OutputJsonTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)5593 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5594 const char* test_suite_name,
5595 const TestInfo& test_info) {
5596 const TestResult& result = *test_info.result();
5597 const std::string kTestsuite = "testcase";
5598 const std::string kIndent = Indent(10);
5599
5600 *stream << Indent(8) << "{\n";
5601 OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
5602
5603 if (test_info.value_param() != nullptr) {
5604 OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
5605 kIndent);
5606 }
5607 if (test_info.type_param() != nullptr) {
5608 OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
5609 kIndent);
5610 }
5611 if (GTEST_FLAG(list_tests)) {
5612 OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
5613 OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
5614 *stream << "\n" << Indent(8) << "}";
5615 return;
5616 }
5617
5618 OutputJsonKey(stream, kTestsuite, "status",
5619 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
5620 OutputJsonKey(stream, kTestsuite, "result",
5621 test_info.should_run()
5622 ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
5623 : "SUPPRESSED",
5624 kIndent);
5625 OutputJsonKey(stream, kTestsuite, "time",
5626 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5627 OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
5628 false);
5629 *stream << TestPropertiesAsJson(result, kIndent);
5630
5631 int failures = 0;
5632 for (int i = 0; i < result.total_part_count(); ++i) {
5633 const TestPartResult& part = result.GetTestPartResult(i);
5634 if (part.failed()) {
5635 *stream << ",\n";
5636 if (++failures == 1) {
5637 *stream << kIndent << "\"" << "failures" << "\": [\n";
5638 }
5639 const std::string location =
5640 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5641 part.line_number());
5642 const std::string message = EscapeJson(location + "\n" + part.message());
5643 *stream << kIndent << " {\n"
5644 << kIndent << " \"failure\": \"" << message << "\",\n"
5645 << kIndent << " \"type\": \"\"\n"
5646 << kIndent << " }";
5647 }
5648 }
5649
5650 if (failures > 0)
5651 *stream << "\n" << kIndent << "]";
5652 *stream << "\n" << Indent(8) << "}";
5653 }
5654
5655 // Prints an JSON representation of a TestSuite object
PrintJsonTestSuite(std::ostream * stream,const TestSuite & test_suite)5656 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
5657 std::ostream* stream, const TestSuite& test_suite) {
5658 const std::string kTestsuite = "testsuite";
5659 const std::string kIndent = Indent(6);
5660
5661 *stream << Indent(4) << "{\n";
5662 OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
5663 OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
5664 kIndent);
5665 if (!GTEST_FLAG(list_tests)) {
5666 OutputJsonKey(stream, kTestsuite, "failures",
5667 test_suite.failed_test_count(), kIndent);
5668 OutputJsonKey(stream, kTestsuite, "disabled",
5669 test_suite.reportable_disabled_test_count(), kIndent);
5670 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
5671 OutputJsonKey(stream, kTestsuite, "time",
5672 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
5673 kIndent, false);
5674 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
5675 << ",\n";
5676 }
5677
5678 *stream << kIndent << "\"" << kTestsuite << "\": [\n";
5679
5680 bool comma = false;
5681 for (int i = 0; i < test_suite.total_test_count(); ++i) {
5682 if (test_suite.GetTestInfo(i)->is_reportable()) {
5683 if (comma) {
5684 *stream << ",\n";
5685 } else {
5686 comma = true;
5687 }
5688 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5689 }
5690 }
5691 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
5692 }
5693
5694 // Prints a JSON summary of unit_test to output stream out.
PrintJsonUnitTest(std::ostream * stream,const UnitTest & unit_test)5695 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5696 const UnitTest& unit_test) {
5697 const std::string kTestsuites = "testsuites";
5698 const std::string kIndent = Indent(2);
5699 *stream << "{\n";
5700
5701 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
5702 kIndent);
5703 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
5704 kIndent);
5705 OutputJsonKey(stream, kTestsuites, "disabled",
5706 unit_test.reportable_disabled_test_count(), kIndent);
5707 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
5708 if (GTEST_FLAG(shuffle)) {
5709 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
5710 kIndent);
5711 }
5712 OutputJsonKey(stream, kTestsuites, "timestamp",
5713 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5714 kIndent);
5715 OutputJsonKey(stream, kTestsuites, "time",
5716 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5717 false);
5718
5719 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5720 << ",\n";
5721
5722 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5723 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5724
5725 bool comma = false;
5726 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5727 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
5728 if (comma) {
5729 *stream << ",\n";
5730 } else {
5731 comma = true;
5732 }
5733 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
5734 }
5735 }
5736
5737 *stream << "\n" << kIndent << "]\n" << "}\n";
5738 }
5739
PrintJsonTestList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)5740 void JsonUnitTestResultPrinter::PrintJsonTestList(
5741 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5742 const std::string kTestsuites = "testsuites";
5743 const std::string kIndent = Indent(2);
5744 *stream << "{\n";
5745 int total_tests = 0;
5746 for (auto test_suite : test_suites) {
5747 total_tests += test_suite->total_test_count();
5748 }
5749 OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
5750
5751 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5752 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5753
5754 for (size_t i = 0; i < test_suites.size(); ++i) {
5755 if (i != 0) {
5756 *stream << ",\n";
5757 }
5758 PrintJsonTestSuite(stream, *test_suites[i]);
5759 }
5760
5761 *stream << "\n"
5762 << kIndent << "]\n"
5763 << "}\n";
5764 }
5765 // Produces a string representing the test properties in a result as
5766 // a JSON dictionary.
TestPropertiesAsJson(const TestResult & result,const std::string & indent)5767 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5768 const TestResult& result, const std::string& indent) {
5769 Message attributes;
5770 for (int i = 0; i < result.test_property_count(); ++i) {
5771 const TestProperty& property = result.GetTestProperty(i);
5772 attributes << ",\n" << indent << "\"" << property.key() << "\": "
5773 << "\"" << EscapeJson(property.value()) << "\"";
5774 }
5775 return attributes.GetString();
5776 }
5777
5778 // End JsonUnitTestResultPrinter
5779
5780 #if GTEST_CAN_STREAM_RESULTS_
5781
5782 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5783 // replaces them by "%xx" where xx is their hexadecimal value. For
5784 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
5785 // in both time and space -- important as the input str may contain an
5786 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)5787 std::string StreamingListener::UrlEncode(const char* str) {
5788 std::string result;
5789 result.reserve(strlen(str) + 1);
5790 for (char ch = *str; ch != '\0'; ch = *++str) {
5791 switch (ch) {
5792 case '%':
5793 case '=':
5794 case '&':
5795 case '\n':
5796 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5797 break;
5798 default:
5799 result.push_back(ch);
5800 break;
5801 }
5802 }
5803 return result;
5804 }
5805
MakeConnection()5806 void StreamingListener::SocketWriter::MakeConnection() {
5807 GTEST_CHECK_(sockfd_ == -1)
5808 << "MakeConnection() can't be called when there is already a connection.";
5809
5810 addrinfo hints;
5811 memset(&hints, 0, sizeof(hints));
5812 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5813 hints.ai_socktype = SOCK_STREAM;
5814 addrinfo* servinfo = nullptr;
5815
5816 // Use the getaddrinfo() to get a linked list of IP addresses for
5817 // the given host name.
5818 const int error_num = getaddrinfo(
5819 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5820 if (error_num != 0) {
5821 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5822 << gai_strerror(error_num);
5823 }
5824
5825 // Loop through all the results and connect to the first we can.
5826 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
5827 cur_addr = cur_addr->ai_next) {
5828 sockfd_ = socket(
5829 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5830 if (sockfd_ != -1) {
5831 // Connect the client socket to the server socket.
5832 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5833 close(sockfd_);
5834 sockfd_ = -1;
5835 }
5836 }
5837 }
5838
5839 freeaddrinfo(servinfo); // all done with this structure
5840
5841 if (sockfd_ == -1) {
5842 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5843 << host_name_ << ":" << port_num_;
5844 }
5845 }
5846
5847 // End of class Streaming Listener
5848 #endif // GTEST_CAN_STREAM_RESULTS__
5849
5850 // class OsStackTraceGetter
5851
5852 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5853 "... " GTEST_NAME_ " internal frames ...";
5854
CurrentStackTrace(int max_depth,int skip_count)5855 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5856 GTEST_LOCK_EXCLUDED_(mutex_) {
5857 #if GTEST_HAS_ABSL
5858 std::string result;
5859
5860 if (max_depth <= 0) {
5861 return result;
5862 }
5863
5864 max_depth = std::min(max_depth, kMaxStackTraceDepth);
5865
5866 std::vector<void*> raw_stack(max_depth);
5867 // Skips the frames requested by the caller, plus this function.
5868 const int raw_stack_size =
5869 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5870
5871 void* caller_frame = nullptr;
5872 {
5873 MutexLock lock(&mutex_);
5874 caller_frame = caller_frame_;
5875 }
5876
5877 for (int i = 0; i < raw_stack_size; ++i) {
5878 if (raw_stack[i] == caller_frame &&
5879 !GTEST_FLAG(show_internal_stack_frames)) {
5880 // Add a marker to the trace and stop adding frames.
5881 absl::StrAppend(&result, kElidedFramesMarker, "\n");
5882 break;
5883 }
5884
5885 char tmp[1024];
5886 const char* symbol = "(unknown)";
5887 if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5888 symbol = tmp;
5889 }
5890
5891 char line[1024];
5892 snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
5893 result += line;
5894 }
5895
5896 return result;
5897
5898 #else // !GTEST_HAS_ABSL
5899 static_cast<void>(max_depth);
5900 static_cast<void>(skip_count);
5901 return "";
5902 #endif // GTEST_HAS_ABSL
5903 }
5904
UponLeavingGTest()5905 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5906 #if GTEST_HAS_ABSL
5907 void* caller_frame = nullptr;
5908 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5909 caller_frame = nullptr;
5910 }
5911
5912 MutexLock lock(&mutex_);
5913 caller_frame_ = caller_frame;
5914 #endif // GTEST_HAS_ABSL
5915 }
5916
5917 // A helper class that creates the premature-exit file in its
5918 // constructor and deletes the file in its destructor.
5919 class ScopedPrematureExitFile {
5920 public:
ScopedPrematureExitFile(const char * premature_exit_filepath)5921 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5922 : premature_exit_filepath_(premature_exit_filepath ?
5923 premature_exit_filepath : "") {
5924 // If a path to the premature-exit file is specified...
5925 if (!premature_exit_filepath_.empty()) {
5926 // create the file with a single "0" character in it. I/O
5927 // errors are ignored as there's nothing better we can do and we
5928 // don't want to fail the test because of this.
5929 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5930 fwrite("0", 1, 1, pfile);
5931 fclose(pfile);
5932 }
5933 }
5934
~ScopedPrematureExitFile()5935 ~ScopedPrematureExitFile() {
5936 if (!premature_exit_filepath_.empty()) {
5937 int retval = remove(premature_exit_filepath_.c_str());
5938 if (retval) {
5939 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5940 << premature_exit_filepath_ << "\" with error "
5941 << retval;
5942 }
5943 }
5944 }
5945
5946 private:
5947 const std::string premature_exit_filepath_;
5948
5949 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5950 };
5951
5952 } // namespace internal
5953
5954 // class TestEventListeners
5955
TestEventListeners()5956 TestEventListeners::TestEventListeners()
5957 : repeater_(new internal::TestEventRepeater()),
5958 default_result_printer_(nullptr),
5959 default_xml_generator_(nullptr) {}
5960
~TestEventListeners()5961 TestEventListeners::~TestEventListeners() { delete repeater_; }
5962
5963 // Returns the standard listener responsible for the default console
5964 // output. Can be removed from the listeners list to shut down default
5965 // console output. Note that removing this object from the listener list
5966 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)5967 void TestEventListeners::Append(TestEventListener* listener) {
5968 repeater_->Append(listener);
5969 }
5970
5971 // Removes the given event listener from the list and returns it. It then
5972 // becomes the caller's responsibility to delete the listener. Returns
5973 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)5974 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5975 if (listener == default_result_printer_)
5976 default_result_printer_ = nullptr;
5977 else if (listener == default_xml_generator_)
5978 default_xml_generator_ = nullptr;
5979 return repeater_->Release(listener);
5980 }
5981
5982 // Returns repeater that broadcasts the TestEventListener events to all
5983 // subscribers.
repeater()5984 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5985
5986 // Sets the default_result_printer attribute to the provided listener.
5987 // The listener is also added to the listener list and previous
5988 // default_result_printer is removed from it and deleted. The listener can
5989 // also be NULL in which case it will not be added to the list. Does
5990 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)5991 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5992 if (default_result_printer_ != listener) {
5993 // It is an error to pass this method a listener that is already in the
5994 // list.
5995 delete Release(default_result_printer_);
5996 default_result_printer_ = listener;
5997 if (listener != nullptr) Append(listener);
5998 }
5999 }
6000
6001 // Sets the default_xml_generator attribute to the provided listener. The
6002 // listener is also added to the listener list and previous
6003 // default_xml_generator is removed from it and deleted. The listener can
6004 // also be NULL in which case it will not be added to the list. Does
6005 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)6006 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
6007 if (default_xml_generator_ != listener) {
6008 // It is an error to pass this method a listener that is already in the
6009 // list.
6010 delete Release(default_xml_generator_);
6011 default_xml_generator_ = listener;
6012 if (listener != nullptr) Append(listener);
6013 }
6014 }
6015
6016 // Controls whether events will be forwarded by the repeater to the
6017 // listeners in the list.
EventForwardingEnabled() const6018 bool TestEventListeners::EventForwardingEnabled() const {
6019 return repeater_->forwarding_enabled();
6020 }
6021
SuppressEventForwarding()6022 void TestEventListeners::SuppressEventForwarding() {
6023 repeater_->set_forwarding_enabled(false);
6024 }
6025
6026 // class UnitTest
6027
6028 // Gets the singleton UnitTest object. The first time this method is
6029 // called, a UnitTest object is constructed and returned. Consecutive
6030 // calls will return the same object.
6031 //
6032 // We don't protect this under mutex_ as a user is not supposed to
6033 // call this before main() starts, from which point on the return
6034 // value will never change.
GetInstance()6035 UnitTest* UnitTest::GetInstance() {
6036 // CodeGear C++Builder insists on a public destructor for the
6037 // default implementation. Use this implementation to keep good OO
6038 // design with private destructor.
6039
6040 #if defined(__BORLANDC__)
6041 static UnitTest* const instance = new UnitTest;
6042 return instance;
6043 #else
6044 static UnitTest instance;
6045 return &instance;
6046 #endif // defined(__BORLANDC__)
6047 }
6048
6049 // Gets the number of successful test suites.
successful_test_suite_count() const6050 int UnitTest::successful_test_suite_count() const {
6051 return impl()->successful_test_suite_count();
6052 }
6053
6054 // Gets the number of failed test suites.
failed_test_suite_count() const6055 int UnitTest::failed_test_suite_count() const {
6056 return impl()->failed_test_suite_count();
6057 }
6058
6059 // Gets the number of all test suites.
total_test_suite_count() const6060 int UnitTest::total_test_suite_count() const {
6061 return impl()->total_test_suite_count();
6062 }
6063
6064 // Gets the number of all test suites that contain at least one test
6065 // that should run.
test_suite_to_run_count() const6066 int UnitTest::test_suite_to_run_count() const {
6067 return impl()->test_suite_to_run_count();
6068 }
6069
6070 // Legacy API is deprecated but still available
6071 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
successful_test_case_count() const6072 int UnitTest::successful_test_case_count() const {
6073 return impl()->successful_test_suite_count();
6074 }
failed_test_case_count() const6075 int UnitTest::failed_test_case_count() const {
6076 return impl()->failed_test_suite_count();
6077 }
total_test_case_count() const6078 int UnitTest::total_test_case_count() const {
6079 return impl()->total_test_suite_count();
6080 }
test_case_to_run_count() const6081 int UnitTest::test_case_to_run_count() const {
6082 return impl()->test_suite_to_run_count();
6083 }
6084 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6085
6086 // Gets the number of successful tests.
successful_test_count() const6087 int UnitTest::successful_test_count() const {
6088 return impl()->successful_test_count();
6089 }
6090
6091 // Gets the number of skipped tests.
skipped_test_count() const6092 int UnitTest::skipped_test_count() const {
6093 return impl()->skipped_test_count();
6094 }
6095
6096 // Gets the number of failed tests.
failed_test_count() const6097 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6098
6099 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const6100 int UnitTest::reportable_disabled_test_count() const {
6101 return impl()->reportable_disabled_test_count();
6102 }
6103
6104 // Gets the number of disabled tests.
disabled_test_count() const6105 int UnitTest::disabled_test_count() const {
6106 return impl()->disabled_test_count();
6107 }
6108
6109 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const6110 int UnitTest::reportable_test_count() const {
6111 return impl()->reportable_test_count();
6112 }
6113
6114 // Gets the number of all tests.
total_test_count() const6115 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6116
6117 // Gets the number of tests that should run.
test_to_run_count() const6118 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6119
6120 // Gets the time of the test program start, in ms from the start of the
6121 // UNIX epoch.
start_timestamp() const6122 internal::TimeInMillis UnitTest::start_timestamp() const {
6123 return impl()->start_timestamp();
6124 }
6125
6126 // Gets the elapsed time, in milliseconds.
elapsed_time() const6127 internal::TimeInMillis UnitTest::elapsed_time() const {
6128 return impl()->elapsed_time();
6129 }
6130
6131 // Returns true iff the unit test passed (i.e. all test suites passed).
Passed() const6132 bool UnitTest::Passed() const { return impl()->Passed(); }
6133
6134 // Returns true iff the unit test failed (i.e. some test suite failed
6135 // or something outside of all tests failed).
Failed() const6136 bool UnitTest::Failed() const { return impl()->Failed(); }
6137
6138 // Gets the i-th test suite among all the test suites. i can range from 0 to
6139 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i) const6140 const TestSuite* UnitTest::GetTestSuite(int i) const {
6141 return impl()->GetTestSuite(i);
6142 }
6143
6144 // Legacy API is deprecated but still available
6145 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i) const6146 const TestCase* UnitTest::GetTestCase(int i) const {
6147 return impl()->GetTestCase(i);
6148 }
6149 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6150
6151 // Returns the TestResult containing information on test failures and
6152 // properties logged outside of individual test suites.
ad_hoc_test_result() const6153 const TestResult& UnitTest::ad_hoc_test_result() const {
6154 return *impl()->ad_hoc_test_result();
6155 }
6156
6157 // Gets the i-th test suite among all the test suites. i can range from 0 to
6158 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableTestSuite(int i)6159 TestSuite* UnitTest::GetMutableTestSuite(int i) {
6160 return impl()->GetMutableSuiteCase(i);
6161 }
6162
6163 // Returns the list of event listeners that can be used to track events
6164 // inside Google Test.
listeners()6165 TestEventListeners& UnitTest::listeners() {
6166 return *impl()->listeners();
6167 }
6168
6169 // Registers and returns a global test environment. When a test
6170 // program is run, all global test environments will be set-up in the
6171 // order they were registered. After all tests in the program have
6172 // finished, all global test environments will be torn-down in the
6173 // *reverse* order they were registered.
6174 //
6175 // The UnitTest object takes ownership of the given environment.
6176 //
6177 // We don't protect this under mutex_, as we only support calling it
6178 // from the main thread.
AddEnvironment(Environment * env)6179 Environment* UnitTest::AddEnvironment(Environment* env) {
6180 if (env == nullptr) {
6181 return nullptr;
6182 }
6183
6184 impl_->environments().push_back(env);
6185 return env;
6186 }
6187
6188 // Adds a TestPartResult to the current TestResult object. All Google Test
6189 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6190 // this to report their results. The user code should use the
6191 // assertion macros instead of calling this directly.
AddTestPartResult(TestPartResult::Type result_type,const char * file_name,int line_number,const std::string & message,const std::string & os_stack_trace)6192 void UnitTest::AddTestPartResult(
6193 TestPartResult::Type result_type,
6194 const char* file_name,
6195 int line_number,
6196 const std::string& message,
6197 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6198 Message msg;
6199 msg << message;
6200
6201 internal::MutexLock lock(&mutex_);
6202 if (impl_->gtest_trace_stack().size() > 0) {
6203 msg << "\n" << GTEST_NAME_ << " trace:";
6204
6205 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
6206 i > 0; --i) {
6207 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6208 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6209 << " " << trace.message;
6210 }
6211 }
6212
6213 if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
6214 msg << internal::kStackTraceMarker << os_stack_trace;
6215 }
6216
6217 const TestPartResult result = TestPartResult(
6218 result_type, file_name, line_number, msg.GetString().c_str());
6219 impl_->GetTestPartResultReporterForCurrentThread()->
6220 ReportTestPartResult(result);
6221
6222 if (result_type != TestPartResult::kSuccess &&
6223 result_type != TestPartResult::kSkip) {
6224 // gtest_break_on_failure takes precedence over
6225 // gtest_throw_on_failure. This allows a user to set the latter
6226 // in the code (perhaps in order to use Google Test assertions
6227 // with another testing framework) and specify the former on the
6228 // command line for debugging.
6229 if (GTEST_FLAG(break_on_failure)) {
6230 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6231 // Using DebugBreak on Windows allows gtest to still break into a debugger
6232 // when a failure happens and both the --gtest_break_on_failure and
6233 // the --gtest_catch_exceptions flags are specified.
6234 DebugBreak();
6235 #elif (!defined(__native_client__)) && \
6236 ((defined(__clang__) || defined(__GNUC__)) && \
6237 (defined(__x86_64__) || defined(__i386__)))
6238 // with clang/gcc we can achieve the same effect on x86 by invoking int3
6239 asm("int3");
6240 #else
6241 // Dereference nullptr through a volatile pointer to prevent the compiler
6242 // from removing. We use this rather than abort() or __builtin_trap() for
6243 // portability: some debuggers don't correctly trap abort().
6244 *static_cast<volatile int*>(nullptr) = 1;
6245 #endif // GTEST_OS_WINDOWS
6246 } else if (GTEST_FLAG(throw_on_failure)) {
6247 #if GTEST_HAS_EXCEPTIONS
6248 throw internal::GoogleTestFailureException(result);
6249 #else
6250 // We cannot call abort() as it generates a pop-up in debug mode
6251 // that cannot be suppressed in VC 7.1 or below.
6252 exit(1);
6253 #endif
6254 }
6255 }
6256 }
6257
6258 // Adds a TestProperty to the current TestResult object when invoked from
6259 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
6260 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
6261 // when invoked elsewhere. If the result already contains a property with
6262 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)6263 void UnitTest::RecordProperty(const std::string& key,
6264 const std::string& value) {
6265 impl_->RecordProperty(TestProperty(key, value));
6266 }
6267
6268 // Runs all tests in this UnitTest object and prints the result.
6269 // Returns 0 if successful, or 1 otherwise.
6270 //
6271 // We don't protect this under mutex_, as we only support calling it
6272 // from the main thread.
Run()6273 int UnitTest::Run() {
6274 const bool in_death_test_child_process =
6275 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6276
6277 // Google Test implements this protocol for catching that a test
6278 // program exits before returning control to Google Test:
6279 //
6280 // 1. Upon start, Google Test creates a file whose absolute path
6281 // is specified by the environment variable
6282 // TEST_PREMATURE_EXIT_FILE.
6283 // 2. When Google Test has finished its work, it deletes the file.
6284 //
6285 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6286 // running a Google-Test-based test program and check the existence
6287 // of the file at the end of the test execution to see if it has
6288 // exited prematurely.
6289
6290 // If we are in the child process of a death test, don't
6291 // create/delete the premature exit file, as doing so is unnecessary
6292 // and will confuse the parent process. Otherwise, create/delete
6293 // the file upon entering/leaving this function. If the program
6294 // somehow exits before this function has a chance to return, the
6295 // premature-exit file will be left undeleted, causing a test runner
6296 // that understands the premature-exit-file protocol to report the
6297 // test as having failed.
6298 const internal::ScopedPrematureExitFile premature_exit_file(
6299 in_death_test_child_process
6300 ? nullptr
6301 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6302
6303 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
6304 // used for the duration of the program.
6305 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6306
6307 #if GTEST_OS_WINDOWS
6308 // Either the user wants Google Test to catch exceptions thrown by the
6309 // tests or this is executing in the context of death test child
6310 // process. In either case the user does not want to see pop-up dialogs
6311 // about crashes - they are expected.
6312 if (impl()->catch_exceptions() || in_death_test_child_process) {
6313 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6314 // SetErrorMode doesn't exist on CE.
6315 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6316 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6317 # endif // !GTEST_OS_WINDOWS_MOBILE
6318
6319 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6320 // Death test children can be terminated with _abort(). On Windows,
6321 // _abort() can show a dialog with a warning message. This forces the
6322 // abort message to go to stderr instead.
6323 _set_error_mode(_OUT_TO_STDERR);
6324 # endif
6325
6326 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
6327 // In the debug version, Visual Studio pops up a separate dialog
6328 // offering a choice to debug the aborted program. We need to suppress
6329 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6330 // executed. Google Test will notify the user of any unexpected
6331 // failure via stderr.
6332 if (!GTEST_FLAG(break_on_failure))
6333 _set_abort_behavior(
6334 0x0, // Clear the following flags:
6335 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
6336 # endif
6337 }
6338 #endif // GTEST_OS_WINDOWS
6339
6340 return internal::HandleExceptionsInMethodIfSupported(
6341 impl(),
6342 &internal::UnitTestImpl::RunAllTests,
6343 "auxiliary test code (environments or event listeners)") ? 0 : 1;
6344 }
6345
6346 // Returns the working directory when the first TEST() or TEST_F() was
6347 // executed.
original_working_dir() const6348 const char* UnitTest::original_working_dir() const {
6349 return impl_->original_working_dir_.c_str();
6350 }
6351
6352 // Returns the TestSuite object for the test that's currently running,
6353 // or NULL if no test is running.
current_test_suite() const6354 const TestSuite* UnitTest::current_test_suite() const
6355 GTEST_LOCK_EXCLUDED_(mutex_) {
6356 internal::MutexLock lock(&mutex_);
6357 return impl_->current_test_suite();
6358 }
6359
6360 // Legacy API is still available but deprecated
6361 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
current_test_case() const6362 const TestCase* UnitTest::current_test_case() const
6363 GTEST_LOCK_EXCLUDED_(mutex_) {
6364 internal::MutexLock lock(&mutex_);
6365 return impl_->current_test_suite();
6366 }
6367 #endif
6368
6369 // Returns the TestInfo object for the test that's currently running,
6370 // or NULL if no test is running.
current_test_info() const6371 const TestInfo* UnitTest::current_test_info() const
6372 GTEST_LOCK_EXCLUDED_(mutex_) {
6373 internal::MutexLock lock(&mutex_);
6374 return impl_->current_test_info();
6375 }
6376
6377 // Returns the random seed used at the start of the current test run.
random_seed() const6378 int UnitTest::random_seed() const { return impl_->random_seed(); }
6379
6380 // Returns ParameterizedTestSuiteRegistry object used to keep track of
6381 // value-parameterized tests and instantiate and register them.
6382 internal::ParameterizedTestSuiteRegistry&
parameterized_test_registry()6383 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
6384 return impl_->parameterized_test_registry();
6385 }
6386
6387 // Creates an empty UnitTest.
UnitTest()6388 UnitTest::UnitTest() {
6389 impl_ = new internal::UnitTestImpl(this);
6390 }
6391
6392 // Destructor of UnitTest.
~UnitTest()6393 UnitTest::~UnitTest() {
6394 delete impl_;
6395 }
6396
6397 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6398 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)6399 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6400 GTEST_LOCK_EXCLUDED_(mutex_) {
6401 internal::MutexLock lock(&mutex_);
6402 impl_->gtest_trace_stack().push_back(trace);
6403 }
6404
6405 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()6406 void UnitTest::PopGTestTrace()
6407 GTEST_LOCK_EXCLUDED_(mutex_) {
6408 internal::MutexLock lock(&mutex_);
6409 impl_->gtest_trace_stack().pop_back();
6410 }
6411
6412 namespace internal {
6413
UnitTestImpl(UnitTest * parent)6414 UnitTestImpl::UnitTestImpl(UnitTest* parent)
6415 : parent_(parent),
6416 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
6417 default_global_test_part_result_reporter_(this),
6418 default_per_thread_test_part_result_reporter_(this),
6419 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
6420 &default_global_test_part_result_reporter_),
6421 per_thread_test_part_result_reporter_(
6422 &default_per_thread_test_part_result_reporter_),
6423 parameterized_test_registry_(),
6424 parameterized_tests_registered_(false),
6425 last_death_test_suite_(-1),
6426 current_test_suite_(nullptr),
6427 current_test_info_(nullptr),
6428 ad_hoc_test_result_(),
6429 os_stack_trace_getter_(nullptr),
6430 post_flag_parse_init_performed_(false),
6431 random_seed_(0), // Will be overridden by the flag before first use.
6432 random_(0), // Will be reseeded before first use.
6433 start_timestamp_(0),
6434 elapsed_time_(0),
6435 #if GTEST_HAS_DEATH_TEST
6436 death_test_factory_(new DefaultDeathTestFactory),
6437 #endif
6438 // Will be overridden by the flag before first use.
6439 catch_exceptions_(false) {
6440 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
6441 }
6442
~UnitTestImpl()6443 UnitTestImpl::~UnitTestImpl() {
6444 // Deletes every TestSuite.
6445 ForEach(test_suites_, internal::Delete<TestSuite>);
6446
6447 // Deletes every Environment.
6448 ForEach(environments_, internal::Delete<Environment>);
6449
6450 delete os_stack_trace_getter_;
6451 }
6452
6453 // Adds a TestProperty to the current TestResult object when invoked in a
6454 // context of a test, to current test suite's ad_hoc_test_result when invoke
6455 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
6456 // otherwise. If the result already contains a property with the same key,
6457 // the value will be updated.
RecordProperty(const TestProperty & test_property)6458 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
6459 std::string xml_element;
6460 TestResult* test_result; // TestResult appropriate for property recording.
6461
6462 if (current_test_info_ != nullptr) {
6463 xml_element = "testcase";
6464 test_result = &(current_test_info_->result_);
6465 } else if (current_test_suite_ != nullptr) {
6466 xml_element = "testsuite";
6467 test_result = &(current_test_suite_->ad_hoc_test_result_);
6468 } else {
6469 xml_element = "testsuites";
6470 test_result = &ad_hoc_test_result_;
6471 }
6472 test_result->RecordProperty(xml_element, test_property);
6473 }
6474
6475 #if GTEST_HAS_DEATH_TEST
6476 // Disables event forwarding if the control is currently in a death test
6477 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()6478 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
6479 if (internal_run_death_test_flag_.get() != nullptr)
6480 listeners()->SuppressEventForwarding();
6481 }
6482 #endif // GTEST_HAS_DEATH_TEST
6483
6484 // Initializes event listeners performing XML output as specified by
6485 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()6486 void UnitTestImpl::ConfigureXmlOutput() {
6487 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6488 if (output_format == "xml") {
6489 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
6490 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6491 } else if (output_format == "json") {
6492 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
6493 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6494 } else if (output_format != "") {
6495 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
6496 << output_format << "\" ignored.";
6497 }
6498 }
6499
6500 #if GTEST_CAN_STREAM_RESULTS_
6501 // Initializes event listeners for streaming test results in string form.
6502 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()6503 void UnitTestImpl::ConfigureStreamingOutput() {
6504 const std::string& target = GTEST_FLAG(stream_result_to);
6505 if (!target.empty()) {
6506 const size_t pos = target.find(':');
6507 if (pos != std::string::npos) {
6508 listeners()->Append(new StreamingListener(target.substr(0, pos),
6509 target.substr(pos+1)));
6510 } else {
6511 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
6512 << "\" ignored.";
6513 }
6514 }
6515 }
6516 #endif // GTEST_CAN_STREAM_RESULTS_
6517
6518 // Performs initialization dependent upon flag values obtained in
6519 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
6520 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
6521 // this function is also called from RunAllTests. Since this function can be
6522 // called more than once, it has to be idempotent.
PostFlagParsingInit()6523 void UnitTestImpl::PostFlagParsingInit() {
6524 // Ensures that this function does not execute more than once.
6525 if (!post_flag_parse_init_performed_) {
6526 post_flag_parse_init_performed_ = true;
6527
6528 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6529 // Register to send notifications about key process state changes.
6530 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6531 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6532
6533 #if GTEST_HAS_DEATH_TEST
6534 InitDeathTestSubprocessControlInfo();
6535 SuppressTestEventsIfInSubprocess();
6536 #endif // GTEST_HAS_DEATH_TEST
6537
6538 // Registers parameterized tests. This makes parameterized tests
6539 // available to the UnitTest reflection API without running
6540 // RUN_ALL_TESTS.
6541 RegisterParameterizedTests();
6542
6543 // Configures listeners for XML output. This makes it possible for users
6544 // to shut down the default XML output before invoking RUN_ALL_TESTS.
6545 ConfigureXmlOutput();
6546
6547 #if GTEST_CAN_STREAM_RESULTS_
6548 // Configures listeners for streaming test results to the specified server.
6549 ConfigureStreamingOutput();
6550 #endif // GTEST_CAN_STREAM_RESULTS_
6551
6552 #if GTEST_HAS_ABSL
6553 if (GTEST_FLAG(install_failure_signal_handler)) {
6554 absl::FailureSignalHandlerOptions options;
6555 absl::InstallFailureSignalHandler(options);
6556 }
6557 #endif // GTEST_HAS_ABSL
6558 }
6559 }
6560
6561 // A predicate that checks the name of a TestSuite against a known
6562 // value.
6563 //
6564 // This is used for implementation of the UnitTest class only. We put
6565 // it in the anonymous namespace to prevent polluting the outer
6566 // namespace.
6567 //
6568 // TestSuiteNameIs is copyable.
6569 class TestSuiteNameIs {
6570 public:
6571 // Constructor.
TestSuiteNameIs(const std::string & name)6572 explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
6573
6574 // Returns true iff the name of test_suite matches name_.
operator ()(const TestSuite * test_suite) const6575 bool operator()(const TestSuite* test_suite) const {
6576 return test_suite != nullptr &&
6577 strcmp(test_suite->name(), name_.c_str()) == 0;
6578 }
6579
6580 private:
6581 std::string name_;
6582 };
6583
6584 // Finds and returns a TestSuite with the given name. If one doesn't
6585 // exist, creates one and returns it. It's the CALLER'S
6586 // RESPONSIBILITY to ensure that this function is only called WHEN THE
6587 // TESTS ARE NOT SHUFFLED.
6588 //
6589 // Arguments:
6590 //
6591 // test_suite_name: name of the test suite
6592 // type_param: the name of the test suite's type parameter, or NULL if
6593 // this is not a typed or a type-parameterized test suite.
6594 // set_up_tc: pointer to the function that sets up the test suite
6595 // tear_down_tc: pointer to the function that tears down the test suite
GetTestSuite(const char * test_suite_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)6596 TestSuite* UnitTestImpl::GetTestSuite(
6597 const char* test_suite_name, const char* type_param,
6598 internal::SetUpTestSuiteFunc set_up_tc,
6599 internal::TearDownTestSuiteFunc tear_down_tc) {
6600 // Can we find a TestSuite with the given name?
6601 const auto test_suite =
6602 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
6603 TestSuiteNameIs(test_suite_name));
6604
6605 if (test_suite != test_suites_.rend()) return *test_suite;
6606
6607 // No. Let's create one.
6608 auto* const new_test_suite =
6609 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
6610
6611 // Is this a death test suite?
6612 if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
6613 kDeathTestSuiteFilter)) {
6614 // Yes. Inserts the test suite after the last death test suite
6615 // defined so far. This only works when the test suites haven't
6616 // been shuffled. Otherwise we may end up running a death test
6617 // after a non-death test.
6618 ++last_death_test_suite_;
6619 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
6620 new_test_suite);
6621 } else {
6622 // No. Appends to the end of the list.
6623 test_suites_.push_back(new_test_suite);
6624 }
6625
6626 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
6627 return new_test_suite;
6628 }
6629
6630 // Helpers for setting up / tearing down the given environment. They
6631 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)6632 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)6633 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6634
6635 // Runs all tests in this UnitTest object, prints the result, and
6636 // returns true if all tests are successful. If any exception is
6637 // thrown during a test, the test is considered to be failed, but the
6638 // rest of the tests will still be run.
6639 //
6640 // When parameterized tests are enabled, it expands and registers
6641 // parameterized tests first in RegisterParameterizedTests().
6642 // All other functions called from RunAllTests() may safely assume that
6643 // parameterized tests are ready to be counted and run.
RunAllTests()6644 bool UnitTestImpl::RunAllTests() {
6645 // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
6646 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
6647
6648 // Do not run any test if the --help flag was specified.
6649 if (g_help_flag)
6650 return true;
6651
6652 // Repeats the call to the post-flag parsing initialization in case the
6653 // user didn't call InitGoogleTest.
6654 PostFlagParsingInit();
6655
6656 // Even if sharding is not on, test runners may want to use the
6657 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6658 // protocol.
6659 internal::WriteToShardStatusFileIfNeeded();
6660
6661 // True iff we are in a subprocess for running a thread-safe-style
6662 // death test.
6663 bool in_subprocess_for_death_test = false;
6664
6665 #if GTEST_HAS_DEATH_TEST
6666 in_subprocess_for_death_test =
6667 (internal_run_death_test_flag_.get() != nullptr);
6668 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6669 if (in_subprocess_for_death_test) {
6670 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6671 }
6672 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6673 #endif // GTEST_HAS_DEATH_TEST
6674
6675 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6676 in_subprocess_for_death_test);
6677
6678 // Compares the full test names with the filter to decide which
6679 // tests to run.
6680 const bool has_tests_to_run = FilterTests(should_shard
6681 ? HONOR_SHARDING_PROTOCOL
6682 : IGNORE_SHARDING_PROTOCOL) > 0;
6683
6684 // Lists the tests and exits if the --gtest_list_tests flag was specified.
6685 if (GTEST_FLAG(list_tests)) {
6686 // This must be called *after* FilterTests() has been called.
6687 ListTestsMatchingFilter();
6688 return true;
6689 }
6690
6691 random_seed_ = GTEST_FLAG(shuffle) ?
6692 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6693
6694 // True iff at least one test has failed.
6695 bool failed = false;
6696
6697 TestEventListener* repeater = listeners()->repeater();
6698
6699 start_timestamp_ = GetTimeInMillis();
6700 repeater->OnTestProgramStart(*parent_);
6701
6702 // How many times to repeat the tests? We don't want to repeat them
6703 // when we are inside the subprocess of a death test.
6704 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6705 // Repeats forever if the repeat count is negative.
6706 const bool forever = repeat < 0;
6707 for (int i = 0; forever || i != repeat; i++) {
6708 // We want to preserve failures generated by ad-hoc test
6709 // assertions executed before RUN_ALL_TESTS().
6710 ClearNonAdHocTestResult();
6711
6712 const TimeInMillis start = GetTimeInMillis();
6713
6714 // Shuffles test suites and tests if requested.
6715 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6716 random()->Reseed(random_seed_);
6717 // This should be done before calling OnTestIterationStart(),
6718 // such that a test event listener can see the actual test order
6719 // in the event.
6720 ShuffleTests();
6721 }
6722
6723 // Tells the unit test event listeners that the tests are about to start.
6724 repeater->OnTestIterationStart(*parent_, i);
6725
6726 // Runs each test suite if there is at least one test to run.
6727 if (has_tests_to_run) {
6728 // Sets up all environments beforehand.
6729 repeater->OnEnvironmentsSetUpStart(*parent_);
6730 ForEach(environments_, SetUpEnvironment);
6731 repeater->OnEnvironmentsSetUpEnd(*parent_);
6732
6733 // Runs the tests only if there was no fatal failure or skip triggered
6734 // during global set-up.
6735 if (Test::IsSkipped()) {
6736 // Emit diagnostics when global set-up calls skip, as it will not be
6737 // emitted by default.
6738 TestResult& test_result =
6739 *internal::GetUnitTestImpl()->current_test_result();
6740 for (int j = 0; j < test_result.total_part_count(); ++j) {
6741 const TestPartResult& test_part_result =
6742 test_result.GetTestPartResult(j);
6743 if (test_part_result.type() == TestPartResult::kSkip) {
6744 const std::string& result = test_part_result.message();
6745 printf("%s\n", result.c_str());
6746 }
6747 }
6748 fflush(stdout);
6749 } else if (!Test::HasFatalFailure()) {
6750 for (int test_index = 0; test_index < total_test_suite_count();
6751 test_index++) {
6752 GetMutableSuiteCase(test_index)->Run();
6753 }
6754 }
6755
6756 // Tears down all environments in reverse order afterwards.
6757 repeater->OnEnvironmentsTearDownStart(*parent_);
6758 std::for_each(environments_.rbegin(), environments_.rend(),
6759 TearDownEnvironment);
6760 repeater->OnEnvironmentsTearDownEnd(*parent_);
6761 }
6762
6763 elapsed_time_ = GetTimeInMillis() - start;
6764
6765 // Tells the unit test event listener that the tests have just finished.
6766 repeater->OnTestIterationEnd(*parent_, i);
6767
6768 // Gets the result and clears it.
6769 if (!Passed()) {
6770 failed = true;
6771 }
6772
6773 // Restores the original test order after the iteration. This
6774 // allows the user to quickly repro a failure that happens in the
6775 // N-th iteration without repeating the first (N - 1) iterations.
6776 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6777 // case the user somehow changes the value of the flag somewhere
6778 // (it's always safe to unshuffle the tests).
6779 UnshuffleTests();
6780
6781 if (GTEST_FLAG(shuffle)) {
6782 // Picks a new random seed for each iteration.
6783 random_seed_ = GetNextRandomSeed(random_seed_);
6784 }
6785 }
6786
6787 repeater->OnTestProgramEnd(*parent_);
6788
6789 if (!gtest_is_initialized_before_run_all_tests) {
6790 ColoredPrintf(
6791 COLOR_RED,
6792 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6793 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6794 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6795 " will start to enforce the valid usage. "
6796 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
6797 #if GTEST_FOR_GOOGLE_
6798 ColoredPrintf(COLOR_RED,
6799 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
6800 #endif // GTEST_FOR_GOOGLE_
6801 }
6802
6803 return !failed;
6804 }
6805
6806 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6807 // if the variable is present. If a file already exists at this location, this
6808 // function will write over it. If the variable is present, but the file cannot
6809 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()6810 void WriteToShardStatusFileIfNeeded() {
6811 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6812 if (test_shard_file != nullptr) {
6813 FILE* const file = posix::FOpen(test_shard_file, "w");
6814 if (file == nullptr) {
6815 ColoredPrintf(COLOR_RED,
6816 "Could not write to the test shard status file \"%s\" "
6817 "specified by the %s environment variable.\n",
6818 test_shard_file, kTestShardStatusFile);
6819 fflush(stdout);
6820 exit(EXIT_FAILURE);
6821 }
6822 fclose(file);
6823 }
6824 }
6825
6826 // Checks whether sharding is enabled by examining the relevant
6827 // environment variable values. If the variables are present,
6828 // but inconsistent (i.e., shard_index >= total_shards), prints
6829 // an error and exits. If in_subprocess_for_death_test, sharding is
6830 // disabled because it must only be applied to the original test
6831 // process. Otherwise, we could filter out death tests we intended to execute.
ShouldShard(const char * total_shards_env,const char * shard_index_env,bool in_subprocess_for_death_test)6832 bool ShouldShard(const char* total_shards_env,
6833 const char* shard_index_env,
6834 bool in_subprocess_for_death_test) {
6835 if (in_subprocess_for_death_test) {
6836 return false;
6837 }
6838
6839 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6840 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6841
6842 if (total_shards == -1 && shard_index == -1) {
6843 return false;
6844 } else if (total_shards == -1 && shard_index != -1) {
6845 const Message msg = Message()
6846 << "Invalid environment variables: you have "
6847 << kTestShardIndex << " = " << shard_index
6848 << ", but have left " << kTestTotalShards << " unset.\n";
6849 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6850 fflush(stdout);
6851 exit(EXIT_FAILURE);
6852 } else if (total_shards != -1 && shard_index == -1) {
6853 const Message msg = Message()
6854 << "Invalid environment variables: you have "
6855 << kTestTotalShards << " = " << total_shards
6856 << ", but have left " << kTestShardIndex << " unset.\n";
6857 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6858 fflush(stdout);
6859 exit(EXIT_FAILURE);
6860 } else if (shard_index < 0 || shard_index >= total_shards) {
6861 const Message msg = Message()
6862 << "Invalid environment variables: we require 0 <= "
6863 << kTestShardIndex << " < " << kTestTotalShards
6864 << ", but you have " << kTestShardIndex << "=" << shard_index
6865 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6866 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6867 fflush(stdout);
6868 exit(EXIT_FAILURE);
6869 }
6870
6871 return total_shards > 1;
6872 }
6873
6874 // Parses the environment variable var as an Int32. If it is unset,
6875 // returns default_val. If it is not an Int32, prints an error
6876 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)6877 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6878 const char* str_val = posix::GetEnv(var);
6879 if (str_val == nullptr) {
6880 return default_val;
6881 }
6882
6883 Int32 result;
6884 if (!ParseInt32(Message() << "The value of environment variable " << var,
6885 str_val, &result)) {
6886 exit(EXIT_FAILURE);
6887 }
6888 return result;
6889 }
6890
6891 // Given the total number of shards, the shard index, and the test id,
6892 // returns true iff the test should be run on this shard. The test id is
6893 // some arbitrary but unique non-negative integer assigned to each test
6894 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)6895 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6896 return (test_id % total_shards) == shard_index;
6897 }
6898
6899 // Compares the name of each test with the user-specified filter to
6900 // decide whether the test should be run, then records the result in
6901 // each TestSuite and TestInfo object.
6902 // If shard_tests == true, further filters tests based on sharding
6903 // variables in the environment - see
6904 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6905 // . Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)6906 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6907 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6908 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6909 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6910 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6911
6912 // num_runnable_tests are the number of tests that will
6913 // run across all shards (i.e., match filter and are not disabled).
6914 // num_selected_tests are the number of tests to be run on
6915 // this shard.
6916 int num_runnable_tests = 0;
6917 int num_selected_tests = 0;
6918 for (auto* test_suite : test_suites_) {
6919 const std::string& test_suite_name = test_suite->name();
6920 test_suite->set_should_run(false);
6921
6922 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6923 TestInfo* const test_info = test_suite->test_info_list()[j];
6924 const std::string test_name(test_info->name());
6925 // A test is disabled if test suite name or test name matches
6926 // kDisableTestFilter.
6927 const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
6928 test_suite_name, kDisableTestFilter) ||
6929 internal::UnitTestOptions::MatchesFilter(
6930 test_name, kDisableTestFilter);
6931 test_info->is_disabled_ = is_disabled;
6932
6933 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
6934 test_suite_name, test_name);
6935 test_info->matches_filter_ = matches_filter;
6936
6937 const bool is_runnable =
6938 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6939 matches_filter;
6940
6941 const bool is_in_another_shard =
6942 shard_tests != IGNORE_SHARDING_PROTOCOL &&
6943 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6944 test_info->is_in_another_shard_ = is_in_another_shard;
6945 const bool is_selected = is_runnable && !is_in_another_shard;
6946
6947 num_runnable_tests += is_runnable;
6948 num_selected_tests += is_selected;
6949
6950 test_info->should_run_ = is_selected;
6951 test_suite->set_should_run(test_suite->should_run() || is_selected);
6952 }
6953 }
6954 return num_selected_tests;
6955 }
6956
6957 // Prints the given C-string on a single line by replacing all '\n'
6958 // characters with string "\\n". If the output takes more than
6959 // max_length characters, only prints the first max_length characters
6960 // and "...".
PrintOnOneLine(const char * str,int max_length)6961 static void PrintOnOneLine(const char* str, int max_length) {
6962 if (str != nullptr) {
6963 for (int i = 0; *str != '\0'; ++str) {
6964 if (i >= max_length) {
6965 printf("...");
6966 break;
6967 }
6968 if (*str == '\n') {
6969 printf("\\n");
6970 i += 2;
6971 } else {
6972 printf("%c", *str);
6973 ++i;
6974 }
6975 }
6976 }
6977 }
6978
6979 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()6980 void UnitTestImpl::ListTestsMatchingFilter() {
6981 // Print at most this many characters for each type/value parameter.
6982 const int kMaxParamLength = 250;
6983
6984 for (auto* test_suite : test_suites_) {
6985 bool printed_test_suite_name = false;
6986
6987 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6988 const TestInfo* const test_info = test_suite->test_info_list()[j];
6989 if (test_info->matches_filter_) {
6990 if (!printed_test_suite_name) {
6991 printed_test_suite_name = true;
6992 printf("%s.", test_suite->name());
6993 if (test_suite->type_param() != nullptr) {
6994 printf(" # %s = ", kTypeParamLabel);
6995 // We print the type parameter on a single line to make
6996 // the output easy to parse by a program.
6997 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6998 }
6999 printf("\n");
7000 }
7001 printf(" %s", test_info->name());
7002 if (test_info->value_param() != nullptr) {
7003 printf(" # %s = ", kValueParamLabel);
7004 // We print the value parameter on a single line to make the
7005 // output easy to parse by a program.
7006 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
7007 }
7008 printf("\n");
7009 }
7010 }
7011 }
7012 fflush(stdout);
7013 const std::string& output_format = UnitTestOptions::GetOutputFormat();
7014 if (output_format == "xml" || output_format == "json") {
7015 FILE* fileout = OpenFileForWriting(
7016 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
7017 std::stringstream stream;
7018 if (output_format == "xml") {
7019 XmlUnitTestResultPrinter(
7020 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7021 .PrintXmlTestsList(&stream, test_suites_);
7022 } else if (output_format == "json") {
7023 JsonUnitTestResultPrinter(
7024 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7025 .PrintJsonTestList(&stream, test_suites_);
7026 }
7027 fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
7028 fclose(fileout);
7029 }
7030 }
7031
7032 // Sets the OS stack trace getter.
7033 //
7034 // Does nothing if the input and the current OS stack trace getter are
7035 // the same; otherwise, deletes the old getter and makes the input the
7036 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)7037 void UnitTestImpl::set_os_stack_trace_getter(
7038 OsStackTraceGetterInterface* getter) {
7039 if (os_stack_trace_getter_ != getter) {
7040 delete os_stack_trace_getter_;
7041 os_stack_trace_getter_ = getter;
7042 }
7043 }
7044
7045 // Returns the current OS stack trace getter if it is not NULL;
7046 // otherwise, creates an OsStackTraceGetter, makes it the current
7047 // getter, and returns it.
os_stack_trace_getter()7048 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
7049 if (os_stack_trace_getter_ == nullptr) {
7050 #ifdef GTEST_OS_STACK_TRACE_GETTER_
7051 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
7052 #else
7053 os_stack_trace_getter_ = new OsStackTraceGetter;
7054 #endif // GTEST_OS_STACK_TRACE_GETTER_
7055 }
7056
7057 return os_stack_trace_getter_;
7058 }
7059
7060 // Returns the most specific TestResult currently running.
current_test_result()7061 TestResult* UnitTestImpl::current_test_result() {
7062 if (current_test_info_ != nullptr) {
7063 return ¤t_test_info_->result_;
7064 }
7065 if (current_test_suite_ != nullptr) {
7066 return ¤t_test_suite_->ad_hoc_test_result_;
7067 }
7068 return &ad_hoc_test_result_;
7069 }
7070
7071 // Shuffles all test suites, and the tests within each test suite,
7072 // making sure that death tests are still run first.
ShuffleTests()7073 void UnitTestImpl::ShuffleTests() {
7074 // Shuffles the death test suites.
7075 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
7076
7077 // Shuffles the non-death test suites.
7078 ShuffleRange(random(), last_death_test_suite_ + 1,
7079 static_cast<int>(test_suites_.size()), &test_suite_indices_);
7080
7081 // Shuffles the tests inside each test suite.
7082 for (auto& test_suite : test_suites_) {
7083 test_suite->ShuffleTests(random());
7084 }
7085 }
7086
7087 // Restores the test suites and tests to their order before the first shuffle.
UnshuffleTests()7088 void UnitTestImpl::UnshuffleTests() {
7089 for (size_t i = 0; i < test_suites_.size(); i++) {
7090 // Unshuffles the tests in each test suite.
7091 test_suites_[i]->UnshuffleTests();
7092 // Resets the index of each test suite.
7093 test_suite_indices_[i] = static_cast<int>(i);
7094 }
7095 }
7096
7097 // Returns the current OS stack trace as an std::string.
7098 //
7099 // The maximum number of stack frames to be included is specified by
7100 // the gtest_stack_trace_depth flag. The skip_count parameter
7101 // specifies the number of top frames to be skipped, which doesn't
7102 // count against the number of frames to be included.
7103 //
7104 // For example, if Foo() calls Bar(), which in turn calls
7105 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7106 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)7107 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7108 int skip_count) {
7109 // We pass skip_count + 1 to skip this wrapper function in addition
7110 // to what the user really wants to skip.
7111 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7112 }
7113
7114 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7115 // suppress unreachable code warnings.
7116 namespace {
7117 class ClassUniqueToAlwaysTrue {};
7118 }
7119
IsTrue(bool condition)7120 bool IsTrue(bool condition) { return condition; }
7121
AlwaysTrue()7122 bool AlwaysTrue() {
7123 #if GTEST_HAS_EXCEPTIONS
7124 // This condition is always false so AlwaysTrue() never actually throws,
7125 // but it makes the compiler think that it may throw.
7126 if (IsTrue(false))
7127 throw ClassUniqueToAlwaysTrue();
7128 #endif // GTEST_HAS_EXCEPTIONS
7129 return true;
7130 }
7131
7132 // If *pstr starts with the given prefix, modifies *pstr to be right
7133 // past the prefix and returns true; otherwise leaves *pstr unchanged
7134 // and returns false. None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)7135 bool SkipPrefix(const char* prefix, const char** pstr) {
7136 const size_t prefix_len = strlen(prefix);
7137 if (strncmp(*pstr, prefix, prefix_len) == 0) {
7138 *pstr += prefix_len;
7139 return true;
7140 }
7141 return false;
7142 }
7143
7144 // Parses a string as a command line flag. The string should have
7145 // the format "--flag=value". When def_optional is true, the "=value"
7146 // part can be omitted.
7147 //
7148 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)7149 static const char* ParseFlagValue(const char* str, const char* flag,
7150 bool def_optional) {
7151 // str and flag must not be NULL.
7152 if (str == nullptr || flag == nullptr) return nullptr;
7153
7154 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7155 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7156 const size_t flag_len = flag_str.length();
7157 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
7158
7159 // Skips the flag name.
7160 const char* flag_end = str + flag_len;
7161
7162 // When def_optional is true, it's OK to not have a "=value" part.
7163 if (def_optional && (flag_end[0] == '\0')) {
7164 return flag_end;
7165 }
7166
7167 // If def_optional is true and there are more characters after the
7168 // flag name, or if def_optional is false, there must be a '=' after
7169 // the flag name.
7170 if (flag_end[0] != '=') return nullptr;
7171
7172 // Returns the string after "=".
7173 return flag_end + 1;
7174 }
7175
7176 // Parses a string for a bool flag, in the form of either
7177 // "--flag=value" or "--flag".
7178 //
7179 // In the former case, the value is taken as true as long as it does
7180 // not start with '0', 'f', or 'F'.
7181 //
7182 // In the latter case, the value is taken as true.
7183 //
7184 // On success, stores the value of the flag in *value, and returns
7185 // true. On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)7186 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7187 // Gets the value of the flag as a string.
7188 const char* const value_str = ParseFlagValue(str, flag, true);
7189
7190 // Aborts if the parsing failed.
7191 if (value_str == nullptr) return false;
7192
7193 // Converts the string value to a bool.
7194 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7195 return true;
7196 }
7197
7198 // Parses a string for an Int32 flag, in the form of
7199 // "--flag=value".
7200 //
7201 // On success, stores the value of the flag in *value, and returns
7202 // true. On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)7203 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
7204 // Gets the value of the flag as a string.
7205 const char* const value_str = ParseFlagValue(str, flag, false);
7206
7207 // Aborts if the parsing failed.
7208 if (value_str == nullptr) return false;
7209
7210 // Sets *value to the value of the flag.
7211 return ParseInt32(Message() << "The value of flag --" << flag,
7212 value_str, value);
7213 }
7214
7215 // Parses a string for a string flag, in the form of
7216 // "--flag=value".
7217 //
7218 // On success, stores the value of the flag in *value, and returns
7219 // true. On failure, returns false without changing *value.
7220 template <typename String>
ParseStringFlag(const char * str,const char * flag,String * value)7221 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7222 // Gets the value of the flag as a string.
7223 const char* const value_str = ParseFlagValue(str, flag, false);
7224
7225 // Aborts if the parsing failed.
7226 if (value_str == nullptr) return false;
7227
7228 // Sets *value to the value of the flag.
7229 *value = value_str;
7230 return true;
7231 }
7232
7233 // Determines whether a string has a prefix that Google Test uses for its
7234 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7235 // If Google Test detects that a command line flag has its prefix but is not
7236 // recognized, it will print its help message. Flags starting with
7237 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7238 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)7239 static bool HasGoogleTestFlagPrefix(const char* str) {
7240 return (SkipPrefix("--", &str) ||
7241 SkipPrefix("-", &str) ||
7242 SkipPrefix("/", &str)) &&
7243 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7244 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7245 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7246 }
7247
7248 // Prints a string containing code-encoded text. The following escape
7249 // sequences can be used in the string to control the text color:
7250 //
7251 // @@ prints a single '@' character.
7252 // @R changes the color to red.
7253 // @G changes the color to green.
7254 // @Y changes the color to yellow.
7255 // @D changes to the default terminal text color.
7256 //
PrintColorEncoded(const char * str)7257 static void PrintColorEncoded(const char* str) {
7258 GTestColor color = COLOR_DEFAULT; // The current color.
7259
7260 // Conceptually, we split the string into segments divided by escape
7261 // sequences. Then we print one segment at a time. At the end of
7262 // each iteration, the str pointer advances to the beginning of the
7263 // next segment.
7264 for (;;) {
7265 const char* p = strchr(str, '@');
7266 if (p == nullptr) {
7267 ColoredPrintf(color, "%s", str);
7268 return;
7269 }
7270
7271 ColoredPrintf(color, "%s", std::string(str, p).c_str());
7272
7273 const char ch = p[1];
7274 str = p + 2;
7275 if (ch == '@') {
7276 ColoredPrintf(color, "@");
7277 } else if (ch == 'D') {
7278 color = COLOR_DEFAULT;
7279 } else if (ch == 'R') {
7280 color = COLOR_RED;
7281 } else if (ch == 'G') {
7282 color = COLOR_GREEN;
7283 } else if (ch == 'Y') {
7284 color = COLOR_YELLOW;
7285 } else {
7286 --str;
7287 }
7288 }
7289 }
7290
7291 static const char kColorEncodedHelpMessage[] =
7292 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
7293 "following command line flags to control its behavior:\n"
7294 "\n"
7295 "Test Selection:\n"
7296 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
7297 " List the names of all tests instead of running them. The name of\n"
7298 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
7299 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
7300 "[@G-@YNEGATIVE_PATTERNS]@D\n"
7301 " Run only the tests whose name matches one of the positive patterns but\n"
7302 " none of the negative patterns. '?' matches any single character; '*'\n"
7303 " matches any substring; ':' separates two patterns.\n"
7304 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
7305 " Run all disabled tests too.\n"
7306 "\n"
7307 "Test Execution:\n"
7308 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
7309 " Run the tests repeatedly; use a negative count to repeat forever.\n"
7310 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
7311 " Randomize tests' orders on every iteration.\n"
7312 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
7313 " Random number seed to use for shuffling test orders (between 1 and\n"
7314 " 99999, or 0 to use a seed based on the current time).\n"
7315 "\n"
7316 "Test Output:\n"
7317 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7318 " Enable/disable colored output. The default is @Gauto@D.\n"
7319 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
7320 " Don't print the elapsed time of each test.\n"
7321 " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
7322 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
7323 " Generate a JSON or XML report in the given directory or with the given\n"
7324 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
7325 # if GTEST_CAN_STREAM_RESULTS_
7326 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
7327 " Stream test results to the given server.\n"
7328 # endif // GTEST_CAN_STREAM_RESULTS_
7329 "\n"
7330 "Assertion Behavior:\n"
7331 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7332 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7333 " Set the default death test style.\n"
7334 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7335 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
7336 " Turn assertion failures into debugger break-points.\n"
7337 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
7338 " Turn assertion failures into C++ exceptions for use by an external\n"
7339 " test framework.\n"
7340 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
7341 " Do not report exceptions as test failures. Instead, allow them\n"
7342 " to crash the program or throw a pop-up (on Windows).\n"
7343 "\n"
7344 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
7345 "the corresponding\n"
7346 "environment variable of a flag (all letters in upper-case). For example, to\n"
7347 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
7348 "color=no@D or set\n"
7349 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
7350 "\n"
7351 "For more information, please read the " GTEST_NAME_ " documentation at\n"
7352 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
7353 "(not one in your own code or tests), please report it to\n"
7354 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7355
ParseGoogleTestFlag(const char * const arg)7356 static bool ParseGoogleTestFlag(const char* const arg) {
7357 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7358 >EST_FLAG(also_run_disabled_tests)) ||
7359 ParseBoolFlag(arg, kBreakOnFailureFlag,
7360 >EST_FLAG(break_on_failure)) ||
7361 ParseBoolFlag(arg, kCatchExceptionsFlag,
7362 >EST_FLAG(catch_exceptions)) ||
7363 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
7364 ParseStringFlag(arg, kDeathTestStyleFlag,
7365 >EST_FLAG(death_test_style)) ||
7366 ParseBoolFlag(arg, kDeathTestUseFork,
7367 >EST_FLAG(death_test_use_fork)) ||
7368 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
7369 ParseStringFlag(arg, kInternalRunDeathTestFlag,
7370 >EST_FLAG(internal_run_death_test)) ||
7371 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
7372 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
7373 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
7374 ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) ||
7375 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
7376 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
7377 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
7378 ParseInt32Flag(arg, kStackTraceDepthFlag,
7379 >EST_FLAG(stack_trace_depth)) ||
7380 ParseStringFlag(arg, kStreamResultToFlag,
7381 >EST_FLAG(stream_result_to)) ||
7382 ParseBoolFlag(arg, kThrowOnFailureFlag,
7383 >EST_FLAG(throw_on_failure));
7384 }
7385
7386 #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)7387 static void LoadFlagsFromFile(const std::string& path) {
7388 FILE* flagfile = posix::FOpen(path.c_str(), "r");
7389 if (!flagfile) {
7390 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
7391 << "\"";
7392 }
7393 std::string contents(ReadEntireFile(flagfile));
7394 posix::FClose(flagfile);
7395 std::vector<std::string> lines;
7396 SplitString(contents, '\n', &lines);
7397 for (size_t i = 0; i < lines.size(); ++i) {
7398 if (lines[i].empty())
7399 continue;
7400 if (!ParseGoogleTestFlag(lines[i].c_str()))
7401 g_help_flag = true;
7402 }
7403 }
7404 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7405
7406 // Parses the command line for Google Test flags, without initializing
7407 // other parts of Google Test. The type parameter CharType can be
7408 // instantiated to either char or wchar_t.
7409 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)7410 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
7411 for (int i = 1; i < *argc; i++) {
7412 const std::string arg_string = StreamableToString(argv[i]);
7413 const char* const arg = arg_string.c_str();
7414
7415 using internal::ParseBoolFlag;
7416 using internal::ParseInt32Flag;
7417 using internal::ParseStringFlag;
7418
7419 bool remove_flag = false;
7420 if (ParseGoogleTestFlag(arg)) {
7421 remove_flag = true;
7422 #if GTEST_USE_OWN_FLAGFILE_FLAG_
7423 } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) {
7424 LoadFlagsFromFile(GTEST_FLAG(flagfile));
7425 remove_flag = true;
7426 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7427 } else if (arg_string == "--help" || arg_string == "-h" ||
7428 arg_string == "-?" || arg_string == "/?" ||
7429 HasGoogleTestFlagPrefix(arg)) {
7430 // Both help flag and unrecognized Google Test flags (excluding
7431 // internal ones) trigger help display.
7432 g_help_flag = true;
7433 }
7434
7435 if (remove_flag) {
7436 // Shift the remainder of the argv list left by one. Note
7437 // that argv has (*argc + 1) elements, the last one always being
7438 // NULL. The following loop moves the trailing NULL element as
7439 // well.
7440 for (int j = i; j != *argc; j++) {
7441 argv[j] = argv[j + 1];
7442 }
7443
7444 // Decrements the argument count.
7445 (*argc)--;
7446
7447 // We also need to decrement the iterator as we just removed
7448 // an element.
7449 i--;
7450 }
7451 }
7452
7453 if (g_help_flag) {
7454 // We print the help here instead of in RUN_ALL_TESTS(), as the
7455 // latter may not be called at all if the user is using Google
7456 // Test with another testing framework.
7457 PrintColorEncoded(kColorEncodedHelpMessage);
7458 }
7459 }
7460
7461 // Parses the command line for Google Test flags, without initializing
7462 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)7463 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
7464 ParseGoogleTestFlagsOnlyImpl(argc, argv);
7465
7466 // Fix the value of *_NSGetArgc() on macOS, but iff
7467 // *_NSGetArgv() == argv
7468 // Only applicable to char** version of argv
7469 #if GTEST_OS_MAC
7470 #ifndef GTEST_OS_IOS
7471 if (*_NSGetArgv() == argv) {
7472 *_NSGetArgc() = *argc;
7473 }
7474 #endif
7475 #endif
7476 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)7477 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
7478 ParseGoogleTestFlagsOnlyImpl(argc, argv);
7479 }
7480
7481 // The internal implementation of InitGoogleTest().
7482 //
7483 // The type parameter CharType can be instantiated to either char or
7484 // wchar_t.
7485 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)7486 void InitGoogleTestImpl(int* argc, CharType** argv) {
7487 // We don't want to run the initialization code twice.
7488 if (GTestIsInitialized()) return;
7489
7490 if (*argc <= 0) return;
7491
7492 g_argvs.clear();
7493 for (int i = 0; i != *argc; i++) {
7494 g_argvs.push_back(StreamableToString(argv[i]));
7495 }
7496
7497 #if GTEST_HAS_ABSL
7498 absl::InitializeSymbolizer(g_argvs[0].c_str());
7499 #endif // GTEST_HAS_ABSL
7500
7501 ParseGoogleTestFlagsOnly(argc, argv);
7502 GetUnitTestImpl()->PostFlagParsingInit();
7503 }
7504
7505 } // namespace internal
7506
7507 // Initializes Google Test. This must be called before calling
7508 // RUN_ALL_TESTS(). In particular, it parses a command line for the
7509 // flags that Google Test recognizes. Whenever a Google Test flag is
7510 // seen, it is removed from argv, and *argc is decremented.
7511 //
7512 // No value is returned. Instead, the Google Test flag variables are
7513 // updated.
7514 //
7515 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)7516 void InitGoogleTest(int* argc, char** argv) {
7517 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7518 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7519 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7520 internal::InitGoogleTestImpl(argc, argv);
7521 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7522 }
7523
7524 // This overloaded version can be used in Windows programs compiled in
7525 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)7526 void InitGoogleTest(int* argc, wchar_t** argv) {
7527 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7528 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7529 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7530 internal::InitGoogleTestImpl(argc, argv);
7531 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7532 }
7533
7534 // This overloaded version can be used on Arduino/embedded platforms where
7535 // there is no argc/argv.
InitGoogleTest()7536 void InitGoogleTest() {
7537 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
7538 int argc = 1;
7539 const auto arg0 = "dummy";
7540 char* argv0 = const_cast<char*>(arg0);
7541 char** argv = &argv0;
7542
7543 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7544 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
7545 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7546 internal::InitGoogleTestImpl(&argc, argv);
7547 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7548 }
7549
TempDir()7550 std::string TempDir() {
7551 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7552 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7553 #endif
7554
7555 #if GTEST_OS_WINDOWS_MOBILE
7556 return "\\temp\\";
7557 #elif GTEST_OS_WINDOWS
7558 const char* temp_dir = internal::posix::GetEnv("TEMP");
7559 if (temp_dir == nullptr || temp_dir[0] == '\0')
7560 return "\\temp\\";
7561 else if (temp_dir[strlen(temp_dir) - 1] == '\\')
7562 return temp_dir;
7563 else
7564 return std::string(temp_dir) + "\\";
7565 #elif GTEST_OS_LINUX_ANDROID
7566 return "/sdcard/";
7567 #else
7568 return "/tmp/";
7569 #endif // GTEST_OS_WINDOWS_MOBILE
7570 }
7571
7572 // Class ScopedTrace
7573
7574 // Pushes the given source file location and message onto a per-thread
7575 // trace stack maintained by Google Test.
PushTrace(const char * file,int line,std::string message)7576 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7577 internal::TraceInfo trace;
7578 trace.file = file;
7579 trace.line = line;
7580 trace.message.swap(message);
7581
7582 UnitTest::GetInstance()->PushGTestTrace(trace);
7583 }
7584
7585 // Pops the info pushed by the c'tor.
~ScopedTrace()7586 ScopedTrace::~ScopedTrace()
7587 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7588 UnitTest::GetInstance()->PopGTestTrace();
7589 }
7590
7591 } // namespace testing
7592 // Copyright 2005, Google Inc.
7593 // All rights reserved.
7594 //
7595 // Redistribution and use in source and binary forms, with or without
7596 // modification, are permitted provided that the following conditions are
7597 // met:
7598 //
7599 // * Redistributions of source code must retain the above copyright
7600 // notice, this list of conditions and the following disclaimer.
7601 // * Redistributions in binary form must reproduce the above
7602 // copyright notice, this list of conditions and the following disclaimer
7603 // in the documentation and/or other materials provided with the
7604 // distribution.
7605 // * Neither the name of Google Inc. nor the names of its
7606 // contributors may be used to endorse or promote products derived from
7607 // this software without specific prior written permission.
7608 //
7609 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7610 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7611 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7612 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7613 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7614 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7615 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7616 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7617 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7618 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7619 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7620
7621 //
7622 // This file implements death tests.
7623
7624
7625 #include <utility>
7626
7627
7628 #if GTEST_HAS_DEATH_TEST
7629
7630 # if GTEST_OS_MAC
7631 # include <crt_externs.h>
7632 # endif // GTEST_OS_MAC
7633
7634 # include <errno.h>
7635 # include <fcntl.h>
7636 # include <limits.h>
7637
7638 # if GTEST_OS_LINUX
7639 # include <signal.h>
7640 # endif // GTEST_OS_LINUX
7641
7642 # include <stdarg.h>
7643
7644 # if GTEST_OS_WINDOWS
7645 # include <windows.h>
7646 # else
7647 # include <sys/mman.h>
7648 # include <sys/wait.h>
7649 # endif // GTEST_OS_WINDOWS
7650
7651 # if GTEST_OS_QNX
7652 # include <spawn.h>
7653 # endif // GTEST_OS_QNX
7654
7655 # if GTEST_OS_FUCHSIA
7656 # include <lib/fdio/fd.h>
7657 # include <lib/fdio/io.h>
7658 # include <lib/fdio/spawn.h>
7659 # include <lib/zx/port.h>
7660 # include <lib/zx/process.h>
7661 # include <lib/zx/socket.h>
7662 # include <zircon/processargs.h>
7663 # include <zircon/syscalls.h>
7664 # include <zircon/syscalls/policy.h>
7665 # include <zircon/syscalls/port.h>
7666 # endif // GTEST_OS_FUCHSIA
7667
7668 #endif // GTEST_HAS_DEATH_TEST
7669
7670
7671 namespace testing {
7672
7673 // Constants.
7674
7675 // The default death test style.
7676 //
7677 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
7678 // a definition in internal/custom/gtest-port.h. The recommended value, which is
7679 // used internally at Google, is "threadsafe".
7680 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
7681
7682 GTEST_DEFINE_string_(
7683 death_test_style,
7684 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
7685 "Indicates how to run a death test in a forked child process: "
7686 "\"threadsafe\" (child process re-executes the test binary "
7687 "from the beginning, running only the specific death test) or "
7688 "\"fast\" (child process runs the death test immediately "
7689 "after forking).");
7690
7691 GTEST_DEFINE_bool_(
7692 death_test_use_fork,
7693 internal::BoolFromGTestEnv("death_test_use_fork", false),
7694 "Instructs to use fork()/_exit() instead of clone() in death tests. "
7695 "Ignored and always uses fork() on POSIX systems where clone() is not "
7696 "implemented. Useful when running under valgrind or similar tools if "
7697 "those do not support clone(). Valgrind 3.3.1 will just fail if "
7698 "it sees an unsupported combination of clone() flags. "
7699 "It is not recommended to use this flag w/o valgrind though it will "
7700 "work in 99% of the cases. Once valgrind is fixed, this flag will "
7701 "most likely be removed.");
7702
7703 namespace internal {
7704 GTEST_DEFINE_string_(
7705 internal_run_death_test, "",
7706 "Indicates the file, line number, temporal index of "
7707 "the single death test to run, and a file descriptor to "
7708 "which a success code may be sent, all separated by "
7709 "the '|' characters. This flag is specified if and only if the current "
7710 "process is a sub-process launched for running a thread-safe "
7711 "death test. FOR INTERNAL USE ONLY.");
7712 } // namespace internal
7713
7714 #if GTEST_HAS_DEATH_TEST
7715
7716 namespace internal {
7717
7718 // Valid only for fast death tests. Indicates the code is running in the
7719 // child process of a fast style death test.
7720 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7721 static bool g_in_fast_death_test_child = false;
7722 # endif
7723
7724 // Returns a Boolean value indicating whether the caller is currently
7725 // executing in the context of the death test child process. Tools such as
7726 // Valgrind heap checkers may need this to modify their behavior in death
7727 // tests. IMPORTANT: This is an internal utility. Using it may break the
7728 // implementation of death tests. User code MUST NOT use it.
InDeathTestChild()7729 bool InDeathTestChild() {
7730 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7731
7732 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
7733 // of the death_test_style flag.
7734 return !GTEST_FLAG(internal_run_death_test).empty();
7735
7736 # else
7737
7738 if (GTEST_FLAG(death_test_style) == "threadsafe")
7739 return !GTEST_FLAG(internal_run_death_test).empty();
7740 else
7741 return g_in_fast_death_test_child;
7742 #endif
7743 }
7744
7745 } // namespace internal
7746
7747 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)7748 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
7749 }
7750
7751 // ExitedWithCode function-call operator.
operator ()(int exit_status) const7752 bool ExitedWithCode::operator()(int exit_status) const {
7753 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7754
7755 return exit_status == exit_code_;
7756
7757 # else
7758
7759 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7760
7761 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7762 }
7763
7764 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7765 // KilledBySignal constructor.
KilledBySignal(int signum)7766 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7767 }
7768
7769 // KilledBySignal function-call operator.
operator ()(int exit_status) const7770 bool KilledBySignal::operator()(int exit_status) const {
7771 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7772 {
7773 bool result;
7774 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7775 return result;
7776 }
7777 }
7778 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7779 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7780 }
7781 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7782
7783 namespace internal {
7784
7785 // Utilities needed for death tests.
7786
7787 // Generates a textual description of a given exit code, in the format
7788 // specified by wait(2).
ExitSummary(int exit_code)7789 static std::string ExitSummary(int exit_code) {
7790 Message m;
7791
7792 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7793
7794 m << "Exited with exit status " << exit_code;
7795
7796 # else
7797
7798 if (WIFEXITED(exit_code)) {
7799 m << "Exited with exit status " << WEXITSTATUS(exit_code);
7800 } else if (WIFSIGNALED(exit_code)) {
7801 m << "Terminated by signal " << WTERMSIG(exit_code);
7802 }
7803 # ifdef WCOREDUMP
7804 if (WCOREDUMP(exit_code)) {
7805 m << " (core dumped)";
7806 }
7807 # endif
7808 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7809
7810 return m.GetString();
7811 }
7812
7813 // Returns true if exit_status describes a process that was terminated
7814 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)7815 bool ExitedUnsuccessfully(int exit_status) {
7816 return !ExitedWithCode(0)(exit_status);
7817 }
7818
7819 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7820 // Generates a textual failure message when a death test finds more than
7821 // one thread running, or cannot determine the number of threads, prior
7822 // to executing the given statement. It is the responsibility of the
7823 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)7824 static std::string DeathTestThreadWarning(size_t thread_count) {
7825 Message msg;
7826 msg << "Death tests use fork(), which is unsafe particularly"
7827 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7828 if (thread_count == 0) {
7829 msg << "couldn't detect the number of threads.";
7830 } else {
7831 msg << "detected " << thread_count << " threads.";
7832 }
7833 msg << " See "
7834 "https://github.com/google/googletest/blob/master/googletest/docs/"
7835 "advanced.md#death-tests-and-threads"
7836 << " for more explanation and suggested solutions, especially if"
7837 << " this is the last message you see before your test times out.";
7838 return msg.GetString();
7839 }
7840 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7841
7842 // Flag characters for reporting a death test that did not die.
7843 static const char kDeathTestLived = 'L';
7844 static const char kDeathTestReturned = 'R';
7845 static const char kDeathTestThrew = 'T';
7846 static const char kDeathTestInternalError = 'I';
7847
7848 #if GTEST_OS_FUCHSIA
7849
7850 // File descriptor used for the pipe in the child process.
7851 static const int kFuchsiaReadPipeFd = 3;
7852
7853 #endif
7854
7855 // An enumeration describing all of the possible ways that a death test can
7856 // conclude. DIED means that the process died while executing the test
7857 // code; LIVED means that process lived beyond the end of the test code;
7858 // RETURNED means that the test statement attempted to execute a return
7859 // statement, which is not allowed; THREW means that the test statement
7860 // returned control by throwing an exception. IN_PROGRESS means the test
7861 // has not yet concluded.
7862 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7863
7864 // Routine for aborting the program which is safe to call from an
7865 // exec-style death test child process, in which case the error
7866 // message is propagated back to the parent process. Otherwise, the
7867 // message is simply printed to stderr. In either case, the program
7868 // then exits with status 1.
DeathTestAbort(const std::string & message)7869 static void DeathTestAbort(const std::string& message) {
7870 // On a POSIX system, this function may be called from a threadsafe-style
7871 // death test child process, which operates on a very small stack. Use
7872 // the heap for any additional non-minuscule memory requirements.
7873 const InternalRunDeathTestFlag* const flag =
7874 GetUnitTestImpl()->internal_run_death_test_flag();
7875 if (flag != nullptr) {
7876 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7877 fputc(kDeathTestInternalError, parent);
7878 fprintf(parent, "%s", message.c_str());
7879 fflush(parent);
7880 _exit(1);
7881 } else {
7882 fprintf(stderr, "%s", message.c_str());
7883 fflush(stderr);
7884 posix::Abort();
7885 }
7886 }
7887
7888 // A replacement for CHECK that calls DeathTestAbort if the assertion
7889 // fails.
7890 # define GTEST_DEATH_TEST_CHECK_(expression) \
7891 do { \
7892 if (!::testing::internal::IsTrue(expression)) { \
7893 DeathTestAbort( \
7894 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7895 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7896 + #expression); \
7897 } \
7898 } while (::testing::internal::AlwaysFalse())
7899
7900 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7901 // evaluating any system call that fulfills two conditions: it must return
7902 // -1 on failure, and set errno to EINTR when it is interrupted and
7903 // should be tried again. The macro expands to a loop that repeatedly
7904 // evaluates the expression as long as it evaluates to -1 and sets
7905 // errno to EINTR. If the expression evaluates to -1 but errno is
7906 // something other than EINTR, DeathTestAbort is called.
7907 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7908 do { \
7909 int gtest_retval; \
7910 do { \
7911 gtest_retval = (expression); \
7912 } while (gtest_retval == -1 && errno == EINTR); \
7913 if (gtest_retval == -1) { \
7914 DeathTestAbort( \
7915 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7916 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7917 + #expression + " != -1"); \
7918 } \
7919 } while (::testing::internal::AlwaysFalse())
7920
7921 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()7922 std::string GetLastErrnoDescription() {
7923 return errno == 0 ? "" : posix::StrError(errno);
7924 }
7925
7926 // This is called from a death test parent process to read a failure
7927 // message from the death test child process and log it with the FATAL
7928 // severity. On Windows, the message is read from a pipe handle. On other
7929 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)7930 static void FailFromInternalError(int fd) {
7931 Message error;
7932 char buffer[256];
7933 int num_read;
7934
7935 do {
7936 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7937 buffer[num_read] = '\0';
7938 error << buffer;
7939 }
7940 } while (num_read == -1 && errno == EINTR);
7941
7942 if (num_read == 0) {
7943 GTEST_LOG_(FATAL) << error.GetString();
7944 } else {
7945 const int last_error = errno;
7946 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7947 << GetLastErrnoDescription() << " [" << last_error << "]";
7948 }
7949 }
7950
7951 // Death test constructor. Increments the running death test count
7952 // for the current test.
DeathTest()7953 DeathTest::DeathTest() {
7954 TestInfo* const info = GetUnitTestImpl()->current_test_info();
7955 if (info == nullptr) {
7956 DeathTestAbort("Cannot run a death test outside of a TEST or "
7957 "TEST_F construct");
7958 }
7959 }
7960
7961 // Creates and returns a death test by dispatching to the current
7962 // death test factory.
Create(const char * statement,Matcher<const std::string &> matcher,const char * file,int line,DeathTest ** test)7963 bool DeathTest::Create(const char* statement,
7964 Matcher<const std::string&> matcher, const char* file,
7965 int line, DeathTest** test) {
7966 return GetUnitTestImpl()->death_test_factory()->Create(
7967 statement, std::move(matcher), file, line, test);
7968 }
7969
LastMessage()7970 const char* DeathTest::LastMessage() {
7971 return last_death_test_message_.c_str();
7972 }
7973
set_last_death_test_message(const std::string & message)7974 void DeathTest::set_last_death_test_message(const std::string& message) {
7975 last_death_test_message_ = message;
7976 }
7977
7978 std::string DeathTest::last_death_test_message_;
7979
7980 // Provides cross platform implementation for some death functionality.
7981 class DeathTestImpl : public DeathTest {
7982 protected:
DeathTestImpl(const char * a_statement,Matcher<const std::string &> matcher)7983 DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
7984 : statement_(a_statement),
7985 matcher_(std::move(matcher)),
7986 spawned_(false),
7987 status_(-1),
7988 outcome_(IN_PROGRESS),
7989 read_fd_(-1),
7990 write_fd_(-1) {}
7991
7992 // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()7993 ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7994
7995 void Abort(AbortReason reason) override;
7996 bool Passed(bool status_ok) override;
7997
statement() const7998 const char* statement() const { return statement_; }
spawned() const7999 bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)8000 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const8001 int status() const { return status_; }
set_status(int a_status)8002 void set_status(int a_status) { status_ = a_status; }
outcome() const8003 DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)8004 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const8005 int read_fd() const { return read_fd_; }
set_read_fd(int fd)8006 void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const8007 int write_fd() const { return write_fd_; }
set_write_fd(int fd)8008 void set_write_fd(int fd) { write_fd_ = fd; }
8009
8010 // Called in the parent process only. Reads the result code of the death
8011 // test child process via a pipe, interprets it to set the outcome_
8012 // member, and closes read_fd_. Outputs diagnostics and terminates in
8013 // case of unexpected codes.
8014 void ReadAndInterpretStatusByte();
8015
8016 // Returns stderr output from the child process.
8017 virtual std::string GetErrorLogs();
8018
8019 private:
8020 // The textual content of the code this object is testing. This class
8021 // doesn't own this string and should not attempt to delete it.
8022 const char* const statement_;
8023 // A matcher that's expected to match the stderr output by the child process.
8024 Matcher<const std::string&> matcher_;
8025 // True if the death test child process has been successfully spawned.
8026 bool spawned_;
8027 // The exit status of the child process.
8028 int status_;
8029 // How the death test concluded.
8030 DeathTestOutcome outcome_;
8031 // Descriptor to the read end of the pipe to the child process. It is
8032 // always -1 in the child process. The child keeps its write end of the
8033 // pipe in write_fd_.
8034 int read_fd_;
8035 // Descriptor to the child's write end of the pipe to the parent process.
8036 // It is always -1 in the parent process. The parent keeps its end of the
8037 // pipe in read_fd_.
8038 int write_fd_;
8039 };
8040
8041 // Called in the parent process only. Reads the result code of the death
8042 // test child process via a pipe, interprets it to set the outcome_
8043 // member, and closes read_fd_. Outputs diagnostics and terminates in
8044 // case of unexpected codes.
ReadAndInterpretStatusByte()8045 void DeathTestImpl::ReadAndInterpretStatusByte() {
8046 char flag;
8047 int bytes_read;
8048
8049 // The read() here blocks until data is available (signifying the
8050 // failure of the death test) or until the pipe is closed (signifying
8051 // its success), so it's okay to call this in the parent before
8052 // the child process has exited.
8053 do {
8054 bytes_read = posix::Read(read_fd(), &flag, 1);
8055 } while (bytes_read == -1 && errno == EINTR);
8056
8057 if (bytes_read == 0) {
8058 set_outcome(DIED);
8059 } else if (bytes_read == 1) {
8060 switch (flag) {
8061 case kDeathTestReturned:
8062 set_outcome(RETURNED);
8063 break;
8064 case kDeathTestThrew:
8065 set_outcome(THREW);
8066 break;
8067 case kDeathTestLived:
8068 set_outcome(LIVED);
8069 break;
8070 case kDeathTestInternalError:
8071 FailFromInternalError(read_fd()); // Does not return.
8072 break;
8073 default:
8074 GTEST_LOG_(FATAL) << "Death test child process reported "
8075 << "unexpected status byte ("
8076 << static_cast<unsigned int>(flag) << ")";
8077 }
8078 } else {
8079 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
8080 << GetLastErrnoDescription();
8081 }
8082 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
8083 set_read_fd(-1);
8084 }
8085
GetErrorLogs()8086 std::string DeathTestImpl::GetErrorLogs() {
8087 return GetCapturedStderr();
8088 }
8089
8090 // Signals that the death test code which should have exited, didn't.
8091 // Should be called only in a death test child process.
8092 // Writes a status byte to the child's status file descriptor, then
8093 // calls _exit(1).
Abort(AbortReason reason)8094 void DeathTestImpl::Abort(AbortReason reason) {
8095 // The parent process considers the death test to be a failure if
8096 // it finds any data in our pipe. So, here we write a single flag byte
8097 // to the pipe, then exit.
8098 const char status_ch =
8099 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8100 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8101
8102 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8103 // We are leaking the descriptor here because on some platforms (i.e.,
8104 // when built as Windows DLL), destructors of global objects will still
8105 // run after calling _exit(). On such systems, write_fd_ will be
8106 // indirectly closed from the destructor of UnitTestImpl, causing double
8107 // close if it is also closed here. On debug configurations, double close
8108 // may assert. As there are no in-process buffers to flush here, we are
8109 // relying on the OS to close the descriptor after the process terminates
8110 // when the destructors are not run.
8111 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
8112 }
8113
8114 // Returns an indented copy of stderr output for a death test.
8115 // This makes distinguishing death test output lines from regular log lines
8116 // much easier.
FormatDeathTestOutput(const::std::string & output)8117 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8118 ::std::string ret;
8119 for (size_t at = 0; ; ) {
8120 const size_t line_end = output.find('\n', at);
8121 ret += "[ DEATH ] ";
8122 if (line_end == ::std::string::npos) {
8123 ret += output.substr(at);
8124 break;
8125 }
8126 ret += output.substr(at, line_end + 1 - at);
8127 at = line_end + 1;
8128 }
8129 return ret;
8130 }
8131
8132 // Assesses the success or failure of a death test, using both private
8133 // members which have previously been set, and one argument:
8134 //
8135 // Private data members:
8136 // outcome: An enumeration describing how the death test
8137 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
8138 // fails in the latter three cases.
8139 // status: The exit status of the child process. On *nix, it is in the
8140 // in the format specified by wait(2). On Windows, this is the
8141 // value supplied to the ExitProcess() API or a numeric code
8142 // of the exception that terminated the program.
8143 // matcher_: A matcher that's expected to match the stderr output by the child
8144 // process.
8145 //
8146 // Argument:
8147 // status_ok: true if exit_status is acceptable in the context of
8148 // this particular death test, which fails if it is false
8149 //
8150 // Returns true iff all of the above conditions are met. Otherwise, the
8151 // first failing condition, in the order given above, is the one that is
8152 // reported. Also sets the last death test message string.
Passed(bool status_ok)8153 bool DeathTestImpl::Passed(bool status_ok) {
8154 if (!spawned())
8155 return false;
8156
8157 const std::string error_message = GetErrorLogs();
8158
8159 bool success = false;
8160 Message buffer;
8161
8162 buffer << "Death test: " << statement() << "\n";
8163 switch (outcome()) {
8164 case LIVED:
8165 buffer << " Result: failed to die.\n"
8166 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8167 break;
8168 case THREW:
8169 buffer << " Result: threw an exception.\n"
8170 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8171 break;
8172 case RETURNED:
8173 buffer << " Result: illegal return in test statement.\n"
8174 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8175 break;
8176 case DIED:
8177 if (status_ok) {
8178 if (matcher_.Matches(error_message)) {
8179 success = true;
8180 } else {
8181 std::ostringstream stream;
8182 matcher_.DescribeTo(&stream);
8183 buffer << " Result: died but not with expected error.\n"
8184 << " Expected: " << stream.str() << "\n"
8185 << "Actual msg:\n"
8186 << FormatDeathTestOutput(error_message);
8187 }
8188 } else {
8189 buffer << " Result: died but not with expected exit code:\n"
8190 << " " << ExitSummary(status()) << "\n"
8191 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8192 }
8193 break;
8194 case IN_PROGRESS:
8195 default:
8196 GTEST_LOG_(FATAL)
8197 << "DeathTest::Passed somehow called before conclusion of test";
8198 }
8199
8200 DeathTest::set_last_death_test_message(buffer.GetString());
8201 return success;
8202 }
8203
8204 # if GTEST_OS_WINDOWS
8205 // WindowsDeathTest implements death tests on Windows. Due to the
8206 // specifics of starting new processes on Windows, death tests there are
8207 // always threadsafe, and Google Test considers the
8208 // --gtest_death_test_style=fast setting to be equivalent to
8209 // --gtest_death_test_style=threadsafe there.
8210 //
8211 // A few implementation notes: Like the Linux version, the Windows
8212 // implementation uses pipes for child-to-parent communication. But due to
8213 // the specifics of pipes on Windows, some extra steps are required:
8214 //
8215 // 1. The parent creates a communication pipe and stores handles to both
8216 // ends of it.
8217 // 2. The parent starts the child and provides it with the information
8218 // necessary to acquire the handle to the write end of the pipe.
8219 // 3. The child acquires the write end of the pipe and signals the parent
8220 // using a Windows event.
8221 // 4. Now the parent can release the write end of the pipe on its side. If
8222 // this is done before step 3, the object's reference count goes down to
8223 // 0 and it is destroyed, preventing the child from acquiring it. The
8224 // parent now has to release it, or read operations on the read end of
8225 // the pipe will not return when the child terminates.
8226 // 5. The parent reads child's output through the pipe (outcome code and
8227 // any possible error messages) from the pipe, and its stderr and then
8228 // determines whether to fail the test.
8229 //
8230 // Note: to distinguish Win32 API calls from the local method and function
8231 // calls, the former are explicitly resolved in the global namespace.
8232 //
8233 class WindowsDeathTest : public DeathTestImpl {
8234 public:
WindowsDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)8235 WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8236 const char* file, int line)
8237 : DeathTestImpl(a_statement, std::move(matcher)),
8238 file_(file),
8239 line_(line) {}
8240
8241 // All of these virtual functions are inherited from DeathTest.
8242 virtual int Wait();
8243 virtual TestRole AssumeRole();
8244
8245 private:
8246 // The name of the file in which the death test is located.
8247 const char* const file_;
8248 // The line number on which the death test is located.
8249 const int line_;
8250 // Handle to the write end of the pipe to the child process.
8251 AutoHandle write_handle_;
8252 // Child process handle.
8253 AutoHandle child_handle_;
8254 // Event the child process uses to signal the parent that it has
8255 // acquired the handle to the write end of the pipe. After seeing this
8256 // event the parent can release its own handles to make sure its
8257 // ReadFile() calls return when the child terminates.
8258 AutoHandle event_handle_;
8259 };
8260
8261 // Waits for the child in a death test to exit, returning its exit
8262 // status, or 0 if no child process exists. As a side effect, sets the
8263 // outcome data member.
Wait()8264 int WindowsDeathTest::Wait() {
8265 if (!spawned())
8266 return 0;
8267
8268 // Wait until the child either signals that it has acquired the write end
8269 // of the pipe or it dies.
8270 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8271 switch (::WaitForMultipleObjects(2,
8272 wait_handles,
8273 FALSE, // Waits for any of the handles.
8274 INFINITE)) {
8275 case WAIT_OBJECT_0:
8276 case WAIT_OBJECT_0 + 1:
8277 break;
8278 default:
8279 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
8280 }
8281
8282 // The child has acquired the write end of the pipe or exited.
8283 // We release the handle on our side and continue.
8284 write_handle_.Reset();
8285 event_handle_.Reset();
8286
8287 ReadAndInterpretStatusByte();
8288
8289 // Waits for the child process to exit if it haven't already. This
8290 // returns immediately if the child has already exited, regardless of
8291 // whether previous calls to WaitForMultipleObjects synchronized on this
8292 // handle or not.
8293 GTEST_DEATH_TEST_CHECK_(
8294 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8295 INFINITE));
8296 DWORD status_code;
8297 GTEST_DEATH_TEST_CHECK_(
8298 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8299 child_handle_.Reset();
8300 set_status(static_cast<int>(status_code));
8301 return status();
8302 }
8303
8304 // The AssumeRole process for a Windows death test. It creates a child
8305 // process with the same executable as the current process to run the
8306 // death test. The child process is given the --gtest_filter and
8307 // --gtest_internal_run_death_test flags such that it knows to run the
8308 // current death test only.
AssumeRole()8309 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8310 const UnitTestImpl* const impl = GetUnitTestImpl();
8311 const InternalRunDeathTestFlag* const flag =
8312 impl->internal_run_death_test_flag();
8313 const TestInfo* const info = impl->current_test_info();
8314 const int death_test_index = info->result()->death_test_count();
8315
8316 if (flag != nullptr) {
8317 // ParseInternalRunDeathTestFlag() has performed all the necessary
8318 // processing.
8319 set_write_fd(flag->write_fd());
8320 return EXECUTE_TEST;
8321 }
8322
8323 // WindowsDeathTest uses an anonymous pipe to communicate results of
8324 // a death test.
8325 SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
8326 nullptr, TRUE};
8327 HANDLE read_handle, write_handle;
8328 GTEST_DEATH_TEST_CHECK_(
8329 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8330 0) // Default buffer size.
8331 != FALSE);
8332 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8333 O_RDONLY));
8334 write_handle_.Reset(write_handle);
8335 event_handle_.Reset(::CreateEvent(
8336 &handles_are_inheritable,
8337 TRUE, // The event will automatically reset to non-signaled state.
8338 FALSE, // The initial state is non-signalled.
8339 nullptr)); // The even is unnamed.
8340 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
8341 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8342 kFilterFlag + "=" + info->test_suite_name() +
8343 "." + info->name();
8344 const std::string internal_flag =
8345 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8346 "=" + file_ + "|" + StreamableToString(line_) + "|" +
8347 StreamableToString(death_test_index) + "|" +
8348 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8349 // size_t has the same width as pointers on both 32-bit and 64-bit
8350 // Windows platforms.
8351 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8352 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
8353 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
8354
8355 char executable_path[_MAX_PATH + 1]; // NOLINT
8356 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
8357 executable_path,
8358 _MAX_PATH));
8359
8360 std::string command_line =
8361 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
8362 internal_flag + "\"";
8363
8364 DeathTest::set_last_death_test_message("");
8365
8366 CaptureStderr();
8367 // Flush the log buffers since the log streams are shared with the child.
8368 FlushInfoLog();
8369
8370 // The child process will share the standard handles with the parent.
8371 STARTUPINFOA startup_info;
8372 memset(&startup_info, 0, sizeof(STARTUPINFO));
8373 startup_info.dwFlags = STARTF_USESTDHANDLES;
8374 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8375 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8376 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8377
8378 PROCESS_INFORMATION process_info;
8379 GTEST_DEATH_TEST_CHECK_(
8380 ::CreateProcessA(
8381 executable_path, const_cast<char*>(command_line.c_str()),
8382 nullptr, // Retuned process handle is not inheritable.
8383 nullptr, // Retuned thread handle is not inheritable.
8384 TRUE, // Child inherits all inheritable handles (for write_handle_).
8385 0x0, // Default creation flags.
8386 nullptr, // Inherit the parent's environment.
8387 UnitTest::GetInstance()->original_working_dir(), &startup_info,
8388 &process_info) != FALSE);
8389 child_handle_.Reset(process_info.hProcess);
8390 ::CloseHandle(process_info.hThread);
8391 set_spawned(true);
8392 return OVERSEE_TEST;
8393 }
8394
8395 # elif GTEST_OS_FUCHSIA
8396
8397 class FuchsiaDeathTest : public DeathTestImpl {
8398 public:
FuchsiaDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)8399 FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8400 const char* file, int line)
8401 : DeathTestImpl(a_statement, std::move(matcher)),
8402 file_(file),
8403 line_(line) {}
8404
8405 // All of these virtual functions are inherited from DeathTest.
8406 int Wait() override;
8407 TestRole AssumeRole() override;
8408 std::string GetErrorLogs() override;
8409
8410 private:
8411 // The name of the file in which the death test is located.
8412 const char* const file_;
8413 // The line number on which the death test is located.
8414 const int line_;
8415 // The stderr data captured by the child process.
8416 std::string captured_stderr_;
8417
8418 zx::process child_process_;
8419 zx::port port_;
8420 zx::socket stderr_socket_;
8421 };
8422
8423 // Utility class for accumulating command-line arguments.
8424 class Arguments {
8425 public:
Arguments()8426 Arguments() { args_.push_back(nullptr); }
8427
~Arguments()8428 ~Arguments() {
8429 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8430 ++i) {
8431 free(*i);
8432 }
8433 }
AddArgument(const char * argument)8434 void AddArgument(const char* argument) {
8435 args_.insert(args_.end() - 1, posix::StrDup(argument));
8436 }
8437
8438 template <typename Str>
AddArguments(const::std::vector<Str> & arguments)8439 void AddArguments(const ::std::vector<Str>& arguments) {
8440 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8441 i != arguments.end();
8442 ++i) {
8443 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8444 }
8445 }
Argv()8446 char* const* Argv() {
8447 return &args_[0];
8448 }
8449
size()8450 int size() {
8451 return args_.size() - 1;
8452 }
8453
8454 private:
8455 std::vector<char*> args_;
8456 };
8457
8458 // Waits for the child in a death test to exit, returning its exit
8459 // status, or 0 if no child process exists. As a side effect, sets the
8460 // outcome data member.
Wait()8461 int FuchsiaDeathTest::Wait() {
8462 const int kProcessKey = 0;
8463 const int kSocketKey = 1;
8464
8465 if (!spawned())
8466 return 0;
8467
8468 // Register to wait for the child process to terminate.
8469 zx_status_t status_zx;
8470 status_zx = child_process_.wait_async(
8471 port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
8472 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8473 // Register to wait for the socket to be readable or closed.
8474 status_zx = stderr_socket_.wait_async(
8475 port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
8476 ZX_WAIT_ASYNC_REPEATING);
8477 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8478
8479 bool process_terminated = false;
8480 bool socket_closed = false;
8481 do {
8482 zx_port_packet_t packet = {};
8483 status_zx = port_.wait(zx::time::infinite(), &packet);
8484 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8485
8486 if (packet.key == kProcessKey) {
8487 if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8488 // Process encountered an exception. Kill it directly rather than
8489 // letting other handlers process the event. We will get a second
8490 // kProcessKey event when the process actually terminates.
8491 status_zx = child_process_.kill();
8492 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8493 } else {
8494 // Process terminated.
8495 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8496 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8497 process_terminated = true;
8498 }
8499 } else if (packet.key == kSocketKey) {
8500 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type));
8501 if (packet.signal.observed & ZX_SOCKET_READABLE) {
8502 // Read data from the socket.
8503 constexpr size_t kBufferSize = 1024;
8504 do {
8505 size_t old_length = captured_stderr_.length();
8506 size_t bytes_read = 0;
8507 captured_stderr_.resize(old_length + kBufferSize);
8508 status_zx = stderr_socket_.read(
8509 0, &captured_stderr_.front() + old_length, kBufferSize,
8510 &bytes_read);
8511 captured_stderr_.resize(old_length + bytes_read);
8512 } while (status_zx == ZX_OK);
8513 if (status_zx == ZX_ERR_PEER_CLOSED) {
8514 socket_closed = true;
8515 } else {
8516 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
8517 }
8518 } else {
8519 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
8520 socket_closed = true;
8521 }
8522 }
8523 } while (!process_terminated && !socket_closed);
8524
8525 ReadAndInterpretStatusByte();
8526
8527 zx_info_process_t buffer;
8528 status_zx = child_process_.get_info(
8529 ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
8530 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8531
8532 GTEST_DEATH_TEST_CHECK_(buffer.exited);
8533 set_status(buffer.return_code);
8534 return status();
8535 }
8536
8537 // The AssumeRole process for a Fuchsia death test. It creates a child
8538 // process with the same executable as the current process to run the
8539 // death test. The child process is given the --gtest_filter and
8540 // --gtest_internal_run_death_test flags such that it knows to run the
8541 // current death test only.
AssumeRole()8542 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8543 const UnitTestImpl* const impl = GetUnitTestImpl();
8544 const InternalRunDeathTestFlag* const flag =
8545 impl->internal_run_death_test_flag();
8546 const TestInfo* const info = impl->current_test_info();
8547 const int death_test_index = info->result()->death_test_count();
8548
8549 if (flag != nullptr) {
8550 // ParseInternalRunDeathTestFlag() has performed all the necessary
8551 // processing.
8552 set_write_fd(kFuchsiaReadPipeFd);
8553 return EXECUTE_TEST;
8554 }
8555
8556 // Flush the log buffers since the log streams are shared with the child.
8557 FlushInfoLog();
8558
8559 // Build the child process command line.
8560 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8561 kFilterFlag + "=" + info->test_suite_name() +
8562 "." + info->name();
8563 const std::string internal_flag =
8564 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8565 + file_ + "|"
8566 + StreamableToString(line_) + "|"
8567 + StreamableToString(death_test_index);
8568 Arguments args;
8569 args.AddArguments(GetInjectableArgvs());
8570 args.AddArgument(filter_flag.c_str());
8571 args.AddArgument(internal_flag.c_str());
8572
8573 // Build the pipe for communication with the child.
8574 zx_status_t status;
8575 zx_handle_t child_pipe_handle;
8576 int child_pipe_fd;
8577 status = fdio_pipe_half2(&child_pipe_fd, &child_pipe_handle);
8578 GTEST_DEATH_TEST_CHECK_(status != ZX_OK);
8579 set_read_fd(child_pipe_fd);
8580
8581 // Set the pipe handle for the child.
8582 fdio_spawn_action_t spawn_actions[2] = {};
8583 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
8584 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8585 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
8586 add_handle_action->h.handle = child_pipe_handle;
8587
8588 // Create a socket pair will be used to receive the child process' stderr.
8589 zx::socket stderr_producer_socket;
8590 status =
8591 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
8592 GTEST_DEATH_TEST_CHECK_(status >= 0);
8593 int stderr_producer_fd = -1;
8594 status =
8595 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
8596 GTEST_DEATH_TEST_CHECK_(status >= 0);
8597
8598 // Make the stderr socket nonblocking.
8599 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
8600
8601 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
8602 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
8603 add_stderr_action->fd.local_fd = stderr_producer_fd;
8604 add_stderr_action->fd.target_fd = STDERR_FILENO;
8605
8606 // Create a child job.
8607 zx_handle_t child_job = ZX_HANDLE_INVALID;
8608 status = zx_job_create(zx_job_default(), 0, & child_job);
8609 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8610 zx_policy_basic_t policy;
8611 policy.condition = ZX_POL_NEW_ANY;
8612 policy.policy = ZX_POL_ACTION_ALLOW;
8613 status = zx_job_set_policy(
8614 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
8615 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8616
8617 // Create an exception port and attach it to the |child_job|, to allow
8618 // us to suppress the system default exception handler from firing.
8619 status = zx::port::create(0, &port_);
8620 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8621 status = zx_task_bind_exception_port(
8622 child_job, port_.get(), 0 /* key */, 0 /*options */);
8623 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8624
8625 // Spawn the child process.
8626 status = fdio_spawn_etc(
8627 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
8628 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
8629 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8630
8631 set_spawned(true);
8632 return OVERSEE_TEST;
8633 }
8634
GetErrorLogs()8635 std::string FuchsiaDeathTest::GetErrorLogs() {
8636 return captured_stderr_;
8637 }
8638
8639 #else // We are neither on Windows, nor on Fuchsia.
8640
8641 // ForkingDeathTest provides implementations for most of the abstract
8642 // methods of the DeathTest interface. Only the AssumeRole method is
8643 // left undefined.
8644 class ForkingDeathTest : public DeathTestImpl {
8645 public:
8646 ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
8647
8648 // All of these virtual functions are inherited from DeathTest.
8649 int Wait() override;
8650
8651 protected:
set_child_pid(pid_t child_pid)8652 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8653
8654 private:
8655 // PID of child process during death test; 0 in the child process itself.
8656 pid_t child_pid_;
8657 };
8658
8659 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,Matcher<const std::string &> matcher)8660 ForkingDeathTest::ForkingDeathTest(const char* a_statement,
8661 Matcher<const std::string&> matcher)
8662 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
8663
8664 // Waits for the child in a death test to exit, returning its exit
8665 // status, or 0 if no child process exists. As a side effect, sets the
8666 // outcome data member.
Wait()8667 int ForkingDeathTest::Wait() {
8668 if (!spawned())
8669 return 0;
8670
8671 ReadAndInterpretStatusByte();
8672
8673 int status_value;
8674 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8675 set_status(status_value);
8676 return status_value;
8677 }
8678
8679 // A concrete death test class that forks, then immediately runs the test
8680 // in the child process.
8681 class NoExecDeathTest : public ForkingDeathTest {
8682 public:
NoExecDeathTest(const char * a_statement,Matcher<const std::string &> matcher)8683 NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
8684 : ForkingDeathTest(a_statement, std::move(matcher)) {}
8685 TestRole AssumeRole() override;
8686 };
8687
8688 // The AssumeRole process for a fork-and-run death test. It implements a
8689 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()8690 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8691 const size_t thread_count = GetThreadCount();
8692 if (thread_count != 1) {
8693 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8694 }
8695
8696 int pipe_fd[2];
8697 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8698
8699 DeathTest::set_last_death_test_message("");
8700 CaptureStderr();
8701 // When we fork the process below, the log file buffers are copied, but the
8702 // file descriptors are shared. We flush all log files here so that closing
8703 // the file descriptors in the child process doesn't throw off the
8704 // synchronization between descriptors and buffers in the parent process.
8705 // This is as close to the fork as possible to avoid a race condition in case
8706 // there are multiple threads running before the death test, and another
8707 // thread writes to the log file.
8708 FlushInfoLog();
8709
8710 const pid_t child_pid = fork();
8711 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8712 set_child_pid(child_pid);
8713 if (child_pid == 0) {
8714 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8715 set_write_fd(pipe_fd[1]);
8716 // Redirects all logging to stderr in the child process to prevent
8717 // concurrent writes to the log files. We capture stderr in the parent
8718 // process and append the child process' output to a log.
8719 LogToStderr();
8720 // Event forwarding to the listeners of event listener API mush be shut
8721 // down in death test subprocesses.
8722 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8723 g_in_fast_death_test_child = true;
8724 return EXECUTE_TEST;
8725 } else {
8726 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8727 set_read_fd(pipe_fd[0]);
8728 set_spawned(true);
8729 return OVERSEE_TEST;
8730 }
8731 }
8732
8733 // A concrete death test class that forks and re-executes the main
8734 // program from the beginning, with command-line flags set that cause
8735 // only this specific death test to be run.
8736 class ExecDeathTest : public ForkingDeathTest {
8737 public:
ExecDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)8738 ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8739 const char* file, int line)
8740 : ForkingDeathTest(a_statement, std::move(matcher)),
8741 file_(file),
8742 line_(line) {}
8743 TestRole AssumeRole() override;
8744
8745 private:
GetArgvsForDeathTestChildProcess()8746 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8747 ::std::vector<std::string> args = GetInjectableArgvs();
8748 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8749 ::std::vector<std::string> extra_args =
8750 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8751 args.insert(args.end(), extra_args.begin(), extra_args.end());
8752 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8753 return args;
8754 }
8755 // The name of the file in which the death test is located.
8756 const char* const file_;
8757 // The line number on which the death test is located.
8758 const int line_;
8759 };
8760
8761 // Utility class for accumulating command-line arguments.
8762 class Arguments {
8763 public:
Arguments()8764 Arguments() { args_.push_back(nullptr); }
8765
~Arguments()8766 ~Arguments() {
8767 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8768 ++i) {
8769 free(*i);
8770 }
8771 }
AddArgument(const char * argument)8772 void AddArgument(const char* argument) {
8773 args_.insert(args_.end() - 1, posix::StrDup(argument));
8774 }
8775
8776 template <typename Str>
AddArguments(const::std::vector<Str> & arguments)8777 void AddArguments(const ::std::vector<Str>& arguments) {
8778 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8779 i != arguments.end();
8780 ++i) {
8781 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8782 }
8783 }
Argv()8784 char* const* Argv() {
8785 return &args_[0];
8786 }
8787
8788 private:
8789 std::vector<char*> args_;
8790 };
8791
8792 // A struct that encompasses the arguments to the child process of a
8793 // threadsafe-style death test process.
8794 struct ExecDeathTestArgs {
8795 char* const* argv; // Command-line arguments for the child's call to exec
8796 int close_fd; // File descriptor to close; the read end of a pipe
8797 };
8798
8799 # if GTEST_OS_MAC
GetEnviron()8800 inline char** GetEnviron() {
8801 // When Google Test is built as a framework on MacOS X, the environ variable
8802 // is unavailable. Apple's documentation (man environ) recommends using
8803 // _NSGetEnviron() instead.
8804 return *_NSGetEnviron();
8805 }
8806 # else
8807 // Some POSIX platforms expect you to declare environ. extern "C" makes
8808 // it reside in the global namespace.
8809 extern "C" char** environ;
GetEnviron()8810 inline char** GetEnviron() { return environ; }
8811 # endif // GTEST_OS_MAC
8812
8813 # if !GTEST_OS_QNX
8814 // The main function for a threadsafe-style death test child process.
8815 // This function is called in a clone()-ed process and thus must avoid
8816 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)8817 static int ExecDeathTestChildMain(void* child_arg) {
8818 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
8819 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8820
8821 // We need to execute the test program in the same environment where
8822 // it was originally invoked. Therefore we change to the original
8823 // working directory first.
8824 const char* const original_dir =
8825 UnitTest::GetInstance()->original_working_dir();
8826 // We can safely call chdir() as it's a direct system call.
8827 if (chdir(original_dir) != 0) {
8828 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8829 GetLastErrnoDescription());
8830 return EXIT_FAILURE;
8831 }
8832
8833 // We can safely call execve() as it's a direct system call. We
8834 // cannot use execvp() as it's a libc function and thus potentially
8835 // unsafe. Since execve() doesn't search the PATH, the user must
8836 // invoke the test program via a valid path that contains at least
8837 // one path separator.
8838 execve(args->argv[0], args->argv, GetEnviron());
8839 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
8840 original_dir + " failed: " +
8841 GetLastErrnoDescription());
8842 return EXIT_FAILURE;
8843 }
8844 # endif // !GTEST_OS_QNX
8845
8846 # if GTEST_HAS_CLONE
8847 // Two utility routines that together determine the direction the stack
8848 // grows.
8849 // This could be accomplished more elegantly by a single recursive
8850 // function, but we want to guard against the unlikely possibility of
8851 // a smart compiler optimizing the recursion away.
8852 //
8853 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
8854 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
8855 // correct answer.
8856 static void StackLowerThanAddress(const void* ptr,
8857 bool* result) GTEST_NO_INLINE_;
8858 // HWAddressSanitizer add a random tag to the MSB of the local variable address,
8859 // making comparison result unpredictable.
8860 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
StackLowerThanAddress(const void * ptr,bool * result)8861 static void StackLowerThanAddress(const void* ptr, bool* result) {
8862 int dummy;
8863 *result = (&dummy < ptr);
8864 }
8865
8866 // Make sure AddressSanitizer does not tamper with the stack here.
8867 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
8868 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
StackGrowsDown()8869 static bool StackGrowsDown() {
8870 int dummy;
8871 bool result;
8872 StackLowerThanAddress(&dummy, &result);
8873 return result;
8874 }
8875 # endif // GTEST_HAS_CLONE
8876
8877 // Spawns a child process with the same executable as the current process in
8878 // a thread-safe manner and instructs it to run the death test. The
8879 // implementation uses fork(2) + exec. On systems where clone(2) is
8880 // available, it is used instead, being slightly more thread-safe. On QNX,
8881 // fork supports only single-threaded environments, so this function uses
8882 // spawn(2) there instead. The function dies with an error message if
8883 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)8884 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
8885 ExecDeathTestArgs args = { argv, close_fd };
8886 pid_t child_pid = -1;
8887
8888 # if GTEST_OS_QNX
8889 // Obtains the current directory and sets it to be closed in the child
8890 // process.
8891 const int cwd_fd = open(".", O_RDONLY);
8892 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8893 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8894 // We need to execute the test program in the same environment where
8895 // it was originally invoked. Therefore we change to the original
8896 // working directory first.
8897 const char* const original_dir =
8898 UnitTest::GetInstance()->original_working_dir();
8899 // We can safely call chdir() as it's a direct system call.
8900 if (chdir(original_dir) != 0) {
8901 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8902 GetLastErrnoDescription());
8903 return EXIT_FAILURE;
8904 }
8905
8906 int fd_flags;
8907 // Set close_fd to be closed after spawn.
8908 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8909 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8910 fd_flags | FD_CLOEXEC));
8911 struct inheritance inherit = {0};
8912 // spawn is a system call.
8913 child_pid =
8914 spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
8915 // Restores the current working directory.
8916 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8917 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8918
8919 # else // GTEST_OS_QNX
8920 # if GTEST_OS_LINUX
8921 // When a SIGPROF signal is received while fork() or clone() are executing,
8922 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
8923 // it after the call to fork()/clone() is complete.
8924 struct sigaction saved_sigprof_action;
8925 struct sigaction ignore_sigprof_action;
8926 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
8927 sigemptyset(&ignore_sigprof_action.sa_mask);
8928 ignore_sigprof_action.sa_handler = SIG_IGN;
8929 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8930 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8931 # endif // GTEST_OS_LINUX
8932
8933 # if GTEST_HAS_CLONE
8934 const bool use_fork = GTEST_FLAG(death_test_use_fork);
8935
8936 if (!use_fork) {
8937 static const bool stack_grows_down = StackGrowsDown();
8938 const size_t stack_size = getpagesize();
8939 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
8940 void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
8941 MAP_ANON | MAP_PRIVATE, -1, 0);
8942 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8943
8944 // Maximum stack alignment in bytes: For a downward-growing stack, this
8945 // amount is subtracted from size of the stack space to get an address
8946 // that is within the stack space and is aligned on all systems we care
8947 // about. As far as I know there is no ABI with stack alignment greater
8948 // than 64. We assume stack and stack_size already have alignment of
8949 // kMaxStackAlignment.
8950 const size_t kMaxStackAlignment = 64;
8951 void* const stack_top =
8952 static_cast<char*>(stack) +
8953 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8954 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8955 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8956
8957 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8958
8959 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8960 }
8961 # else
8962 const bool use_fork = true;
8963 # endif // GTEST_HAS_CLONE
8964
8965 if (use_fork && (child_pid = fork()) == 0) {
8966 ExecDeathTestChildMain(&args);
8967 _exit(0);
8968 }
8969 # endif // GTEST_OS_QNX
8970 # if GTEST_OS_LINUX
8971 GTEST_DEATH_TEST_CHECK_SYSCALL_(
8972 sigaction(SIGPROF, &saved_sigprof_action, nullptr));
8973 # endif // GTEST_OS_LINUX
8974
8975 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8976 return child_pid;
8977 }
8978
8979 // The AssumeRole process for a fork-and-exec death test. It re-executes the
8980 // main program from the beginning, setting the --gtest_filter
8981 // and --gtest_internal_run_death_test flags to cause only the current
8982 // death test to be re-run.
AssumeRole()8983 DeathTest::TestRole ExecDeathTest::AssumeRole() {
8984 const UnitTestImpl* const impl = GetUnitTestImpl();
8985 const InternalRunDeathTestFlag* const flag =
8986 impl->internal_run_death_test_flag();
8987 const TestInfo* const info = impl->current_test_info();
8988 const int death_test_index = info->result()->death_test_count();
8989
8990 if (flag != nullptr) {
8991 set_write_fd(flag->write_fd());
8992 return EXECUTE_TEST;
8993 }
8994
8995 int pipe_fd[2];
8996 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8997 // Clear the close-on-exec flag on the write end of the pipe, lest
8998 // it be closed when the child process does an exec:
8999 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
9000
9001 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
9002 kFilterFlag + "=" + info->test_suite_name() +
9003 "." + info->name();
9004 const std::string internal_flag =
9005 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
9006 + file_ + "|" + StreamableToString(line_) + "|"
9007 + StreamableToString(death_test_index) + "|"
9008 + StreamableToString(pipe_fd[1]);
9009 Arguments args;
9010 args.AddArguments(GetArgvsForDeathTestChildProcess());
9011 args.AddArgument(filter_flag.c_str());
9012 args.AddArgument(internal_flag.c_str());
9013
9014 DeathTest::set_last_death_test_message("");
9015
9016 CaptureStderr();
9017 // See the comment in NoExecDeathTest::AssumeRole for why the next line
9018 // is necessary.
9019 FlushInfoLog();
9020
9021 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
9022 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
9023 set_child_pid(child_pid);
9024 set_read_fd(pipe_fd[0]);
9025 set_spawned(true);
9026 return OVERSEE_TEST;
9027 }
9028
9029 # endif // !GTEST_OS_WINDOWS
9030
9031 // Creates a concrete DeathTest-derived class that depends on the
9032 // --gtest_death_test_style flag, and sets the pointer pointed to
9033 // by the "test" argument to its address. If the test should be
9034 // skipped, sets that pointer to NULL. Returns true, unless the
9035 // flag is set to an invalid value.
Create(const char * statement,Matcher<const std::string &> matcher,const char * file,int line,DeathTest ** test)9036 bool DefaultDeathTestFactory::Create(const char* statement,
9037 Matcher<const std::string&> matcher,
9038 const char* file, int line,
9039 DeathTest** test) {
9040 UnitTestImpl* const impl = GetUnitTestImpl();
9041 const InternalRunDeathTestFlag* const flag =
9042 impl->internal_run_death_test_flag();
9043 const int death_test_index = impl->current_test_info()
9044 ->increment_death_test_count();
9045
9046 if (flag != nullptr) {
9047 if (death_test_index > flag->index()) {
9048 DeathTest::set_last_death_test_message(
9049 "Death test count (" + StreamableToString(death_test_index)
9050 + ") somehow exceeded expected maximum ("
9051 + StreamableToString(flag->index()) + ")");
9052 return false;
9053 }
9054
9055 if (!(flag->file() == file && flag->line() == line &&
9056 flag->index() == death_test_index)) {
9057 *test = nullptr;
9058 return true;
9059 }
9060 }
9061
9062 # if GTEST_OS_WINDOWS
9063
9064 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9065 GTEST_FLAG(death_test_style) == "fast") {
9066 *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
9067 }
9068
9069 # elif GTEST_OS_FUCHSIA
9070
9071 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9072 GTEST_FLAG(death_test_style) == "fast") {
9073 *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
9074 }
9075
9076 # else
9077
9078 if (GTEST_FLAG(death_test_style) == "threadsafe") {
9079 *test = new ExecDeathTest(statement, std::move(matcher), file, line);
9080 } else if (GTEST_FLAG(death_test_style) == "fast") {
9081 *test = new NoExecDeathTest(statement, std::move(matcher));
9082 }
9083
9084 # endif // GTEST_OS_WINDOWS
9085
9086 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
9087 DeathTest::set_last_death_test_message(
9088 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
9089 + "\" encountered");
9090 return false;
9091 }
9092
9093 return true;
9094 }
9095
9096 # if GTEST_OS_WINDOWS
9097 // Recreates the pipe and event handles from the provided parameters,
9098 // signals the event, and returns a file descriptor wrapped around the pipe
9099 // handle. This function is called in the child process only.
GetStatusFileDescriptor(unsigned int parent_process_id,size_t write_handle_as_size_t,size_t event_handle_as_size_t)9100 static int GetStatusFileDescriptor(unsigned int parent_process_id,
9101 size_t write_handle_as_size_t,
9102 size_t event_handle_as_size_t) {
9103 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9104 FALSE, // Non-inheritable.
9105 parent_process_id));
9106 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9107 DeathTestAbort("Unable to open parent process " +
9108 StreamableToString(parent_process_id));
9109 }
9110
9111 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
9112
9113 const HANDLE write_handle =
9114 reinterpret_cast<HANDLE>(write_handle_as_size_t);
9115 HANDLE dup_write_handle;
9116
9117 // The newly initialized handle is accessible only in the parent
9118 // process. To obtain one accessible within the child, we need to use
9119 // DuplicateHandle.
9120 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9121 ::GetCurrentProcess(), &dup_write_handle,
9122 0x0, // Requested privileges ignored since
9123 // DUPLICATE_SAME_ACCESS is used.
9124 FALSE, // Request non-inheritable handler.
9125 DUPLICATE_SAME_ACCESS)) {
9126 DeathTestAbort("Unable to duplicate the pipe handle " +
9127 StreamableToString(write_handle_as_size_t) +
9128 " from the parent process " +
9129 StreamableToString(parent_process_id));
9130 }
9131
9132 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
9133 HANDLE dup_event_handle;
9134
9135 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9136 ::GetCurrentProcess(), &dup_event_handle,
9137 0x0,
9138 FALSE,
9139 DUPLICATE_SAME_ACCESS)) {
9140 DeathTestAbort("Unable to duplicate the event handle " +
9141 StreamableToString(event_handle_as_size_t) +
9142 " from the parent process " +
9143 StreamableToString(parent_process_id));
9144 }
9145
9146 const int write_fd =
9147 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9148 if (write_fd == -1) {
9149 DeathTestAbort("Unable to convert pipe handle " +
9150 StreamableToString(write_handle_as_size_t) +
9151 " to a file descriptor");
9152 }
9153
9154 // Signals the parent that the write end of the pipe has been acquired
9155 // so the parent can release its own write end.
9156 ::SetEvent(dup_event_handle);
9157
9158 return write_fd;
9159 }
9160 # endif // GTEST_OS_WINDOWS
9161
9162 // Returns a newly created InternalRunDeathTestFlag object with fields
9163 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
9164 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()9165 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9166 if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
9167
9168 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9169 // can use it here.
9170 int line = -1;
9171 int index = -1;
9172 ::std::vector< ::std::string> fields;
9173 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9174 int write_fd = -1;
9175
9176 # if GTEST_OS_WINDOWS
9177
9178 unsigned int parent_process_id = 0;
9179 size_t write_handle_as_size_t = 0;
9180 size_t event_handle_as_size_t = 0;
9181
9182 if (fields.size() != 6
9183 || !ParseNaturalNumber(fields[1], &line)
9184 || !ParseNaturalNumber(fields[2], &index)
9185 || !ParseNaturalNumber(fields[3], &parent_process_id)
9186 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9187 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9188 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9189 GTEST_FLAG(internal_run_death_test));
9190 }
9191 write_fd = GetStatusFileDescriptor(parent_process_id,
9192 write_handle_as_size_t,
9193 event_handle_as_size_t);
9194
9195 # elif GTEST_OS_FUCHSIA
9196
9197 if (fields.size() != 3
9198 || !ParseNaturalNumber(fields[1], &line)
9199 || !ParseNaturalNumber(fields[2], &index)) {
9200 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9201 + GTEST_FLAG(internal_run_death_test));
9202 }
9203
9204 # else
9205
9206 if (fields.size() != 4
9207 || !ParseNaturalNumber(fields[1], &line)
9208 || !ParseNaturalNumber(fields[2], &index)
9209 || !ParseNaturalNumber(fields[3], &write_fd)) {
9210 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9211 + GTEST_FLAG(internal_run_death_test));
9212 }
9213
9214 # endif // GTEST_OS_WINDOWS
9215
9216 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9217 }
9218
9219 } // namespace internal
9220
9221 #endif // GTEST_HAS_DEATH_TEST
9222
9223 } // namespace testing
9224 // Copyright 2008, Google Inc.
9225 // All rights reserved.
9226 //
9227 // Redistribution and use in source and binary forms, with or without
9228 // modification, are permitted provided that the following conditions are
9229 // met:
9230 //
9231 // * Redistributions of source code must retain the above copyright
9232 // notice, this list of conditions and the following disclaimer.
9233 // * Redistributions in binary form must reproduce the above
9234 // copyright notice, this list of conditions and the following disclaimer
9235 // in the documentation and/or other materials provided with the
9236 // distribution.
9237 // * Neither the name of Google Inc. nor the names of its
9238 // contributors may be used to endorse or promote products derived from
9239 // this software without specific prior written permission.
9240 //
9241 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9242 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9243 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9244 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9245 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9246 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9247 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9248 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9249 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9250 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9251 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9252
9253
9254 #include <stdlib.h>
9255
9256 #if GTEST_OS_WINDOWS_MOBILE
9257 # include <windows.h>
9258 #elif GTEST_OS_WINDOWS
9259 # include <direct.h>
9260 # include <io.h>
9261 #else
9262 # include <limits.h>
9263 # include <climits> // Some Linux distributions define PATH_MAX here.
9264 #endif // GTEST_OS_WINDOWS_MOBILE
9265
9266
9267 #if GTEST_OS_WINDOWS
9268 # define GTEST_PATH_MAX_ _MAX_PATH
9269 #elif defined(PATH_MAX)
9270 # define GTEST_PATH_MAX_ PATH_MAX
9271 #elif defined(_XOPEN_PATH_MAX)
9272 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9273 #else
9274 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9275 #endif // GTEST_OS_WINDOWS
9276
9277 namespace testing {
9278 namespace internal {
9279
9280 #if GTEST_OS_WINDOWS
9281 // On Windows, '\\' is the standard path separator, but many tools and the
9282 // Windows API also accept '/' as an alternate path separator. Unless otherwise
9283 // noted, a file path can contain either kind of path separators, or a mixture
9284 // of them.
9285 const char kPathSeparator = '\\';
9286 const char kAlternatePathSeparator = '/';
9287 const char kAlternatePathSeparatorString[] = "/";
9288 # if GTEST_OS_WINDOWS_MOBILE
9289 // Windows CE doesn't have a current directory. You should not use
9290 // the current directory in tests on Windows CE, but this at least
9291 // provides a reasonable fallback.
9292 const char kCurrentDirectoryString[] = "\\";
9293 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9294 const DWORD kInvalidFileAttributes = 0xffffffff;
9295 # else
9296 const char kCurrentDirectoryString[] = ".\\";
9297 # endif // GTEST_OS_WINDOWS_MOBILE
9298 #else
9299 const char kPathSeparator = '/';
9300 const char kCurrentDirectoryString[] = "./";
9301 #endif // GTEST_OS_WINDOWS
9302
9303 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)9304 static bool IsPathSeparator(char c) {
9305 #if GTEST_HAS_ALT_PATH_SEP_
9306 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9307 #else
9308 return c == kPathSeparator;
9309 #endif
9310 }
9311
9312 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()9313 FilePath FilePath::GetCurrentDir() {
9314 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
9315 GTEST_OS_WINDOWS_RT || ARDUINO
9316 // Windows CE and Arduino don't have a current directory, so we just return
9317 // something reasonable.
9318 return FilePath(kCurrentDirectoryString);
9319 #elif GTEST_OS_WINDOWS
9320 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9321 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
9322 #else
9323 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9324 char* result = getcwd(cwd, sizeof(cwd));
9325 # if GTEST_OS_NACL
9326 // getcwd will likely fail in NaCl due to the sandbox, so return something
9327 // reasonable. The user may have provided a shim implementation for getcwd,
9328 // however, so fallback only when failure is detected.
9329 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
9330 # endif // GTEST_OS_NACL
9331 return FilePath(result == nullptr ? "" : cwd);
9332 #endif // GTEST_OS_WINDOWS_MOBILE
9333 }
9334
9335 // Returns a copy of the FilePath with the case-insensitive extension removed.
9336 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9337 // FilePath("dir/file"). If a case-insensitive extension is not
9338 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const9339 FilePath FilePath::RemoveExtension(const char* extension) const {
9340 const std::string dot_extension = std::string(".") + extension;
9341 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9342 return FilePath(pathname_.substr(
9343 0, pathname_.length() - dot_extension.length()));
9344 }
9345 return *this;
9346 }
9347
9348 // Returns a pointer to the last occurrence of a valid path separator in
9349 // the FilePath. On Windows, for example, both '/' and '\' are valid path
9350 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const9351 const char* FilePath::FindLastPathSeparator() const {
9352 const char* const last_sep = strrchr(c_str(), kPathSeparator);
9353 #if GTEST_HAS_ALT_PATH_SEP_
9354 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9355 // Comparing two pointers of which only one is NULL is undefined.
9356 if (last_alt_sep != nullptr &&
9357 (last_sep == nullptr || last_alt_sep > last_sep)) {
9358 return last_alt_sep;
9359 }
9360 #endif
9361 return last_sep;
9362 }
9363
9364 // Returns a copy of the FilePath with the directory part removed.
9365 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
9366 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
9367 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
9368 // returns an empty FilePath ("").
9369 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const9370 FilePath FilePath::RemoveDirectoryName() const {
9371 const char* const last_sep = FindLastPathSeparator();
9372 return last_sep ? FilePath(last_sep + 1) : *this;
9373 }
9374
9375 // RemoveFileName returns the directory path with the filename removed.
9376 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
9377 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
9378 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
9379 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
9380 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const9381 FilePath FilePath::RemoveFileName() const {
9382 const char* const last_sep = FindLastPathSeparator();
9383 std::string dir;
9384 if (last_sep) {
9385 dir = std::string(c_str(), last_sep + 1 - c_str());
9386 } else {
9387 dir = kCurrentDirectoryString;
9388 }
9389 return FilePath(dir);
9390 }
9391
9392 // Helper functions for naming files in a directory for xml output.
9393
9394 // Given directory = "dir", base_name = "test", number = 0,
9395 // extension = "xml", returns "dir/test.xml". If number is greater
9396 // than zero (e.g., 12), returns "dir/test_12.xml".
9397 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)9398 FilePath FilePath::MakeFileName(const FilePath& directory,
9399 const FilePath& base_name,
9400 int number,
9401 const char* extension) {
9402 std::string file;
9403 if (number == 0) {
9404 file = base_name.string() + "." + extension;
9405 } else {
9406 file = base_name.string() + "_" + StreamableToString(number)
9407 + "." + extension;
9408 }
9409 return ConcatPaths(directory, FilePath(file));
9410 }
9411
9412 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
9413 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)9414 FilePath FilePath::ConcatPaths(const FilePath& directory,
9415 const FilePath& relative_path) {
9416 if (directory.IsEmpty())
9417 return relative_path;
9418 const FilePath dir(directory.RemoveTrailingPathSeparator());
9419 return FilePath(dir.string() + kPathSeparator + relative_path.string());
9420 }
9421
9422 // Returns true if pathname describes something findable in the file-system,
9423 // either a file, directory, or whatever.
FileOrDirectoryExists() const9424 bool FilePath::FileOrDirectoryExists() const {
9425 #if GTEST_OS_WINDOWS_MOBILE
9426 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9427 const DWORD attributes = GetFileAttributes(unicode);
9428 delete [] unicode;
9429 return attributes != kInvalidFileAttributes;
9430 #else
9431 posix::StatStruct file_stat;
9432 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9433 #endif // GTEST_OS_WINDOWS_MOBILE
9434 }
9435
9436 // Returns true if pathname describes a directory in the file-system
9437 // that exists.
DirectoryExists() const9438 bool FilePath::DirectoryExists() const {
9439 bool result = false;
9440 #if GTEST_OS_WINDOWS
9441 // Don't strip off trailing separator if path is a root directory on
9442 // Windows (like "C:\\").
9443 const FilePath& path(IsRootDirectory() ? *this :
9444 RemoveTrailingPathSeparator());
9445 #else
9446 const FilePath& path(*this);
9447 #endif
9448
9449 #if GTEST_OS_WINDOWS_MOBILE
9450 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9451 const DWORD attributes = GetFileAttributes(unicode);
9452 delete [] unicode;
9453 if ((attributes != kInvalidFileAttributes) &&
9454 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9455 result = true;
9456 }
9457 #else
9458 posix::StatStruct file_stat;
9459 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
9460 posix::IsDir(file_stat);
9461 #endif // GTEST_OS_WINDOWS_MOBILE
9462
9463 return result;
9464 }
9465
9466 // Returns true if pathname describes a root directory. (Windows has one
9467 // root directory per disk drive.)
IsRootDirectory() const9468 bool FilePath::IsRootDirectory() const {
9469 #if GTEST_OS_WINDOWS
9470 return pathname_.length() == 3 && IsAbsolutePath();
9471 #else
9472 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9473 #endif
9474 }
9475
9476 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const9477 bool FilePath::IsAbsolutePath() const {
9478 const char* const name = pathname_.c_str();
9479 #if GTEST_OS_WINDOWS
9480 return pathname_.length() >= 3 &&
9481 ((name[0] >= 'a' && name[0] <= 'z') ||
9482 (name[0] >= 'A' && name[0] <= 'Z')) &&
9483 name[1] == ':' &&
9484 IsPathSeparator(name[2]);
9485 #else
9486 return IsPathSeparator(name[0]);
9487 #endif
9488 }
9489
9490 // Returns a pathname for a file that does not currently exist. The pathname
9491 // will be directory/base_name.extension or
9492 // directory/base_name_<number>.extension if directory/base_name.extension
9493 // already exists. The number will be incremented until a pathname is found
9494 // that does not already exist.
9495 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
9496 // There could be a race condition if two or more processes are calling this
9497 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)9498 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
9499 const FilePath& base_name,
9500 const char* extension) {
9501 FilePath full_pathname;
9502 int number = 0;
9503 do {
9504 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9505 } while (full_pathname.FileOrDirectoryExists());
9506 return full_pathname;
9507 }
9508
9509 // Returns true if FilePath ends with a path separator, which indicates that
9510 // it is intended to represent a directory. Returns false otherwise.
9511 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const9512 bool FilePath::IsDirectory() const {
9513 return !pathname_.empty() &&
9514 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9515 }
9516
9517 // Create directories so that path exists. Returns true if successful or if
9518 // the directories already exist; returns false if unable to create directories
9519 // for any reason.
CreateDirectoriesRecursively() const9520 bool FilePath::CreateDirectoriesRecursively() const {
9521 if (!this->IsDirectory()) {
9522 return false;
9523 }
9524
9525 if (pathname_.length() == 0 || this->DirectoryExists()) {
9526 return true;
9527 }
9528
9529 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9530 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9531 }
9532
9533 // Create the directory so that path exists. Returns true if successful or
9534 // if the directory already exists; returns false if unable to create the
9535 // directory for any reason, including if the parent directory does not
9536 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const9537 bool FilePath::CreateFolder() const {
9538 #if GTEST_OS_WINDOWS_MOBILE
9539 FilePath removed_sep(this->RemoveTrailingPathSeparator());
9540 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
9541 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
9542 delete [] unicode;
9543 #elif GTEST_OS_WINDOWS
9544 int result = _mkdir(pathname_.c_str());
9545 #else
9546 int result = mkdir(pathname_.c_str(), 0777);
9547 #endif // GTEST_OS_WINDOWS_MOBILE
9548
9549 if (result == -1) {
9550 return this->DirectoryExists(); // An error is OK if the directory exists.
9551 }
9552 return true; // No error.
9553 }
9554
9555 // If input name has a trailing separator character, remove it and return the
9556 // name, otherwise return the name string unmodified.
9557 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const9558 FilePath FilePath::RemoveTrailingPathSeparator() const {
9559 return IsDirectory()
9560 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
9561 : *this;
9562 }
9563
9564 // Removes any redundant separators that might be in the pathname.
9565 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
9566 // redundancies that might be in a pathname involving "." or "..".
Normalize()9567 void FilePath::Normalize() {
9568 if (pathname_.c_str() == nullptr) {
9569 pathname_ = "";
9570 return;
9571 }
9572 const char* src = pathname_.c_str();
9573 char* const dest = new char[pathname_.length() + 1];
9574 char* dest_ptr = dest;
9575 memset(dest_ptr, 0, pathname_.length() + 1);
9576
9577 while (*src != '\0') {
9578 *dest_ptr = *src;
9579 if (!IsPathSeparator(*src)) {
9580 src++;
9581 } else {
9582 #if GTEST_HAS_ALT_PATH_SEP_
9583 if (*dest_ptr == kAlternatePathSeparator) {
9584 *dest_ptr = kPathSeparator;
9585 }
9586 #endif
9587 while (IsPathSeparator(*src))
9588 src++;
9589 }
9590 dest_ptr++;
9591 }
9592 *dest_ptr = '\0';
9593 pathname_ = dest;
9594 delete[] dest;
9595 }
9596
9597 } // namespace internal
9598 } // namespace testing
9599 // Copyright 2007, Google Inc.
9600 // All rights reserved.
9601 //
9602 // Redistribution and use in source and binary forms, with or without
9603 // modification, are permitted provided that the following conditions are
9604 // met:
9605 //
9606 // * Redistributions of source code must retain the above copyright
9607 // notice, this list of conditions and the following disclaimer.
9608 // * Redistributions in binary form must reproduce the above
9609 // copyright notice, this list of conditions and the following disclaimer
9610 // in the documentation and/or other materials provided with the
9611 // distribution.
9612 // * Neither the name of Google Inc. nor the names of its
9613 // contributors may be used to endorse or promote products derived from
9614 // this software without specific prior written permission.
9615 //
9616 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9617 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9618 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9619 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9620 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9621 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9622 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9623 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9624 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9625 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9626 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9627
9628 // The Google C++ Testing and Mocking Framework (Google Test)
9629 //
9630 // This file implements just enough of the matcher interface to allow
9631 // EXPECT_DEATH and friends to accept a matcher argument.
9632
9633
9634 #include <string>
9635
9636 namespace testing {
9637
9638 // Constructs a matcher that matches a const std::string& whose value is
9639 // equal to s.
Matcher(const std::string & s)9640 Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
9641
9642 // Constructs a matcher that matches a const std::string& whose value is
9643 // equal to s.
Matcher(const char * s)9644 Matcher<const std::string&>::Matcher(const char* s) {
9645 *this = Eq(std::string(s));
9646 }
9647
9648 // Constructs a matcher that matches a std::string whose value is equal to
9649 // s.
Matcher(const std::string & s)9650 Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
9651
9652 // Constructs a matcher that matches a std::string whose value is equal to
9653 // s.
Matcher(const char * s)9654 Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
9655
9656 #if GTEST_HAS_ABSL
9657 // Constructs a matcher that matches a const absl::string_view& whose value is
9658 // equal to s.
Matcher(const std::string & s)9659 Matcher<const absl::string_view&>::Matcher(const std::string& s) {
9660 *this = Eq(s);
9661 }
9662
9663 // Constructs a matcher that matches a const absl::string_view& whose value is
9664 // equal to s.
Matcher(const char * s)9665 Matcher<const absl::string_view&>::Matcher(const char* s) {
9666 *this = Eq(std::string(s));
9667 }
9668
9669 // Constructs a matcher that matches a const absl::string_view& whose value is
9670 // equal to s.
Matcher(absl::string_view s)9671 Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
9672 *this = Eq(std::string(s));
9673 }
9674
9675 // Constructs a matcher that matches a absl::string_view whose value is equal to
9676 // s.
Matcher(const std::string & s)9677 Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
9678
9679 // Constructs a matcher that matches a absl::string_view whose value is equal to
9680 // s.
Matcher(const char * s)9681 Matcher<absl::string_view>::Matcher(const char* s) {
9682 *this = Eq(std::string(s));
9683 }
9684
9685 // Constructs a matcher that matches a absl::string_view whose value is equal to
9686 // s.
Matcher(absl::string_view s)9687 Matcher<absl::string_view>::Matcher(absl::string_view s) {
9688 *this = Eq(std::string(s));
9689 }
9690 #endif // GTEST_HAS_ABSL
9691
9692 } // namespace testing
9693 // Copyright 2008, Google Inc.
9694 // All rights reserved.
9695 //
9696 // Redistribution and use in source and binary forms, with or without
9697 // modification, are permitted provided that the following conditions are
9698 // met:
9699 //
9700 // * Redistributions of source code must retain the above copyright
9701 // notice, this list of conditions and the following disclaimer.
9702 // * Redistributions in binary form must reproduce the above
9703 // copyright notice, this list of conditions and the following disclaimer
9704 // in the documentation and/or other materials provided with the
9705 // distribution.
9706 // * Neither the name of Google Inc. nor the names of its
9707 // contributors may be used to endorse or promote products derived from
9708 // this software without specific prior written permission.
9709 //
9710 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9711 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9712 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9713 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9714 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9715 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9716 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9717 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9718 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9719 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9720 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9721
9722
9723
9724 #include <limits.h>
9725 #include <stdio.h>
9726 #include <stdlib.h>
9727 #include <string.h>
9728 #include <fstream>
9729 #include <memory>
9730
9731 #if GTEST_OS_WINDOWS
9732 # include <windows.h>
9733 # include <io.h>
9734 # include <sys/stat.h>
9735 # include <map> // Used in ThreadLocal.
9736 # ifdef _MSC_VER
9737 # include <crtdbg.h>
9738 # endif // _MSC_VER
9739 #else
9740 # include <unistd.h>
9741 #endif // GTEST_OS_WINDOWS
9742
9743 #if GTEST_OS_MAC
9744 # include <mach/mach_init.h>
9745 # include <mach/task.h>
9746 # include <mach/vm_map.h>
9747 #endif // GTEST_OS_MAC
9748
9749 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
9750 GTEST_OS_NETBSD || GTEST_OS_OPENBSD
9751 # include <sys/sysctl.h>
9752 # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
9753 # include <sys/user.h>
9754 # endif
9755 #endif
9756
9757 #if GTEST_OS_QNX
9758 # include <devctl.h>
9759 # include <fcntl.h>
9760 # include <sys/procfs.h>
9761 #endif // GTEST_OS_QNX
9762
9763 #if GTEST_OS_AIX
9764 # include <procinfo.h>
9765 # include <sys/types.h>
9766 #endif // GTEST_OS_AIX
9767
9768 #if GTEST_OS_FUCHSIA
9769 # include <zircon/process.h>
9770 # include <zircon/syscalls.h>
9771 #endif // GTEST_OS_FUCHSIA
9772
9773
9774 namespace testing {
9775 namespace internal {
9776
9777 #if defined(_MSC_VER) || defined(__BORLANDC__)
9778 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
9779 const int kStdOutFileno = 1;
9780 const int kStdErrFileno = 2;
9781 #else
9782 const int kStdOutFileno = STDOUT_FILENO;
9783 const int kStdErrFileno = STDERR_FILENO;
9784 #endif // _MSC_VER
9785
9786 #if GTEST_OS_LINUX
9787
9788 namespace {
9789 template <typename T>
ReadProcFileField(const std::string & filename,int field)9790 T ReadProcFileField(const std::string& filename, int field) {
9791 std::string dummy;
9792 std::ifstream file(filename.c_str());
9793 while (field-- > 0) {
9794 file >> dummy;
9795 }
9796 T output = 0;
9797 file >> output;
9798 return output;
9799 }
9800 } // namespace
9801
9802 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()9803 size_t GetThreadCount() {
9804 const std::string filename =
9805 (Message() << "/proc/" << getpid() << "/stat").GetString();
9806 return ReadProcFileField<int>(filename, 19);
9807 }
9808
9809 #elif GTEST_OS_MAC
9810
GetThreadCount()9811 size_t GetThreadCount() {
9812 const task_t task = mach_task_self();
9813 mach_msg_type_number_t thread_count;
9814 thread_act_array_t thread_list;
9815 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9816 if (status == KERN_SUCCESS) {
9817 // task_threads allocates resources in thread_list and we need to free them
9818 // to avoid leaks.
9819 vm_deallocate(task,
9820 reinterpret_cast<vm_address_t>(thread_list),
9821 sizeof(thread_t) * thread_count);
9822 return static_cast<size_t>(thread_count);
9823 } else {
9824 return 0;
9825 }
9826 }
9827
9828 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
9829 GTEST_OS_NETBSD
9830
9831 #if GTEST_OS_NETBSD
9832 #undef KERN_PROC
9833 #define KERN_PROC KERN_PROC2
9834 #define kinfo_proc kinfo_proc2
9835 #endif
9836
9837 #if GTEST_OS_DRAGONFLY
9838 #define KP_NLWP(kp) (kp.kp_nthreads)
9839 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
9840 #define KP_NLWP(kp) (kp.ki_numthreads)
9841 #elif GTEST_OS_NETBSD
9842 #define KP_NLWP(kp) (kp.p_nlwps)
9843 #endif
9844
9845 // Returns the number of threads running in the process, or 0 to indicate that
9846 // we cannot detect it.
GetThreadCount()9847 size_t GetThreadCount() {
9848 int mib[] = {
9849 CTL_KERN,
9850 KERN_PROC,
9851 KERN_PROC_PID,
9852 getpid(),
9853 #if GTEST_OS_NETBSD
9854 sizeof(struct kinfo_proc),
9855 1,
9856 #endif
9857 };
9858 u_int miblen = sizeof(mib) / sizeof(mib[0]);
9859 struct kinfo_proc info;
9860 size_t size = sizeof(info);
9861 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
9862 return 0;
9863 }
9864 return KP_NLWP(info);
9865 }
9866 #elif GTEST_OS_OPENBSD
9867
9868 // Returns the number of threads running in the process, or 0 to indicate that
9869 // we cannot detect it.
GetThreadCount()9870 size_t GetThreadCount() {
9871 int mib[] = {
9872 CTL_KERN,
9873 KERN_PROC,
9874 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
9875 getpid(),
9876 sizeof(struct kinfo_proc),
9877 0,
9878 };
9879 u_int miblen = sizeof(mib) / sizeof(mib[0]);
9880
9881 // get number of structs
9882 size_t size;
9883 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
9884 return 0;
9885 }
9886 mib[5] = size / mib[4];
9887
9888 // populate array of structs
9889 struct kinfo_proc info[mib[5]];
9890 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
9891 return 0;
9892 }
9893
9894 // exclude empty members
9895 int nthreads = 0;
9896 for (int i = 0; i < size / mib[4]; i++) {
9897 if (info[i].p_tid != -1)
9898 nthreads++;
9899 }
9900 return nthreads;
9901 }
9902
9903 #elif GTEST_OS_QNX
9904
9905 // Returns the number of threads running in the process, or 0 to indicate that
9906 // we cannot detect it.
GetThreadCount()9907 size_t GetThreadCount() {
9908 const int fd = open("/proc/self/as", O_RDONLY);
9909 if (fd < 0) {
9910 return 0;
9911 }
9912 procfs_info process_info;
9913 const int status =
9914 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
9915 close(fd);
9916 if (status == EOK) {
9917 return static_cast<size_t>(process_info.num_threads);
9918 } else {
9919 return 0;
9920 }
9921 }
9922
9923 #elif GTEST_OS_AIX
9924
GetThreadCount()9925 size_t GetThreadCount() {
9926 struct procentry64 entry;
9927 pid_t pid = getpid();
9928 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
9929 if (status == 1) {
9930 return entry.pi_thcount;
9931 } else {
9932 return 0;
9933 }
9934 }
9935
9936 #elif GTEST_OS_FUCHSIA
9937
GetThreadCount()9938 size_t GetThreadCount() {
9939 int dummy_buffer;
9940 size_t avail;
9941 zx_status_t status = zx_object_get_info(
9942 zx_process_self(),
9943 ZX_INFO_PROCESS_THREADS,
9944 &dummy_buffer,
9945 0,
9946 nullptr,
9947 &avail);
9948 if (status == ZX_OK) {
9949 return avail;
9950 } else {
9951 return 0;
9952 }
9953 }
9954
9955 #else
9956
GetThreadCount()9957 size_t GetThreadCount() {
9958 // There's no portable way to detect the number of threads, so we just
9959 // return 0 to indicate that we cannot detect it.
9960 return 0;
9961 }
9962
9963 #endif // GTEST_OS_LINUX
9964
9965 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9966
SleepMilliseconds(int n)9967 void SleepMilliseconds(int n) {
9968 ::Sleep(n);
9969 }
9970
AutoHandle()9971 AutoHandle::AutoHandle()
9972 : handle_(INVALID_HANDLE_VALUE) {}
9973
AutoHandle(Handle handle)9974 AutoHandle::AutoHandle(Handle handle)
9975 : handle_(handle) {}
9976
~AutoHandle()9977 AutoHandle::~AutoHandle() {
9978 Reset();
9979 }
9980
Get() const9981 AutoHandle::Handle AutoHandle::Get() const {
9982 return handle_;
9983 }
9984
Reset()9985 void AutoHandle::Reset() {
9986 Reset(INVALID_HANDLE_VALUE);
9987 }
9988
Reset(HANDLE handle)9989 void AutoHandle::Reset(HANDLE handle) {
9990 // Resetting with the same handle we already own is invalid.
9991 if (handle_ != handle) {
9992 if (IsCloseable()) {
9993 ::CloseHandle(handle_);
9994 }
9995 handle_ = handle;
9996 } else {
9997 GTEST_CHECK_(!IsCloseable())
9998 << "Resetting a valid handle to itself is likely a programmer error "
9999 "and thus not allowed.";
10000 }
10001 }
10002
IsCloseable() const10003 bool AutoHandle::IsCloseable() const {
10004 // Different Windows APIs may use either of these values to represent an
10005 // invalid handle.
10006 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
10007 }
10008
Notification()10009 Notification::Notification()
10010 : event_(::CreateEvent(nullptr, // Default security attributes.
10011 TRUE, // Do not reset automatically.
10012 FALSE, // Initially unset.
10013 nullptr)) { // Anonymous event.
10014 GTEST_CHECK_(event_.Get() != nullptr);
10015 }
10016
Notify()10017 void Notification::Notify() {
10018 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
10019 }
10020
WaitForNotification()10021 void Notification::WaitForNotification() {
10022 GTEST_CHECK_(
10023 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
10024 }
10025
Mutex()10026 Mutex::Mutex()
10027 : owner_thread_id_(0),
10028 type_(kDynamic),
10029 critical_section_init_phase_(0),
10030 critical_section_(new CRITICAL_SECTION) {
10031 ::InitializeCriticalSection(critical_section_);
10032 }
10033
~Mutex()10034 Mutex::~Mutex() {
10035 // Static mutexes are leaked intentionally. It is not thread-safe to try
10036 // to clean them up.
10037 if (type_ == kDynamic) {
10038 ::DeleteCriticalSection(critical_section_);
10039 delete critical_section_;
10040 critical_section_ = nullptr;
10041 }
10042 }
10043
Lock()10044 void Mutex::Lock() {
10045 ThreadSafeLazyInit();
10046 ::EnterCriticalSection(critical_section_);
10047 owner_thread_id_ = ::GetCurrentThreadId();
10048 }
10049
Unlock()10050 void Mutex::Unlock() {
10051 ThreadSafeLazyInit();
10052 // We don't protect writing to owner_thread_id_ here, as it's the
10053 // caller's responsibility to ensure that the current thread holds the
10054 // mutex when this is called.
10055 owner_thread_id_ = 0;
10056 ::LeaveCriticalSection(critical_section_);
10057 }
10058
10059 // Does nothing if the current thread holds the mutex. Otherwise, crashes
10060 // with high probability.
AssertHeld()10061 void Mutex::AssertHeld() {
10062 ThreadSafeLazyInit();
10063 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
10064 << "The current thread is not holding the mutex @" << this;
10065 }
10066
10067 namespace {
10068
10069 #ifdef _MSC_VER
10070 // Use the RAII idiom to flag mem allocs that are intentionally never
10071 // deallocated. The motivation is to silence the false positive mem leaks
10072 // that are reported by the debug version of MS's CRT which can only detect
10073 // if an alloc is missing a matching deallocation.
10074 // Example:
10075 // MemoryIsNotDeallocated memory_is_not_deallocated;
10076 // critical_section_ = new CRITICAL_SECTION;
10077 //
10078 class MemoryIsNotDeallocated
10079 {
10080 public:
MemoryIsNotDeallocated()10081 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
10082 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10083 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
10084 // doesn't report mem leak if there's no matching deallocation.
10085 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10086 }
10087
~MemoryIsNotDeallocated()10088 ~MemoryIsNotDeallocated() {
10089 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
10090 _CrtSetDbgFlag(old_crtdbg_flag_);
10091 }
10092
10093 private:
10094 int old_crtdbg_flag_;
10095
10096 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
10097 };
10098 #endif // _MSC_VER
10099
10100 } // namespace
10101
10102 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()10103 void Mutex::ThreadSafeLazyInit() {
10104 // Dynamic mutexes are initialized in the constructor.
10105 if (type_ == kStatic) {
10106 switch (
10107 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10108 case 0:
10109 // If critical_section_init_phase_ was 0 before the exchange, we
10110 // are the first to test it and need to perform the initialization.
10111 owner_thread_id_ = 0;
10112 {
10113 // Use RAII to flag that following mem alloc is never deallocated.
10114 #ifdef _MSC_VER
10115 MemoryIsNotDeallocated memory_is_not_deallocated;
10116 #endif // _MSC_VER
10117 critical_section_ = new CRITICAL_SECTION;
10118 }
10119 ::InitializeCriticalSection(critical_section_);
10120 // Updates the critical_section_init_phase_ to 2 to signal
10121 // initialization complete.
10122 GTEST_CHECK_(::InterlockedCompareExchange(
10123 &critical_section_init_phase_, 2L, 1L) ==
10124 1L);
10125 break;
10126 case 1:
10127 // Somebody else is already initializing the mutex; spin until they
10128 // are done.
10129 while (::InterlockedCompareExchange(&critical_section_init_phase_,
10130 2L,
10131 2L) != 2L) {
10132 // Possibly yields the rest of the thread's time slice to other
10133 // threads.
10134 ::Sleep(0);
10135 }
10136 break;
10137
10138 case 2:
10139 break; // The mutex is already initialized and ready for use.
10140
10141 default:
10142 GTEST_CHECK_(false)
10143 << "Unexpected value of critical_section_init_phase_ "
10144 << "while initializing a static mutex.";
10145 }
10146 }
10147 }
10148
10149 namespace {
10150
10151 class ThreadWithParamSupport : public ThreadWithParamBase {
10152 public:
CreateThread(Runnable * runnable,Notification * thread_can_start)10153 static HANDLE CreateThread(Runnable* runnable,
10154 Notification* thread_can_start) {
10155 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
10156 DWORD thread_id;
10157 HANDLE thread_handle = ::CreateThread(
10158 nullptr, // Default security.
10159 0, // Default stack size.
10160 &ThreadWithParamSupport::ThreadMain,
10161 param, // Parameter to ThreadMainStatic
10162 0x0, // Default creation flags.
10163 &thread_id); // Need a valid pointer for the call to work under Win98.
10164 GTEST_CHECK_(thread_handle != nullptr)
10165 << "CreateThread failed with error " << ::GetLastError() << ".";
10166 if (thread_handle == nullptr) {
10167 delete param;
10168 }
10169 return thread_handle;
10170 }
10171
10172 private:
10173 struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon5f4f31690a11::ThreadWithParamSupport::ThreadMainParam10174 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10175 : runnable_(runnable),
10176 thread_can_start_(thread_can_start) {
10177 }
10178 std::unique_ptr<Runnable> runnable_;
10179 // Does not own.
10180 Notification* thread_can_start_;
10181 };
10182
ThreadMain(void * ptr)10183 static DWORD WINAPI ThreadMain(void* ptr) {
10184 // Transfers ownership.
10185 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10186 if (param->thread_can_start_ != nullptr)
10187 param->thread_can_start_->WaitForNotification();
10188 param->runnable_->Run();
10189 return 0;
10190 }
10191
10192 // Prohibit instantiation.
10193 ThreadWithParamSupport();
10194
10195 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
10196 };
10197
10198 } // namespace
10199
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)10200 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10201 Notification* thread_can_start)
10202 : thread_(ThreadWithParamSupport::CreateThread(runnable,
10203 thread_can_start)) {
10204 }
10205
~ThreadWithParamBase()10206 ThreadWithParamBase::~ThreadWithParamBase() {
10207 Join();
10208 }
10209
Join()10210 void ThreadWithParamBase::Join() {
10211 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10212 << "Failed to join the thread with error " << ::GetLastError() << ".";
10213 }
10214
10215 // Maps a thread to a set of ThreadIdToThreadLocals that have values
10216 // instantiated on that thread and notifies them when the thread exits. A
10217 // ThreadLocal instance is expected to persist until all threads it has
10218 // values on have terminated.
10219 class ThreadLocalRegistryImpl {
10220 public:
10221 // Registers thread_local_instance as having value on the current thread.
10222 // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)10223 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10224 const ThreadLocalBase* thread_local_instance) {
10225 DWORD current_thread = ::GetCurrentThreadId();
10226 MutexLock lock(&mutex_);
10227 ThreadIdToThreadLocals* const thread_to_thread_locals =
10228 GetThreadLocalsMapLocked();
10229 ThreadIdToThreadLocals::iterator thread_local_pos =
10230 thread_to_thread_locals->find(current_thread);
10231 if (thread_local_pos == thread_to_thread_locals->end()) {
10232 thread_local_pos = thread_to_thread_locals->insert(
10233 std::make_pair(current_thread, ThreadLocalValues())).first;
10234 StartWatcherThreadFor(current_thread);
10235 }
10236 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10237 ThreadLocalValues::iterator value_pos =
10238 thread_local_values.find(thread_local_instance);
10239 if (value_pos == thread_local_values.end()) {
10240 value_pos =
10241 thread_local_values
10242 .insert(std::make_pair(
10243 thread_local_instance,
10244 std::shared_ptr<ThreadLocalValueHolderBase>(
10245 thread_local_instance->NewValueForCurrentThread())))
10246 .first;
10247 }
10248 return value_pos->second.get();
10249 }
10250
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)10251 static void OnThreadLocalDestroyed(
10252 const ThreadLocalBase* thread_local_instance) {
10253 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10254 // Clean up the ThreadLocalValues data structure while holding the lock, but
10255 // defer the destruction of the ThreadLocalValueHolderBases.
10256 {
10257 MutexLock lock(&mutex_);
10258 ThreadIdToThreadLocals* const thread_to_thread_locals =
10259 GetThreadLocalsMapLocked();
10260 for (ThreadIdToThreadLocals::iterator it =
10261 thread_to_thread_locals->begin();
10262 it != thread_to_thread_locals->end();
10263 ++it) {
10264 ThreadLocalValues& thread_local_values = it->second;
10265 ThreadLocalValues::iterator value_pos =
10266 thread_local_values.find(thread_local_instance);
10267 if (value_pos != thread_local_values.end()) {
10268 value_holders.push_back(value_pos->second);
10269 thread_local_values.erase(value_pos);
10270 // This 'if' can only be successful at most once, so theoretically we
10271 // could break out of the loop here, but we don't bother doing so.
10272 }
10273 }
10274 }
10275 // Outside the lock, let the destructor for 'value_holders' deallocate the
10276 // ThreadLocalValueHolderBases.
10277 }
10278
OnThreadExit(DWORD thread_id)10279 static void OnThreadExit(DWORD thread_id) {
10280 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
10281 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10282 // Clean up the ThreadIdToThreadLocals data structure while holding the
10283 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
10284 {
10285 MutexLock lock(&mutex_);
10286 ThreadIdToThreadLocals* const thread_to_thread_locals =
10287 GetThreadLocalsMapLocked();
10288 ThreadIdToThreadLocals::iterator thread_local_pos =
10289 thread_to_thread_locals->find(thread_id);
10290 if (thread_local_pos != thread_to_thread_locals->end()) {
10291 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10292 for (ThreadLocalValues::iterator value_pos =
10293 thread_local_values.begin();
10294 value_pos != thread_local_values.end();
10295 ++value_pos) {
10296 value_holders.push_back(value_pos->second);
10297 }
10298 thread_to_thread_locals->erase(thread_local_pos);
10299 }
10300 }
10301 // Outside the lock, let the destructor for 'value_holders' deallocate the
10302 // ThreadLocalValueHolderBases.
10303 }
10304
10305 private:
10306 // In a particular thread, maps a ThreadLocal object to its value.
10307 typedef std::map<const ThreadLocalBase*,
10308 std::shared_ptr<ThreadLocalValueHolderBase> >
10309 ThreadLocalValues;
10310 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
10311 // thread's ID.
10312 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10313
10314 // Holds the thread id and thread handle that we pass from
10315 // StartWatcherThreadFor to WatcherThreadFunc.
10316 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10317
StartWatcherThreadFor(DWORD thread_id)10318 static void StartWatcherThreadFor(DWORD thread_id) {
10319 // The returned handle will be kept in thread_map and closed by
10320 // watcher_thread in WatcherThreadFunc.
10321 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10322 FALSE,
10323 thread_id);
10324 GTEST_CHECK_(thread != nullptr);
10325 // We need to pass a valid thread ID pointer into CreateThread for it
10326 // to work correctly under Win98.
10327 DWORD watcher_thread_id;
10328 HANDLE watcher_thread = ::CreateThread(
10329 nullptr, // Default security.
10330 0, // Default stack size
10331 &ThreadLocalRegistryImpl::WatcherThreadFunc,
10332 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
10333 CREATE_SUSPENDED, &watcher_thread_id);
10334 GTEST_CHECK_(watcher_thread != nullptr);
10335 // Give the watcher thread the same priority as ours to avoid being
10336 // blocked by it.
10337 ::SetThreadPriority(watcher_thread,
10338 ::GetThreadPriority(::GetCurrentThread()));
10339 ::ResumeThread(watcher_thread);
10340 ::CloseHandle(watcher_thread);
10341 }
10342
10343 // Monitors exit from a given thread and notifies those
10344 // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)10345 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10346 const ThreadIdAndHandle* tah =
10347 reinterpret_cast<const ThreadIdAndHandle*>(param);
10348 GTEST_CHECK_(
10349 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10350 OnThreadExit(tah->first);
10351 ::CloseHandle(tah->second);
10352 delete tah;
10353 return 0;
10354 }
10355
10356 // Returns map of thread local instances.
GetThreadLocalsMapLocked()10357 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
10358 mutex_.AssertHeld();
10359 #ifdef _MSC_VER
10360 MemoryIsNotDeallocated memory_is_not_deallocated;
10361 #endif // _MSC_VER
10362 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
10363 return map;
10364 }
10365
10366 // Protects access to GetThreadLocalsMapLocked() and its return value.
10367 static Mutex mutex_;
10368 // Protects access to GetThreadMapLocked() and its return value.
10369 static Mutex thread_map_mutex_;
10370 };
10371
10372 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10373 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10374
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)10375 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10376 const ThreadLocalBase* thread_local_instance) {
10377 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10378 thread_local_instance);
10379 }
10380
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)10381 void ThreadLocalRegistry::OnThreadLocalDestroyed(
10382 const ThreadLocalBase* thread_local_instance) {
10383 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10384 }
10385
10386 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10387
10388 #if GTEST_USES_POSIX_RE
10389
10390 // Implements RE. Currently only needed for death tests.
10391
~RE()10392 RE::~RE() {
10393 if (is_valid_) {
10394 // regfree'ing an invalid regex might crash because the content
10395 // of the regex is undefined. Since the regex's are essentially
10396 // the same, one cannot be valid (or invalid) without the other
10397 // being so too.
10398 regfree(&partial_regex_);
10399 regfree(&full_regex_);
10400 }
10401 free(const_cast<char*>(pattern_));
10402 }
10403
10404 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)10405 bool RE::FullMatch(const char* str, const RE& re) {
10406 if (!re.is_valid_) return false;
10407
10408 regmatch_t match;
10409 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10410 }
10411
10412 // Returns true iff regular expression re matches a substring of str
10413 // (including str itself).
PartialMatch(const char * str,const RE & re)10414 bool RE::PartialMatch(const char* str, const RE& re) {
10415 if (!re.is_valid_) return false;
10416
10417 regmatch_t match;
10418 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10419 }
10420
10421 // Initializes an RE from its string representation.
Init(const char * regex)10422 void RE::Init(const char* regex) {
10423 pattern_ = posix::StrDup(regex);
10424
10425 // Reserves enough bytes to hold the regular expression used for a
10426 // full match.
10427 const size_t full_regex_len = strlen(regex) + 10;
10428 char* const full_pattern = new char[full_regex_len];
10429
10430 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
10431 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10432 // We want to call regcomp(&partial_regex_, ...) even if the
10433 // previous expression returns false. Otherwise partial_regex_ may
10434 // not be properly initialized can may cause trouble when it's
10435 // freed.
10436 //
10437 // Some implementation of POSIX regex (e.g. on at least some
10438 // versions of Cygwin) doesn't accept the empty string as a valid
10439 // regex. We change it to an equivalent form "()" to be safe.
10440 if (is_valid_) {
10441 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
10442 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10443 }
10444 EXPECT_TRUE(is_valid_)
10445 << "Regular expression \"" << regex
10446 << "\" is not a valid POSIX Extended regular expression.";
10447
10448 delete[] full_pattern;
10449 }
10450
10451 #elif GTEST_USES_SIMPLE_RE
10452
10453 // Returns true iff ch appears anywhere in str (excluding the
10454 // terminating '\0' character).
IsInSet(char ch,const char * str)10455 bool IsInSet(char ch, const char* str) {
10456 return ch != '\0' && strchr(str, ch) != nullptr;
10457 }
10458
10459 // Returns true iff ch belongs to the given classification. Unlike
10460 // similar functions in <ctype.h>, these aren't affected by the
10461 // current locale.
IsAsciiDigit(char ch)10462 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)10463 bool IsAsciiPunct(char ch) {
10464 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10465 }
IsRepeat(char ch)10466 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)10467 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)10468 bool IsAsciiWordChar(char ch) {
10469 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
10470 ('0' <= ch && ch <= '9') || ch == '_';
10471 }
10472
10473 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)10474 bool IsValidEscape(char c) {
10475 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
10476 }
10477
10478 // Returns true iff the given atom (specified by escaped and pattern)
10479 // matches ch. The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)10480 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
10481 if (escaped) { // "\\p" where p is pattern_char.
10482 switch (pattern_char) {
10483 case 'd': return IsAsciiDigit(ch);
10484 case 'D': return !IsAsciiDigit(ch);
10485 case 'f': return ch == '\f';
10486 case 'n': return ch == '\n';
10487 case 'r': return ch == '\r';
10488 case 's': return IsAsciiWhiteSpace(ch);
10489 case 'S': return !IsAsciiWhiteSpace(ch);
10490 case 't': return ch == '\t';
10491 case 'v': return ch == '\v';
10492 case 'w': return IsAsciiWordChar(ch);
10493 case 'W': return !IsAsciiWordChar(ch);
10494 }
10495 return IsAsciiPunct(pattern_char) && pattern_char == ch;
10496 }
10497
10498 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
10499 }
10500
10501 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)10502 static std::string FormatRegexSyntaxError(const char* regex, int index) {
10503 return (Message() << "Syntax error at index " << index
10504 << " in simple regular expression \"" << regex << "\": ").GetString();
10505 }
10506
10507 // Generates non-fatal failures and returns false if regex is invalid;
10508 // otherwise returns true.
ValidateRegex(const char * regex)10509 bool ValidateRegex(const char* regex) {
10510 if (regex == nullptr) {
10511 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
10512 return false;
10513 }
10514
10515 bool is_valid = true;
10516
10517 // True iff ?, *, or + can follow the previous atom.
10518 bool prev_repeatable = false;
10519 for (int i = 0; regex[i]; i++) {
10520 if (regex[i] == '\\') { // An escape sequence
10521 i++;
10522 if (regex[i] == '\0') {
10523 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10524 << "'\\' cannot appear at the end.";
10525 return false;
10526 }
10527
10528 if (!IsValidEscape(regex[i])) {
10529 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10530 << "invalid escape sequence \"\\" << regex[i] << "\".";
10531 is_valid = false;
10532 }
10533 prev_repeatable = true;
10534 } else { // Not an escape sequence.
10535 const char ch = regex[i];
10536
10537 if (ch == '^' && i > 0) {
10538 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10539 << "'^' can only appear at the beginning.";
10540 is_valid = false;
10541 } else if (ch == '$' && regex[i + 1] != '\0') {
10542 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10543 << "'$' can only appear at the end.";
10544 is_valid = false;
10545 } else if (IsInSet(ch, "()[]{}|")) {
10546 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10547 << "'" << ch << "' is unsupported.";
10548 is_valid = false;
10549 } else if (IsRepeat(ch) && !prev_repeatable) {
10550 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10551 << "'" << ch << "' can only follow a repeatable token.";
10552 is_valid = false;
10553 }
10554
10555 prev_repeatable = !IsInSet(ch, "^$?*+");
10556 }
10557 }
10558
10559 return is_valid;
10560 }
10561
10562 // Matches a repeated regex atom followed by a valid simple regular
10563 // expression. The regex atom is defined as c if escaped is false,
10564 // or \c otherwise. repeat is the repetition meta character (?, *,
10565 // or +). The behavior is undefined if str contains too many
10566 // characters to be indexable by size_t, in which case the test will
10567 // probably time out anyway. We are fine with this limitation as
10568 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)10569 bool MatchRepetitionAndRegexAtHead(
10570 bool escaped, char c, char repeat, const char* regex,
10571 const char* str) {
10572 const size_t min_count = (repeat == '+') ? 1 : 0;
10573 const size_t max_count = (repeat == '?') ? 1 :
10574 static_cast<size_t>(-1) - 1;
10575 // We cannot call numeric_limits::max() as it conflicts with the
10576 // max() macro on Windows.
10577
10578 for (size_t i = 0; i <= max_count; ++i) {
10579 // We know that the atom matches each of the first i characters in str.
10580 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10581 // We have enough matches at the head, and the tail matches too.
10582 // Since we only care about *whether* the pattern matches str
10583 // (as opposed to *how* it matches), there is no need to find a
10584 // greedy match.
10585 return true;
10586 }
10587 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
10588 return false;
10589 }
10590 return false;
10591 }
10592
10593 // Returns true iff regex matches a prefix of str. regex must be a
10594 // valid simple regular expression and not start with "^", or the
10595 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)10596 bool MatchRegexAtHead(const char* regex, const char* str) {
10597 if (*regex == '\0') // An empty regex matches a prefix of anything.
10598 return true;
10599
10600 // "$" only matches the end of a string. Note that regex being
10601 // valid guarantees that there's nothing after "$" in it.
10602 if (*regex == '$')
10603 return *str == '\0';
10604
10605 // Is the first thing in regex an escape sequence?
10606 const bool escaped = *regex == '\\';
10607 if (escaped)
10608 ++regex;
10609 if (IsRepeat(regex[1])) {
10610 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
10611 // here's an indirect recursion. It terminates as the regex gets
10612 // shorter in each recursion.
10613 return MatchRepetitionAndRegexAtHead(
10614 escaped, regex[0], regex[1], regex + 2, str);
10615 } else {
10616 // regex isn't empty, isn't "$", and doesn't start with a
10617 // repetition. We match the first atom of regex with the first
10618 // character of str and recurse.
10619 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
10620 MatchRegexAtHead(regex + 1, str + 1);
10621 }
10622 }
10623
10624 // Returns true iff regex matches any substring of str. regex must be
10625 // a valid simple regular expression, or the result is undefined.
10626 //
10627 // The algorithm is recursive, but the recursion depth doesn't exceed
10628 // the regex length, so we won't need to worry about running out of
10629 // stack space normally. In rare cases the time complexity can be
10630 // exponential with respect to the regex length + the string length,
10631 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)10632 bool MatchRegexAnywhere(const char* regex, const char* str) {
10633 if (regex == nullptr || str == nullptr) return false;
10634
10635 if (*regex == '^')
10636 return MatchRegexAtHead(regex + 1, str);
10637
10638 // A successful match can be anywhere in str.
10639 do {
10640 if (MatchRegexAtHead(regex, str))
10641 return true;
10642 } while (*str++ != '\0');
10643 return false;
10644 }
10645
10646 // Implements the RE class.
10647
~RE()10648 RE::~RE() {
10649 free(const_cast<char*>(pattern_));
10650 free(const_cast<char*>(full_pattern_));
10651 }
10652
10653 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)10654 bool RE::FullMatch(const char* str, const RE& re) {
10655 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10656 }
10657
10658 // Returns true iff regular expression re matches a substring of str
10659 // (including str itself).
PartialMatch(const char * str,const RE & re)10660 bool RE::PartialMatch(const char* str, const RE& re) {
10661 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10662 }
10663
10664 // Initializes an RE from its string representation.
Init(const char * regex)10665 void RE::Init(const char* regex) {
10666 pattern_ = full_pattern_ = nullptr;
10667 if (regex != nullptr) {
10668 pattern_ = posix::StrDup(regex);
10669 }
10670
10671 is_valid_ = ValidateRegex(regex);
10672 if (!is_valid_) {
10673 // No need to calculate the full pattern when the regex is invalid.
10674 return;
10675 }
10676
10677 const size_t len = strlen(regex);
10678 // Reserves enough bytes to hold the regular expression used for a
10679 // full match: we need space to prepend a '^', append a '$', and
10680 // terminate the string with '\0'.
10681 char* buffer = static_cast<char*>(malloc(len + 3));
10682 full_pattern_ = buffer;
10683
10684 if (*regex != '^')
10685 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
10686
10687 // We don't use snprintf or strncpy, as they trigger a warning when
10688 // compiled with VC++ 8.0.
10689 memcpy(buffer, regex, len);
10690 buffer += len;
10691
10692 if (len == 0 || regex[len - 1] != '$')
10693 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
10694
10695 *buffer = '\0';
10696 }
10697
10698 #endif // GTEST_USES_POSIX_RE
10699
10700 const char kUnknownFile[] = "unknown file";
10701
10702 // Formats a source file path and a line number as they would appear
10703 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)10704 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
10705 const std::string file_name(file == nullptr ? kUnknownFile : file);
10706
10707 if (line < 0) {
10708 return file_name + ":";
10709 }
10710 #ifdef _MSC_VER
10711 return file_name + "(" + StreamableToString(line) + "):";
10712 #else
10713 return file_name + ":" + StreamableToString(line) + ":";
10714 #endif // _MSC_VER
10715 }
10716
10717 // Formats a file location for compiler-independent XML output.
10718 // Although this function is not platform dependent, we put it next to
10719 // FormatFileLocation in order to contrast the two functions.
10720 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
10721 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)10722 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
10723 const char* file, int line) {
10724 const std::string file_name(file == nullptr ? kUnknownFile : file);
10725
10726 if (line < 0)
10727 return file_name;
10728 else
10729 return file_name + ":" + StreamableToString(line);
10730 }
10731
GTestLog(GTestLogSeverity severity,const char * file,int line)10732 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
10733 : severity_(severity) {
10734 const char* const marker =
10735 severity == GTEST_INFO ? "[ INFO ]" :
10736 severity == GTEST_WARNING ? "[WARNING]" :
10737 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
10738 GetStream() << ::std::endl << marker << " "
10739 << FormatFileLocation(file, line).c_str() << ": ";
10740 }
10741
10742 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()10743 GTestLog::~GTestLog() {
10744 GetStream() << ::std::endl;
10745 if (severity_ == GTEST_FATAL) {
10746 fflush(stderr);
10747 posix::Abort();
10748 }
10749 }
10750
10751 // Disable Microsoft deprecation warnings for POSIX functions called from
10752 // this class (creat, dup, dup2, and close)
10753 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
10754
10755 #if GTEST_HAS_STREAM_REDIRECTION
10756
10757 // Object that captures an output stream (stdout/stderr).
10758 class CapturedStream {
10759 public:
10760 // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)10761 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
10762 # if GTEST_OS_WINDOWS
10763 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10764 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10765
10766 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
10767 const UINT success = ::GetTempFileNameA(temp_dir_path,
10768 "gtest_redir",
10769 0, // Generate unique file name.
10770 temp_file_path);
10771 GTEST_CHECK_(success != 0)
10772 << "Unable to create a temporary file in " << temp_dir_path;
10773 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10774 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
10775 << temp_file_path;
10776 filename_ = temp_file_path;
10777 # else
10778 // There's no guarantee that a test has write access to the current
10779 // directory, so we create the temporary file in the /tmp directory
10780 // instead. We use /tmp on most systems, and /sdcard on Android.
10781 // That's because Android doesn't have /tmp.
10782 # if GTEST_OS_LINUX_ANDROID
10783 // Note: Android applications are expected to call the framework's
10784 // Context.getExternalStorageDirectory() method through JNI to get
10785 // the location of the world-writable SD Card directory. However,
10786 // this requires a Context handle, which cannot be retrieved
10787 // globally from native code. Doing so also precludes running the
10788 // code as part of a regular standalone executable, which doesn't
10789 // run in a Dalvik process (e.g. when running it through 'adb shell').
10790 //
10791 // The location /sdcard is directly accessible from native code
10792 // and is the only location (unofficially) supported by the Android
10793 // team. It's generally a symlink to the real SD Card mount point
10794 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
10795 // other OEM-customized locations. Never rely on these, and always
10796 // use /sdcard.
10797 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
10798 # else
10799 char name_template[] = "/tmp/captured_stream.XXXXXX";
10800 # endif // GTEST_OS_LINUX_ANDROID
10801 const int captured_fd = mkstemp(name_template);
10802 filename_ = name_template;
10803 # endif // GTEST_OS_WINDOWS
10804 fflush(nullptr);
10805 dup2(captured_fd, fd_);
10806 close(captured_fd);
10807 }
10808
~CapturedStream()10809 ~CapturedStream() {
10810 remove(filename_.c_str());
10811 }
10812
GetCapturedString()10813 std::string GetCapturedString() {
10814 if (uncaptured_fd_ != -1) {
10815 // Restores the original stream.
10816 fflush(nullptr);
10817 dup2(uncaptured_fd_, fd_);
10818 close(uncaptured_fd_);
10819 uncaptured_fd_ = -1;
10820 }
10821
10822 FILE* const file = posix::FOpen(filename_.c_str(), "r");
10823 const std::string content = ReadEntireFile(file);
10824 posix::FClose(file);
10825 return content;
10826 }
10827
10828 private:
10829 const int fd_; // A stream to capture.
10830 int uncaptured_fd_;
10831 // Name of the temporary file holding the stderr output.
10832 ::std::string filename_;
10833
10834 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
10835 };
10836
10837 GTEST_DISABLE_MSC_DEPRECATED_POP_()
10838
10839 static CapturedStream* g_captured_stderr = nullptr;
10840 static CapturedStream* g_captured_stdout = nullptr;
10841
10842 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)10843 static void CaptureStream(int fd, const char* stream_name,
10844 CapturedStream** stream) {
10845 if (*stream != nullptr) {
10846 GTEST_LOG_(FATAL) << "Only one " << stream_name
10847 << " capturer can exist at a time.";
10848 }
10849 *stream = new CapturedStream(fd);
10850 }
10851
10852 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)10853 static std::string GetCapturedStream(CapturedStream** captured_stream) {
10854 const std::string content = (*captured_stream)->GetCapturedString();
10855
10856 delete *captured_stream;
10857 *captured_stream = nullptr;
10858
10859 return content;
10860 }
10861
10862 // Starts capturing stdout.
CaptureStdout()10863 void CaptureStdout() {
10864 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
10865 }
10866
10867 // Starts capturing stderr.
CaptureStderr()10868 void CaptureStderr() {
10869 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
10870 }
10871
10872 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()10873 std::string GetCapturedStdout() {
10874 return GetCapturedStream(&g_captured_stdout);
10875 }
10876
10877 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()10878 std::string GetCapturedStderr() {
10879 return GetCapturedStream(&g_captured_stderr);
10880 }
10881
10882 #endif // GTEST_HAS_STREAM_REDIRECTION
10883
10884
10885
10886
10887
GetFileSize(FILE * file)10888 size_t GetFileSize(FILE* file) {
10889 fseek(file, 0, SEEK_END);
10890 return static_cast<size_t>(ftell(file));
10891 }
10892
ReadEntireFile(FILE * file)10893 std::string ReadEntireFile(FILE* file) {
10894 const size_t file_size = GetFileSize(file);
10895 char* const buffer = new char[file_size];
10896
10897 size_t bytes_last_read = 0; // # of bytes read in the last fread()
10898 size_t bytes_read = 0; // # of bytes read so far
10899
10900 fseek(file, 0, SEEK_SET);
10901
10902 // Keeps reading the file until we cannot read further or the
10903 // pre-determined file size is reached.
10904 do {
10905 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10906 bytes_read += bytes_last_read;
10907 } while (bytes_last_read > 0 && bytes_read < file_size);
10908
10909 const std::string content(buffer, bytes_read);
10910 delete[] buffer;
10911
10912 return content;
10913 }
10914
10915 #if GTEST_HAS_DEATH_TEST
10916 static const std::vector<std::string>* g_injected_test_argvs =
10917 nullptr; // Owned.
10918
GetInjectableArgvs()10919 std::vector<std::string> GetInjectableArgvs() {
10920 if (g_injected_test_argvs != nullptr) {
10921 return *g_injected_test_argvs;
10922 }
10923 return GetArgvs();
10924 }
10925
SetInjectableArgvs(const std::vector<std::string> * new_argvs)10926 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
10927 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
10928 g_injected_test_argvs = new_argvs;
10929 }
10930
SetInjectableArgvs(const std::vector<std::string> & new_argvs)10931 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
10932 SetInjectableArgvs(
10933 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10934 }
10935
ClearInjectableArgvs()10936 void ClearInjectableArgvs() {
10937 delete g_injected_test_argvs;
10938 g_injected_test_argvs = nullptr;
10939 }
10940 #endif // GTEST_HAS_DEATH_TEST
10941
10942 #if GTEST_OS_WINDOWS_MOBILE
10943 namespace posix {
Abort()10944 void Abort() {
10945 DebugBreak();
10946 TerminateProcess(GetCurrentProcess(), 1);
10947 }
10948 } // namespace posix
10949 #endif // GTEST_OS_WINDOWS_MOBILE
10950
10951 // Returns the name of the environment variable corresponding to the
10952 // given flag. For example, FlagToEnvVar("foo") will return
10953 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)10954 static std::string FlagToEnvVar(const char* flag) {
10955 const std::string full_flag =
10956 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
10957
10958 Message env_var;
10959 for (size_t i = 0; i != full_flag.length(); i++) {
10960 env_var << ToUpper(full_flag.c_str()[i]);
10961 }
10962
10963 return env_var.GetString();
10964 }
10965
10966 // Parses 'str' for a 32-bit signed integer. If successful, writes
10967 // the result to *value and returns true; otherwise leaves *value
10968 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)10969 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
10970 // Parses the environment variable as a decimal integer.
10971 char* end = nullptr;
10972 const long long_value = strtol(str, &end, 10); // NOLINT
10973
10974 // Has strtol() consumed all characters in the string?
10975 if (*end != '\0') {
10976 // No - an invalid character was encountered.
10977 Message msg;
10978 msg << "WARNING: " << src_text
10979 << " is expected to be a 32-bit integer, but actually"
10980 << " has value \"" << str << "\".\n";
10981 printf("%s", msg.GetString().c_str());
10982 fflush(stdout);
10983 return false;
10984 }
10985
10986 // Is the parsed value in the range of an Int32?
10987 const Int32 result = static_cast<Int32>(long_value);
10988 if (long_value == LONG_MAX || long_value == LONG_MIN ||
10989 // The parsed value overflows as a long. (strtol() returns
10990 // LONG_MAX or LONG_MIN when the input overflows.)
10991 result != long_value
10992 // The parsed value overflows as an Int32.
10993 ) {
10994 Message msg;
10995 msg << "WARNING: " << src_text
10996 << " is expected to be a 32-bit integer, but actually"
10997 << " has value " << str << ", which overflows.\n";
10998 printf("%s", msg.GetString().c_str());
10999 fflush(stdout);
11000 return false;
11001 }
11002
11003 *value = result;
11004 return true;
11005 }
11006
11007 // Reads and returns the Boolean environment variable corresponding to
11008 // the given flag; if it's not set, returns default_value.
11009 //
11010 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)11011 bool BoolFromGTestEnv(const char* flag, bool default_value) {
11012 #if defined(GTEST_GET_BOOL_FROM_ENV_)
11013 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
11014 #else
11015 const std::string env_var = FlagToEnvVar(flag);
11016 const char* const string_value = posix::GetEnv(env_var.c_str());
11017 return string_value == nullptr ? default_value
11018 : strcmp(string_value, "0") != 0;
11019 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
11020 }
11021
11022 // Reads and returns a 32-bit integer stored in the environment
11023 // variable corresponding to the given flag; if it isn't set or
11024 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)11025 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
11026 #if defined(GTEST_GET_INT32_FROM_ENV_)
11027 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
11028 #else
11029 const std::string env_var = FlagToEnvVar(flag);
11030 const char* const string_value = posix::GetEnv(env_var.c_str());
11031 if (string_value == nullptr) {
11032 // The environment variable is not set.
11033 return default_value;
11034 }
11035
11036 Int32 result = default_value;
11037 if (!ParseInt32(Message() << "Environment variable " << env_var,
11038 string_value, &result)) {
11039 printf("The default value %s is used.\n",
11040 (Message() << default_value).GetString().c_str());
11041 fflush(stdout);
11042 return default_value;
11043 }
11044
11045 return result;
11046 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
11047 }
11048
11049 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
11050 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
11051 // system. The value of XML_OUTPUT_FILE is a filename without the
11052 // "xml:" prefix of GTEST_OUTPUT.
11053 // Note that this is meant to be called at the call site so it does
11054 // not check that the flag is 'output'
11055 // In essence this checks an env variable called XML_OUTPUT_FILE
11056 // and if it is set we prepend "xml:" to its value, if it not set we return ""
OutputFlagAlsoCheckEnvVar()11057 std::string OutputFlagAlsoCheckEnvVar(){
11058 std::string default_value_for_output_flag = "";
11059 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
11060 if (nullptr != xml_output_file_env) {
11061 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
11062 }
11063 return default_value_for_output_flag;
11064 }
11065
11066 // Reads and returns the string environment variable corresponding to
11067 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)11068 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
11069 #if defined(GTEST_GET_STRING_FROM_ENV_)
11070 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
11071 #else
11072 const std::string env_var = FlagToEnvVar(flag);
11073 const char* const value = posix::GetEnv(env_var.c_str());
11074 return value == nullptr ? default_value : value;
11075 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
11076 }
11077
11078 } // namespace internal
11079 } // namespace testing
11080 // Copyright 2007, Google Inc.
11081 // All rights reserved.
11082 //
11083 // Redistribution and use in source and binary forms, with or without
11084 // modification, are permitted provided that the following conditions are
11085 // met:
11086 //
11087 // * Redistributions of source code must retain the above copyright
11088 // notice, this list of conditions and the following disclaimer.
11089 // * Redistributions in binary form must reproduce the above
11090 // copyright notice, this list of conditions and the following disclaimer
11091 // in the documentation and/or other materials provided with the
11092 // distribution.
11093 // * Neither the name of Google Inc. nor the names of its
11094 // contributors may be used to endorse or promote products derived from
11095 // this software without specific prior written permission.
11096 //
11097 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11098 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11099 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11100 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11101 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11102 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11103 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11104 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11105 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11106 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11107 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11108
11109
11110 // Google Test - The Google C++ Testing and Mocking Framework
11111 //
11112 // This file implements a universal value printer that can print a
11113 // value of any type T:
11114 //
11115 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
11116 //
11117 // It uses the << operator when possible, and prints the bytes in the
11118 // object otherwise. A user can override its behavior for a class
11119 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
11120 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
11121 // defines Foo.
11122
11123 #include <stdio.h>
11124 #include <cctype>
11125 #include <cwchar>
11126 #include <ostream> // NOLINT
11127 #include <string>
11128
11129 namespace testing {
11130
11131 namespace {
11132
11133 using ::std::ostream;
11134
11135 // Prints a segment of bytes in the given object.
11136 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11137 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11138 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
11139 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)11140 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
11141 size_t count, ostream* os) {
11142 char text[5] = "";
11143 for (size_t i = 0; i != count; i++) {
11144 const size_t j = start + i;
11145 if (i != 0) {
11146 // Organizes the bytes into groups of 2 for easy parsing by
11147 // human.
11148 if ((j % 2) == 0)
11149 *os << ' ';
11150 else
11151 *os << '-';
11152 }
11153 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
11154 *os << text;
11155 }
11156 }
11157
11158 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)11159 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
11160 ostream* os) {
11161 // Tells the user how big the object is.
11162 *os << count << "-byte object <";
11163
11164 const size_t kThreshold = 132;
11165 const size_t kChunkSize = 64;
11166 // If the object size is bigger than kThreshold, we'll have to omit
11167 // some details by printing only the first and the last kChunkSize
11168 // bytes.
11169 if (count < kThreshold) {
11170 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
11171 } else {
11172 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11173 *os << " ... ";
11174 // Rounds up to 2-byte boundary.
11175 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
11176 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
11177 }
11178 *os << ">";
11179 }
11180
11181 } // namespace
11182
11183 namespace internal2 {
11184
11185 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
11186 // given object. The delegation simplifies the implementation, which
11187 // uses the << operator and thus is easier done outside of the
11188 // ::testing::internal namespace, which contains a << operator that
11189 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)11190 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
11191 ostream* os) {
11192 PrintBytesInObjectToImpl(obj_bytes, count, os);
11193 }
11194
11195 } // namespace internal2
11196
11197 namespace internal {
11198
11199 // Depending on the value of a char (or wchar_t), we print it in one
11200 // of three formats:
11201 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
11202 // - as a hexadecimal escape sequence (e.g. '\x7F'), or
11203 // - as a special escape sequence (e.g. '\r', '\n').
11204 enum CharFormat {
11205 kAsIs,
11206 kHexEscape,
11207 kSpecialEscape
11208 };
11209
11210 // Returns true if c is a printable ASCII character. We test the
11211 // value of c directly instead of calling isprint(), which is buggy on
11212 // Windows Mobile.
IsPrintableAscii(wchar_t c)11213 inline bool IsPrintableAscii(wchar_t c) {
11214 return 0x20 <= c && c <= 0x7E;
11215 }
11216
11217 // Prints a wide or narrow char c as a character literal without the
11218 // quotes, escaping it when necessary; returns how c was formatted.
11219 // The template argument UnsignedChar is the unsigned version of Char,
11220 // which is the type of c.
11221 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)11222 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11223 switch (static_cast<wchar_t>(c)) {
11224 case L'\0':
11225 *os << "\\0";
11226 break;
11227 case L'\'':
11228 *os << "\\'";
11229 break;
11230 case L'\\':
11231 *os << "\\\\";
11232 break;
11233 case L'\a':
11234 *os << "\\a";
11235 break;
11236 case L'\b':
11237 *os << "\\b";
11238 break;
11239 case L'\f':
11240 *os << "\\f";
11241 break;
11242 case L'\n':
11243 *os << "\\n";
11244 break;
11245 case L'\r':
11246 *os << "\\r";
11247 break;
11248 case L'\t':
11249 *os << "\\t";
11250 break;
11251 case L'\v':
11252 *os << "\\v";
11253 break;
11254 default:
11255 if (IsPrintableAscii(c)) {
11256 *os << static_cast<char>(c);
11257 return kAsIs;
11258 } else {
11259 ostream::fmtflags flags = os->flags();
11260 *os << "\\x" << std::hex << std::uppercase
11261 << static_cast<int>(static_cast<UnsignedChar>(c));
11262 os->flags(flags);
11263 return kHexEscape;
11264 }
11265 }
11266 return kSpecialEscape;
11267 }
11268
11269 // Prints a wchar_t c as if it's part of a string literal, escaping it when
11270 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)11271 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
11272 switch (c) {
11273 case L'\'':
11274 *os << "'";
11275 return kAsIs;
11276 case L'"':
11277 *os << "\\\"";
11278 return kSpecialEscape;
11279 default:
11280 return PrintAsCharLiteralTo<wchar_t>(c, os);
11281 }
11282 }
11283
11284 // Prints a char c as if it's part of a string literal, escaping it when
11285 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)11286 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
11287 return PrintAsStringLiteralTo(
11288 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
11289 }
11290
11291 // Prints a wide or narrow character c and its code. '\0' is printed
11292 // as "'\\0'", other unprintable characters are also properly escaped
11293 // using the standard C++ escape sequence. The template argument
11294 // UnsignedChar is the unsigned version of Char, which is the type of c.
11295 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)11296 void PrintCharAndCodeTo(Char c, ostream* os) {
11297 // First, print c as a literal in the most readable form we can find.
11298 *os << ((sizeof(c) > 1) ? "L'" : "'");
11299 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
11300 *os << "'";
11301
11302 // To aid user debugging, we also print c's code in decimal, unless
11303 // it's 0 (in which case c was printed as '\\0', making the code
11304 // obvious).
11305 if (c == 0)
11306 return;
11307 *os << " (" << static_cast<int>(c);
11308
11309 // For more convenience, we print c's code again in hexadecimal,
11310 // unless c was already printed in the form '\x##' or the code is in
11311 // [1, 9].
11312 if (format == kHexEscape || (1 <= c && c <= 9)) {
11313 // Do nothing.
11314 } else {
11315 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
11316 }
11317 *os << ")";
11318 }
11319
PrintTo(unsigned char c,::std::ostream * os)11320 void PrintTo(unsigned char c, ::std::ostream* os) {
11321 PrintCharAndCodeTo<unsigned char>(c, os);
11322 }
PrintTo(signed char c,::std::ostream * os)11323 void PrintTo(signed char c, ::std::ostream* os) {
11324 PrintCharAndCodeTo<unsigned char>(c, os);
11325 }
11326
11327 // Prints a wchar_t as a symbol if it is printable or as its internal
11328 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)11329 void PrintTo(wchar_t wc, ostream* os) {
11330 PrintCharAndCodeTo<wchar_t>(wc, os);
11331 }
11332
11333 // Prints the given array of characters to the ostream. CharType must be either
11334 // char or wchar_t.
11335 // The array starts at begin, the length is len, it may include '\0' characters
11336 // and may not be NUL-terminated.
11337 template <typename CharType>
11338 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11339 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11340 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
11341 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)11342 static CharFormat PrintCharsAsStringTo(
11343 const CharType* begin, size_t len, ostream* os) {
11344 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
11345 *os << kQuoteBegin;
11346 bool is_previous_hex = false;
11347 CharFormat print_format = kAsIs;
11348 for (size_t index = 0; index < len; ++index) {
11349 const CharType cur = begin[index];
11350 if (is_previous_hex && IsXDigit(cur)) {
11351 // Previous character is of '\x..' form and this character can be
11352 // interpreted as another hexadecimal digit in its number. Break string to
11353 // disambiguate.
11354 *os << "\" " << kQuoteBegin;
11355 }
11356 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
11357 // Remember if any characters required hex escaping.
11358 if (is_previous_hex) {
11359 print_format = kHexEscape;
11360 }
11361 }
11362 *os << "\"";
11363 return print_format;
11364 }
11365
11366 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
11367 // 'begin'. CharType must be either char or wchar_t.
11368 template <typename CharType>
11369 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11370 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11371 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
11372 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)11373 static void UniversalPrintCharArray(
11374 const CharType* begin, size_t len, ostream* os) {
11375 // The code
11376 // const char kFoo[] = "foo";
11377 // generates an array of 4, not 3, elements, with the last one being '\0'.
11378 //
11379 // Therefore when printing a char array, we don't print the last element if
11380 // it's '\0', such that the output matches the string literal as it's
11381 // written in the source code.
11382 if (len > 0 && begin[len - 1] == '\0') {
11383 PrintCharsAsStringTo(begin, len - 1, os);
11384 return;
11385 }
11386
11387 // If, however, the last element in the array is not '\0', e.g.
11388 // const char kFoo[] = { 'f', 'o', 'o' };
11389 // we must print the entire array. We also print a message to indicate
11390 // that the array is not NUL-terminated.
11391 PrintCharsAsStringTo(begin, len, os);
11392 *os << " (no terminating NUL)";
11393 }
11394
11395 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)11396 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
11397 UniversalPrintCharArray(begin, len, os);
11398 }
11399
11400 // Prints a (const) wchar_t array of 'len' elements, starting at address
11401 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)11402 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
11403 UniversalPrintCharArray(begin, len, os);
11404 }
11405
11406 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)11407 void PrintTo(const char* s, ostream* os) {
11408 if (s == nullptr) {
11409 *os << "NULL";
11410 } else {
11411 *os << ImplicitCast_<const void*>(s) << " pointing to ";
11412 PrintCharsAsStringTo(s, strlen(s), os);
11413 }
11414 }
11415
11416 // MSVC compiler can be configured to define whar_t as a typedef
11417 // of unsigned short. Defining an overload for const wchar_t* in that case
11418 // would cause pointers to unsigned shorts be printed as wide strings,
11419 // possibly accessing more memory than intended and causing invalid
11420 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
11421 // wchar_t is implemented as a native type.
11422 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
11423 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)11424 void PrintTo(const wchar_t* s, ostream* os) {
11425 if (s == nullptr) {
11426 *os << "NULL";
11427 } else {
11428 *os << ImplicitCast_<const void*>(s) << " pointing to ";
11429 PrintCharsAsStringTo(s, wcslen(s), os);
11430 }
11431 }
11432 #endif // wchar_t is native
11433
11434 namespace {
11435
ContainsUnprintableControlCodes(const char * str,size_t length)11436 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
11437 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11438
11439 for (size_t i = 0; i < length; i++) {
11440 unsigned char ch = *s++;
11441 if (std::iscntrl(ch)) {
11442 switch (ch) {
11443 case '\t':
11444 case '\n':
11445 case '\r':
11446 break;
11447 default:
11448 return true;
11449 }
11450 }
11451 }
11452 return false;
11453 }
11454
IsUTF8TrailByte(unsigned char t)11455 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
11456
IsValidUTF8(const char * str,size_t length)11457 bool IsValidUTF8(const char* str, size_t length) {
11458 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11459
11460 for (size_t i = 0; i < length;) {
11461 unsigned char lead = s[i++];
11462
11463 if (lead <= 0x7f) {
11464 continue; // single-byte character (ASCII) 0..7F
11465 }
11466 if (lead < 0xc2) {
11467 return false; // trail byte or non-shortest form
11468 } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11469 ++i; // 2-byte character
11470 } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11471 IsUTF8TrailByte(s[i]) &&
11472 IsUTF8TrailByte(s[i + 1]) &&
11473 // check for non-shortest form and surrogate
11474 (lead != 0xe0 || s[i] >= 0xa0) &&
11475 (lead != 0xed || s[i] < 0xa0)) {
11476 i += 2; // 3-byte character
11477 } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11478 IsUTF8TrailByte(s[i]) &&
11479 IsUTF8TrailByte(s[i + 1]) &&
11480 IsUTF8TrailByte(s[i + 2]) &&
11481 // check for non-shortest form
11482 (lead != 0xf0 || s[i] >= 0x90) &&
11483 (lead != 0xf4 || s[i] < 0x90)) {
11484 i += 3; // 4-byte character
11485 } else {
11486 return false;
11487 }
11488 }
11489 return true;
11490 }
11491
ConditionalPrintAsText(const char * str,size_t length,ostream * os)11492 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
11493 if (!ContainsUnprintableControlCodes(str, length) &&
11494 IsValidUTF8(str, length)) {
11495 *os << "\n As Text: \"" << str << "\"";
11496 }
11497 }
11498
11499 } // anonymous namespace
11500
PrintStringTo(const::std::string & s,ostream * os)11501 void PrintStringTo(const ::std::string& s, ostream* os) {
11502 if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11503 if (GTEST_FLAG(print_utf8)) {
11504 ConditionalPrintAsText(s.data(), s.size(), os);
11505 }
11506 }
11507 }
11508
11509 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)11510 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
11511 PrintCharsAsStringTo(s.data(), s.size(), os);
11512 }
11513 #endif // GTEST_HAS_STD_WSTRING
11514
11515 } // namespace internal
11516
11517 } // namespace testing
11518 // Copyright 2008, Google Inc.
11519 // All rights reserved.
11520 //
11521 // Redistribution and use in source and binary forms, with or without
11522 // modification, are permitted provided that the following conditions are
11523 // met:
11524 //
11525 // * Redistributions of source code must retain the above copyright
11526 // notice, this list of conditions and the following disclaimer.
11527 // * Redistributions in binary form must reproduce the above
11528 // copyright notice, this list of conditions and the following disclaimer
11529 // in the documentation and/or other materials provided with the
11530 // distribution.
11531 // * Neither the name of Google Inc. nor the names of its
11532 // contributors may be used to endorse or promote products derived from
11533 // this software without specific prior written permission.
11534 //
11535 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11536 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11537 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11538 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11539 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11540 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11541 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11542 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11543 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11544 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11545 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11546
11547 //
11548 // The Google C++ Testing and Mocking Framework (Google Test)
11549
11550
11551 namespace testing {
11552
11553 using internal::GetUnitTestImpl;
11554
11555 // Gets the summary of the failure message by omitting the stack trace
11556 // in it.
ExtractSummary(const char * message)11557 std::string TestPartResult::ExtractSummary(const char* message) {
11558 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
11559 return stack_trace == nullptr ? message : std::string(message, stack_trace);
11560 }
11561
11562 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)11563 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
11564 return os << result.file_name() << ":" << result.line_number() << ": "
11565 << (result.type() == TestPartResult::kSuccess
11566 ? "Success"
11567 : result.type() == TestPartResult::kSkip
11568 ? "Skipped"
11569 : result.type() == TestPartResult::kFatalFailure
11570 ? "Fatal failure"
11571 : "Non-fatal failure")
11572 << ":\n"
11573 << result.message() << std::endl;
11574 }
11575
11576 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)11577 void TestPartResultArray::Append(const TestPartResult& result) {
11578 array_.push_back(result);
11579 }
11580
11581 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const11582 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
11583 if (index < 0 || index >= size()) {
11584 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
11585 internal::posix::Abort();
11586 }
11587
11588 return array_[index];
11589 }
11590
11591 // Returns the number of TestPartResult objects in the array.
size() const11592 int TestPartResultArray::size() const {
11593 return static_cast<int>(array_.size());
11594 }
11595
11596 namespace internal {
11597
HasNewFatalFailureHelper()11598 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11599 : has_new_fatal_failure_(false),
11600 original_reporter_(GetUnitTestImpl()->
11601 GetTestPartResultReporterForCurrentThread()) {
11602 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
11603 }
11604
~HasNewFatalFailureHelper()11605 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11606 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11607 original_reporter_);
11608 }
11609
ReportTestPartResult(const TestPartResult & result)11610 void HasNewFatalFailureHelper::ReportTestPartResult(
11611 const TestPartResult& result) {
11612 if (result.fatally_failed())
11613 has_new_fatal_failure_ = true;
11614 original_reporter_->ReportTestPartResult(result);
11615 }
11616
11617 } // namespace internal
11618
11619 } // namespace testing
11620 // Copyright 2008 Google Inc.
11621 // All Rights Reserved.
11622 //
11623 // Redistribution and use in source and binary forms, with or without
11624 // modification, are permitted provided that the following conditions are
11625 // met:
11626 //
11627 // * Redistributions of source code must retain the above copyright
11628 // notice, this list of conditions and the following disclaimer.
11629 // * Redistributions in binary form must reproduce the above
11630 // copyright notice, this list of conditions and the following disclaimer
11631 // in the documentation and/or other materials provided with the
11632 // distribution.
11633 // * Neither the name of Google Inc. nor the names of its
11634 // contributors may be used to endorse or promote products derived from
11635 // this software without specific prior written permission.
11636 //
11637 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11638 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11639 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11640 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11641 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11642 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11643 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11644 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11645 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11646 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11647 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11648
11649
11650
11651
11652 namespace testing {
11653 namespace internal {
11654
11655 #if GTEST_HAS_TYPED_TEST_P
11656
11657 // Skips to the first non-space char in str. Returns an empty string if str
11658 // contains only whitespace characters.
SkipSpaces(const char * str)11659 static const char* SkipSpaces(const char* str) {
11660 while (IsSpace(*str))
11661 str++;
11662 return str;
11663 }
11664
SplitIntoTestNames(const char * src)11665 static std::vector<std::string> SplitIntoTestNames(const char* src) {
11666 std::vector<std::string> name_vec;
11667 src = SkipSpaces(src);
11668 for (; src != nullptr; src = SkipComma(src)) {
11669 name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
11670 }
11671 return name_vec;
11672 }
11673
11674 // Verifies that registered_tests match the test names in
11675 // registered_tests_; returns registered_tests if successful, or
11676 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)11677 const char* TypedTestSuitePState::VerifyRegisteredTestNames(
11678 const char* file, int line, const char* registered_tests) {
11679 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11680 registered_ = true;
11681
11682 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11683
11684 Message errors;
11685
11686 std::set<std::string> tests;
11687 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11688 name_it != name_vec.end(); ++name_it) {
11689 const std::string& name = *name_it;
11690 if (tests.count(name) != 0) {
11691 errors << "Test " << name << " is listed more than once.\n";
11692 continue;
11693 }
11694
11695 bool found = false;
11696 for (RegisteredTestIter it = registered_tests_.begin();
11697 it != registered_tests_.end();
11698 ++it) {
11699 if (name == it->first) {
11700 found = true;
11701 break;
11702 }
11703 }
11704
11705 if (found) {
11706 tests.insert(name);
11707 } else {
11708 errors << "No test named " << name
11709 << " can be found in this test suite.\n";
11710 }
11711 }
11712
11713 for (RegisteredTestIter it = registered_tests_.begin();
11714 it != registered_tests_.end();
11715 ++it) {
11716 if (tests.count(it->first) == 0) {
11717 errors << "You forgot to list test " << it->first << ".\n";
11718 }
11719 }
11720
11721 const std::string& errors_str = errors.GetString();
11722 if (errors_str != "") {
11723 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
11724 errors_str.c_str());
11725 fflush(stderr);
11726 posix::Abort();
11727 }
11728
11729 return registered_tests;
11730 }
11731
11732 #endif // GTEST_HAS_TYPED_TEST_P
11733
11734 } // namespace internal
11735 } // namespace testing
11736