blob: dd43444e9697f36dcd4470e9a5a1444a75854e95 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080029
Austin Schuh70cc9552019-01-21 19:46:48 -080030//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080031// Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -080032//
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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080069
Austin Schuh70cc9552019-01-21 19:46:48 -080070//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080071// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -080072
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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800101
Austin Schuh70cc9552019-01-21 19:46:48 -0800102//
103// Utilities for testing Google Test itself and code that uses Google Test
104// (e.g. frameworks built on top of Google Test).
105
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800106// GOOGLETEST_CM0004 DO NOT DELETE
107
Austin Schuh70cc9552019-01-21 19:46:48 -0800108#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
109#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110
111
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800112GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
113/* class A needs to have dll-interface to be used by clients of class B */)
114
Austin Schuh70cc9552019-01-21 19:46:48 -0800115namespace 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.
126class 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800146 ~ScopedFakeTestPartResultReporter() override;
Austin Schuh70cc9552019-01-21 19:46:48 -0800147
148 // Appends the TestPartResult object to the TestPartResultArray
149 // received in the constructor.
150 //
151 // This method is from the TestPartResultReporterInterface
152 // interface.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800153 void ReportTestPartResult(const TestPartResult& result) override;
154
Austin Schuh70cc9552019-01-21 19:46:48 -0800155 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
165namespace 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.
172class GTEST_API_ SingleFailureChecker {
173 public:
174 // The constructor remembers the arguments.
175 SingleFailureChecker(const TestPartResultArray* results,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800176 TestPartResult::Type type, const std::string& substr);
Austin Schuh70cc9552019-01-21 19:46:48 -0800177 ~SingleFailureChecker();
178 private:
179 const TestPartResultArray* const results_;
180 const TestPartResult::Type type_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800181 const std::string substr_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800182
183 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184};
185
186} // namespace internal
187
188} // namespace testing
189
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800190GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
191
Austin Schuh70cc9552019-01-21 19:46:48 -0800192// 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 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
224 {\
225 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
226 ::testing::ScopedFakeTestPartResultReporter:: \
227 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_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 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
241 {\
242 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
243 ::testing::ScopedFakeTestPartResultReporter:: \
244 INTERCEPT_ALL_THREADS, &gtest_failures);\
245 GTestExpectFatalFailureHelper::Execute();\
246 }\
247 } while (::testing::internal::AlwaysFalse())
248
249// A macro for testing Google Test assertions or code that's expected to
250// generate Google Test non-fatal failures. It asserts that the given
251// statement will cause exactly one non-fatal Google Test failure with 'substr'
252// being part of the failure message.
253//
254// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255// affects and considers failures generated in the current thread and
256// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257//
258// 'statement' is allowed to reference local variables and members of
259// the current object.
260//
261// The verification of the assertion is done correctly even when the statement
262// throws an exception or aborts the current function.
263//
264// Known restrictions:
265// - You cannot stream a failure message to this macro.
266//
267// Note that even though the implementations of the following two
268// macros are much alike, we cannot refactor them to use a common
269// helper macro, due to some peculiarity in how the preprocessor
270// works. If we do that, the code won't compile when the user gives
271// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272// expands to code containing an unprotected comma. The
273// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274// catches that.
275//
276// For the same reason, we have to write
277// if (::testing::internal::AlwaysTrue()) { statement; }
278// instead of
279// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280// to avoid an MSVC warning on unreachable code.
281#define EXPECT_NONFATAL_FAILURE(statement, substr) \
282 do {\
283 ::testing::TestPartResultArray gtest_failures;\
284 ::testing::internal::SingleFailureChecker gtest_checker(\
285 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
286 (substr));\
287 {\
288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
289 ::testing::ScopedFakeTestPartResultReporter:: \
290 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_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 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
300 (substr));\
301 {\
302 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
303 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
304 &gtest_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
Austin Schuh70cc9552019-01-21 19:46:48 -0800331# 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
Austin Schuh70cc9552019-01-21 19:46:48 -0800343#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().
Austin Schuh70cc9552019-01-21 19:46:48 -0800364# 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().
Austin Schuh70cc9552019-01-21 19:46:48 -0800376# 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
Austin Schuh70cc9552019-01-21 19:46:48 -0800396// 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800425// Utility functions and classes used by the Google C++ testing framework.//
Austin Schuh70cc9552019-01-21 19:46:48 -0800426// 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
Austin Schuh70cc9552019-01-21 19:46:48 -0800432#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>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800440#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -0800441#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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800455GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
456/* class A needs to have dll-interface to be used by clients of class B */)
457
Austin Schuh70cc9552019-01-21 19:46:48 -0800458namespace 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.
465GTEST_DECLARE_bool_(death_test_use_fork);
466
467namespace internal {
468
469// The value of GetTestTypeId() as seen from within the Google Test
470// library. This is solely for testing GetTestTypeId().
471GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
472
473// Names of the flags (needed for parsing Google Test flags).
474const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
475const char kBreakOnFailureFlag[] = "break_on_failure";
476const char kCatchExceptionsFlag[] = "catch_exceptions";
477const char kColorFlag[] = "color";
478const char kFilterFlag[] = "filter";
479const char kListTestsFlag[] = "list_tests";
480const char kOutputFlag[] = "output";
481const char kPrintTimeFlag[] = "print_time";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800482const char kPrintUTF8Flag[] = "print_utf8";
Austin Schuh70cc9552019-01-21 19:46:48 -0800483const char kRandomSeedFlag[] = "random_seed";
484const char kRepeatFlag[] = "repeat";
485const char kShuffleFlag[] = "shuffle";
486const char kStackTraceDepthFlag[] = "stack_trace_depth";
487const char kStreamResultToFlag[] = "stream_result_to";
488const char kThrowOnFailureFlag[] = "throw_on_failure";
489const char kFlagfileFlag[] = "flagfile";
490
491// A valid random seed must be in [1, kMaxRandomSeed].
492const 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.
496GTEST_API_ extern bool g_help_flag;
497
498// Returns the current time in milliseconds.
499GTEST_API_ TimeInMillis GetTimeInMillis();
500
501// Returns true iff Google Test should use colors in the output.
502GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
503
504// Formats the given time in milliseconds as seconds.
505GTEST_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.
511GTEST_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.
517GTEST_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.
522inline 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.
538inline 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.
548class GTestFlagSaver {
549 public:
550 // The c'tor.
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);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800563 print_utf8_ = GTEST_FLAG(print_utf8);
Austin Schuh70cc9552019-01-21 19:46:48 -0800564 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.
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_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800585 GTEST_FLAG(print_utf8) = print_utf8_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800586 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_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800607 bool print_utf8_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800608 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)".
622GTEST_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:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800626// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
Austin Schuh70cc9552019-01-21 19:46:48 -0800627// 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.
637GTEST_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.
643void 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.
651GTEST_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.
658GTEST_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.
664GTEST_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.
671template <class Container, typename Predicate>
672inline 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.
684template <class Container, typename Functor>
685void 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()).
691template <typename E>
692inline 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.
700template <typename E>
701void 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.
721template <typename E>
722inline 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.
728template <typename T>
729static 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.
736class TestPropertyKeyIs {
737 public:
738 // Constructor.
739 //
740 // TestPropertyKeyIs has NO default constructor.
741 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
742
743 // Returns true iff the test name of test property matches on key_.
744 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.
762class 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800783 // Returns true iff the user-specified filter matches the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -0800784 // name and the test name.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800785 static bool FilterMatchesTest(const std::string& test_suite_name,
786 const std::string& test_name);
Austin Schuh70cc9552019-01-21 19:46:48 -0800787
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.
804GTEST_API_ FilePath GetCurrentExecutableName();
805
806// The role interface for getting the OS stack trace as a string.
807class OsStackTraceGetterInterface {
808 public:
809 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800818 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
Austin Schuh70cc9552019-01-21 19:46:48 -0800819
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.
834class OsStackTraceGetter : public OsStackTraceGetterInterface {
835 public:
836 OsStackTraceGetter() {}
837
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800838 std::string CurrentStackTrace(int max_depth, int skip_count) override;
839 void UponLeavingGTest() override;
Austin Schuh70cc9552019-01-21 19:46:48 -0800840
841 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800842#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
Austin Schuh70cc9552019-01-21 19:46:48 -0800852 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
853};
854
855// Information about a Google Test trace point.
856struct 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.
864class 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800870 void ReportTestPartResult(const TestPartResult& result) override;
Austin Schuh70cc9552019-01-21 19:46:48 -0800871
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.
880class 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_.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800886 void ReportTestPartResult(const TestPartResult& result) override;
Austin Schuh70cc9552019-01-21 19:46:48 -0800887
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.
898class 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800924 // Gets the number of successful test suites.
925 int successful_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -0800926
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800927 // Gets the number of failed test suites.
928 int failed_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -0800929
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800930 // Gets the number of all test suites.
931 int total_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -0800932
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800933 // Gets the number of all test suites that contain at least one test
Austin Schuh70cc9552019-01-21 19:46:48 -0800934 // that should run.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800935 int test_suite_to_run_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -0800936
937 // Gets the number of successful tests.
938 int successful_test_count() const;
939
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800940 // Gets the number of skipped tests.
941 int skipped_test_count() const;
942
Austin Schuh70cc9552019-01-21 19:46:48 -0800943 // 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.
963 TimeInMillis start_timestamp() const { return start_timestamp_; }
964
965 // Gets the elapsed time, in milliseconds.
966 TimeInMillis elapsed_time() const { return elapsed_time_; }
967
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800968 // Returns true iff the unit test passed (i.e. all test suites passed).
Austin Schuh70cc9552019-01-21 19:46:48 -0800969 bool Passed() const { return !Failed(); }
970
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800971 // Returns true iff the unit test failed (i.e. some test suite failed
Austin Schuh70cc9552019-01-21 19:46:48 -0800972 // or something outside of all tests failed).
973 bool Failed() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800974 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
Austin Schuh70cc9552019-01-21 19:46:48 -0800975 }
976
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800977 // 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.
979 const TestSuite* GetTestSuite(int i) const {
980 const int index = GetElementOr(test_suite_indices_, i, -1);
981 return index < 0 ? nullptr : test_suites_[i];
Austin Schuh70cc9552019-01-21 19:46:48 -0800982 }
983
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800984 // Legacy API is deprecated but still available
985#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
986 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.
991 TestSuite* GetMutableSuiteCase(int i) {
992 const int index = GetElementOr(test_suite_indices_, i, -1);
993 return index < 0 ? nullptr : test_suites_[index];
Austin Schuh70cc9552019-01-21 19:46:48 -0800994 }
995
996 // Provides access to the event listener list.
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.
1004 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001030 // Finds and returns a TestSuite with the given name. If one doesn't
Austin Schuh70cc9552019-01-21 19:46:48 -08001031 // exist, creates one and returns it.
1032 //
1033 // Arguments:
1034 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001035 // test_suite_name: name of the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08001036 // type_param: the name of the test's type parameter, or NULL if
1037 // this is not a typed or a type-parameterized test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001038 // 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_
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_
Austin Schuh70cc9552019-01-21 19:46:48 -08001052
1053 // Adds a TestInfo to the unit test.
1054 //
1055 // Arguments:
1056 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001057 // 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001059 // test_info: the TestInfo object
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001060 void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
1061 internal::TearDownTestSuiteFunc tear_down_tc,
Austin Schuh70cc9552019-01-21 19:46:48 -08001062 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001076 GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1077 set_up_tc, tear_down_tc)
1078 ->AddTestInfo(test_info);
Austin Schuh70cc9552019-01-21 19:46:48 -08001079 }
1080
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001081 // Returns ParameterizedTestSuiteRegistry object used to keep track of
Austin Schuh70cc9552019-01-21 19:46:48 -08001082 // value-parameterized tests and instantiate and register them.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001083 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
Austin Schuh70cc9552019-01-21 19:46:48 -08001084 return parameterized_test_registry_;
1085 }
Austin Schuh70cc9552019-01-21 19:46:48 -08001086
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001087 // Sets the TestSuite object for the test that's currently running.
1088 void set_current_test_suite(TestSuite* a_current_test_suite) {
1089 current_test_suite_ = a_current_test_suite;
Austin Schuh70cc9552019-01-21 19:46:48 -08001090 }
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_.
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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001100 // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
Austin Schuh70cc9552019-01-21 19:46:48 -08001101 // 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.
1114 void ClearNonAdHocTestResult() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001115 ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
Austin Schuh70cc9552019-01-21 19:46:48 -08001116 }
1117
1118 // Clears the results of ad-hoc test assertions.
1119 void ClearAdHocTestResult() {
1120 ad_hoc_test_result_.Clear();
1121 }
1122
1123 // Adds a TestProperty to the current TestResult object when invoked in a
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001124 // context of a test or a test suite, or to the global property set. If the
Austin Schuh70cc9552019-01-21 19:46:48 -08001125 // 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001136 // result in each TestSuite and TestInfo object.
Austin Schuh70cc9552019-01-21 19:46:48 -08001137 // 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001145 const TestSuite* current_test_suite() const { return current_test_suite_; }
Austin Schuh70cc9552019-01-21 19:46:48 -08001146 TestInfo* current_test_info() { return current_test_info_; }
1147 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.
1151 std::vector<Environment*>& environments() { return environments_; }
1152
1153 // Getters for the per-thread Google Test trace stack.
1154 std::vector<TraceInfo>& gtest_trace_stack() {
1155 return *(gtest_trace_stack_.pointer());
1156 }
1157 const std::vector<TraceInfo>& gtest_trace_stack() const {
1158 return gtest_trace_stack_.get();
1159 }
1160
1161#if GTEST_HAS_DEATH_TEST
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.
1169 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.
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.
1201 int random_seed() const { return random_seed_; }
1202
1203 // Gets the random number generator.
1204 internal::Random* random() { return &random_; }
1205
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001206 // Shuffles all test suites, and the tests within each test suite,
Austin Schuh70cc9552019-01-21 19:46:48 -08001207 // making sure that death tests are still run first.
1208 void ShuffleTests();
1209
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001210 // Restores the test suites and tests to their order before the first shuffle.
Austin Schuh70cc9552019-01-21 19:46:48 -08001211 void UnshuffleTests();
1212
1213 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1214 // UnitTest::Run() starts.
1215 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.
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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001250 // The vector of TestSuites in their original order. It owns the
Austin Schuh70cc9552019-01-21 19:46:48 -08001251 // elements in the vector.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001252 std::vector<TestSuite*> test_suites_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001253
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001254 // 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001257 // shuffled order.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001258 std::vector<int> test_suite_indices_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001259
Austin Schuh70cc9552019-01-21 19:46:48 -08001260 // ParameterizedTestRegistry object used to register value-parameterized
1261 // tests.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001262 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001263
1264 // Indicates whether RegisterParameterizedTests() has been called already.
1265 bool parameterized_tests_registered_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001266
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001267 // Index of the last death test suite registered. Initially -1.
1268 int last_death_test_suite_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001269
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001270 // This points to the TestSuite for the currently running test. It
1271 // changes as Google Test goes through one test suite after another.
Austin Schuh70cc9552019-01-21 19:46:48 -08001272 // When no test is running, this is set to NULL and Google Test
1273 // stores assertion results in ad_hoc_test_result_. Initially NULL.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001274 TestSuite* current_test_suite_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001275
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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001321 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322 std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001323#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.
1337inline 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.
1345GTEST_API_ bool IsInSet(char ch, const char* str);
1346GTEST_API_ bool IsAsciiDigit(char ch);
1347GTEST_API_ bool IsAsciiPunct(char ch);
1348GTEST_API_ bool IsRepeat(char ch);
1349GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1350GTEST_API_ bool IsAsciiWordChar(char ch);
1351GTEST_API_ bool IsValidEscape(char ch);
1352GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1353GTEST_API_ bool ValidateRegex(const char* regex);
1354GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped, char ch, char repeat, const char* regex, const char* str);
1357GTEST_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.
1363GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364GTEST_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.
1370GTEST_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.
1376template <typename Integer>
1377bool 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001405 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.
1422class TestResultAccessor {
1423 public:
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
1430 static void ClearTestPartResults(TestResult* test_result) {
1431 test_result->ClearTestPartResults();
1432 }
1433
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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001443class StreamingListener : public EmptyTestEventListener {
Austin Schuh70cc9552019-01-21 19:46:48 -08001444 public:
1445 // Abstract base class for writing strings to a socket.
1446 class AbstractSocketWriter {
1447 public:
1448 virtual ~AbstractSocketWriter() {}
1449
1450 // Sends a string to the socket.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001451 virtual void Send(const std::string& message) = 0;
Austin Schuh70cc9552019-01-21 19:46:48 -08001452
1453 // Closes the socket.
1454 virtual void CloseConnection() {}
1455
1456 // Sends a string and a newline to the socket.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001457 void SendLn(const std::string& message) { Send(message + "\n"); }
Austin Schuh70cc9552019-01-21 19:46:48 -08001458 };
1459
1460 // Concrete class for actually writing strings to a socket.
1461 class SocketWriter : public AbstractSocketWriter {
1462 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001463 SocketWriter(const std::string& host, const std::string& port)
Austin Schuh70cc9552019-01-21 19:46:48 -08001464 : sockfd_(-1), host_name_(host), port_num_(port) {
1465 MakeConnection();
1466 }
1467
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001468 ~SocketWriter() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001469 if (sockfd_ != -1)
1470 CloseConnection();
1471 }
1472
1473 // Sends a string to the socket.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001474 void Send(const std::string& message) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001475 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001491 void CloseConnection() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001492 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001500 const std::string host_name_;
1501 const std::string port_num_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001502
1503 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1504 }; // class SocketWriter
1505
1506 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001507 static std::string UrlEncode(const char* str);
Austin Schuh70cc9552019-01-21 19:46:48 -08001508
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001509 StreamingListener(const std::string& host, const std::string& port)
1510 : socket_writer_(new SocketWriter(host, port)) {
1511 Start();
1512 }
Austin Schuh70cc9552019-01-21 19:46:48 -08001513
1514 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1515 : socket_writer_(socket_writer) { Start(); }
1516
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001517 void OnTestProgramStart(const UnitTest& /* unit_test */) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001518 SendLn("event=TestProgramStart");
1519 }
1520
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001521 void OnTestProgramEnd(const UnitTest& unit_test) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001522 // 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001530 void OnTestIterationStart(const UnitTest& /* unit_test */,
1531 int iteration) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001532 SendLn("event=TestIterationStart&iteration=" +
1533 StreamableToString(iteration));
1534 }
1535
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001536 void OnTestIterationEnd(const UnitTest& unit_test,
1537 int /* iteration */) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001538 SendLn("event=TestIterationEnd&passed=" +
1539 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1540 StreamableToString(unit_test.elapsed_time()) + "ms");
1541 }
1542
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001543 // Note that "event=TestCaseStart" is a wire format and has to remain
1544 // "case" for compatibilty
1545 void OnTestCaseStart(const TestCase& test_case) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001546 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1547 }
1548
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001549 // Note that "event=TestCaseEnd" is a wire format and has to remain
1550 // "case" for compatibilty
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");
Austin Schuh70cc9552019-01-21 19:46:48 -08001555 }
1556
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001557 void OnTestStart(const TestInfo& test_info) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001558 SendLn(std::string("event=TestStart&name=") + test_info.name());
1559 }
1560
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001561 void OnTestEnd(const TestInfo& test_info) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001562 SendLn("event=TestEnd&passed=" +
1563 FormatBool((test_info.result())->Passed()) +
1564 "&elapsed_time=" +
1565 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1566 }
1567
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001568 void OnTestPartResult(const TestPartResult& test_part_result) override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001569 const char* file_name = test_part_result.file_name();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001570 if (file_name == nullptr) file_name = "";
Austin Schuh70cc9552019-01-21 19:46:48 -08001571 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001578 void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
Austin Schuh70cc9552019-01-21 19:46:48 -08001579
1580 // Called at the start of streaming to notify the receiver what
1581 // protocol we are using.
1582 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1583
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001584 std::string FormatBool(bool value) { return value ? "1" : "0"; }
Austin Schuh70cc9552019-01-21 19:46:48 -08001585
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001586 const std::unique_ptr<AbstractSocketWriter> socket_writer_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001587
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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001596GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1597
Austin Schuh70cc9552019-01-21 19:46:48 -08001598#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08001599
1600#if GTEST_OS_WINDOWS
1601# define vsnprintf _vsnprintf
1602#endif // GTEST_OS_WINDOWS
1603
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001604#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
Austin Schuh70cc9552019-01-21 19:46:48 -08001617namespace testing {
1618
1619using internal::CountIf;
1620using internal::ForEach;
1621using internal::GetElementOr;
1622using internal::Shuffle;
1623
1624// Constants.
1625
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001626// A test whose test suite name or test name matches this filter is
Austin Schuh70cc9552019-01-21 19:46:48 -08001627// disabled and not run.
1628static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1629
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001630// 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001632// match this filter.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001633static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
Austin Schuh70cc9552019-01-21 19:46:48 -08001634
1635// A test filter that matches everything.
1636static const char kUniversalFilter[] = "*";
1637
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001638// The default output format.
1639static const char kDefaultOutputFormat[] = "xml";
1640// The default output file.
1641static const char kDefaultOutputFile[] = "test_detail";
Austin Schuh70cc9552019-01-21 19:46:48 -08001642
1643// The environment variable name for the test shard index.
1644static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1645// The environment variable name for the total number of test shards.
1646static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1647// The environment variable name for the test shard status file.
1648static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1649
1650namespace internal {
1651
1652// The text used in failure messages to indicate the start of the
1653// stack trace.
1654const 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.
1658bool g_help_flag = false;
1659
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001660// Utilty function to Open File for Writing
1661static 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001675} // namespace internal
1676
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001677// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1678// environment variable.
Austin Schuh70cc9552019-01-21 19:46:48 -08001679static const char* GetDefaultFilter() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001680 const char* const testbridge_test_only =
1681 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1682 if (testbridge_test_only != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08001683 return testbridge_test_only;
1684 }
Austin Schuh70cc9552019-01-21 19:46:48 -08001685 return kUniversalFilter;
1686}
1687
1688GTEST_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
1693GTEST_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
1698GTEST_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
1704GTEST_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
1712GTEST_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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001721GTEST_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
Austin Schuh70cc9552019-01-21 19:46:48 -08001728GTEST_DEFINE_bool_(list_tests, false,
1729 "List all tests without running them.");
1730
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001731// 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// ''
Austin Schuh70cc9552019-01-21 19:46:48 -08001736GTEST_DEFINE_string_(
1737 output,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001738 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. "
Austin Schuh70cc9552019-01-21 19:46:48 -08001743 "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
1749GTEST_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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001755GTEST_DEFINE_bool_(
1756 print_utf8,
1757 internal::BoolFromGTestEnv("print_utf8", true),
1758 "True iff " GTEST_NAME_
1759 " prints UTF8 characters as text.");
1760
Austin Schuh70cc9552019-01-21 19:46:48 -08001761GTEST_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
1767GTEST_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
1773GTEST_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
1778GTEST_DEFINE_bool_(
1779 shuffle,
1780 internal::BoolFromGTestEnv("shuffle", false),
1781 "True iff " GTEST_NAME_
1782 " should randomize tests' order on every run.");
1783
1784GTEST_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
1790GTEST_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
1797GTEST_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 "
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001802 "otherwise. For use with an external test framework.");
Austin Schuh70cc9552019-01-21 19:46:48 -08001803
1804#if GTEST_USE_OWN_FLAGFILE_FLAG_
1805GTEST_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
1811namespace 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.
1816UInt32 Random::Generate(UInt32 range) {
1817 // These constants are the same as are used in glibc's rand(3).
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001818 // Use wider types than necessary to prevent unsigned overflow diagnostics.
1819 state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
Austin Schuh70cc9552019-01-21 19:46:48 -08001820
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().
1836static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1837
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001838// Iterates over a vector of TestSuites, keeping a running sum of the
Austin Schuh70cc9552019-01-21 19:46:48 -08001839// results of calling a given int-returning method on each.
1840// Returns the sum.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001841static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
1842 int (TestSuite::*method)() const) {
Austin Schuh70cc9552019-01-21 19:46:48 -08001843 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001850// Returns true iff the test suite passed.
1851static bool TestSuitePassed(const TestSuite* test_suite) {
1852 return test_suite->should_run() && test_suite->Passed();
Austin Schuh70cc9552019-01-21 19:46:48 -08001853}
1854
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001855// Returns true iff the test suite failed.
1856static bool TestSuiteFailed(const TestSuite* test_suite) {
1857 return test_suite->should_run() && test_suite->Failed();
Austin Schuh70cc9552019-01-21 19:46:48 -08001858}
1859
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001860// Returns true iff test_suite contains at least one test that should
Austin Schuh70cc9552019-01-21 19:46:48 -08001861// run.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001862static bool ShouldRunTestSuite(const TestSuite* test_suite) {
1863 return test_suite->should_run();
Austin Schuh70cc9552019-01-21 19:46:48 -08001864}
1865
1866// AssertHelper constructor.
1867AssertHelper::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
1874AssertHelper::~AssertHelper() {
1875 delete data_;
1876}
1877
1878// Message assignment, for assertion streaming support.
1879void 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
Austin Schuh70cc9552019-01-21 19:46:48 -08001889// A copy of all command line arguments. Set by InitGoogleTest().
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001890static ::std::vector<std::string> g_argvs;
Austin Schuh70cc9552019-01-21 19:46:48 -08001891
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001892::std::vector<std::string> GetArgvs() {
Austin Schuh70cc9552019-01-21 19:46:48 -08001893#if defined(GTEST_CUSTOM_GET_ARGVS_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001894 // 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_)
Austin Schuh70cc9552019-01-21 19:46:48 -08001899 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.
1905FilePath GetCurrentExecutableName() {
1906 FilePath result;
1907
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001908#if GTEST_OS_WINDOWS || GTEST_OS_OS2
Austin Schuh70cc9552019-01-21 19:46:48 -08001909 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.
1920std::string UnitTestOptions::GetOutputFormat() {
1921 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
Austin Schuh70cc9552019-01-21 19:46:48 -08001922 const char* const colon = strchr(gtest_output_flag, ':');
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001923 return (colon == nullptr)
1924 ? std::string(gtest_output_flag)
1925 : std::string(gtest_output_flag, colon - gtest_output_flag);
Austin Schuh70cc9552019-01-21 19:46:48 -08001926}
1927
1928// Returns the name of the requested output file, or the default if none
1929// was explicitly specified.
1930std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1931 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001932
1933 std::string format = GetOutputFormat();
1934 if (format.empty())
1935 format = std::string(kDefaultOutputFormat);
Austin Schuh70cc9552019-01-21 19:46:48 -08001936
1937 const char* const colon = strchr(gtest_output_flag, ':');
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001938 if (colon == nullptr)
1939 return internal::FilePath::MakeFileName(
Austin Schuh70cc9552019-01-21 19:46:48 -08001940 internal::FilePath(
1941 UnitTest::GetInstance()->original_working_dir()),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001942 internal::FilePath(kDefaultOutputFile), 0,
1943 format.c_str()).string();
Austin Schuh70cc9552019-01-21 19:46:48 -08001944
1945 internal::FilePath output_name(colon + 1);
1946 if (!output_name.IsAbsolutePath())
Austin Schuh70cc9552019-01-21 19:46:48 -08001947 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.
1965bool 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
1982bool 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001994 if (cur_pattern == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08001995 return false;
1996 }
1997
1998 // Skips the pattern separater (the ':' character).
1999 cur_pattern++;
2000 }
2001}
2002
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002003// Returns true iff the user-specified filter matches the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08002004// name and the test name.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002005bool 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();
Austin Schuh70cc9552019-01-21 19:46:48 -08002008
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;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002015 if (dash == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08002016 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.
2037int 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.
2066ScopedFakeTestPartResultReporter::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.
2076ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2077 InterceptMode intercept_mode, TestPartResultArray* result)
2078 : intercept_mode_(intercept_mode),
2079 result_(result) {
2080 Init();
2081}
2082
2083void 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.
2096ScopedFakeTestPartResultReporter::~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.
2107void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2108 const TestPartResult& result) {
2109 result_->Append(result);
2110}
2111
2112namespace 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.
2123TypeId 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().
2129extern 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002134static 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) {
Austin Schuh70cc9552019-01-21 19:46:48 -08002140 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
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002160 if (strstr(r.message(), substr.c_str()) == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08002161 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002173SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2174 TestPartResult::Type type,
2175 const std::string& substr)
2176 : results_(results), type_(type), substr_(substr) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08002177
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.
2182SingleFailureChecker::~SingleFailureChecker() {
2183 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2184}
2185
2186DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2187 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2188
2189void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2190 const TestPartResult& result) {
2191 unit_test_->current_test_result()->AddTestPartResult(result);
2192 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2193}
2194
2195DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2196 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2197
2198void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2199 const TestPartResult& result) {
2200 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2201}
2202
2203// Returns the global test part result reporter.
2204TestPartResultReporterInterface*
2205UnitTestImpl::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.
2211void 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.
2218TestPartResultReporterInterface*
2219UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2220 return per_thread_test_part_result_reporter_.get();
2221}
2222
2223// Sets the test part result reporter for the current thread.
2224void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2225 TestPartResultReporterInterface* reporter) {
2226 per_thread_test_part_result_reporter_.set(reporter);
2227}
2228
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002229// Gets the number of successful test suites.
2230int UnitTestImpl::successful_test_suite_count() const {
2231 return CountIf(test_suites_, TestSuitePassed);
Austin Schuh70cc9552019-01-21 19:46:48 -08002232}
2233
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002234// Gets the number of failed test suites.
2235int UnitTestImpl::failed_test_suite_count() const {
2236 return CountIf(test_suites_, TestSuiteFailed);
Austin Schuh70cc9552019-01-21 19:46:48 -08002237}
2238
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002239// Gets the number of all test suites.
2240int UnitTestImpl::total_test_suite_count() const {
2241 return static_cast<int>(test_suites_.size());
Austin Schuh70cc9552019-01-21 19:46:48 -08002242}
2243
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002244// Gets the number of all test suites that contain at least one test
Austin Schuh70cc9552019-01-21 19:46:48 -08002245// that should run.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002246int UnitTestImpl::test_suite_to_run_count() const {
2247 return CountIf(test_suites_, ShouldRunTestSuite);
Austin Schuh70cc9552019-01-21 19:46:48 -08002248}
2249
2250// Gets the number of successful tests.
2251int UnitTestImpl::successful_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002252 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2253}
2254
2255// Gets the number of skipped tests.
2256int UnitTestImpl::skipped_test_count() const {
2257 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002258}
2259
2260// Gets the number of failed tests.
2261int UnitTestImpl::failed_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002262 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002263}
2264
2265// Gets the number of disabled tests that will be reported in the XML report.
2266int UnitTestImpl::reportable_disabled_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002267 return SumOverTestSuiteList(test_suites_,
2268 &TestSuite::reportable_disabled_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002269}
2270
2271// Gets the number of disabled tests.
2272int UnitTestImpl::disabled_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002273 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002274}
2275
2276// Gets the number of tests to be printed in the XML report.
2277int UnitTestImpl::reportable_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002278 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002279}
2280
2281// Gets the number of all tests.
2282int UnitTestImpl::total_test_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002283 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002284}
2285
2286// Gets the number of tests that should run.
2287int UnitTestImpl::test_to_run_count() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002288 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08002289}
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.
2301std::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.
2311TimeInMillis 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;
Austin Schuh70cc9552019-01-21 19:46:48 -08002322 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.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002336 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
Austin Schuh70cc9552019-01-21 19:46:48 -08002337 _ftime64(&now);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002338 GTEST_DISABLE_MSC_DEPRECATED_POP_()
Austin Schuh70cc9552019-01-21 19:46:48 -08002339
2340 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2341#elif GTEST_HAS_GETTIMEOFDAY_
2342 struct timeval now;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002343 gettimeofday(&now, nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08002344 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.
2359LPCWSTR String::AnsiToUtf16(const char* ansi) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002360 if (!ansi) return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08002361 const int length = strlen(ansi);
2362 const int unicode_length =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002363 MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
Austin Schuh70cc9552019-01-21 19:46:48 -08002364 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.
2375const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002376 if (!utf16_str) return nullptr;
2377 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
2378 0, nullptr, nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08002379 char* ansi = new char[ansi_length + 1];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002380 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
2381 nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08002382 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.
2393bool String::CStringEquals(const char * lhs, const char * rhs) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002394 if (lhs == nullptr) return rhs == nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08002395
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002396 if (rhs == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08002397
2398 return strcmp(lhs, rhs) == 0;
2399}
2400
2401#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_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.
2405static 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 || GTEST_HAS_GLOBAL_WSTRING
2420
2421void 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.
2445Message::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.
2453Message& Message::operator <<(const wchar_t* wide_c_str) {
2454 return *this << internal::String::ShowWideCString(wide_c_str);
2455}
2456Message& 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.
2463Message& 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#if GTEST_HAS_GLOBAL_WSTRING
2470// Converts the given wide string to a narrow string using the UTF-8
2471// encoding, and streams the result to this Message object.
2472Message& Message::operator <<(const ::wstring& wstr) {
2473 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2474 return *this;
2475}
2476#endif // GTEST_HAS_GLOBAL_WSTRING
2477
2478// Gets the text streamed to this object so far as an std::string.
2479// Each '\0' character in the buffer is replaced with "\\0".
2480std::string Message::GetString() const {
2481 return internal::StringStreamToString(ss_.get());
2482}
2483
2484// AssertionResult constructors.
2485// Used in EXPECT_TRUE/FALSE(assertion_result).
2486AssertionResult::AssertionResult(const AssertionResult& other)
2487 : success_(other.success_),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002488 message_(other.message_.get() != nullptr
2489 ? new ::std::string(*other.message_)
2490 : static_cast< ::std::string*>(nullptr)) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08002491
2492// Swaps two AssertionResults.
2493void AssertionResult::swap(AssertionResult& other) {
2494 using std::swap;
2495 swap(success_, other.success_);
2496 swap(message_, other.message_);
2497}
2498
2499// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2500AssertionResult AssertionResult::operator!() const {
2501 AssertionResult negation(!success_);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002502 if (message_.get() != nullptr) negation << *message_;
Austin Schuh70cc9552019-01-21 19:46:48 -08002503 return negation;
2504}
2505
2506// Makes a successful assertion result.
2507AssertionResult AssertionSuccess() {
2508 return AssertionResult(true);
2509}
2510
2511// Makes a failed assertion result.
2512AssertionResult AssertionFailure() {
2513 return AssertionResult(false);
2514}
2515
2516// Makes a failed assertion result with the given failure message.
2517// Deprecated; use AssertionFailure() << message.
2518AssertionResult AssertionFailure(const Message& message) {
2519 return AssertionFailure() << message;
2520}
2521
2522namespace internal {
2523
2524namespace edit_distance {
2525std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2526 const std::vector<size_t>& right) {
2527 std::vector<std::vector<double> > costs(
2528 left.size() + 1, std::vector<double>(right.size() + 1));
2529 std::vector<std::vector<EditType> > best_move(
2530 left.size() + 1, std::vector<EditType>(right.size() + 1));
2531
2532 // Populate for empty right.
2533 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2534 costs[l_i][0] = static_cast<double>(l_i);
2535 best_move[l_i][0] = kRemove;
2536 }
2537 // Populate for empty left.
2538 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2539 costs[0][r_i] = static_cast<double>(r_i);
2540 best_move[0][r_i] = kAdd;
2541 }
2542
2543 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2544 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2545 if (left[l_i] == right[r_i]) {
2546 // Found a match. Consume it.
2547 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2548 best_move[l_i + 1][r_i + 1] = kMatch;
2549 continue;
2550 }
2551
2552 const double add = costs[l_i + 1][r_i];
2553 const double remove = costs[l_i][r_i + 1];
2554 const double replace = costs[l_i][r_i];
2555 if (add < remove && add < replace) {
2556 costs[l_i + 1][r_i + 1] = add + 1;
2557 best_move[l_i + 1][r_i + 1] = kAdd;
2558 } else if (remove < add && remove < replace) {
2559 costs[l_i + 1][r_i + 1] = remove + 1;
2560 best_move[l_i + 1][r_i + 1] = kRemove;
2561 } else {
2562 // We make replace a little more expensive than add/remove to lower
2563 // their priority.
2564 costs[l_i + 1][r_i + 1] = replace + 1.00001;
2565 best_move[l_i + 1][r_i + 1] = kReplace;
2566 }
2567 }
2568 }
2569
2570 // Reconstruct the best path. We do it in reverse order.
2571 std::vector<EditType> best_path;
2572 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2573 EditType move = best_move[l_i][r_i];
2574 best_path.push_back(move);
2575 l_i -= move != kAdd;
2576 r_i -= move != kRemove;
2577 }
2578 std::reverse(best_path.begin(), best_path.end());
2579 return best_path;
2580}
2581
2582namespace {
2583
2584// Helper class to convert string into ids with deduplication.
2585class InternalStrings {
2586 public:
2587 size_t GetId(const std::string& str) {
2588 IdMap::iterator it = ids_.find(str);
2589 if (it != ids_.end()) return it->second;
2590 size_t id = ids_.size();
2591 return ids_[str] = id;
2592 }
2593
2594 private:
2595 typedef std::map<std::string, size_t> IdMap;
2596 IdMap ids_;
2597};
2598
2599} // namespace
2600
2601std::vector<EditType> CalculateOptimalEdits(
2602 const std::vector<std::string>& left,
2603 const std::vector<std::string>& right) {
2604 std::vector<size_t> left_ids, right_ids;
2605 {
2606 InternalStrings intern_table;
2607 for (size_t i = 0; i < left.size(); ++i) {
2608 left_ids.push_back(intern_table.GetId(left[i]));
2609 }
2610 for (size_t i = 0; i < right.size(); ++i) {
2611 right_ids.push_back(intern_table.GetId(right[i]));
2612 }
2613 }
2614 return CalculateOptimalEdits(left_ids, right_ids);
2615}
2616
2617namespace {
2618
2619// Helper class that holds the state for one hunk and prints it out to the
2620// stream.
2621// It reorders adds/removes when possible to group all removes before all
2622// adds. It also adds the hunk header before printint into the stream.
2623class Hunk {
2624 public:
2625 Hunk(size_t left_start, size_t right_start)
2626 : left_start_(left_start),
2627 right_start_(right_start),
2628 adds_(),
2629 removes_(),
2630 common_() {}
2631
2632 void PushLine(char edit, const char* line) {
2633 switch (edit) {
2634 case ' ':
2635 ++common_;
2636 FlushEdits();
2637 hunk_.push_back(std::make_pair(' ', line));
2638 break;
2639 case '-':
2640 ++removes_;
2641 hunk_removes_.push_back(std::make_pair('-', line));
2642 break;
2643 case '+':
2644 ++adds_;
2645 hunk_adds_.push_back(std::make_pair('+', line));
2646 break;
2647 }
2648 }
2649
2650 void PrintTo(std::ostream* os) {
2651 PrintHeader(os);
2652 FlushEdits();
2653 for (std::list<std::pair<char, const char*> >::const_iterator it =
2654 hunk_.begin();
2655 it != hunk_.end(); ++it) {
2656 *os << it->first << it->second << "\n";
2657 }
2658 }
2659
2660 bool has_edits() const { return adds_ || removes_; }
2661
2662 private:
2663 void FlushEdits() {
2664 hunk_.splice(hunk_.end(), hunk_removes_);
2665 hunk_.splice(hunk_.end(), hunk_adds_);
2666 }
2667
2668 // Print a unified diff header for one hunk.
2669 // The format is
2670 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002671 // where the left/right parts are omitted if unnecessary.
Austin Schuh70cc9552019-01-21 19:46:48 -08002672 void PrintHeader(std::ostream* ss) const {
2673 *ss << "@@ ";
2674 if (removes_) {
2675 *ss << "-" << left_start_ << "," << (removes_ + common_);
2676 }
2677 if (removes_ && adds_) {
2678 *ss << " ";
2679 }
2680 if (adds_) {
2681 *ss << "+" << right_start_ << "," << (adds_ + common_);
2682 }
2683 *ss << " @@\n";
2684 }
2685
2686 size_t left_start_, right_start_;
2687 size_t adds_, removes_, common_;
2688 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2689};
2690
2691} // namespace
2692
2693// Create a list of diff hunks in Unified diff format.
2694// Each hunk has a header generated by PrintHeader above plus a body with
2695// lines prefixed with ' ' for no change, '-' for deletion and '+' for
2696// addition.
2697// 'context' represents the desired unchanged prefix/suffix around the diff.
2698// If two hunks are close enough that their contexts overlap, then they are
2699// joined into one hunk.
2700std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2701 const std::vector<std::string>& right,
2702 size_t context) {
2703 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2704
2705 size_t l_i = 0, r_i = 0, edit_i = 0;
2706 std::stringstream ss;
2707 while (edit_i < edits.size()) {
2708 // Find first edit.
2709 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2710 ++l_i;
2711 ++r_i;
2712 ++edit_i;
2713 }
2714
2715 // Find the first line to include in the hunk.
2716 const size_t prefix_context = std::min(l_i, context);
2717 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2718 for (size_t i = prefix_context; i > 0; --i) {
2719 hunk.PushLine(' ', left[l_i - i].c_str());
2720 }
2721
2722 // Iterate the edits until we found enough suffix for the hunk or the input
2723 // is over.
2724 size_t n_suffix = 0;
2725 for (; edit_i < edits.size(); ++edit_i) {
2726 if (n_suffix >= context) {
2727 // Continue only if the next hunk is very close.
2728 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2729 while (it != edits.end() && *it == kMatch) ++it;
2730 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2731 // There is no next edit or it is too far away.
2732 break;
2733 }
2734 }
2735
2736 EditType edit = edits[edit_i];
2737 // Reset count when a non match is found.
2738 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2739
2740 if (edit == kMatch || edit == kRemove || edit == kReplace) {
2741 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2742 }
2743 if (edit == kAdd || edit == kReplace) {
2744 hunk.PushLine('+', right[r_i].c_str());
2745 }
2746
2747 // Advance indices, depending on edit type.
2748 l_i += edit != kAdd;
2749 r_i += edit != kRemove;
2750 }
2751
2752 if (!hunk.has_edits()) {
2753 // We are done. We don't want this hunk.
2754 break;
2755 }
2756
2757 hunk.PrintTo(&ss);
2758 }
2759 return ss.str();
2760}
2761
2762} // namespace edit_distance
2763
2764namespace {
2765
2766// The string representation of the values received in EqFailure() are already
2767// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2768// characters the same.
2769std::vector<std::string> SplitEscapedString(const std::string& str) {
2770 std::vector<std::string> lines;
2771 size_t start = 0, end = str.size();
2772 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2773 ++start;
2774 --end;
2775 }
2776 bool escaped = false;
2777 for (size_t i = start; i + 1 < end; ++i) {
2778 if (escaped) {
2779 escaped = false;
2780 if (str[i] == 'n') {
2781 lines.push_back(str.substr(start, i - start - 1));
2782 start = i + 1;
2783 }
2784 } else {
2785 escaped = str[i] == '\\';
2786 }
2787 }
2788 lines.push_back(str.substr(start, end - start));
2789 return lines;
2790}
2791
2792} // namespace
2793
2794// Constructs and returns the message for an equality assertion
2795// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2796//
2797// The first four parameters are the expressions used in the assertion
2798// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2799// where foo is 5 and bar is 6, we have:
2800//
2801// lhs_expression: "foo"
2802// rhs_expression: "bar"
2803// lhs_value: "5"
2804// rhs_value: "6"
2805//
2806// The ignoring_case parameter is true iff the assertion is a
2807// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
2808// be inserted into the message.
2809AssertionResult EqFailure(const char* lhs_expression,
2810 const char* rhs_expression,
2811 const std::string& lhs_value,
2812 const std::string& rhs_value,
2813 bool ignoring_case) {
2814 Message msg;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002815 msg << "Expected equality of these values:";
2816 msg << "\n " << lhs_expression;
Austin Schuh70cc9552019-01-21 19:46:48 -08002817 if (lhs_value != lhs_expression) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002818 msg << "\n Which is: " << lhs_value;
Austin Schuh70cc9552019-01-21 19:46:48 -08002819 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002820 msg << "\n " << rhs_expression;
Austin Schuh70cc9552019-01-21 19:46:48 -08002821 if (rhs_value != rhs_expression) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002822 msg << "\n Which is: " << rhs_value;
Austin Schuh70cc9552019-01-21 19:46:48 -08002823 }
2824
2825 if (ignoring_case) {
2826 msg << "\nIgnoring case";
2827 }
2828
2829 if (!lhs_value.empty() && !rhs_value.empty()) {
2830 const std::vector<std::string> lhs_lines =
2831 SplitEscapedString(lhs_value);
2832 const std::vector<std::string> rhs_lines =
2833 SplitEscapedString(rhs_value);
2834 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2835 msg << "\nWith diff:\n"
2836 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2837 }
2838 }
2839
2840 return AssertionFailure() << msg;
2841}
2842
2843// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2844std::string GetBoolAssertionFailureMessage(
2845 const AssertionResult& assertion_result,
2846 const char* expression_text,
2847 const char* actual_predicate_value,
2848 const char* expected_predicate_value) {
2849 const char* actual_message = assertion_result.message();
2850 Message msg;
2851 msg << "Value of: " << expression_text
2852 << "\n Actual: " << actual_predicate_value;
2853 if (actual_message[0] != '\0')
2854 msg << " (" << actual_message << ")";
2855 msg << "\nExpected: " << expected_predicate_value;
2856 return msg.GetString();
2857}
2858
2859// Helper function for implementing ASSERT_NEAR.
2860AssertionResult DoubleNearPredFormat(const char* expr1,
2861 const char* expr2,
2862 const char* abs_error_expr,
2863 double val1,
2864 double val2,
2865 double abs_error) {
2866 const double diff = fabs(val1 - val2);
2867 if (diff <= abs_error) return AssertionSuccess();
2868
Austin Schuh70cc9552019-01-21 19:46:48 -08002869 return AssertionFailure()
2870 << "The difference between " << expr1 << " and " << expr2
2871 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2872 << expr1 << " evaluates to " << val1 << ",\n"
2873 << expr2 << " evaluates to " << val2 << ", and\n"
2874 << abs_error_expr << " evaluates to " << abs_error << ".";
2875}
2876
2877
2878// Helper template for implementing FloatLE() and DoubleLE().
2879template <typename RawType>
2880AssertionResult FloatingPointLE(const char* expr1,
2881 const char* expr2,
2882 RawType val1,
2883 RawType val2) {
2884 // Returns success if val1 is less than val2,
2885 if (val1 < val2) {
2886 return AssertionSuccess();
2887 }
2888
2889 // or if val1 is almost equal to val2.
2890 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2891 if (lhs.AlmostEquals(rhs)) {
2892 return AssertionSuccess();
2893 }
2894
2895 // Note that the above two checks will both fail if either val1 or
2896 // val2 is NaN, as the IEEE floating-point standard requires that
2897 // any predicate involving a NaN must return false.
2898
2899 ::std::stringstream val1_ss;
2900 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2901 << val1;
2902
2903 ::std::stringstream val2_ss;
2904 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2905 << val2;
2906
2907 return AssertionFailure()
2908 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2909 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2910 << StringStreamToString(&val2_ss);
2911}
2912
2913} // namespace internal
2914
2915// Asserts that val1 is less than, or almost equal to, val2. Fails
2916// otherwise. In particular, it fails if either val1 or val2 is NaN.
2917AssertionResult FloatLE(const char* expr1, const char* expr2,
2918 float val1, float val2) {
2919 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2920}
2921
2922// Asserts that val1 is less than, or almost equal to, val2. Fails
2923// otherwise. In particular, it fails if either val1 or val2 is NaN.
2924AssertionResult DoubleLE(const char* expr1, const char* expr2,
2925 double val1, double val2) {
2926 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2927}
2928
2929namespace internal {
2930
2931// The helper function for {ASSERT|EXPECT}_EQ with int or enum
2932// arguments.
2933AssertionResult CmpHelperEQ(const char* lhs_expression,
2934 const char* rhs_expression,
2935 BiggestInt lhs,
2936 BiggestInt rhs) {
2937 if (lhs == rhs) {
2938 return AssertionSuccess();
2939 }
2940
2941 return EqFailure(lhs_expression,
2942 rhs_expression,
2943 FormatForComparisonFailureMessage(lhs, rhs),
2944 FormatForComparisonFailureMessage(rhs, lhs),
2945 false);
2946}
2947
2948// A macro for implementing the helper functions needed to implement
2949// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2950// just to avoid copy-and-paste of similar code.
2951#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2952AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2953 BiggestInt val1, BiggestInt val2) {\
2954 if (val1 op val2) {\
2955 return AssertionSuccess();\
2956 } else {\
2957 return AssertionFailure() \
2958 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2959 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2960 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2961 }\
2962}
2963
2964// Implements the helper function for {ASSERT|EXPECT}_NE with int or
2965// enum arguments.
2966GTEST_IMPL_CMP_HELPER_(NE, !=)
2967// Implements the helper function for {ASSERT|EXPECT}_LE with int or
2968// enum arguments.
2969GTEST_IMPL_CMP_HELPER_(LE, <=)
2970// Implements the helper function for {ASSERT|EXPECT}_LT with int or
2971// enum arguments.
2972GTEST_IMPL_CMP_HELPER_(LT, < )
2973// Implements the helper function for {ASSERT|EXPECT}_GE with int or
2974// enum arguments.
2975GTEST_IMPL_CMP_HELPER_(GE, >=)
2976// Implements the helper function for {ASSERT|EXPECT}_GT with int or
2977// enum arguments.
2978GTEST_IMPL_CMP_HELPER_(GT, > )
2979
2980#undef GTEST_IMPL_CMP_HELPER_
2981
2982// The helper function for {ASSERT|EXPECT}_STREQ.
2983AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2984 const char* rhs_expression,
2985 const char* lhs,
2986 const char* rhs) {
2987 if (String::CStringEquals(lhs, rhs)) {
2988 return AssertionSuccess();
2989 }
2990
2991 return EqFailure(lhs_expression,
2992 rhs_expression,
2993 PrintToString(lhs),
2994 PrintToString(rhs),
2995 false);
2996}
2997
2998// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2999AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3000 const char* rhs_expression,
3001 const char* lhs,
3002 const char* rhs) {
3003 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3004 return AssertionSuccess();
3005 }
3006
3007 return EqFailure(lhs_expression,
3008 rhs_expression,
3009 PrintToString(lhs),
3010 PrintToString(rhs),
3011 true);
3012}
3013
3014// The helper function for {ASSERT|EXPECT}_STRNE.
3015AssertionResult CmpHelperSTRNE(const char* s1_expression,
3016 const char* s2_expression,
3017 const char* s1,
3018 const char* s2) {
3019 if (!String::CStringEquals(s1, s2)) {
3020 return AssertionSuccess();
3021 } else {
3022 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3023 << s2_expression << "), actual: \""
3024 << s1 << "\" vs \"" << s2 << "\"";
3025 }
3026}
3027
3028// The helper function for {ASSERT|EXPECT}_STRCASENE.
3029AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3030 const char* s2_expression,
3031 const char* s1,
3032 const char* s2) {
3033 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3034 return AssertionSuccess();
3035 } else {
3036 return AssertionFailure()
3037 << "Expected: (" << s1_expression << ") != ("
3038 << s2_expression << ") (ignoring case), actual: \""
3039 << s1 << "\" vs \"" << s2 << "\"";
3040 }
3041}
3042
3043} // namespace internal
3044
3045namespace {
3046
3047// Helper functions for implementing IsSubString() and IsNotSubstring().
3048
3049// This group of overloaded functions return true iff needle is a
3050// substring of haystack. NULL is considered a substring of itself
3051// only.
3052
3053bool IsSubstringPred(const char* needle, const char* haystack) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003054 if (needle == nullptr || haystack == nullptr) return needle == haystack;
Austin Schuh70cc9552019-01-21 19:46:48 -08003055
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003056 return strstr(haystack, needle) != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08003057}
3058
3059bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003060 if (needle == nullptr || haystack == nullptr) return needle == haystack;
Austin Schuh70cc9552019-01-21 19:46:48 -08003061
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003062 return wcsstr(haystack, needle) != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08003063}
3064
3065// StringType here can be either ::std::string or ::std::wstring.
3066template <typename StringType>
3067bool IsSubstringPred(const StringType& needle,
3068 const StringType& haystack) {
3069 return haystack.find(needle) != StringType::npos;
3070}
3071
3072// This function implements either IsSubstring() or IsNotSubstring(),
3073// depending on the value of the expected_to_be_substring parameter.
3074// StringType here can be const char*, const wchar_t*, ::std::string,
3075// or ::std::wstring.
3076template <typename StringType>
3077AssertionResult IsSubstringImpl(
3078 bool expected_to_be_substring,
3079 const char* needle_expr, const char* haystack_expr,
3080 const StringType& needle, const StringType& haystack) {
3081 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3082 return AssertionSuccess();
3083
3084 const bool is_wide_string = sizeof(needle[0]) > 1;
3085 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3086 return AssertionFailure()
3087 << "Value of: " << needle_expr << "\n"
3088 << " Actual: " << begin_string_quote << needle << "\"\n"
3089 << "Expected: " << (expected_to_be_substring ? "" : "not ")
3090 << "a substring of " << haystack_expr << "\n"
3091 << "Which is: " << begin_string_quote << haystack << "\"";
3092}
3093
3094} // namespace
3095
3096// IsSubstring() and IsNotSubstring() check whether needle is a
3097// substring of haystack (NULL is considered a substring of itself
3098// only), and return an appropriate error message when they fail.
3099
3100AssertionResult IsSubstring(
3101 const char* needle_expr, const char* haystack_expr,
3102 const char* needle, const char* haystack) {
3103 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3104}
3105
3106AssertionResult IsSubstring(
3107 const char* needle_expr, const char* haystack_expr,
3108 const wchar_t* needle, const wchar_t* haystack) {
3109 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3110}
3111
3112AssertionResult IsNotSubstring(
3113 const char* needle_expr, const char* haystack_expr,
3114 const char* needle, const char* haystack) {
3115 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3116}
3117
3118AssertionResult IsNotSubstring(
3119 const char* needle_expr, const char* haystack_expr,
3120 const wchar_t* needle, const wchar_t* haystack) {
3121 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3122}
3123
3124AssertionResult IsSubstring(
3125 const char* needle_expr, const char* haystack_expr,
3126 const ::std::string& needle, const ::std::string& haystack) {
3127 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3128}
3129
3130AssertionResult IsNotSubstring(
3131 const char* needle_expr, const char* haystack_expr,
3132 const ::std::string& needle, const ::std::string& haystack) {
3133 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3134}
3135
3136#if GTEST_HAS_STD_WSTRING
3137AssertionResult IsSubstring(
3138 const char* needle_expr, const char* haystack_expr,
3139 const ::std::wstring& needle, const ::std::wstring& haystack) {
3140 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3141}
3142
3143AssertionResult IsNotSubstring(
3144 const char* needle_expr, const char* haystack_expr,
3145 const ::std::wstring& needle, const ::std::wstring& haystack) {
3146 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3147}
3148#endif // GTEST_HAS_STD_WSTRING
3149
3150namespace internal {
3151
3152#if GTEST_OS_WINDOWS
3153
3154namespace {
3155
3156// Helper function for IsHRESULT{SuccessFailure} predicates
3157AssertionResult HRESULTFailureHelper(const char* expr,
3158 const char* expected,
3159 long hr) { // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003160# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
Austin Schuh70cc9552019-01-21 19:46:48 -08003161
3162 // Windows CE doesn't support FormatMessage.
3163 const char error_text[] = "";
3164
3165# else
3166
3167 // Looks up the human-readable system message for the HRESULT code
3168 // and since we're not passing any params to FormatMessage, we don't
3169 // want inserts expanded.
3170 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3171 FORMAT_MESSAGE_IGNORE_INSERTS;
3172 const DWORD kBufSize = 4096;
3173 // Gets the system's human readable message string for this HRESULT.
3174 char error_text[kBufSize] = { '\0' };
3175 DWORD message_length = ::FormatMessageA(kFlags,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003176 0, // no source, we're asking system
Austin Schuh70cc9552019-01-21 19:46:48 -08003177 hr, // the error
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003178 0, // no line width restrictions
Austin Schuh70cc9552019-01-21 19:46:48 -08003179 error_text, // output buffer
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003180 kBufSize, // buf size
3181 nullptr); // no arguments for inserts
Austin Schuh70cc9552019-01-21 19:46:48 -08003182 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3183 for (; message_length && IsSpace(error_text[message_length - 1]);
3184 --message_length) {
3185 error_text[message_length - 1] = '\0';
3186 }
3187
3188# endif // GTEST_OS_WINDOWS_MOBILE
3189
3190 const std::string error_hex("0x" + String::FormatHexInt(hr));
3191 return ::testing::AssertionFailure()
3192 << "Expected: " << expr << " " << expected << ".\n"
3193 << " Actual: " << error_hex << " " << error_text << "\n";
3194}
3195
3196} // namespace
3197
3198AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3199 if (SUCCEEDED(hr)) {
3200 return AssertionSuccess();
3201 }
3202 return HRESULTFailureHelper(expr, "succeeds", hr);
3203}
3204
3205AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3206 if (FAILED(hr)) {
3207 return AssertionSuccess();
3208 }
3209 return HRESULTFailureHelper(expr, "fails", hr);
3210}
3211
3212#endif // GTEST_OS_WINDOWS
3213
3214// Utility functions for encoding Unicode text (wide strings) in
3215// UTF-8.
3216
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003217// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
Austin Schuh70cc9552019-01-21 19:46:48 -08003218// like this:
3219//
3220// Code-point length Encoding
3221// 0 - 7 bits 0xxxxxxx
3222// 8 - 11 bits 110xxxxx 10xxxxxx
3223// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3224// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3225
3226// The maximum code-point a one-byte UTF-8 sequence can represent.
3227const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
3228
3229// The maximum code-point a two-byte UTF-8 sequence can represent.
3230const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3231
3232// The maximum code-point a three-byte UTF-8 sequence can represent.
3233const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3234
3235// The maximum code-point a four-byte UTF-8 sequence can represent.
3236const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3237
3238// Chops off the n lowest bits from a bit pattern. Returns the n
3239// lowest bits. As a side effect, the original bit pattern will be
3240// shifted to the right by n bits.
3241inline UInt32 ChopLowBits(UInt32* bits, int n) {
3242 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3243 *bits >>= n;
3244 return low_bits;
3245}
3246
3247// Converts a Unicode code point to a narrow string in UTF-8 encoding.
3248// code_point parameter is of type UInt32 because wchar_t may not be
3249// wide enough to contain a code point.
3250// If the code_point is not a valid Unicode code point
3251// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3252// to "(Invalid Unicode 0xXXXXXXXX)".
3253std::string CodePointToUtf8(UInt32 code_point) {
3254 if (code_point > kMaxCodePoint4) {
3255 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3256 }
3257
3258 char str[5]; // Big enough for the largest valid code point.
3259 if (code_point <= kMaxCodePoint1) {
3260 str[1] = '\0';
3261 str[0] = static_cast<char>(code_point); // 0xxxxxxx
3262 } else if (code_point <= kMaxCodePoint2) {
3263 str[2] = '\0';
3264 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3265 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3266 } else if (code_point <= kMaxCodePoint3) {
3267 str[3] = '\0';
3268 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3269 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3270 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3271 } else { // code_point <= kMaxCodePoint4
3272 str[4] = '\0';
3273 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3274 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3275 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3276 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3277 }
3278 return str;
3279}
3280
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003281// The following two functions only make sense if the system
Austin Schuh70cc9552019-01-21 19:46:48 -08003282// uses UTF-16 for wide string encoding. All supported systems
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003283// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
Austin Schuh70cc9552019-01-21 19:46:48 -08003284
3285// Determines if the arguments constitute UTF-16 surrogate pair
3286// and thus should be combined into a single Unicode code point
3287// using CreateCodePointFromUtf16SurrogatePair.
3288inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3289 return sizeof(wchar_t) == 2 &&
3290 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3291}
3292
3293// Creates a Unicode code point from UTF16 surrogate pair.
3294inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3295 wchar_t second) {
3296 const UInt32 mask = (1 << 10) - 1;
3297 return (sizeof(wchar_t) == 2) ?
3298 (((first & mask) << 10) | (second & mask)) + 0x10000 :
3299 // This function should not be called when the condition is
3300 // false, but we provide a sensible default in case it is.
3301 static_cast<UInt32>(first);
3302}
3303
3304// Converts a wide string to a narrow string in UTF-8 encoding.
3305// The wide string is assumed to have the following encoding:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003306// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
Austin Schuh70cc9552019-01-21 19:46:48 -08003307// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3308// Parameter str points to a null-terminated wide string.
3309// Parameter num_chars may additionally limit the number
3310// of wchar_t characters processed. -1 is used when the entire string
3311// should be processed.
3312// If the string contains code points that are not valid Unicode code points
3313// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3314// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3315// and contains invalid UTF-16 surrogate pairs, values in those pairs
3316// will be encoded as individual Unicode characters from Basic Normal Plane.
3317std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3318 if (num_chars == -1)
3319 num_chars = static_cast<int>(wcslen(str));
3320
3321 ::std::stringstream stream;
3322 for (int i = 0; i < num_chars; ++i) {
3323 UInt32 unicode_code_point;
3324
3325 if (str[i] == L'\0') {
3326 break;
3327 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3328 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3329 str[i + 1]);
3330 i++;
3331 } else {
3332 unicode_code_point = static_cast<UInt32>(str[i]);
3333 }
3334
3335 stream << CodePointToUtf8(unicode_code_point);
3336 }
3337 return StringStreamToString(&stream);
3338}
3339
3340// Converts a wide C string to an std::string using the UTF-8 encoding.
3341// NULL will be converted to "(null)".
3342std::string String::ShowWideCString(const wchar_t * wide_c_str) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003343 if (wide_c_str == nullptr) return "(null)";
Austin Schuh70cc9552019-01-21 19:46:48 -08003344
3345 return internal::WideStringToUtf8(wide_c_str, -1);
3346}
3347
3348// Compares two wide C strings. Returns true iff they have the same
3349// content.
3350//
3351// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3352// C string is considered different to any non-NULL C string,
3353// including the empty string.
3354bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003355 if (lhs == nullptr) return rhs == nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08003356
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003357 if (rhs == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08003358
3359 return wcscmp(lhs, rhs) == 0;
3360}
3361
3362// Helper function for *_STREQ on wide strings.
3363AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3364 const char* rhs_expression,
3365 const wchar_t* lhs,
3366 const wchar_t* rhs) {
3367 if (String::WideCStringEquals(lhs, rhs)) {
3368 return AssertionSuccess();
3369 }
3370
3371 return EqFailure(lhs_expression,
3372 rhs_expression,
3373 PrintToString(lhs),
3374 PrintToString(rhs),
3375 false);
3376}
3377
3378// Helper function for *_STRNE on wide strings.
3379AssertionResult CmpHelperSTRNE(const char* s1_expression,
3380 const char* s2_expression,
3381 const wchar_t* s1,
3382 const wchar_t* s2) {
3383 if (!String::WideCStringEquals(s1, s2)) {
3384 return AssertionSuccess();
3385 }
3386
3387 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3388 << s2_expression << "), actual: "
3389 << PrintToString(s1)
3390 << " vs " << PrintToString(s2);
3391}
3392
3393// Compares two C strings, ignoring case. Returns true iff they have
3394// the same content.
3395//
3396// Unlike strcasecmp(), this function can handle NULL argument(s). A
3397// NULL C string is considered different to any non-NULL C string,
3398// including the empty string.
3399bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003400 if (lhs == nullptr) return rhs == nullptr;
3401 if (rhs == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08003402 return posix::StrCaseCmp(lhs, rhs) == 0;
3403}
3404
3405 // Compares two wide C strings, ignoring case. Returns true iff they
3406 // have the same content.
3407 //
3408 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3409 // A NULL C string is considered different to any non-NULL wide C string,
3410 // including the empty string.
3411 // NB: The implementations on different platforms slightly differ.
3412 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3413 // environment variable. On GNU platform this method uses wcscasecmp
3414 // which compares according to LC_CTYPE category of the current locale.
3415 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3416 // current locale.
3417bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3418 const wchar_t* rhs) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003419 if (lhs == nullptr) return rhs == nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08003420
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003421 if (rhs == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08003422
3423#if GTEST_OS_WINDOWS
3424 return _wcsicmp(lhs, rhs) == 0;
3425#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3426 return wcscasecmp(lhs, rhs) == 0;
3427#else
3428 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3429 // Other unknown OSes may not define it either.
3430 wint_t left, right;
3431 do {
3432 left = towlower(*lhs++);
3433 right = towlower(*rhs++);
3434 } while (left && left == right);
3435 return left == right;
3436#endif // OS selector
3437}
3438
3439// Returns true iff str ends with the given suffix, ignoring case.
3440// Any string is considered to end with an empty suffix.
3441bool String::EndsWithCaseInsensitive(
3442 const std::string& str, const std::string& suffix) {
3443 const size_t str_len = str.length();
3444 const size_t suffix_len = suffix.length();
3445 return (str_len >= suffix_len) &&
3446 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3447 suffix.c_str());
3448}
3449
3450// Formats an int value as "%02d".
3451std::string String::FormatIntWidth2(int value) {
3452 std::stringstream ss;
3453 ss << std::setfill('0') << std::setw(2) << value;
3454 return ss.str();
3455}
3456
3457// Formats an int value as "%X".
3458std::string String::FormatHexInt(int value) {
3459 std::stringstream ss;
3460 ss << std::hex << std::uppercase << value;
3461 return ss.str();
3462}
3463
3464// Formats a byte as "%02X".
3465std::string String::FormatByte(unsigned char value) {
3466 std::stringstream ss;
3467 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3468 << static_cast<unsigned int>(value);
3469 return ss.str();
3470}
3471
3472// Converts the buffer in a stringstream to an std::string, converting NUL
3473// bytes to "\\0" along the way.
3474std::string StringStreamToString(::std::stringstream* ss) {
3475 const ::std::string& str = ss->str();
3476 const char* const start = str.c_str();
3477 const char* const end = start + str.length();
3478
3479 std::string result;
3480 result.reserve(2 * (end - start));
3481 for (const char* ch = start; ch != end; ++ch) {
3482 if (*ch == '\0') {
3483 result += "\\0"; // Replaces NUL with "\\0";
3484 } else {
3485 result += *ch;
3486 }
3487 }
3488
3489 return result;
3490}
3491
3492// Appends the user-supplied message to the Google-Test-generated message.
3493std::string AppendUserMessage(const std::string& gtest_msg,
3494 const Message& user_msg) {
3495 // Appends the user message if it's non-empty.
3496 const std::string user_msg_string = user_msg.GetString();
3497 if (user_msg_string.empty()) {
3498 return gtest_msg;
3499 }
3500
3501 return gtest_msg + "\n" + user_msg_string;
3502}
3503
3504} // namespace internal
3505
3506// class TestResult
3507
3508// Creates an empty TestResult.
3509TestResult::TestResult()
3510 : death_test_count_(0),
3511 elapsed_time_(0) {
3512}
3513
3514// D'tor.
3515TestResult::~TestResult() {
3516}
3517
3518// Returns the i-th test part result among all the results. i can
3519// range from 0 to total_part_count() - 1. If i is not in that range,
3520// aborts the program.
3521const TestPartResult& TestResult::GetTestPartResult(int i) const {
3522 if (i < 0 || i >= total_part_count())
3523 internal::posix::Abort();
3524 return test_part_results_.at(i);
3525}
3526
3527// Returns the i-th test property. i can range from 0 to
3528// test_property_count() - 1. If i is not in that range, aborts the
3529// program.
3530const TestProperty& TestResult::GetTestProperty(int i) const {
3531 if (i < 0 || i >= test_property_count())
3532 internal::posix::Abort();
3533 return test_properties_.at(i);
3534}
3535
3536// Clears the test part results.
3537void TestResult::ClearTestPartResults() {
3538 test_part_results_.clear();
3539}
3540
3541// Adds a test part result to the list.
3542void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3543 test_part_results_.push_back(test_part_result);
3544}
3545
3546// Adds a test property to the list. If a property with the same key as the
3547// supplied property is already represented, the value of this test_property
3548// replaces the old value for that key.
3549void TestResult::RecordProperty(const std::string& xml_element,
3550 const TestProperty& test_property) {
3551 if (!ValidateTestProperty(xml_element, test_property)) {
3552 return;
3553 }
3554 internal::MutexLock lock(&test_properites_mutex_);
3555 const std::vector<TestProperty>::iterator property_with_matching_key =
3556 std::find_if(test_properties_.begin(), test_properties_.end(),
3557 internal::TestPropertyKeyIs(test_property.key()));
3558 if (property_with_matching_key == test_properties_.end()) {
3559 test_properties_.push_back(test_property);
3560 return;
3561 }
3562 property_with_matching_key->SetValue(test_property.value());
3563}
3564
3565// The list of reserved attributes used in the <testsuites> element of XML
3566// output.
3567static const char* const kReservedTestSuitesAttributes[] = {
3568 "disabled",
3569 "errors",
3570 "failures",
3571 "name",
3572 "random_seed",
3573 "tests",
3574 "time",
3575 "timestamp"
3576};
3577
3578// The list of reserved attributes used in the <testsuite> element of XML
3579// output.
3580static const char* const kReservedTestSuiteAttributes[] = {
3581 "disabled",
3582 "errors",
3583 "failures",
3584 "name",
3585 "tests",
3586 "time"
3587};
3588
3589// The list of reserved attributes used in the <testcase> element of XML output.
3590static const char* const kReservedTestCaseAttributes[] = {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003591 "classname", "name", "status", "time",
3592 "type_param", "value_param", "file", "line"};
Austin Schuh70cc9552019-01-21 19:46:48 -08003593
3594template <int kSize>
3595std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3596 return std::vector<std::string>(array, array + kSize);
3597}
3598
3599static std::vector<std::string> GetReservedAttributesForElement(
3600 const std::string& xml_element) {
3601 if (xml_element == "testsuites") {
3602 return ArrayAsVector(kReservedTestSuitesAttributes);
3603 } else if (xml_element == "testsuite") {
3604 return ArrayAsVector(kReservedTestSuiteAttributes);
3605 } else if (xml_element == "testcase") {
3606 return ArrayAsVector(kReservedTestCaseAttributes);
3607 } else {
3608 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3609 }
3610 // This code is unreachable but some compilers may not realizes that.
3611 return std::vector<std::string>();
3612}
3613
3614static std::string FormatWordList(const std::vector<std::string>& words) {
3615 Message word_list;
3616 for (size_t i = 0; i < words.size(); ++i) {
3617 if (i > 0 && words.size() > 2) {
3618 word_list << ", ";
3619 }
3620 if (i == words.size() - 1) {
3621 word_list << "and ";
3622 }
3623 word_list << "'" << words[i] << "'";
3624 }
3625 return word_list.GetString();
3626}
3627
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003628static bool ValidateTestPropertyName(
3629 const std::string& property_name,
3630 const std::vector<std::string>& reserved_names) {
Austin Schuh70cc9552019-01-21 19:46:48 -08003631 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3632 reserved_names.end()) {
3633 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3634 << " (" << FormatWordList(reserved_names)
3635 << " are reserved by " << GTEST_NAME_ << ")";
3636 return false;
3637 }
3638 return true;
3639}
3640
3641// Adds a failure if the key is a reserved attribute of the element named
3642// xml_element. Returns true if the property is valid.
3643bool TestResult::ValidateTestProperty(const std::string& xml_element,
3644 const TestProperty& test_property) {
3645 return ValidateTestPropertyName(test_property.key(),
3646 GetReservedAttributesForElement(xml_element));
3647}
3648
3649// Clears the object.
3650void TestResult::Clear() {
3651 test_part_results_.clear();
3652 test_properties_.clear();
3653 death_test_count_ = 0;
3654 elapsed_time_ = 0;
3655}
3656
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003657// Returns true off the test part was skipped.
3658static bool TestPartSkipped(const TestPartResult& result) {
3659 return result.skipped();
3660}
3661
3662// Returns true iff the test was skipped.
3663bool TestResult::Skipped() const {
3664 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3665}
3666
Austin Schuh70cc9552019-01-21 19:46:48 -08003667// Returns true iff the test failed.
3668bool TestResult::Failed() const {
3669 for (int i = 0; i < total_part_count(); ++i) {
3670 if (GetTestPartResult(i).failed())
3671 return true;
3672 }
3673 return false;
3674}
3675
3676// Returns true iff the test part fatally failed.
3677static bool TestPartFatallyFailed(const TestPartResult& result) {
3678 return result.fatally_failed();
3679}
3680
3681// Returns true iff the test fatally failed.
3682bool TestResult::HasFatalFailure() const {
3683 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3684}
3685
3686// Returns true iff the test part non-fatally failed.
3687static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3688 return result.nonfatally_failed();
3689}
3690
3691// Returns true iff the test has a non-fatal failure.
3692bool TestResult::HasNonfatalFailure() const {
3693 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3694}
3695
3696// Gets the number of all test parts. This is the sum of the number
3697// of successful test parts and the number of failed test parts.
3698int TestResult::total_part_count() const {
3699 return static_cast<int>(test_part_results_.size());
3700}
3701
3702// Returns the number of the test properties.
3703int TestResult::test_property_count() const {
3704 return static_cast<int>(test_properties_.size());
3705}
3706
3707// class Test
3708
3709// Creates a Test object.
3710
3711// The c'tor saves the states of all flags.
3712Test::Test()
3713 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3714}
3715
3716// The d'tor restores the states of all flags. The actual work is
3717// done by the d'tor of the gtest_flag_saver_ field, and thus not
3718// visible here.
3719Test::~Test() {
3720}
3721
3722// Sets up the test fixture.
3723//
3724// A sub-class may override this.
3725void Test::SetUp() {
3726}
3727
3728// Tears down the test fixture.
3729//
3730// A sub-class may override this.
3731void Test::TearDown() {
3732}
3733
3734// Allows user supplied key value pairs to be recorded for later output.
3735void Test::RecordProperty(const std::string& key, const std::string& value) {
3736 UnitTest::GetInstance()->RecordProperty(key, value);
3737}
3738
3739// Allows user supplied key value pairs to be recorded for later output.
3740void Test::RecordProperty(const std::string& key, int value) {
3741 Message value_message;
3742 value_message << value;
3743 RecordProperty(key, value_message.GetString().c_str());
3744}
3745
3746namespace internal {
3747
3748void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3749 const std::string& message) {
3750 // This function is a friend of UnitTest and as such has access to
3751 // AddTestPartResult.
3752 UnitTest::GetInstance()->AddTestPartResult(
3753 result_type,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003754 nullptr, // No info about the source file where the exception occurred.
3755 -1, // We have no info on which line caused the exception.
Austin Schuh70cc9552019-01-21 19:46:48 -08003756 message,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003757 ""); // No stack trace, either.
Austin Schuh70cc9552019-01-21 19:46:48 -08003758}
3759
3760} // namespace internal
3761
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003762// Google Test requires all tests in the same test suite to use the same test
Austin Schuh70cc9552019-01-21 19:46:48 -08003763// fixture class. This function checks if the current test has the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003764// same fixture class as the first test in the current test suite. If
Austin Schuh70cc9552019-01-21 19:46:48 -08003765// yes, it returns true; otherwise it generates a Google Test failure and
3766// returns false.
3767bool Test::HasSameFixtureClass() {
3768 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003769 const TestSuite* const test_suite = impl->current_test_suite();
Austin Schuh70cc9552019-01-21 19:46:48 -08003770
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003771 // Info about the first test in the current test suite.
3772 const TestInfo* const first_test_info = test_suite->test_info_list()[0];
Austin Schuh70cc9552019-01-21 19:46:48 -08003773 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3774 const char* const first_test_name = first_test_info->name();
3775
3776 // Info about the current test.
3777 const TestInfo* const this_test_info = impl->current_test_info();
3778 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3779 const char* const this_test_name = this_test_info->name();
3780
3781 if (this_fixture_id != first_fixture_id) {
3782 // Is the first test defined using TEST?
3783 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3784 // Is this test defined using TEST?
3785 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3786
3787 if (first_is_TEST || this_is_TEST) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003788 // Both TEST and TEST_F appear in same test suite, which is incorrect.
Austin Schuh70cc9552019-01-21 19:46:48 -08003789 // Tell the user how to fix this.
3790
3791 // Gets the name of the TEST and the name of the TEST_F. Note
3792 // that first_is_TEST and this_is_TEST cannot both be true, as
3793 // the fixture IDs are different for the two tests.
3794 const char* const TEST_name =
3795 first_is_TEST ? first_test_name : this_test_name;
3796 const char* const TEST_F_name =
3797 first_is_TEST ? this_test_name : first_test_name;
3798
3799 ADD_FAILURE()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003800 << "All tests in the same test suite must use the same test fixture\n"
3801 << "class, so mixing TEST_F and TEST in the same test suite is\n"
3802 << "illegal. In test suite " << this_test_info->test_suite_name()
Austin Schuh70cc9552019-01-21 19:46:48 -08003803 << ",\n"
3804 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3805 << "test " << TEST_name << " is defined using TEST. You probably\n"
3806 << "want to change the TEST to TEST_F or move it to another test\n"
3807 << "case.";
3808 } else {
3809 // Two fixture classes with the same name appear in two different
3810 // namespaces, which is not allowed. Tell the user how to fix this.
3811 ADD_FAILURE()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003812 << "All tests in the same test suite must use the same test fixture\n"
3813 << "class. However, in test suite "
3814 << this_test_info->test_suite_name() << ",\n"
3815 << "you defined test " << first_test_name << " and test "
3816 << this_test_name << "\n"
Austin Schuh70cc9552019-01-21 19:46:48 -08003817 << "using two different test fixture classes. This can happen if\n"
3818 << "the two classes are from different namespaces or translation\n"
3819 << "units and have the same name. You should probably rename one\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003820 << "of the classes to put the tests into different test suites.";
Austin Schuh70cc9552019-01-21 19:46:48 -08003821 }
3822 return false;
3823 }
3824
3825 return true;
3826}
3827
3828#if GTEST_HAS_SEH
3829
3830// Adds an "exception thrown" fatal failure to the current test. This
3831// function returns its result via an output parameter pointer because VC++
3832// prohibits creation of objects with destructors on stack in functions
3833// using __try (see error C2712).
3834static std::string* FormatSehExceptionMessage(DWORD exception_code,
3835 const char* location) {
3836 Message message;
3837 message << "SEH exception with code 0x" << std::setbase(16) <<
3838 exception_code << std::setbase(10) << " thrown in " << location << ".";
3839
3840 return new std::string(message.GetString());
3841}
3842
3843#endif // GTEST_HAS_SEH
3844
3845namespace internal {
3846
3847#if GTEST_HAS_EXCEPTIONS
3848
3849// Adds an "exception thrown" fatal failure to the current test.
3850static std::string FormatCxxExceptionMessage(const char* description,
3851 const char* location) {
3852 Message message;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003853 if (description != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08003854 message << "C++ exception with description \"" << description << "\"";
3855 } else {
3856 message << "Unknown C++ exception";
3857 }
3858 message << " thrown in " << location << ".";
3859
3860 return message.GetString();
3861}
3862
3863static std::string PrintTestPartResultToString(
3864 const TestPartResult& test_part_result);
3865
3866GoogleTestFailureException::GoogleTestFailureException(
3867 const TestPartResult& failure)
3868 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3869
3870#endif // GTEST_HAS_EXCEPTIONS
3871
3872// We put these helper functions in the internal namespace as IBM's xlC
3873// compiler rejects the code if they were declared static.
3874
3875// Runs the given method and handles SEH exceptions it throws, when
3876// SEH is supported; returns the 0-value for type Result in case of an
3877// SEH exception. (Microsoft compilers cannot handle SEH and C++
3878// exceptions in the same function. Therefore, we provide a separate
3879// wrapper function for handling SEH exceptions.)
3880template <class T, typename Result>
3881Result HandleSehExceptionsInMethodIfSupported(
3882 T* object, Result (T::*method)(), const char* location) {
3883#if GTEST_HAS_SEH
3884 __try {
3885 return (object->*method)();
3886 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3887 GetExceptionCode())) {
3888 // We create the exception message on the heap because VC++ prohibits
3889 // creation of objects with destructors on stack in functions using __try
3890 // (see error C2712).
3891 std::string* exception_message = FormatSehExceptionMessage(
3892 GetExceptionCode(), location);
3893 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3894 *exception_message);
3895 delete exception_message;
3896 return static_cast<Result>(0);
3897 }
3898#else
3899 (void)location;
3900 return (object->*method)();
3901#endif // GTEST_HAS_SEH
3902}
3903
3904// Runs the given method and catches and reports C++ and/or SEH-style
3905// exceptions, if they are supported; returns the 0-value for type
3906// Result in case of an SEH exception.
3907template <class T, typename Result>
3908Result HandleExceptionsInMethodIfSupported(
3909 T* object, Result (T::*method)(), const char* location) {
3910 // NOTE: The user code can affect the way in which Google Test handles
3911 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3912 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3913 // after the exception is caught and either report or re-throw the
3914 // exception based on the flag's value:
3915 //
3916 // try {
3917 // // Perform the test method.
3918 // } catch (...) {
3919 // if (GTEST_FLAG(catch_exceptions))
3920 // // Report the exception as failure.
3921 // else
3922 // throw; // Re-throws the original exception.
3923 // }
3924 //
3925 // However, the purpose of this flag is to allow the program to drop into
3926 // the debugger when the exception is thrown. On most platforms, once the
3927 // control enters the catch block, the exception origin information is
3928 // lost and the debugger will stop the program at the point of the
3929 // re-throw in this function -- instead of at the point of the original
3930 // throw statement in the code under test. For this reason, we perform
3931 // the check early, sacrificing the ability to affect Google Test's
3932 // exception handling in the method where the exception is thrown.
3933 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3934#if GTEST_HAS_EXCEPTIONS
3935 try {
3936 return HandleSehExceptionsInMethodIfSupported(object, method, location);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003937 } catch (const AssertionException&) { // NOLINT
3938 // This failure was reported already.
Austin Schuh70cc9552019-01-21 19:46:48 -08003939 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3940 // This exception type can only be thrown by a failed Google
3941 // Test assertion with the intention of letting another testing
3942 // framework catch it. Therefore we just re-throw it.
3943 throw;
3944 } catch (const std::exception& e) { // NOLINT
3945 internal::ReportFailureInUnknownLocation(
3946 TestPartResult::kFatalFailure,
3947 FormatCxxExceptionMessage(e.what(), location));
3948 } catch (...) { // NOLINT
3949 internal::ReportFailureInUnknownLocation(
3950 TestPartResult::kFatalFailure,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003951 FormatCxxExceptionMessage(nullptr, location));
Austin Schuh70cc9552019-01-21 19:46:48 -08003952 }
3953 return static_cast<Result>(0);
3954#else
3955 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3956#endif // GTEST_HAS_EXCEPTIONS
3957 } else {
3958 return (object->*method)();
3959 }
3960}
3961
3962} // namespace internal
3963
3964// Runs the test and updates the test result.
3965void Test::Run() {
3966 if (!HasSameFixtureClass()) return;
3967
3968 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3969 impl->os_stack_trace_getter()->UponLeavingGTest();
3970 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003971 // We will run the test only if SetUp() was successful and didn't call
3972 // GTEST_SKIP().
3973 if (!HasFatalFailure() && !IsSkipped()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08003974 impl->os_stack_trace_getter()->UponLeavingGTest();
3975 internal::HandleExceptionsInMethodIfSupported(
3976 this, &Test::TestBody, "the test body");
3977 }
3978
3979 // However, we want to clean up as much as possible. Hence we will
3980 // always call TearDown(), even if SetUp() or the test body has
3981 // failed.
3982 impl->os_stack_trace_getter()->UponLeavingGTest();
3983 internal::HandleExceptionsInMethodIfSupported(
3984 this, &Test::TearDown, "TearDown()");
3985}
3986
3987// Returns true iff the current test has a fatal failure.
3988bool Test::HasFatalFailure() {
3989 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3990}
3991
3992// Returns true iff the current test has a non-fatal failure.
3993bool Test::HasNonfatalFailure() {
3994 return internal::GetUnitTestImpl()->current_test_result()->
3995 HasNonfatalFailure();
3996}
3997
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003998// Returns true iff the current test was skipped.
3999bool Test::IsSkipped() {
4000 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4001}
4002
Austin Schuh70cc9552019-01-21 19:46:48 -08004003// class TestInfo
4004
4005// Constructs a TestInfo object. It assumes ownership of the test factory
4006// object.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004007TestInfo::TestInfo(const std::string& a_test_suite_name,
4008 const std::string& a_name, const char* a_type_param,
Austin Schuh70cc9552019-01-21 19:46:48 -08004009 const char* a_value_param,
4010 internal::CodeLocation a_code_location,
4011 internal::TypeId fixture_class_id,
4012 internal::TestFactoryBase* factory)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004013 : test_suite_name_(a_test_suite_name),
Austin Schuh70cc9552019-01-21 19:46:48 -08004014 name_(a_name),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004015 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4016 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
Austin Schuh70cc9552019-01-21 19:46:48 -08004017 location_(a_code_location),
4018 fixture_class_id_(fixture_class_id),
4019 should_run_(false),
4020 is_disabled_(false),
4021 matches_filter_(false),
4022 factory_(factory),
4023 result_() {}
4024
4025// Destructs a TestInfo object.
4026TestInfo::~TestInfo() { delete factory_; }
4027
4028namespace internal {
4029
4030// Creates a new TestInfo object and registers it with Google Test;
4031// returns the created object.
4032//
4033// Arguments:
4034//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004035// test_suite_name: name of the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08004036// name: name of the test
4037// type_param: the name of the test's type parameter, or NULL if
4038// this is not a typed or a type-parameterized test.
4039// value_param: text representation of the test's value parameter,
4040// or NULL if this is not a value-parameterized test.
4041// code_location: code location where the test is defined
4042// fixture_class_id: ID of the test fixture class
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004043// set_up_tc: pointer to the function that sets up the test suite
4044// tear_down_tc: pointer to the function that tears down the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08004045// factory: pointer to the factory that creates a test object.
4046// The newly created TestInfo instance will assume
4047// ownership of the factory object.
4048TestInfo* MakeAndRegisterTestInfo(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004049 const char* test_suite_name, const char* name, const char* type_param,
4050 const char* value_param, CodeLocation code_location,
4051 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
4052 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004053 TestInfo* const test_info =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004054 new TestInfo(test_suite_name, name, type_param, value_param,
Austin Schuh70cc9552019-01-21 19:46:48 -08004055 code_location, fixture_class_id, factory);
4056 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4057 return test_info;
4058}
4059
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004060void ReportInvalidTestSuiteType(const char* test_suite_name,
4061 CodeLocation code_location) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004062 Message errors;
4063 errors
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004064 << "Attempted redefinition of test suite " << test_suite_name << ".\n"
4065 << "All tests in the same test suite must use the same test fixture\n"
4066 << "class. However, in test suite " << test_suite_name << ", you tried\n"
Austin Schuh70cc9552019-01-21 19:46:48 -08004067 << "to define a test using a fixture class different from the one\n"
4068 << "used earlier. This can happen if the two fixture classes are\n"
4069 << "from different namespaces and have the same name. You should\n"
4070 << "probably rename one of the classes to put the tests into different\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004071 << "test suites.";
Austin Schuh70cc9552019-01-21 19:46:48 -08004072
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004073 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4074 code_location.line)
4075 << " " << errors.GetString();
Austin Schuh70cc9552019-01-21 19:46:48 -08004076}
Austin Schuh70cc9552019-01-21 19:46:48 -08004077} // namespace internal
4078
4079namespace {
4080
4081// A predicate that checks the test name of a TestInfo against a known
4082// value.
4083//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004084// This is used for implementation of the TestSuite class only. We put
Austin Schuh70cc9552019-01-21 19:46:48 -08004085// it in the anonymous namespace to prevent polluting the outer
4086// namespace.
4087//
4088// TestNameIs is copyable.
4089class TestNameIs {
4090 public:
4091 // Constructor.
4092 //
4093 // TestNameIs has NO default constructor.
4094 explicit TestNameIs(const char* name)
4095 : name_(name) {}
4096
4097 // Returns true iff the test name of test_info matches name_.
4098 bool operator()(const TestInfo * test_info) const {
4099 return test_info && test_info->name() == name_;
4100 }
4101
4102 private:
4103 std::string name_;
4104};
4105
4106} // namespace
4107
4108namespace internal {
4109
4110// This method expands all parameterized tests registered with macros TEST_P
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004111// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
Austin Schuh70cc9552019-01-21 19:46:48 -08004112// This will be done just once during the program runtime.
4113void UnitTestImpl::RegisterParameterizedTests() {
Austin Schuh70cc9552019-01-21 19:46:48 -08004114 if (!parameterized_tests_registered_) {
4115 parameterized_test_registry_.RegisterTests();
4116 parameterized_tests_registered_ = true;
4117 }
Austin Schuh70cc9552019-01-21 19:46:48 -08004118}
4119
4120} // namespace internal
4121
4122// Creates the test object, runs it, records its result, and then
4123// deletes it.
4124void TestInfo::Run() {
4125 if (!should_run_) return;
4126
4127 // Tells UnitTest where to store test result.
4128 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4129 impl->set_current_test_info(this);
4130
4131 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4132
4133 // Notifies the unit test event listeners that a test is about to start.
4134 repeater->OnTestStart(*this);
4135
4136 const TimeInMillis start = internal::GetTimeInMillis();
4137
4138 impl->os_stack_trace_getter()->UponLeavingGTest();
4139
4140 // Creates the test object.
4141 Test* const test = internal::HandleExceptionsInMethodIfSupported(
4142 factory_, &internal::TestFactoryBase::CreateTest,
4143 "the test fixture's constructor");
4144
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004145 // Runs the test if the constructor didn't generate a fatal failure or invoke
4146 // GTEST_SKIP().
4147 // Note that the object will not be null
4148 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004149 // This doesn't throw as all user code that can throw are wrapped into
4150 // exception handling code.
4151 test->Run();
4152 }
4153
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004154 if (test != nullptr) {
4155 // Deletes the test object.
4156 impl->os_stack_trace_getter()->UponLeavingGTest();
4157 internal::HandleExceptionsInMethodIfSupported(
4158 test, &Test::DeleteSelf_, "the test fixture's destructor");
4159 }
Austin Schuh70cc9552019-01-21 19:46:48 -08004160
4161 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4162
4163 // Notifies the unit test event listener that a test has just finished.
4164 repeater->OnTestEnd(*this);
4165
4166 // Tells UnitTest to stop associating assertion results to this
4167 // test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004168 impl->set_current_test_info(nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08004169}
4170
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004171// class TestSuite
Austin Schuh70cc9552019-01-21 19:46:48 -08004172
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004173// Gets the number of successful tests in this test suite.
4174int TestSuite::successful_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004175 return CountIf(test_info_list_, TestPassed);
4176}
4177
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004178// Gets the number of successful tests in this test suite.
4179int TestSuite::skipped_test_count() const {
4180 return CountIf(test_info_list_, TestSkipped);
4181}
4182
4183// Gets the number of failed tests in this test suite.
4184int TestSuite::failed_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004185 return CountIf(test_info_list_, TestFailed);
4186}
4187
4188// Gets the number of disabled tests that will be reported in the XML report.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004189int TestSuite::reportable_disabled_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004190 return CountIf(test_info_list_, TestReportableDisabled);
4191}
4192
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004193// Gets the number of disabled tests in this test suite.
4194int TestSuite::disabled_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004195 return CountIf(test_info_list_, TestDisabled);
4196}
4197
4198// Gets the number of tests to be printed in the XML report.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004199int TestSuite::reportable_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004200 return CountIf(test_info_list_, TestReportable);
4201}
4202
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004203// Get the number of tests in this test suite that should run.
4204int TestSuite::test_to_run_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004205 return CountIf(test_info_list_, ShouldRunTest);
4206}
4207
4208// Gets the number of all tests.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004209int TestSuite::total_test_count() const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004210 return static_cast<int>(test_info_list_.size());
4211}
4212
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004213// Creates a TestSuite with the given name.
Austin Schuh70cc9552019-01-21 19:46:48 -08004214//
4215// Arguments:
4216//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004217// name: name of the test suite
4218// a_type_param: the name of the test suite's type parameter, or NULL if
4219// this is not a typed or a type-parameterized test suite.
4220// set_up_tc: pointer to the function that sets up the test suite
4221// tear_down_tc: pointer to the function that tears down the test suite
4222TestSuite::TestSuite(const char* a_name, const char* a_type_param,
4223 internal::SetUpTestSuiteFunc set_up_tc,
4224 internal::TearDownTestSuiteFunc tear_down_tc)
Austin Schuh70cc9552019-01-21 19:46:48 -08004225 : name_(a_name),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004226 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
Austin Schuh70cc9552019-01-21 19:46:48 -08004227 set_up_tc_(set_up_tc),
4228 tear_down_tc_(tear_down_tc),
4229 should_run_(false),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004230 elapsed_time_(0) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08004231
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004232// Destructor of TestSuite.
4233TestSuite::~TestSuite() {
Austin Schuh70cc9552019-01-21 19:46:48 -08004234 // Deletes every Test in the collection.
4235 ForEach(test_info_list_, internal::Delete<TestInfo>);
4236}
4237
4238// Returns the i-th test among all the tests. i can range from 0 to
4239// total_test_count() - 1. If i is not in that range, returns NULL.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004240const TestInfo* TestSuite::GetTestInfo(int i) const {
Austin Schuh70cc9552019-01-21 19:46:48 -08004241 const int index = GetElementOr(test_indices_, i, -1);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004242 return index < 0 ? nullptr : test_info_list_[index];
Austin Schuh70cc9552019-01-21 19:46:48 -08004243}
4244
4245// Returns the i-th test among all the tests. i can range from 0 to
4246// total_test_count() - 1. If i is not in that range, returns NULL.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004247TestInfo* TestSuite::GetMutableTestInfo(int i) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004248 const int index = GetElementOr(test_indices_, i, -1);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004249 return index < 0 ? nullptr : test_info_list_[index];
Austin Schuh70cc9552019-01-21 19:46:48 -08004250}
4251
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004252// Adds a test to this test suite. Will delete the test upon
4253// destruction of the TestSuite object.
4254void TestSuite::AddTestInfo(TestInfo* test_info) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004255 test_info_list_.push_back(test_info);
4256 test_indices_.push_back(static_cast<int>(test_indices_.size()));
4257}
4258
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004259// Runs every test in this TestSuite.
4260void TestSuite::Run() {
Austin Schuh70cc9552019-01-21 19:46:48 -08004261 if (!should_run_) return;
4262
4263 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004264 impl->set_current_test_suite(this);
Austin Schuh70cc9552019-01-21 19:46:48 -08004265
4266 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4267
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004268 // Call both legacy and the new API
4269 repeater->OnTestSuiteStart(*this);
4270// Legacy API is deprecated but still available
4271#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
Austin Schuh70cc9552019-01-21 19:46:48 -08004272 repeater->OnTestCaseStart(*this);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004273#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4274
Austin Schuh70cc9552019-01-21 19:46:48 -08004275 impl->os_stack_trace_getter()->UponLeavingGTest();
4276 internal::HandleExceptionsInMethodIfSupported(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004277 this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
Austin Schuh70cc9552019-01-21 19:46:48 -08004278
4279 const internal::TimeInMillis start = internal::GetTimeInMillis();
4280 for (int i = 0; i < total_test_count(); i++) {
4281 GetMutableTestInfo(i)->Run();
4282 }
4283 elapsed_time_ = internal::GetTimeInMillis() - start;
4284
4285 impl->os_stack_trace_getter()->UponLeavingGTest();
4286 internal::HandleExceptionsInMethodIfSupported(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004287 this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
Austin Schuh70cc9552019-01-21 19:46:48 -08004288
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004289 // Call both legacy and the new API
4290 repeater->OnTestSuiteEnd(*this);
4291// Legacy API is deprecated but still available
4292#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
Austin Schuh70cc9552019-01-21 19:46:48 -08004293 repeater->OnTestCaseEnd(*this);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004294#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4295
4296 impl->set_current_test_suite(nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08004297}
4298
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004299// Clears the results of all tests in this test suite.
4300void TestSuite::ClearResult() {
Austin Schuh70cc9552019-01-21 19:46:48 -08004301 ad_hoc_test_result_.Clear();
4302 ForEach(test_info_list_, TestInfo::ClearTestResult);
4303}
4304
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004305// Shuffles the tests in this test suite.
4306void TestSuite::ShuffleTests(internal::Random* random) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004307 Shuffle(random, &test_indices_);
4308}
4309
4310// Restores the test order to before the first shuffle.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004311void TestSuite::UnshuffleTests() {
Austin Schuh70cc9552019-01-21 19:46:48 -08004312 for (size_t i = 0; i < test_indices_.size(); i++) {
4313 test_indices_[i] = static_cast<int>(i);
4314 }
4315}
4316
4317// Formats a countable noun. Depending on its quantity, either the
4318// singular form or the plural form is used. e.g.
4319//
4320// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4321// FormatCountableNoun(5, "book", "books") returns "5 books".
4322static std::string FormatCountableNoun(int count,
4323 const char * singular_form,
4324 const char * plural_form) {
4325 return internal::StreamableToString(count) + " " +
4326 (count == 1 ? singular_form : plural_form);
4327}
4328
4329// Formats the count of tests.
4330static std::string FormatTestCount(int test_count) {
4331 return FormatCountableNoun(test_count, "test", "tests");
4332}
4333
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004334// Formats the count of test suites.
4335static std::string FormatTestSuiteCount(int test_suite_count) {
4336 return FormatCountableNoun(test_suite_count, "test suite", "test suites");
Austin Schuh70cc9552019-01-21 19:46:48 -08004337}
4338
4339// Converts a TestPartResult::Type enum to human-friendly string
4340// representation. Both kNonFatalFailure and kFatalFailure are translated
4341// to "Failure", as the user usually doesn't care about the difference
4342// between the two when viewing the test result.
4343static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4344 switch (type) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004345 case TestPartResult::kSkip:
4346 return "Skipped";
Austin Schuh70cc9552019-01-21 19:46:48 -08004347 case TestPartResult::kSuccess:
4348 return "Success";
4349
4350 case TestPartResult::kNonFatalFailure:
4351 case TestPartResult::kFatalFailure:
4352#ifdef _MSC_VER
4353 return "error: ";
4354#else
4355 return "Failure\n";
4356#endif
4357 default:
4358 return "Unknown result type";
4359 }
4360}
4361
4362namespace internal {
4363
4364// Prints a TestPartResult to an std::string.
4365static std::string PrintTestPartResultToString(
4366 const TestPartResult& test_part_result) {
4367 return (Message()
4368 << internal::FormatFileLocation(test_part_result.file_name(),
4369 test_part_result.line_number())
4370 << " " << TestPartResultTypeToString(test_part_result.type())
4371 << test_part_result.message()).GetString();
4372}
4373
4374// Prints a TestPartResult.
4375static void PrintTestPartResult(const TestPartResult& test_part_result) {
4376 const std::string& result =
4377 PrintTestPartResultToString(test_part_result);
4378 printf("%s\n", result.c_str());
4379 fflush(stdout);
4380 // If the test program runs in Visual Studio or a debugger, the
4381 // following statements add the test part result message to the Output
4382 // window such that the user can double-click on it to jump to the
4383 // corresponding source code location; otherwise they do nothing.
4384#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4385 // We don't call OutputDebugString*() on Windows Mobile, as printing
4386 // to stdout is done by OutputDebugString() there already - we don't
4387 // want the same message printed twice.
4388 ::OutputDebugStringA(result.c_str());
4389 ::OutputDebugStringA("\n");
4390#endif
4391}
4392
4393// class PrettyUnitTestResultPrinter
Austin Schuh70cc9552019-01-21 19:46:48 -08004394#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004395 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
Austin Schuh70cc9552019-01-21 19:46:48 -08004396
4397// Returns the character attribute for the given color.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004398static WORD GetColorAttribute(GTestColor color) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004399 switch (color) {
4400 case COLOR_RED: return FOREGROUND_RED;
4401 case COLOR_GREEN: return FOREGROUND_GREEN;
4402 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4403 default: return 0;
4404 }
4405}
4406
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004407static int GetBitOffset(WORD color_mask) {
4408 if (color_mask == 0) return 0;
4409
4410 int bitOffset = 0;
4411 while ((color_mask & 1) == 0) {
4412 color_mask >>= 1;
4413 ++bitOffset;
4414 }
4415 return bitOffset;
4416}
4417
4418static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4419 // Let's reuse the BG
4420 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4421 BACKGROUND_RED | BACKGROUND_INTENSITY;
4422 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4423 FOREGROUND_RED | FOREGROUND_INTENSITY;
4424 const WORD existing_bg = old_color_attrs & background_mask;
4425
4426 WORD new_color =
4427 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4428 static const int bg_bitOffset = GetBitOffset(background_mask);
4429 static const int fg_bitOffset = GetBitOffset(foreground_mask);
4430
4431 if (((new_color & background_mask) >> bg_bitOffset) ==
4432 ((new_color & foreground_mask) >> fg_bitOffset)) {
4433 new_color ^= FOREGROUND_INTENSITY; // invert intensity
4434 }
4435 return new_color;
4436}
4437
Austin Schuh70cc9552019-01-21 19:46:48 -08004438#else
4439
4440// Returns the ANSI color code for the given color. COLOR_DEFAULT is
4441// an invalid input.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004442static const char* GetAnsiColorCode(GTestColor color) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004443 switch (color) {
4444 case COLOR_RED: return "1";
4445 case COLOR_GREEN: return "2";
4446 case COLOR_YELLOW: return "3";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004447 default:
4448 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08004449 };
4450}
4451
4452#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4453
4454// Returns true iff Google Test should use colors in the output.
4455bool ShouldUseColor(bool stdout_is_tty) {
4456 const char* const gtest_color = GTEST_FLAG(color).c_str();
4457
4458 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004459#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
Austin Schuh70cc9552019-01-21 19:46:48 -08004460 // On Windows the TERM variable is usually not set, but the
4461 // console there does support colors.
4462 return stdout_is_tty;
4463#else
4464 // On non-Windows platforms, we rely on the TERM variable.
4465 const char* const term = posix::GetEnv("TERM");
4466 const bool term_supports_color =
4467 String::CStringEquals(term, "xterm") ||
4468 String::CStringEquals(term, "xterm-color") ||
4469 String::CStringEquals(term, "xterm-256color") ||
4470 String::CStringEquals(term, "screen") ||
4471 String::CStringEquals(term, "screen-256color") ||
4472 String::CStringEquals(term, "tmux") ||
4473 String::CStringEquals(term, "tmux-256color") ||
4474 String::CStringEquals(term, "rxvt-unicode") ||
4475 String::CStringEquals(term, "rxvt-unicode-256color") ||
4476 String::CStringEquals(term, "linux") ||
4477 String::CStringEquals(term, "cygwin");
4478 return stdout_is_tty && term_supports_color;
4479#endif // GTEST_OS_WINDOWS
4480 }
4481
4482 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4483 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4484 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4485 String::CStringEquals(gtest_color, "1");
4486 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4487 // value is neither one of these nor "auto", we treat it as "no" to
4488 // be conservative.
4489}
4490
4491// Helpers for printing colored strings to stdout. Note that on Windows, we
4492// cannot simply emit special characters and have the terminal change colors.
4493// This routine must actually emit the characters rather than return a string
4494// that would be colored when printed, as can be done on Linux.
4495void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4496 va_list args;
4497 va_start(args, fmt);
4498
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004499#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
4500 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
Austin Schuh70cc9552019-01-21 19:46:48 -08004501 const bool use_color = AlwaysFalse();
4502#else
4503 static const bool in_color_mode =
4504 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4505 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004506#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
Austin Schuh70cc9552019-01-21 19:46:48 -08004507
4508 if (!use_color) {
4509 vprintf(fmt, args);
4510 va_end(args);
4511 return;
4512 }
4513
4514#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004515 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
Austin Schuh70cc9552019-01-21 19:46:48 -08004516 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4517
4518 // Gets the current text color.
4519 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4520 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4521 const WORD old_color_attrs = buffer_info.wAttributes;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004522 const WORD new_color = GetNewColor(color, old_color_attrs);
Austin Schuh70cc9552019-01-21 19:46:48 -08004523
4524 // We need to flush the stream buffers into the console before each
4525 // SetConsoleTextAttribute call lest it affect the text that is already
4526 // printed but has not yet reached the console.
4527 fflush(stdout);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004528 SetConsoleTextAttribute(stdout_handle, new_color);
4529
Austin Schuh70cc9552019-01-21 19:46:48 -08004530 vprintf(fmt, args);
4531
4532 fflush(stdout);
4533 // Restores the text color.
4534 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4535#else
4536 printf("\033[0;3%sm", GetAnsiColorCode(color));
4537 vprintf(fmt, args);
4538 printf("\033[m"); // Resets the terminal to default.
4539#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4540 va_end(args);
4541}
4542
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004543// Text printed in Google Test's text output and --gtest_list_tests
Austin Schuh70cc9552019-01-21 19:46:48 -08004544// output to label the type parameter and value parameter for a test.
4545static const char kTypeParamLabel[] = "TypeParam";
4546static const char kValueParamLabel[] = "GetParam()";
4547
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004548static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004549 const char* const type_param = test_info.type_param();
4550 const char* const value_param = test_info.value_param();
4551
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004552 if (type_param != nullptr || value_param != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004553 printf(", where ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004554 if (type_param != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004555 printf("%s = %s", kTypeParamLabel, type_param);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004556 if (value_param != nullptr) printf(" and ");
Austin Schuh70cc9552019-01-21 19:46:48 -08004557 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004558 if (value_param != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004559 printf("%s = %s", kValueParamLabel, value_param);
4560 }
4561 }
4562}
4563
4564// This class implements the TestEventListener interface.
4565//
4566// Class PrettyUnitTestResultPrinter is copyable.
4567class PrettyUnitTestResultPrinter : public TestEventListener {
4568 public:
4569 PrettyUnitTestResultPrinter() {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004570 static void PrintTestName(const char* test_suite, const char* test) {
4571 printf("%s.%s", test_suite, test);
Austin Schuh70cc9552019-01-21 19:46:48 -08004572 }
4573
4574 // The following methods override what's in the TestEventListener class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004575 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
4576 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4577 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4578 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
4579 void OnTestCaseStart(const TestSuite& test_suite) override;
4580 void OnTestStart(const TestInfo& test_info) override;
4581 void OnTestPartResult(const TestPartResult& result) override;
4582 void OnTestEnd(const TestInfo& test_info) override;
4583 void OnTestCaseEnd(const TestSuite& test_suite) override;
4584 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4585 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
4586 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4587 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08004588
4589 private:
4590 static void PrintFailedTests(const UnitTest& unit_test);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004591 static void PrintSkippedTests(const UnitTest& unit_test);
Austin Schuh70cc9552019-01-21 19:46:48 -08004592};
4593
4594 // Fired before each iteration of tests starts.
4595void PrettyUnitTestResultPrinter::OnTestIterationStart(
4596 const UnitTest& unit_test, int iteration) {
4597 if (GTEST_FLAG(repeat) != 1)
4598 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4599
4600 const char* const filter = GTEST_FLAG(filter).c_str();
4601
4602 // Prints the filter if it's not *. This reminds the user that some
4603 // tests may be skipped.
4604 if (!String::CStringEquals(filter, kUniversalFilter)) {
4605 ColoredPrintf(COLOR_YELLOW,
4606 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4607 }
4608
4609 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4610 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4611 ColoredPrintf(COLOR_YELLOW,
4612 "Note: This is test shard %d of %s.\n",
4613 static_cast<int>(shard_index) + 1,
4614 internal::posix::GetEnv(kTestTotalShards));
4615 }
4616
4617 if (GTEST_FLAG(shuffle)) {
4618 ColoredPrintf(COLOR_YELLOW,
4619 "Note: Randomizing tests' orders with a seed of %d .\n",
4620 unit_test.random_seed());
4621 }
4622
4623 ColoredPrintf(COLOR_GREEN, "[==========] ");
4624 printf("Running %s from %s.\n",
4625 FormatTestCount(unit_test.test_to_run_count()).c_str(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004626 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08004627 fflush(stdout);
4628}
4629
4630void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4631 const UnitTest& /*unit_test*/) {
4632 ColoredPrintf(COLOR_GREEN, "[----------] ");
4633 printf("Global test environment set-up.\n");
4634 fflush(stdout);
4635}
4636
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004637void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004638 const std::string counts =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004639 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
Austin Schuh70cc9552019-01-21 19:46:48 -08004640 ColoredPrintf(COLOR_GREEN, "[----------] ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004641 printf("%s from %s", counts.c_str(), test_suite.name());
4642 if (test_suite.type_param() == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004643 printf("\n");
4644 } else {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004645 printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
Austin Schuh70cc9552019-01-21 19:46:48 -08004646 }
4647 fflush(stdout);
4648}
4649
4650void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4651 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004652 PrintTestName(test_info.test_suite_name(), test_info.name());
Austin Schuh70cc9552019-01-21 19:46:48 -08004653 printf("\n");
4654 fflush(stdout);
4655}
4656
4657// Called after an assertion failure.
4658void PrettyUnitTestResultPrinter::OnTestPartResult(
4659 const TestPartResult& result) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004660 switch (result.type()) {
4661 // If the test part succeeded, or was skipped,
4662 // we don't need to do anything.
4663 case TestPartResult::kSkip:
4664 case TestPartResult::kSuccess:
4665 return;
4666 default:
4667 // Print failure message from the assertion
4668 // (e.g. expected this and got that).
4669 PrintTestPartResult(result);
4670 fflush(stdout);
4671 }
Austin Schuh70cc9552019-01-21 19:46:48 -08004672}
4673
4674void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4675 if (test_info.result()->Passed()) {
4676 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004677 } else if (test_info.result()->Skipped()) {
4678 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
Austin Schuh70cc9552019-01-21 19:46:48 -08004679 } else {
4680 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4681 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004682 PrintTestName(test_info.test_suite_name(), test_info.name());
Austin Schuh70cc9552019-01-21 19:46:48 -08004683 if (test_info.result()->Failed())
4684 PrintFullTestCommentIfPresent(test_info);
4685
4686 if (GTEST_FLAG(print_time)) {
4687 printf(" (%s ms)\n", internal::StreamableToString(
4688 test_info.result()->elapsed_time()).c_str());
4689 } else {
4690 printf("\n");
4691 }
4692 fflush(stdout);
4693}
4694
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004695void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004696 if (!GTEST_FLAG(print_time)) return;
4697
4698 const std::string counts =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004699 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
Austin Schuh70cc9552019-01-21 19:46:48 -08004700 ColoredPrintf(COLOR_GREEN, "[----------] ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004701 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
4702 internal::StreamableToString(test_suite.elapsed_time()).c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08004703 fflush(stdout);
4704}
4705
4706void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4707 const UnitTest& /*unit_test*/) {
4708 ColoredPrintf(COLOR_GREEN, "[----------] ");
4709 printf("Global test environment tear-down\n");
4710 fflush(stdout);
4711}
4712
4713// Internal helper for printing the list of failed tests.
4714void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4715 const int failed_test_count = unit_test.failed_test_count();
4716 if (failed_test_count == 0) {
4717 return;
4718 }
4719
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004720 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4721 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4722 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004723 continue;
4724 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004725 for (int j = 0; j < test_suite.total_test_count(); ++j) {
4726 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4727 if (!test_info.should_run() || !test_info.result()->Failed()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004728 continue;
4729 }
4730 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004731 printf("%s.%s", test_suite.name(), test_info.name());
Austin Schuh70cc9552019-01-21 19:46:48 -08004732 PrintFullTestCommentIfPresent(test_info);
4733 printf("\n");
4734 }
4735 }
4736}
4737
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004738// Internal helper for printing the list of skipped tests.
4739void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
4740 const int skipped_test_count = unit_test.skipped_test_count();
4741 if (skipped_test_count == 0) {
4742 return;
4743 }
4744
4745 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4746 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4747 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
4748 continue;
4749 }
4750 for (int j = 0; j < test_suite.total_test_count(); ++j) {
4751 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4752 if (!test_info.should_run() || !test_info.result()->Skipped()) {
4753 continue;
4754 }
4755 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4756 printf("%s.%s", test_suite.name(), test_info.name());
4757 printf("\n");
4758 }
4759 }
4760}
4761
Austin Schuh70cc9552019-01-21 19:46:48 -08004762void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4763 int /*iteration*/) {
4764 ColoredPrintf(COLOR_GREEN, "[==========] ");
4765 printf("%s from %s ran.",
4766 FormatTestCount(unit_test.test_to_run_count()).c_str(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004767 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08004768 if (GTEST_FLAG(print_time)) {
4769 printf(" (%s ms total)",
4770 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4771 }
4772 printf("\n");
4773 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4774 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4775
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004776 const int skipped_test_count = unit_test.skipped_test_count();
4777 if (skipped_test_count > 0) {
4778 ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4779 printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
4780 PrintSkippedTests(unit_test);
4781 }
4782
Austin Schuh70cc9552019-01-21 19:46:48 -08004783 int num_failures = unit_test.failed_test_count();
4784 if (!unit_test.Passed()) {
4785 const int failed_test_count = unit_test.failed_test_count();
4786 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4787 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4788 PrintFailedTests(unit_test);
4789 printf("\n%2d FAILED %s\n", num_failures,
4790 num_failures == 1 ? "TEST" : "TESTS");
4791 }
4792
4793 int num_disabled = unit_test.reportable_disabled_test_count();
4794 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4795 if (!num_failures) {
4796 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4797 }
4798 ColoredPrintf(COLOR_YELLOW,
4799 " YOU HAVE %d DISABLED %s\n\n",
4800 num_disabled,
4801 num_disabled == 1 ? "TEST" : "TESTS");
4802 }
4803 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4804 fflush(stdout);
4805}
4806
4807// End PrettyUnitTestResultPrinter
4808
4809// class TestEventRepeater
4810//
4811// This class forwards events to other event listeners.
4812class TestEventRepeater : public TestEventListener {
4813 public:
4814 TestEventRepeater() : forwarding_enabled_(true) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004815 ~TestEventRepeater() override;
Austin Schuh70cc9552019-01-21 19:46:48 -08004816 void Append(TestEventListener *listener);
4817 TestEventListener* Release(TestEventListener* listener);
4818
4819 // Controls whether events will be forwarded to listeners_. Set to false
4820 // in death test child processes.
4821 bool forwarding_enabled() const { return forwarding_enabled_; }
4822 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4823
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004824 void OnTestProgramStart(const UnitTest& unit_test) override;
4825 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4826 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4827 void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
4828// Legacy API is deprecated but still available
4829#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4830 void OnTestCaseStart(const TestSuite& parameter) override;
4831#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4832 void OnTestSuiteStart(const TestSuite& parameter) override;
4833 void OnTestStart(const TestInfo& test_info) override;
4834 void OnTestPartResult(const TestPartResult& result) override;
4835 void OnTestEnd(const TestInfo& test_info) override;
4836// Legacy API is deprecated but still available
4837#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4838 void OnTestCaseEnd(const TestSuite& parameter) override;
4839#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4840 void OnTestSuiteEnd(const TestSuite& parameter) override;
4841 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4842 void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
4843 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4844 void OnTestProgramEnd(const UnitTest& unit_test) override;
Austin Schuh70cc9552019-01-21 19:46:48 -08004845
4846 private:
4847 // Controls whether events will be forwarded to listeners_. Set to false
4848 // in death test child processes.
4849 bool forwarding_enabled_;
4850 // The list of listeners that receive events.
4851 std::vector<TestEventListener*> listeners_;
4852
4853 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4854};
4855
4856TestEventRepeater::~TestEventRepeater() {
4857 ForEach(listeners_, Delete<TestEventListener>);
4858}
4859
4860void TestEventRepeater::Append(TestEventListener *listener) {
4861 listeners_.push_back(listener);
4862}
4863
Austin Schuh70cc9552019-01-21 19:46:48 -08004864TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4865 for (size_t i = 0; i < listeners_.size(); ++i) {
4866 if (listeners_[i] == listener) {
4867 listeners_.erase(listeners_.begin() + i);
4868 return listener;
4869 }
4870 }
4871
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004872 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08004873}
4874
4875// Since most methods are very similar, use macros to reduce boilerplate.
4876// This defines a member that forwards the call to all listeners.
4877#define GTEST_REPEATER_METHOD_(Name, Type) \
4878void TestEventRepeater::Name(const Type& parameter) { \
4879 if (forwarding_enabled_) { \
4880 for (size_t i = 0; i < listeners_.size(); i++) { \
4881 listeners_[i]->Name(parameter); \
4882 } \
4883 } \
4884}
4885// This defines a member that forwards the call to all listeners in reverse
4886// order.
4887#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4888void TestEventRepeater::Name(const Type& parameter) { \
4889 if (forwarding_enabled_) { \
4890 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4891 listeners_[i]->Name(parameter); \
4892 } \
4893 } \
4894}
4895
4896GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4897GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004898// Legacy API is deprecated but still available
4899#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4900GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
4901#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4902GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
Austin Schuh70cc9552019-01-21 19:46:48 -08004903GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4904GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4905GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4906GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4907GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4908GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004909// Legacy API is deprecated but still available
4910#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4911GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
4912#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4913GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
Austin Schuh70cc9552019-01-21 19:46:48 -08004914GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4915
4916#undef GTEST_REPEATER_METHOD_
4917#undef GTEST_REVERSE_REPEATER_METHOD_
4918
4919void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4920 int iteration) {
4921 if (forwarding_enabled_) {
4922 for (size_t i = 0; i < listeners_.size(); i++) {
4923 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4924 }
4925 }
4926}
4927
4928void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4929 int iteration) {
4930 if (forwarding_enabled_) {
4931 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4932 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4933 }
4934 }
4935}
4936
4937// End TestEventRepeater
4938
4939// This class generates an XML output file.
4940class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4941 public:
4942 explicit XmlUnitTestResultPrinter(const char* output_file);
4943
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004944 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4945 void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
4946
4947 // Prints an XML summary of all unit tests.
4948 static void PrintXmlTestsList(std::ostream* stream,
4949 const std::vector<TestSuite*>& test_suites);
Austin Schuh70cc9552019-01-21 19:46:48 -08004950
4951 private:
4952 // Is c a whitespace character that is normalized to a space character
4953 // when it appears in an XML attribute value?
4954 static bool IsNormalizableWhitespace(char c) {
4955 return c == 0x9 || c == 0xA || c == 0xD;
4956 }
4957
4958 // May c appear in a well-formed XML document?
4959 static bool IsValidXmlCharacter(char c) {
4960 return IsNormalizableWhitespace(c) || c >= 0x20;
4961 }
4962
4963 // Returns an XML-escaped copy of the input string str. If
4964 // is_attribute is true, the text is meant to appear as an attribute
4965 // value, and normalizable whitespace is preserved by replacing it
4966 // with character references.
4967 static std::string EscapeXml(const std::string& str, bool is_attribute);
4968
4969 // Returns the given string with all characters invalid in XML removed.
4970 static std::string RemoveInvalidXmlCharacters(const std::string& str);
4971
4972 // Convenience wrapper around EscapeXml when str is an attribute value.
4973 static std::string EscapeXmlAttribute(const std::string& str) {
4974 return EscapeXml(str, true);
4975 }
4976
4977 // Convenience wrapper around EscapeXml when str is not an attribute value.
4978 static std::string EscapeXmlText(const char* str) {
4979 return EscapeXml(str, false);
4980 }
4981
4982 // Verifies that the given attribute belongs to the given element and
4983 // streams the attribute as XML.
4984 static void OutputXmlAttribute(std::ostream* stream,
4985 const std::string& element_name,
4986 const std::string& name,
4987 const std::string& value);
4988
4989 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4990 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4991
4992 // Streams an XML representation of a TestInfo object.
4993 static void OutputXmlTestInfo(::std::ostream* stream,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004994 const char* test_suite_name,
Austin Schuh70cc9552019-01-21 19:46:48 -08004995 const TestInfo& test_info);
4996
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004997 // Prints an XML representation of a TestSuite object
4998 static void PrintXmlTestSuite(::std::ostream* stream,
4999 const TestSuite& test_suite);
Austin Schuh70cc9552019-01-21 19:46:48 -08005000
5001 // Prints an XML summary of unit_test to output stream out.
5002 static void PrintXmlUnitTest(::std::ostream* stream,
5003 const UnitTest& unit_test);
5004
5005 // Produces a string representing the test properties in a result as space
5006 // delimited XML attributes based on the property key="value" pairs.
5007 // When the std::string is not empty, it includes a space at the beginning,
5008 // to delimit this attribute from prior attributes.
5009 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
5010
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005011 // Streams an XML representation of the test properties of a TestResult
5012 // object.
5013 static void OutputXmlTestProperties(std::ostream* stream,
5014 const TestResult& result);
5015
Austin Schuh70cc9552019-01-21 19:46:48 -08005016 // The output file.
5017 const std::string output_file_;
5018
5019 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
5020};
5021
5022// Creates a new XmlUnitTestResultPrinter.
5023XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
5024 : output_file_(output_file) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005025 if (output_file_.empty()) {
5026 GTEST_LOG_(FATAL) << "XML output file may not be null";
Austin Schuh70cc9552019-01-21 19:46:48 -08005027 }
5028}
5029
5030// Called after the unit test ends.
5031void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5032 int /*iteration*/) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005033 FILE* xmlout = OpenFileForWriting(output_file_);
Austin Schuh70cc9552019-01-21 19:46:48 -08005034 std::stringstream stream;
5035 PrintXmlUnitTest(&stream, unit_test);
5036 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5037 fclose(xmlout);
5038}
5039
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005040void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5041 const std::vector<TestSuite*>& test_suites) {
5042 FILE* xmlout = OpenFileForWriting(output_file_);
5043 std::stringstream stream;
5044 PrintXmlTestsList(&stream, test_suites);
5045 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5046 fclose(xmlout);
5047}
5048
Austin Schuh70cc9552019-01-21 19:46:48 -08005049// Returns an XML-escaped copy of the input string str. If is_attribute
5050// is true, the text is meant to appear as an attribute value, and
5051// normalizable whitespace is preserved by replacing it with character
5052// references.
5053//
5054// Invalid XML characters in str, if any, are stripped from the output.
5055// It is expected that most, if not all, of the text processed by this
5056// module will consist of ordinary English text.
5057// If this module is ever modified to produce version 1.1 XML output,
5058// most invalid characters can be retained using character references.
Austin Schuh70cc9552019-01-21 19:46:48 -08005059std::string XmlUnitTestResultPrinter::EscapeXml(
5060 const std::string& str, bool is_attribute) {
5061 Message m;
5062
5063 for (size_t i = 0; i < str.size(); ++i) {
5064 const char ch = str[i];
5065 switch (ch) {
5066 case '<':
5067 m << "&lt;";
5068 break;
5069 case '>':
5070 m << "&gt;";
5071 break;
5072 case '&':
5073 m << "&amp;";
5074 break;
5075 case '\'':
5076 if (is_attribute)
5077 m << "&apos;";
5078 else
5079 m << '\'';
5080 break;
5081 case '"':
5082 if (is_attribute)
5083 m << "&quot;";
5084 else
5085 m << '"';
5086 break;
5087 default:
5088 if (IsValidXmlCharacter(ch)) {
5089 if (is_attribute && IsNormalizableWhitespace(ch))
5090 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5091 << ";";
5092 else
5093 m << ch;
5094 }
5095 break;
5096 }
5097 }
5098
5099 return m.GetString();
5100}
5101
5102// Returns the given string with all characters invalid in XML removed.
5103// Currently invalid characters are dropped from the string. An
5104// alternative is to replace them with certain characters such as . or ?.
5105std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5106 const std::string& str) {
5107 std::string output;
5108 output.reserve(str.size());
5109 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5110 if (IsValidXmlCharacter(*it))
5111 output.push_back(*it);
5112
5113 return output;
5114}
5115
5116// The following routines generate an XML representation of a UnitTest
5117// object.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005118// GOOGLETEST_CM0009 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -08005119//
5120// This is how Google Test concepts map to the DTD:
5121//
5122// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005123// <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
Austin Schuh70cc9552019-01-21 19:46:48 -08005124// <testcase name="test-name"> <-- corresponds to a TestInfo object
5125// <failure message="...">...</failure>
5126// <failure message="...">...</failure>
5127// <failure message="...">...</failure>
5128// <-- individual assertion failures
5129// </testcase>
5130// </testsuite>
5131// </testsuites>
5132
5133// Formats the given time in milliseconds as seconds.
5134std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5135 ::std::stringstream ss;
5136 ss << (static_cast<double>(ms) * 1e-3);
5137 return ss.str();
5138}
5139
5140static bool PortableLocaltime(time_t seconds, struct tm* out) {
5141#if defined(_MSC_VER)
5142 return localtime_s(out, &seconds) == 0;
5143#elif defined(__MINGW32__) || defined(__MINGW64__)
5144 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5145 // Windows' localtime(), which has a thread-local tm buffer.
5146 struct tm* tm_ptr = localtime(&seconds); // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005147 if (tm_ptr == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08005148 *out = *tm_ptr;
5149 return true;
5150#else
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005151 return localtime_r(&seconds, out) != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08005152#endif
5153}
5154
5155// Converts the given epoch time in milliseconds to a date string in the ISO
5156// 8601 format, without the timezone information.
5157std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5158 struct tm time_struct;
5159 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5160 return "";
5161 // YYYY-MM-DDThh:mm:ss
5162 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5163 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5164 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5165 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5166 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5167 String::FormatIntWidth2(time_struct.tm_sec);
5168}
5169
5170// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5171void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5172 const char* data) {
5173 const char* segment = data;
5174 *stream << "<![CDATA[";
5175 for (;;) {
5176 const char* const next_segment = strstr(segment, "]]>");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005177 if (next_segment != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08005178 stream->write(
5179 segment, static_cast<std::streamsize>(next_segment - segment));
5180 *stream << "]]>]]&gt;<![CDATA[";
5181 segment = next_segment + strlen("]]>");
5182 } else {
5183 *stream << segment;
5184 break;
5185 }
5186 }
5187 *stream << "]]>";
5188}
5189
5190void XmlUnitTestResultPrinter::OutputXmlAttribute(
5191 std::ostream* stream,
5192 const std::string& element_name,
5193 const std::string& name,
5194 const std::string& value) {
5195 const std::vector<std::string>& allowed_names =
5196 GetReservedAttributesForElement(element_name);
5197
5198 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5199 allowed_names.end())
5200 << "Attribute " << name << " is not allowed for element <" << element_name
5201 << ">.";
5202
5203 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5204}
5205
5206// Prints an XML representation of a TestInfo object.
Austin Schuh70cc9552019-01-21 19:46:48 -08005207void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005208 const char* test_suite_name,
Austin Schuh70cc9552019-01-21 19:46:48 -08005209 const TestInfo& test_info) {
5210 const TestResult& result = *test_info.result();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005211 const std::string kTestsuite = "testcase";
5212
5213 if (test_info.is_in_another_shard()) {
5214 return;
5215 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005216
5217 *stream << " <testcase";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005218 OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
Austin Schuh70cc9552019-01-21 19:46:48 -08005219
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005220 if (test_info.value_param() != nullptr) {
5221 OutputXmlAttribute(stream, kTestsuite, "value_param",
Austin Schuh70cc9552019-01-21 19:46:48 -08005222 test_info.value_param());
5223 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005224 if (test_info.type_param() != nullptr) {
5225 OutputXmlAttribute(stream, kTestsuite, "type_param",
5226 test_info.type_param());
5227 }
5228 if (GTEST_FLAG(list_tests)) {
5229 OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
5230 OutputXmlAttribute(stream, kTestsuite, "line",
5231 StreamableToString(test_info.line()));
5232 *stream << " />\n";
5233 return;
Austin Schuh70cc9552019-01-21 19:46:48 -08005234 }
5235
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005236 OutputXmlAttribute(
5237 stream, kTestsuite, "status",
5238 result.Skipped() ? "skipped" : test_info.should_run() ? "run" : "notrun");
5239 OutputXmlAttribute(stream, kTestsuite, "time",
Austin Schuh70cc9552019-01-21 19:46:48 -08005240 FormatTimeInMillisAsSeconds(result.elapsed_time()));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005241 OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
Austin Schuh70cc9552019-01-21 19:46:48 -08005242
5243 int failures = 0;
5244 for (int i = 0; i < result.total_part_count(); ++i) {
5245 const TestPartResult& part = result.GetTestPartResult(i);
5246 if (part.failed()) {
5247 if (++failures == 1) {
5248 *stream << ">\n";
5249 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005250 const std::string location =
5251 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5252 part.line_number());
5253 const std::string summary = location + "\n" + part.summary();
Austin Schuh70cc9552019-01-21 19:46:48 -08005254 *stream << " <failure message=\""
5255 << EscapeXmlAttribute(summary.c_str())
5256 << "\" type=\"\">";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005257 const std::string detail = location + "\n" + part.message();
Austin Schuh70cc9552019-01-21 19:46:48 -08005258 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5259 *stream << "</failure>\n";
5260 }
5261 }
5262
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005263 if (failures == 0 && result.test_property_count() == 0) {
Austin Schuh70cc9552019-01-21 19:46:48 -08005264 *stream << " />\n";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005265 } else {
5266 if (failures == 0) {
5267 *stream << ">\n";
5268 }
5269 OutputXmlTestProperties(stream, result);
Austin Schuh70cc9552019-01-21 19:46:48 -08005270 *stream << " </testcase>\n";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005271 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005272}
5273
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005274// Prints an XML representation of a TestSuite object
5275void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5276 const TestSuite& test_suite) {
Austin Schuh70cc9552019-01-21 19:46:48 -08005277 const std::string kTestsuite = "testsuite";
5278 *stream << " <" << kTestsuite;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005279 OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
Austin Schuh70cc9552019-01-21 19:46:48 -08005280 OutputXmlAttribute(stream, kTestsuite, "tests",
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005281 StreamableToString(test_suite.reportable_test_count()));
5282 if (!GTEST_FLAG(list_tests)) {
5283 OutputXmlAttribute(stream, kTestsuite, "failures",
5284 StreamableToString(test_suite.failed_test_count()));
5285 OutputXmlAttribute(
5286 stream, kTestsuite, "disabled",
5287 StreamableToString(test_suite.reportable_disabled_test_count()));
5288 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5289 OutputXmlAttribute(stream, kTestsuite, "time",
5290 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5291 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5292 }
5293 *stream << ">\n";
5294 for (int i = 0; i < test_suite.total_test_count(); ++i) {
5295 if (test_suite.GetTestInfo(i)->is_reportable())
5296 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
Austin Schuh70cc9552019-01-21 19:46:48 -08005297 }
5298 *stream << " </" << kTestsuite << ">\n";
5299}
5300
5301// Prints an XML summary of unit_test to output stream out.
5302void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5303 const UnitTest& unit_test) {
5304 const std::string kTestsuites = "testsuites";
5305
5306 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5307 *stream << "<" << kTestsuites;
5308
5309 OutputXmlAttribute(stream, kTestsuites, "tests",
5310 StreamableToString(unit_test.reportable_test_count()));
5311 OutputXmlAttribute(stream, kTestsuites, "failures",
5312 StreamableToString(unit_test.failed_test_count()));
5313 OutputXmlAttribute(
5314 stream, kTestsuites, "disabled",
5315 StreamableToString(unit_test.reportable_disabled_test_count()));
5316 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5317 OutputXmlAttribute(
5318 stream, kTestsuites, "timestamp",
5319 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5320 OutputXmlAttribute(stream, kTestsuites, "time",
5321 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5322
5323 if (GTEST_FLAG(shuffle)) {
5324 OutputXmlAttribute(stream, kTestsuites, "random_seed",
5325 StreamableToString(unit_test.random_seed()));
5326 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005327 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5328
5329 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5330 *stream << ">\n";
5331
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005332 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5333 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5334 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5335 }
5336 *stream << "</" << kTestsuites << ">\n";
5337}
5338
5339void XmlUnitTestResultPrinter::PrintXmlTestsList(
5340 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5341 const std::string kTestsuites = "testsuites";
5342
5343 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5344 *stream << "<" << kTestsuites;
5345
5346 int total_tests = 0;
5347 for (auto test_suite : test_suites) {
5348 total_tests += test_suite->total_test_count();
5349 }
5350 OutputXmlAttribute(stream, kTestsuites, "tests",
5351 StreamableToString(total_tests));
5352 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5353 *stream << ">\n";
5354
5355 for (auto test_suite : test_suites) {
5356 PrintXmlTestSuite(stream, *test_suite);
Austin Schuh70cc9552019-01-21 19:46:48 -08005357 }
5358 *stream << "</" << kTestsuites << ">\n";
5359}
5360
5361// Produces a string representing the test properties in a result as space
5362// delimited XML attributes based on the property key="value" pairs.
5363std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5364 const TestResult& result) {
5365 Message attributes;
5366 for (int i = 0; i < result.test_property_count(); ++i) {
5367 const TestProperty& property = result.GetTestProperty(i);
5368 attributes << " " << property.key() << "="
5369 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5370 }
5371 return attributes.GetString();
5372}
5373
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005374void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5375 std::ostream* stream, const TestResult& result) {
5376 const std::string kProperties = "properties";
5377 const std::string kProperty = "property";
5378
5379 if (result.test_property_count() <= 0) {
5380 return;
5381 }
5382
5383 *stream << "<" << kProperties << ">\n";
5384 for (int i = 0; i < result.test_property_count(); ++i) {
5385 const TestProperty& property = result.GetTestProperty(i);
5386 *stream << "<" << kProperty;
5387 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5388 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5389 *stream << "/>\n";
5390 }
5391 *stream << "</" << kProperties << ">\n";
5392}
5393
Austin Schuh70cc9552019-01-21 19:46:48 -08005394// End XmlUnitTestResultPrinter
5395
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005396// This class generates an JSON output file.
5397class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5398 public:
5399 explicit JsonUnitTestResultPrinter(const char* output_file);
5400
5401 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5402
5403 // Prints an JSON summary of all unit tests.
5404 static void PrintJsonTestList(::std::ostream* stream,
5405 const std::vector<TestSuite*>& test_suites);
5406
5407 private:
5408 // Returns an JSON-escaped copy of the input string str.
5409 static std::string EscapeJson(const std::string& str);
5410
5411 //// Verifies that the given attribute belongs to the given element and
5412 //// streams the attribute as JSON.
5413 static void OutputJsonKey(std::ostream* stream,
5414 const std::string& element_name,
5415 const std::string& name,
5416 const std::string& value,
5417 const std::string& indent,
5418 bool comma = true);
5419 static void OutputJsonKey(std::ostream* stream,
5420 const std::string& element_name,
5421 const std::string& name,
5422 int value,
5423 const std::string& indent,
5424 bool comma = true);
5425
5426 // Streams a JSON representation of a TestInfo object.
5427 static void OutputJsonTestInfo(::std::ostream* stream,
5428 const char* test_suite_name,
5429 const TestInfo& test_info);
5430
5431 // Prints a JSON representation of a TestSuite object
5432 static void PrintJsonTestSuite(::std::ostream* stream,
5433 const TestSuite& test_suite);
5434
5435 // Prints a JSON summary of unit_test to output stream out.
5436 static void PrintJsonUnitTest(::std::ostream* stream,
5437 const UnitTest& unit_test);
5438
5439 // Produces a string representing the test properties in a result as
5440 // a JSON dictionary.
5441 static std::string TestPropertiesAsJson(const TestResult& result,
5442 const std::string& indent);
5443
5444 // The output file.
5445 const std::string output_file_;
5446
5447 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5448};
5449
5450// Creates a new JsonUnitTestResultPrinter.
5451JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5452 : output_file_(output_file) {
5453 if (output_file_.empty()) {
5454 GTEST_LOG_(FATAL) << "JSON output file may not be null";
5455 }
5456}
5457
5458void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5459 int /*iteration*/) {
5460 FILE* jsonout = OpenFileForWriting(output_file_);
5461 std::stringstream stream;
5462 PrintJsonUnitTest(&stream, unit_test);
5463 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5464 fclose(jsonout);
5465}
5466
5467// Returns an JSON-escaped copy of the input string str.
5468std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5469 Message m;
5470
5471 for (size_t i = 0; i < str.size(); ++i) {
5472 const char ch = str[i];
5473 switch (ch) {
5474 case '\\':
5475 case '"':
5476 case '/':
5477 m << '\\' << ch;
5478 break;
5479 case '\b':
5480 m << "\\b";
5481 break;
5482 case '\t':
5483 m << "\\t";
5484 break;
5485 case '\n':
5486 m << "\\n";
5487 break;
5488 case '\f':
5489 m << "\\f";
5490 break;
5491 case '\r':
5492 m << "\\r";
5493 break;
5494 default:
5495 if (ch < ' ') {
5496 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5497 } else {
5498 m << ch;
5499 }
5500 break;
5501 }
5502 }
5503
5504 return m.GetString();
5505}
5506
5507// The following routines generate an JSON representation of a UnitTest
5508// object.
5509
5510// Formats the given time in milliseconds as seconds.
5511static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
5512 ::std::stringstream ss;
5513 ss << (static_cast<double>(ms) * 1e-3) << "s";
5514 return ss.str();
5515}
5516
5517// Converts the given epoch time in milliseconds to a date string in the
5518// RFC3339 format, without the timezone information.
5519static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
5520 struct tm time_struct;
5521 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5522 return "";
5523 // YYYY-MM-DDThh:mm:ss
5524 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5525 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5526 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5527 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5528 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5529 String::FormatIntWidth2(time_struct.tm_sec) + "Z";
5530}
5531
5532static inline std::string Indent(int width) {
5533 return std::string(width, ' ');
5534}
5535
5536void JsonUnitTestResultPrinter::OutputJsonKey(
5537 std::ostream* stream,
5538 const std::string& element_name,
5539 const std::string& name,
5540 const std::string& value,
5541 const std::string& indent,
5542 bool comma) {
5543 const std::vector<std::string>& allowed_names =
5544 GetReservedAttributesForElement(element_name);
5545
5546 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5547 allowed_names.end())
5548 << "Key \"" << name << "\" is not allowed for value \"" << element_name
5549 << "\".";
5550
5551 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
5552 if (comma)
5553 *stream << ",\n";
5554}
5555
5556void JsonUnitTestResultPrinter::OutputJsonKey(
5557 std::ostream* stream,
5558 const std::string& element_name,
5559 const std::string& name,
5560 int value,
5561 const std::string& indent,
5562 bool comma) {
5563 const std::vector<std::string>& allowed_names =
5564 GetReservedAttributesForElement(element_name);
5565
5566 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5567 allowed_names.end())
5568 << "Key \"" << name << "\" is not allowed for value \"" << element_name
5569 << "\".";
5570
5571 *stream << indent << "\"" << name << "\": " << StreamableToString(value);
5572 if (comma)
5573 *stream << ",\n";
5574}
5575
5576// Prints a JSON representation of a TestInfo object.
5577void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5578 const char* test_suite_name,
5579 const TestInfo& test_info) {
5580 const TestResult& result = *test_info.result();
5581 const std::string kTestsuite = "testcase";
5582 const std::string kIndent = Indent(10);
5583
5584 *stream << Indent(8) << "{\n";
5585 OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
5586
5587 if (test_info.value_param() != nullptr) {
5588 OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
5589 kIndent);
5590 }
5591 if (test_info.type_param() != nullptr) {
5592 OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
5593 kIndent);
5594 }
5595 if (GTEST_FLAG(list_tests)) {
5596 OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
5597 OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
5598 *stream << "\n" << Indent(8) << "}";
5599 return;
5600 }
5601
5602 OutputJsonKey(
5603 stream, kTestsuite, "status",
5604 result.Skipped() ? "SKIPPED" : test_info.should_run() ? "RUN" : "NOTRUN",
5605 kIndent);
5606 OutputJsonKey(stream, kTestsuite, "time",
5607 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5608 OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
5609 false);
5610 *stream << TestPropertiesAsJson(result, kIndent);
5611
5612 int failures = 0;
5613 for (int i = 0; i < result.total_part_count(); ++i) {
5614 const TestPartResult& part = result.GetTestPartResult(i);
5615 if (part.failed()) {
5616 *stream << ",\n";
5617 if (++failures == 1) {
5618 *stream << kIndent << "\"" << "failures" << "\": [\n";
5619 }
5620 const std::string location =
5621 internal::FormatCompilerIndependentFileLocation(part.file_name(),
5622 part.line_number());
5623 const std::string message = EscapeJson(location + "\n" + part.message());
5624 *stream << kIndent << " {\n"
5625 << kIndent << " \"failure\": \"" << message << "\",\n"
5626 << kIndent << " \"type\": \"\"\n"
5627 << kIndent << " }";
5628 }
5629 }
5630
5631 if (failures > 0)
5632 *stream << "\n" << kIndent << "]";
5633 *stream << "\n" << Indent(8) << "}";
5634}
5635
5636// Prints an JSON representation of a TestSuite object
5637void JsonUnitTestResultPrinter::PrintJsonTestSuite(
5638 std::ostream* stream, const TestSuite& test_suite) {
5639 const std::string kTestsuite = "testsuite";
5640 const std::string kIndent = Indent(6);
5641
5642 *stream << Indent(4) << "{\n";
5643 OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
5644 OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
5645 kIndent);
5646 if (!GTEST_FLAG(list_tests)) {
5647 OutputJsonKey(stream, kTestsuite, "failures",
5648 test_suite.failed_test_count(), kIndent);
5649 OutputJsonKey(stream, kTestsuite, "disabled",
5650 test_suite.reportable_disabled_test_count(), kIndent);
5651 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
5652 OutputJsonKey(stream, kTestsuite, "time",
5653 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
5654 kIndent, false);
5655 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
5656 << ",\n";
5657 }
5658
5659 *stream << kIndent << "\"" << kTestsuite << "\": [\n";
5660
5661 bool comma = false;
5662 for (int i = 0; i < test_suite.total_test_count(); ++i) {
5663 if (test_suite.GetTestInfo(i)->is_reportable()) {
5664 if (comma) {
5665 *stream << ",\n";
5666 } else {
5667 comma = true;
5668 }
5669 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5670 }
5671 }
5672 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
5673}
5674
5675// Prints a JSON summary of unit_test to output stream out.
5676void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5677 const UnitTest& unit_test) {
5678 const std::string kTestsuites = "testsuites";
5679 const std::string kIndent = Indent(2);
5680 *stream << "{\n";
5681
5682 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
5683 kIndent);
5684 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
5685 kIndent);
5686 OutputJsonKey(stream, kTestsuites, "disabled",
5687 unit_test.reportable_disabled_test_count(), kIndent);
5688 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
5689 if (GTEST_FLAG(shuffle)) {
5690 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
5691 kIndent);
5692 }
5693 OutputJsonKey(stream, kTestsuites, "timestamp",
5694 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5695 kIndent);
5696 OutputJsonKey(stream, kTestsuites, "time",
5697 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5698 false);
5699
5700 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5701 << ",\n";
5702
5703 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5704 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5705
5706 bool comma = false;
5707 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5708 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
5709 if (comma) {
5710 *stream << ",\n";
5711 } else {
5712 comma = true;
5713 }
5714 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
5715 }
5716 }
5717
5718 *stream << "\n" << kIndent << "]\n" << "}\n";
5719}
5720
5721void JsonUnitTestResultPrinter::PrintJsonTestList(
5722 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5723 const std::string kTestsuites = "testsuites";
5724 const std::string kIndent = Indent(2);
5725 *stream << "{\n";
5726 int total_tests = 0;
5727 for (auto test_suite : test_suites) {
5728 total_tests += test_suite->total_test_count();
5729 }
5730 OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
5731
5732 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5733 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5734
5735 for (size_t i = 0; i < test_suites.size(); ++i) {
5736 if (i != 0) {
5737 *stream << ",\n";
5738 }
5739 PrintJsonTestSuite(stream, *test_suites[i]);
5740 }
5741
5742 *stream << "\n"
5743 << kIndent << "]\n"
5744 << "}\n";
5745}
5746// Produces a string representing the test properties in a result as
5747// a JSON dictionary.
5748std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5749 const TestResult& result, const std::string& indent) {
5750 Message attributes;
5751 for (int i = 0; i < result.test_property_count(); ++i) {
5752 const TestProperty& property = result.GetTestProperty(i);
5753 attributes << ",\n" << indent << "\"" << property.key() << "\": "
5754 << "\"" << EscapeJson(property.value()) << "\"";
5755 }
5756 return attributes.GetString();
5757}
5758
5759// End JsonUnitTestResultPrinter
5760
Austin Schuh70cc9552019-01-21 19:46:48 -08005761#if GTEST_CAN_STREAM_RESULTS_
5762
5763// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5764// replaces them by "%xx" where xx is their hexadecimal value. For
5765// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
5766// in both time and space -- important as the input str may contain an
5767// arbitrarily long test failure message and stack trace.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005768std::string StreamingListener::UrlEncode(const char* str) {
5769 std::string result;
Austin Schuh70cc9552019-01-21 19:46:48 -08005770 result.reserve(strlen(str) + 1);
5771 for (char ch = *str; ch != '\0'; ch = *++str) {
5772 switch (ch) {
5773 case '%':
5774 case '=':
5775 case '&':
5776 case '\n':
5777 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5778 break;
5779 default:
5780 result.push_back(ch);
5781 break;
5782 }
5783 }
5784 return result;
5785}
5786
5787void StreamingListener::SocketWriter::MakeConnection() {
5788 GTEST_CHECK_(sockfd_ == -1)
5789 << "MakeConnection() can't be called when there is already a connection.";
5790
5791 addrinfo hints;
5792 memset(&hints, 0, sizeof(hints));
5793 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5794 hints.ai_socktype = SOCK_STREAM;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005795 addrinfo* servinfo = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08005796
5797 // Use the getaddrinfo() to get a linked list of IP addresses for
5798 // the given host name.
5799 const int error_num = getaddrinfo(
5800 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5801 if (error_num != 0) {
5802 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5803 << gai_strerror(error_num);
5804 }
5805
5806 // Loop through all the results and connect to the first we can.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005807 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08005808 cur_addr = cur_addr->ai_next) {
5809 sockfd_ = socket(
5810 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5811 if (sockfd_ != -1) {
5812 // Connect the client socket to the server socket.
5813 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5814 close(sockfd_);
5815 sockfd_ = -1;
5816 }
5817 }
5818 }
5819
5820 freeaddrinfo(servinfo); // all done with this structure
5821
5822 if (sockfd_ == -1) {
5823 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5824 << host_name_ << ":" << port_num_;
5825 }
5826}
5827
5828// End of class Streaming Listener
5829#endif // GTEST_CAN_STREAM_RESULTS__
5830
Austin Schuh70cc9552019-01-21 19:46:48 -08005831// class OsStackTraceGetter
5832
5833const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5834 "... " GTEST_NAME_ " internal frames ...";
5835
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005836std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5837 GTEST_LOCK_EXCLUDED_(mutex_) {
5838#if GTEST_HAS_ABSL
5839 std::string result;
5840
5841 if (max_depth <= 0) {
5842 return result;
5843 }
5844
5845 max_depth = std::min(max_depth, kMaxStackTraceDepth);
5846
5847 std::vector<void*> raw_stack(max_depth);
5848 // Skips the frames requested by the caller, plus this function.
5849 const int raw_stack_size =
5850 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5851
5852 void* caller_frame = nullptr;
5853 {
5854 MutexLock lock(&mutex_);
5855 caller_frame = caller_frame_;
5856 }
5857
5858 for (int i = 0; i < raw_stack_size; ++i) {
5859 if (raw_stack[i] == caller_frame &&
5860 !GTEST_FLAG(show_internal_stack_frames)) {
5861 // Add a marker to the trace and stop adding frames.
5862 absl::StrAppend(&result, kElidedFramesMarker, "\n");
5863 break;
5864 }
5865
5866 char tmp[1024];
5867 const char* symbol = "(unknown)";
5868 if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5869 symbol = tmp;
5870 }
5871
5872 char line[1024];
5873 snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
5874 result += line;
5875 }
5876
5877 return result;
5878
5879#else // !GTEST_HAS_ABSL
5880 static_cast<void>(max_depth);
5881 static_cast<void>(skip_count);
Austin Schuh70cc9552019-01-21 19:46:48 -08005882 return "";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005883#endif // GTEST_HAS_ABSL
Austin Schuh70cc9552019-01-21 19:46:48 -08005884}
5885
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005886void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5887#if GTEST_HAS_ABSL
5888 void* caller_frame = nullptr;
5889 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5890 caller_frame = nullptr;
5891 }
5892
5893 MutexLock lock(&mutex_);
5894 caller_frame_ = caller_frame;
5895#endif // GTEST_HAS_ABSL
5896}
Austin Schuh70cc9552019-01-21 19:46:48 -08005897
5898// A helper class that creates the premature-exit file in its
5899// constructor and deletes the file in its destructor.
5900class ScopedPrematureExitFile {
5901 public:
5902 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005903 : premature_exit_filepath_(premature_exit_filepath ?
5904 premature_exit_filepath : "") {
Austin Schuh70cc9552019-01-21 19:46:48 -08005905 // If a path to the premature-exit file is specified...
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005906 if (!premature_exit_filepath_.empty()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08005907 // create the file with a single "0" character in it. I/O
5908 // errors are ignored as there's nothing better we can do and we
5909 // don't want to fail the test because of this.
5910 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5911 fwrite("0", 1, 1, pfile);
5912 fclose(pfile);
5913 }
5914 }
5915
5916 ~ScopedPrematureExitFile() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005917 if (!premature_exit_filepath_.empty()) {
5918 int retval = remove(premature_exit_filepath_.c_str());
5919 if (retval) {
5920 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5921 << premature_exit_filepath_ << "\" with error "
5922 << retval;
5923 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005924 }
5925 }
5926
5927 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005928 const std::string premature_exit_filepath_;
Austin Schuh70cc9552019-01-21 19:46:48 -08005929
5930 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5931};
5932
5933} // namespace internal
5934
5935// class TestEventListeners
5936
5937TestEventListeners::TestEventListeners()
5938 : repeater_(new internal::TestEventRepeater()),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005939 default_result_printer_(nullptr),
5940 default_xml_generator_(nullptr) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08005941
5942TestEventListeners::~TestEventListeners() { delete repeater_; }
5943
5944// Returns the standard listener responsible for the default console
5945// output. Can be removed from the listeners list to shut down default
5946// console output. Note that removing this object from the listener list
5947// with Release transfers its ownership to the user.
5948void TestEventListeners::Append(TestEventListener* listener) {
5949 repeater_->Append(listener);
5950}
5951
5952// Removes the given event listener from the list and returns it. It then
5953// becomes the caller's responsibility to delete the listener. Returns
5954// NULL if the listener is not found in the list.
5955TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5956 if (listener == default_result_printer_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005957 default_result_printer_ = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08005958 else if (listener == default_xml_generator_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005959 default_xml_generator_ = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08005960 return repeater_->Release(listener);
5961}
5962
5963// Returns repeater that broadcasts the TestEventListener events to all
5964// subscribers.
5965TestEventListener* TestEventListeners::repeater() { return repeater_; }
5966
5967// Sets the default_result_printer attribute to the provided listener.
5968// The listener is also added to the listener list and previous
5969// default_result_printer is removed from it and deleted. The listener can
5970// also be NULL in which case it will not be added to the list. Does
5971// nothing if the previous and the current listener objects are the same.
5972void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5973 if (default_result_printer_ != listener) {
5974 // It is an error to pass this method a listener that is already in the
5975 // list.
5976 delete Release(default_result_printer_);
5977 default_result_printer_ = listener;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005978 if (listener != nullptr) Append(listener);
Austin Schuh70cc9552019-01-21 19:46:48 -08005979 }
5980}
5981
5982// Sets the default_xml_generator attribute to the provided listener. The
5983// listener is also added to the listener list and previous
5984// default_xml_generator is removed from it and deleted. The listener can
5985// also be NULL in which case it will not be added to the list. Does
5986// nothing if the previous and the current listener objects are the same.
5987void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5988 if (default_xml_generator_ != listener) {
5989 // It is an error to pass this method a listener that is already in the
5990 // list.
5991 delete Release(default_xml_generator_);
5992 default_xml_generator_ = listener;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005993 if (listener != nullptr) Append(listener);
Austin Schuh70cc9552019-01-21 19:46:48 -08005994 }
5995}
5996
5997// Controls whether events will be forwarded by the repeater to the
5998// listeners in the list.
5999bool TestEventListeners::EventForwardingEnabled() const {
6000 return repeater_->forwarding_enabled();
6001}
6002
6003void TestEventListeners::SuppressEventForwarding() {
6004 repeater_->set_forwarding_enabled(false);
6005}
6006
6007// class UnitTest
6008
6009// Gets the singleton UnitTest object. The first time this method is
6010// called, a UnitTest object is constructed and returned. Consecutive
6011// calls will return the same object.
6012//
6013// We don't protect this under mutex_ as a user is not supposed to
6014// call this before main() starts, from which point on the return
6015// value will never change.
6016UnitTest* UnitTest::GetInstance() {
Austin Schuh70cc9552019-01-21 19:46:48 -08006017 // CodeGear C++Builder insists on a public destructor for the
6018 // default implementation. Use this implementation to keep good OO
6019 // design with private destructor.
6020
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006021#if defined(__BORLANDC__)
Austin Schuh70cc9552019-01-21 19:46:48 -08006022 static UnitTest* const instance = new UnitTest;
6023 return instance;
6024#else
6025 static UnitTest instance;
6026 return &instance;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006027#endif // defined(__BORLANDC__)
Austin Schuh70cc9552019-01-21 19:46:48 -08006028}
6029
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006030// Gets the number of successful test suites.
6031int UnitTest::successful_test_suite_count() const {
6032 return impl()->successful_test_suite_count();
Austin Schuh70cc9552019-01-21 19:46:48 -08006033}
6034
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006035// Gets the number of failed test suites.
6036int UnitTest::failed_test_suite_count() const {
6037 return impl()->failed_test_suite_count();
Austin Schuh70cc9552019-01-21 19:46:48 -08006038}
6039
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006040// Gets the number of all test suites.
6041int UnitTest::total_test_suite_count() const {
6042 return impl()->total_test_suite_count();
Austin Schuh70cc9552019-01-21 19:46:48 -08006043}
6044
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006045// Gets the number of all test suites that contain at least one test
Austin Schuh70cc9552019-01-21 19:46:48 -08006046// that should run.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006047int UnitTest::test_suite_to_run_count() const {
6048 return impl()->test_suite_to_run_count();
Austin Schuh70cc9552019-01-21 19:46:48 -08006049}
6050
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006051// Legacy API is deprecated but still available
6052#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6053int UnitTest::successful_test_case_count() const {
6054 return impl()->successful_test_suite_count();
6055}
6056int UnitTest::failed_test_case_count() const {
6057 return impl()->failed_test_suite_count();
6058}
6059int UnitTest::total_test_case_count() const {
6060 return impl()->total_test_suite_count();
6061}
6062int UnitTest::test_case_to_run_count() const {
6063 return impl()->test_suite_to_run_count();
6064}
6065#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6066
Austin Schuh70cc9552019-01-21 19:46:48 -08006067// Gets the number of successful tests.
6068int UnitTest::successful_test_count() const {
6069 return impl()->successful_test_count();
6070}
6071
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006072// Gets the number of skipped tests.
6073int UnitTest::skipped_test_count() const {
6074 return impl()->skipped_test_count();
6075}
6076
Austin Schuh70cc9552019-01-21 19:46:48 -08006077// Gets the number of failed tests.
6078int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6079
6080// Gets the number of disabled tests that will be reported in the XML report.
6081int UnitTest::reportable_disabled_test_count() const {
6082 return impl()->reportable_disabled_test_count();
6083}
6084
6085// Gets the number of disabled tests.
6086int UnitTest::disabled_test_count() const {
6087 return impl()->disabled_test_count();
6088}
6089
6090// Gets the number of tests to be printed in the XML report.
6091int UnitTest::reportable_test_count() const {
6092 return impl()->reportable_test_count();
6093}
6094
6095// Gets the number of all tests.
6096int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6097
6098// Gets the number of tests that should run.
6099int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6100
6101// Gets the time of the test program start, in ms from the start of the
6102// UNIX epoch.
6103internal::TimeInMillis UnitTest::start_timestamp() const {
6104 return impl()->start_timestamp();
6105}
6106
6107// Gets the elapsed time, in milliseconds.
6108internal::TimeInMillis UnitTest::elapsed_time() const {
6109 return impl()->elapsed_time();
6110}
6111
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006112// Returns true iff the unit test passed (i.e. all test suites passed).
Austin Schuh70cc9552019-01-21 19:46:48 -08006113bool UnitTest::Passed() const { return impl()->Passed(); }
6114
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006115// Returns true iff the unit test failed (i.e. some test suite failed
Austin Schuh70cc9552019-01-21 19:46:48 -08006116// or something outside of all tests failed).
6117bool UnitTest::Failed() const { return impl()->Failed(); }
6118
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006119// Gets the i-th test suite among all the test suites. i can range from 0 to
6120// total_test_suite_count() - 1. If i is not in that range, returns NULL.
6121const TestSuite* UnitTest::GetTestSuite(int i) const {
6122 return impl()->GetTestSuite(i);
6123}
6124
6125// Legacy API is deprecated but still available
6126#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08006127const TestCase* UnitTest::GetTestCase(int i) const {
6128 return impl()->GetTestCase(i);
6129}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006130#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08006131
6132// Returns the TestResult containing information on test failures and
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006133// properties logged outside of individual test suites.
Austin Schuh70cc9552019-01-21 19:46:48 -08006134const TestResult& UnitTest::ad_hoc_test_result() const {
6135 return *impl()->ad_hoc_test_result();
6136}
6137
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006138// 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.
6140TestSuite* UnitTest::GetMutableTestSuite(int i) {
6141 return impl()->GetMutableSuiteCase(i);
Austin Schuh70cc9552019-01-21 19:46:48 -08006142}
6143
6144// Returns the list of event listeners that can be used to track events
6145// inside Google Test.
6146TestEventListeners& UnitTest::listeners() {
6147 return *impl()->listeners();
6148}
6149
6150// Registers and returns a global test environment. When a test
6151// program is run, all global test environments will be set-up in the
6152// order they were registered. After all tests in the program have
6153// finished, all global test environments will be torn-down in the
6154// *reverse* order they were registered.
6155//
6156// The UnitTest object takes ownership of the given environment.
6157//
6158// We don't protect this under mutex_, as we only support calling it
6159// from the main thread.
6160Environment* UnitTest::AddEnvironment(Environment* env) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006161 if (env == nullptr) {
6162 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08006163 }
6164
6165 impl_->environments().push_back(env);
6166 return env;
6167}
6168
6169// Adds a TestPartResult to the current TestResult object. All Google Test
6170// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6171// this to report their results. The user code should use the
6172// assertion macros instead of calling this directly.
6173void UnitTest::AddTestPartResult(
6174 TestPartResult::Type result_type,
6175 const char* file_name,
6176 int line_number,
6177 const std::string& message,
6178 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6179 Message msg;
6180 msg << message;
6181
6182 internal::MutexLock lock(&mutex_);
6183 if (impl_->gtest_trace_stack().size() > 0) {
6184 msg << "\n" << GTEST_NAME_ << " trace:";
6185
6186 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
6187 i > 0; --i) {
6188 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6189 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6190 << " " << trace.message;
6191 }
6192 }
6193
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006194 if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006195 msg << internal::kStackTraceMarker << os_stack_trace;
6196 }
6197
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006198 const TestPartResult result = TestPartResult(
6199 result_type, file_name, line_number, msg.GetString().c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08006200 impl_->GetTestPartResultReporterForCurrentThread()->
6201 ReportTestPartResult(result);
6202
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006203 if (result_type != TestPartResult::kSuccess &&
6204 result_type != TestPartResult::kSkip) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006205 // gtest_break_on_failure takes precedence over
6206 // gtest_throw_on_failure. This allows a user to set the latter
6207 // in the code (perhaps in order to use Google Test assertions
6208 // with another testing framework) and specify the former on the
6209 // command line for debugging.
6210 if (GTEST_FLAG(break_on_failure)) {
6211#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6212 // Using DebugBreak on Windows allows gtest to still break into a debugger
6213 // when a failure happens and both the --gtest_break_on_failure and
6214 // the --gtest_catch_exceptions flags are specified.
6215 DebugBreak();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006216#elif (!defined(__native_client__)) && \
6217 ((defined(__clang__) || defined(__GNUC__)) && \
6218 (defined(__x86_64__) || defined(__i386__)))
6219 // with clang/gcc we can achieve the same effect on x86 by invoking int3
6220 asm("int3");
Austin Schuh70cc9552019-01-21 19:46:48 -08006221#else
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006222 // Dereference nullptr through a volatile pointer to prevent the compiler
Austin Schuh70cc9552019-01-21 19:46:48 -08006223 // from removing. We use this rather than abort() or __builtin_trap() for
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006224 // portability: some debuggers don't correctly trap abort().
6225 *static_cast<volatile int*>(nullptr) = 1;
Austin Schuh70cc9552019-01-21 19:46:48 -08006226#endif // GTEST_OS_WINDOWS
6227 } else if (GTEST_FLAG(throw_on_failure)) {
6228#if GTEST_HAS_EXCEPTIONS
6229 throw internal::GoogleTestFailureException(result);
6230#else
6231 // We cannot call abort() as it generates a pop-up in debug mode
6232 // that cannot be suppressed in VC 7.1 or below.
6233 exit(1);
6234#endif
6235 }
6236 }
6237}
6238
6239// Adds a TestProperty to the current TestResult object when invoked from
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006240// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
6241// from SetUpTestSuite or TearDownTestSuite, or to the global property set
Austin Schuh70cc9552019-01-21 19:46:48 -08006242// when invoked elsewhere. If the result already contains a property with
6243// the same key, the value will be updated.
6244void UnitTest::RecordProperty(const std::string& key,
6245 const std::string& value) {
6246 impl_->RecordProperty(TestProperty(key, value));
6247}
6248
6249// Runs all tests in this UnitTest object and prints the result.
6250// Returns 0 if successful, or 1 otherwise.
6251//
6252// We don't protect this under mutex_, as we only support calling it
6253// from the main thread.
6254int UnitTest::Run() {
6255 const bool in_death_test_child_process =
6256 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6257
6258 // Google Test implements this protocol for catching that a test
6259 // program exits before returning control to Google Test:
6260 //
6261 // 1. Upon start, Google Test creates a file whose absolute path
6262 // is specified by the environment variable
6263 // TEST_PREMATURE_EXIT_FILE.
6264 // 2. When Google Test has finished its work, it deletes the file.
6265 //
6266 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6267 // running a Google-Test-based test program and check the existence
6268 // of the file at the end of the test execution to see if it has
6269 // exited prematurely.
6270
6271 // If we are in the child process of a death test, don't
6272 // create/delete the premature exit file, as doing so is unnecessary
6273 // and will confuse the parent process. Otherwise, create/delete
6274 // the file upon entering/leaving this function. If the program
6275 // somehow exits before this function has a chance to return, the
6276 // premature-exit file will be left undeleted, causing a test runner
6277 // that understands the premature-exit-file protocol to report the
6278 // test as having failed.
6279 const internal::ScopedPrematureExitFile premature_exit_file(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006280 in_death_test_child_process
6281 ? nullptr
6282 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
Austin Schuh70cc9552019-01-21 19:46:48 -08006283
6284 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
6285 // used for the duration of the program.
6286 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6287
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006288#if GTEST_OS_WINDOWS
Austin Schuh70cc9552019-01-21 19:46:48 -08006289 // Either the user wants Google Test to catch exceptions thrown by the
6290 // tests or this is executing in the context of death test child
6291 // process. In either case the user does not want to see pop-up dialogs
6292 // about crashes - they are expected.
6293 if (impl()->catch_exceptions() || in_death_test_child_process) {
6294# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6295 // SetErrorMode doesn't exist on CE.
6296 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6297 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6298# endif // !GTEST_OS_WINDOWS_MOBILE
6299
6300# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6301 // Death test children can be terminated with _abort(). On Windows,
6302 // _abort() can show a dialog with a warning message. This forces the
6303 // abort message to go to stderr instead.
6304 _set_error_mode(_OUT_TO_STDERR);
6305# endif
6306
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006307# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
Austin Schuh70cc9552019-01-21 19:46:48 -08006308 // In the debug version, Visual Studio pops up a separate dialog
6309 // offering a choice to debug the aborted program. We need to suppress
6310 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6311 // executed. Google Test will notify the user of any unexpected
6312 // failure via stderr.
Austin Schuh70cc9552019-01-21 19:46:48 -08006313 if (!GTEST_FLAG(break_on_failure))
6314 _set_abort_behavior(
6315 0x0, // Clear the following flags:
6316 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
6317# endif
6318 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006319#endif // GTEST_OS_WINDOWS
Austin Schuh70cc9552019-01-21 19:46:48 -08006320
6321 return internal::HandleExceptionsInMethodIfSupported(
6322 impl(),
6323 &internal::UnitTestImpl::RunAllTests,
6324 "auxiliary test code (environments or event listeners)") ? 0 : 1;
6325}
6326
6327// Returns the working directory when the first TEST() or TEST_F() was
6328// executed.
6329const char* UnitTest::original_working_dir() const {
6330 return impl_->original_working_dir_.c_str();
6331}
6332
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006333// Returns the TestSuite object for the test that's currently running,
Austin Schuh70cc9552019-01-21 19:46:48 -08006334// or NULL if no test is running.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006335const TestSuite* UnitTest::current_test_suite() const
6336 GTEST_LOCK_EXCLUDED_(mutex_) {
6337 internal::MutexLock lock(&mutex_);
6338 return impl_->current_test_suite();
6339}
6340
6341// Legacy API is still available but deprecated
6342#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08006343const TestCase* UnitTest::current_test_case() const
6344 GTEST_LOCK_EXCLUDED_(mutex_) {
6345 internal::MutexLock lock(&mutex_);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006346 return impl_->current_test_suite();
Austin Schuh70cc9552019-01-21 19:46:48 -08006347}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006348#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08006349
6350// Returns the TestInfo object for the test that's currently running,
6351// or NULL if no test is running.
6352const TestInfo* UnitTest::current_test_info() const
6353 GTEST_LOCK_EXCLUDED_(mutex_) {
6354 internal::MutexLock lock(&mutex_);
6355 return impl_->current_test_info();
6356}
6357
6358// Returns the random seed used at the start of the current test run.
6359int UnitTest::random_seed() const { return impl_->random_seed(); }
6360
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006361// Returns ParameterizedTestSuiteRegistry object used to keep track of
Austin Schuh70cc9552019-01-21 19:46:48 -08006362// value-parameterized tests and instantiate and register them.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006363internal::ParameterizedTestSuiteRegistry&
6364UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006365 return impl_->parameterized_test_registry();
6366}
Austin Schuh70cc9552019-01-21 19:46:48 -08006367
6368// Creates an empty UnitTest.
6369UnitTest::UnitTest() {
6370 impl_ = new internal::UnitTestImpl(this);
6371}
6372
6373// Destructor of UnitTest.
6374UnitTest::~UnitTest() {
6375 delete impl_;
6376}
6377
6378// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6379// Google Test trace stack.
6380void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6381 GTEST_LOCK_EXCLUDED_(mutex_) {
6382 internal::MutexLock lock(&mutex_);
6383 impl_->gtest_trace_stack().push_back(trace);
6384}
6385
6386// Pops a trace from the per-thread Google Test trace stack.
6387void UnitTest::PopGTestTrace()
6388 GTEST_LOCK_EXCLUDED_(mutex_) {
6389 internal::MutexLock lock(&mutex_);
6390 impl_->gtest_trace_stack().pop_back();
6391}
6392
6393namespace internal {
6394
6395UnitTestImpl::UnitTestImpl(UnitTest* parent)
6396 : parent_(parent),
6397 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006398 default_global_test_part_result_reporter_(this),
Austin Schuh70cc9552019-01-21 19:46:48 -08006399 default_per_thread_test_part_result_reporter_(this),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006400 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
Austin Schuh70cc9552019-01-21 19:46:48 -08006401 &default_global_test_part_result_reporter_),
6402 per_thread_test_part_result_reporter_(
6403 &default_per_thread_test_part_result_reporter_),
Austin Schuh70cc9552019-01-21 19:46:48 -08006404 parameterized_test_registry_(),
6405 parameterized_tests_registered_(false),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006406 last_death_test_suite_(-1),
6407 current_test_suite_(nullptr),
6408 current_test_info_(nullptr),
Austin Schuh70cc9552019-01-21 19:46:48 -08006409 ad_hoc_test_result_(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006410 os_stack_trace_getter_(nullptr),
Austin Schuh70cc9552019-01-21 19:46:48 -08006411 post_flag_parse_init_performed_(false),
6412 random_seed_(0), // Will be overridden by the flag before first use.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006413 random_(0), // Will be reseeded before first use.
Austin Schuh70cc9552019-01-21 19:46:48 -08006414 start_timestamp_(0),
6415 elapsed_time_(0),
6416#if GTEST_HAS_DEATH_TEST
6417 death_test_factory_(new DefaultDeathTestFactory),
6418#endif
6419 // Will be overridden by the flag before first use.
6420 catch_exceptions_(false) {
6421 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
6422}
6423
6424UnitTestImpl::~UnitTestImpl() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006425 // Deletes every TestSuite.
6426 ForEach(test_suites_, internal::Delete<TestSuite>);
Austin Schuh70cc9552019-01-21 19:46:48 -08006427
6428 // Deletes every Environment.
6429 ForEach(environments_, internal::Delete<Environment>);
6430
6431 delete os_stack_trace_getter_;
6432}
6433
6434// Adds a TestProperty to the current TestResult object when invoked in a
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006435// context of a test, to current test suite's ad_hoc_test_result when invoke
6436// from SetUpTestSuite/TearDownTestSuite, or to the global property set
Austin Schuh70cc9552019-01-21 19:46:48 -08006437// otherwise. If the result already contains a property with the same key,
6438// the value will be updated.
6439void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
6440 std::string xml_element;
6441 TestResult* test_result; // TestResult appropriate for property recording.
6442
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006443 if (current_test_info_ != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006444 xml_element = "testcase";
6445 test_result = &(current_test_info_->result_);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006446 } else if (current_test_suite_ != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006447 xml_element = "testsuite";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006448 test_result = &(current_test_suite_->ad_hoc_test_result_);
Austin Schuh70cc9552019-01-21 19:46:48 -08006449 } else {
6450 xml_element = "testsuites";
6451 test_result = &ad_hoc_test_result_;
6452 }
6453 test_result->RecordProperty(xml_element, test_property);
6454}
6455
6456#if GTEST_HAS_DEATH_TEST
6457// Disables event forwarding if the control is currently in a death test
6458// subprocess. Must not be called before InitGoogleTest.
6459void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006460 if (internal_run_death_test_flag_.get() != nullptr)
Austin Schuh70cc9552019-01-21 19:46:48 -08006461 listeners()->SuppressEventForwarding();
6462}
6463#endif // GTEST_HAS_DEATH_TEST
6464
6465// Initializes event listeners performing XML output as specified by
6466// UnitTestOptions. Must not be called before InitGoogleTest.
6467void UnitTestImpl::ConfigureXmlOutput() {
6468 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6469 if (output_format == "xml") {
6470 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
6471 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006472 } else if (output_format == "json") {
6473 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
6474 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
Austin Schuh70cc9552019-01-21 19:46:48 -08006475 } else if (output_format != "") {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006476 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
6477 << output_format << "\" ignored.";
Austin Schuh70cc9552019-01-21 19:46:48 -08006478 }
6479}
6480
6481#if GTEST_CAN_STREAM_RESULTS_
6482// Initializes event listeners for streaming test results in string form.
6483// Must not be called before InitGoogleTest.
6484void UnitTestImpl::ConfigureStreamingOutput() {
6485 const std::string& target = GTEST_FLAG(stream_result_to);
6486 if (!target.empty()) {
6487 const size_t pos = target.find(':');
6488 if (pos != std::string::npos) {
6489 listeners()->Append(new StreamingListener(target.substr(0, pos),
6490 target.substr(pos+1)));
6491 } else {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006492 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
6493 << "\" ignored.";
Austin Schuh70cc9552019-01-21 19:46:48 -08006494 }
6495 }
6496}
6497#endif // GTEST_CAN_STREAM_RESULTS_
6498
6499// Performs initialization dependent upon flag values obtained in
6500// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
6501// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
6502// this function is also called from RunAllTests. Since this function can be
6503// called more than once, it has to be idempotent.
6504void UnitTestImpl::PostFlagParsingInit() {
6505 // Ensures that this function does not execute more than once.
6506 if (!post_flag_parse_init_performed_) {
6507 post_flag_parse_init_performed_ = true;
6508
6509#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6510 // Register to send notifications about key process state changes.
6511 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6512#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6513
6514#if GTEST_HAS_DEATH_TEST
6515 InitDeathTestSubprocessControlInfo();
6516 SuppressTestEventsIfInSubprocess();
6517#endif // GTEST_HAS_DEATH_TEST
6518
6519 // Registers parameterized tests. This makes parameterized tests
6520 // available to the UnitTest reflection API without running
6521 // RUN_ALL_TESTS.
6522 RegisterParameterizedTests();
6523
6524 // Configures listeners for XML output. This makes it possible for users
6525 // to shut down the default XML output before invoking RUN_ALL_TESTS.
6526 ConfigureXmlOutput();
6527
6528#if GTEST_CAN_STREAM_RESULTS_
6529 // Configures listeners for streaming test results to the specified server.
6530 ConfigureStreamingOutput();
6531#endif // GTEST_CAN_STREAM_RESULTS_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006532
6533#if GTEST_HAS_ABSL
6534 if (GTEST_FLAG(install_failure_signal_handler)) {
6535 absl::FailureSignalHandlerOptions options;
6536 absl::InstallFailureSignalHandler(options);
6537 }
6538#endif // GTEST_HAS_ABSL
Austin Schuh70cc9552019-01-21 19:46:48 -08006539 }
6540}
6541
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006542// A predicate that checks the name of a TestSuite against a known
Austin Schuh70cc9552019-01-21 19:46:48 -08006543// value.
6544//
6545// This is used for implementation of the UnitTest class only. We put
6546// it in the anonymous namespace to prevent polluting the outer
6547// namespace.
6548//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006549// TestSuiteNameIs is copyable.
6550class TestSuiteNameIs {
Austin Schuh70cc9552019-01-21 19:46:48 -08006551 public:
6552 // Constructor.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006553 explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08006554
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006555 // Returns true iff the name of test_suite matches name_.
6556 bool operator()(const TestSuite* test_suite) const {
6557 return test_suite != nullptr &&
6558 strcmp(test_suite->name(), name_.c_str()) == 0;
Austin Schuh70cc9552019-01-21 19:46:48 -08006559 }
6560
6561 private:
6562 std::string name_;
6563};
6564
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006565// Finds and returns a TestSuite with the given name. If one doesn't
Austin Schuh70cc9552019-01-21 19:46:48 -08006566// exist, creates one and returns it. It's the CALLER'S
6567// RESPONSIBILITY to ensure that this function is only called WHEN THE
6568// TESTS ARE NOT SHUFFLED.
6569//
6570// Arguments:
6571//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006572// test_suite_name: name of the test suite
6573// type_param: the name of the test suite's type parameter, or NULL if
6574// this is not a typed or a type-parameterized test suite.
6575// set_up_tc: pointer to the function that sets up the test suite
6576// tear_down_tc: pointer to the function that tears down the test suite
6577TestSuite* UnitTestImpl::GetTestSuite(
6578 const char* test_suite_name, const char* type_param,
6579 internal::SetUpTestSuiteFunc set_up_tc,
6580 internal::TearDownTestSuiteFunc tear_down_tc) {
6581 // Can we find a TestSuite with the given name?
6582 const auto test_suite =
6583 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
6584 TestSuiteNameIs(test_suite_name));
Austin Schuh70cc9552019-01-21 19:46:48 -08006585
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006586 if (test_suite != test_suites_.rend()) return *test_suite;
Austin Schuh70cc9552019-01-21 19:46:48 -08006587
6588 // No. Let's create one.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006589 auto* const new_test_suite =
6590 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
Austin Schuh70cc9552019-01-21 19:46:48 -08006591
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006592 // Is this a death test suite?
6593 if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
6594 kDeathTestSuiteFilter)) {
6595 // Yes. Inserts the test suite after the last death test suite
6596 // defined so far. This only works when the test suites haven't
Austin Schuh70cc9552019-01-21 19:46:48 -08006597 // been shuffled. Otherwise we may end up running a death test
6598 // after a non-death test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006599 ++last_death_test_suite_;
6600 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
6601 new_test_suite);
Austin Schuh70cc9552019-01-21 19:46:48 -08006602 } else {
6603 // No. Appends to the end of the list.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006604 test_suites_.push_back(new_test_suite);
Austin Schuh70cc9552019-01-21 19:46:48 -08006605 }
6606
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006607 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
6608 return new_test_suite;
Austin Schuh70cc9552019-01-21 19:46:48 -08006609}
6610
6611// Helpers for setting up / tearing down the given environment. They
6612// are for use in the ForEach() function.
6613static void SetUpEnvironment(Environment* env) { env->SetUp(); }
6614static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6615
6616// Runs all tests in this UnitTest object, prints the result, and
6617// returns true if all tests are successful. If any exception is
6618// thrown during a test, the test is considered to be failed, but the
6619// rest of the tests will still be run.
6620//
6621// When parameterized tests are enabled, it expands and registers
6622// parameterized tests first in RegisterParameterizedTests().
6623// All other functions called from RunAllTests() may safely assume that
6624// parameterized tests are ready to be counted and run.
6625bool UnitTestImpl::RunAllTests() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006626 // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
6627 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
Austin Schuh70cc9552019-01-21 19:46:48 -08006628
6629 // Do not run any test if the --help flag was specified.
6630 if (g_help_flag)
6631 return true;
6632
6633 // Repeats the call to the post-flag parsing initialization in case the
6634 // user didn't call InitGoogleTest.
6635 PostFlagParsingInit();
6636
6637 // Even if sharding is not on, test runners may want to use the
6638 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6639 // protocol.
6640 internal::WriteToShardStatusFileIfNeeded();
6641
6642 // True iff we are in a subprocess for running a thread-safe-style
6643 // death test.
6644 bool in_subprocess_for_death_test = false;
6645
6646#if GTEST_HAS_DEATH_TEST
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006647 in_subprocess_for_death_test =
6648 (internal_run_death_test_flag_.get() != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08006649# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6650 if (in_subprocess_for_death_test) {
6651 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6652 }
6653# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6654#endif // GTEST_HAS_DEATH_TEST
6655
6656 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6657 in_subprocess_for_death_test);
6658
6659 // Compares the full test names with the filter to decide which
6660 // tests to run.
6661 const bool has_tests_to_run = FilterTests(should_shard
6662 ? HONOR_SHARDING_PROTOCOL
6663 : IGNORE_SHARDING_PROTOCOL) > 0;
6664
6665 // Lists the tests and exits if the --gtest_list_tests flag was specified.
6666 if (GTEST_FLAG(list_tests)) {
6667 // This must be called *after* FilterTests() has been called.
6668 ListTestsMatchingFilter();
6669 return true;
6670 }
6671
6672 random_seed_ = GTEST_FLAG(shuffle) ?
6673 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6674
6675 // True iff at least one test has failed.
6676 bool failed = false;
6677
6678 TestEventListener* repeater = listeners()->repeater();
6679
6680 start_timestamp_ = GetTimeInMillis();
6681 repeater->OnTestProgramStart(*parent_);
6682
6683 // How many times to repeat the tests? We don't want to repeat them
6684 // when we are inside the subprocess of a death test.
6685 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6686 // Repeats forever if the repeat count is negative.
6687 const bool forever = repeat < 0;
6688 for (int i = 0; forever || i != repeat; i++) {
6689 // We want to preserve failures generated by ad-hoc test
6690 // assertions executed before RUN_ALL_TESTS().
6691 ClearNonAdHocTestResult();
6692
6693 const TimeInMillis start = GetTimeInMillis();
6694
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006695 // Shuffles test suites and tests if requested.
Austin Schuh70cc9552019-01-21 19:46:48 -08006696 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6697 random()->Reseed(random_seed_);
6698 // This should be done before calling OnTestIterationStart(),
6699 // such that a test event listener can see the actual test order
6700 // in the event.
6701 ShuffleTests();
6702 }
6703
6704 // Tells the unit test event listeners that the tests are about to start.
6705 repeater->OnTestIterationStart(*parent_, i);
6706
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006707 // Runs each test suite if there is at least one test to run.
Austin Schuh70cc9552019-01-21 19:46:48 -08006708 if (has_tests_to_run) {
6709 // Sets up all environments beforehand.
6710 repeater->OnEnvironmentsSetUpStart(*parent_);
6711 ForEach(environments_, SetUpEnvironment);
6712 repeater->OnEnvironmentsSetUpEnd(*parent_);
6713
6714 // Runs the tests only if there was no fatal failure during global
6715 // set-up.
6716 if (!Test::HasFatalFailure()) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006717 for (int test_index = 0; test_index < total_test_suite_count();
Austin Schuh70cc9552019-01-21 19:46:48 -08006718 test_index++) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006719 GetMutableSuiteCase(test_index)->Run();
Austin Schuh70cc9552019-01-21 19:46:48 -08006720 }
6721 }
6722
6723 // Tears down all environments in reverse order afterwards.
6724 repeater->OnEnvironmentsTearDownStart(*parent_);
6725 std::for_each(environments_.rbegin(), environments_.rend(),
6726 TearDownEnvironment);
6727 repeater->OnEnvironmentsTearDownEnd(*parent_);
6728 }
6729
6730 elapsed_time_ = GetTimeInMillis() - start;
6731
6732 // Tells the unit test event listener that the tests have just finished.
6733 repeater->OnTestIterationEnd(*parent_, i);
6734
6735 // Gets the result and clears it.
6736 if (!Passed()) {
6737 failed = true;
6738 }
6739
6740 // Restores the original test order after the iteration. This
6741 // allows the user to quickly repro a failure that happens in the
6742 // N-th iteration without repeating the first (N - 1) iterations.
6743 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6744 // case the user somehow changes the value of the flag somewhere
6745 // (it's always safe to unshuffle the tests).
6746 UnshuffleTests();
6747
6748 if (GTEST_FLAG(shuffle)) {
6749 // Picks a new random seed for each iteration.
6750 random_seed_ = GetNextRandomSeed(random_seed_);
6751 }
6752 }
6753
6754 repeater->OnTestProgramEnd(*parent_);
6755
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006756 if (!gtest_is_initialized_before_run_all_tests) {
6757 ColoredPrintf(
6758 COLOR_RED,
6759 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6760 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6761 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6762 " will start to enforce the valid usage. "
6763 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
6764#if GTEST_FOR_GOOGLE_
6765 ColoredPrintf(COLOR_RED,
6766 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
6767#endif // GTEST_FOR_GOOGLE_
6768 }
6769
Austin Schuh70cc9552019-01-21 19:46:48 -08006770 return !failed;
6771}
6772
6773// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6774// if the variable is present. If a file already exists at this location, this
6775// function will write over it. If the variable is present, but the file cannot
6776// be created, prints an error and exits.
6777void WriteToShardStatusFileIfNeeded() {
6778 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006779 if (test_shard_file != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006780 FILE* const file = posix::FOpen(test_shard_file, "w");
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006781 if (file == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006782 ColoredPrintf(COLOR_RED,
6783 "Could not write to the test shard status file \"%s\" "
6784 "specified by the %s environment variable.\n",
6785 test_shard_file, kTestShardStatusFile);
6786 fflush(stdout);
6787 exit(EXIT_FAILURE);
6788 }
6789 fclose(file);
6790 }
6791}
6792
6793// Checks whether sharding is enabled by examining the relevant
6794// environment variable values. If the variables are present,
6795// but inconsistent (i.e., shard_index >= total_shards), prints
6796// an error and exits. If in_subprocess_for_death_test, sharding is
6797// disabled because it must only be applied to the original test
6798// process. Otherwise, we could filter out death tests we intended to execute.
6799bool ShouldShard(const char* total_shards_env,
6800 const char* shard_index_env,
6801 bool in_subprocess_for_death_test) {
6802 if (in_subprocess_for_death_test) {
6803 return false;
6804 }
6805
6806 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6807 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6808
6809 if (total_shards == -1 && shard_index == -1) {
6810 return false;
6811 } else if (total_shards == -1 && shard_index != -1) {
6812 const Message msg = Message()
6813 << "Invalid environment variables: you have "
6814 << kTestShardIndex << " = " << shard_index
6815 << ", but have left " << kTestTotalShards << " unset.\n";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006816 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08006817 fflush(stdout);
6818 exit(EXIT_FAILURE);
6819 } else if (total_shards != -1 && shard_index == -1) {
6820 const Message msg = Message()
6821 << "Invalid environment variables: you have "
6822 << kTestTotalShards << " = " << total_shards
6823 << ", but have left " << kTestShardIndex << " unset.\n";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006824 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08006825 fflush(stdout);
6826 exit(EXIT_FAILURE);
6827 } else if (shard_index < 0 || shard_index >= total_shards) {
6828 const Message msg = Message()
6829 << "Invalid environment variables: we require 0 <= "
6830 << kTestShardIndex << " < " << kTestTotalShards
6831 << ", but you have " << kTestShardIndex << "=" << shard_index
6832 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006833 ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
Austin Schuh70cc9552019-01-21 19:46:48 -08006834 fflush(stdout);
6835 exit(EXIT_FAILURE);
6836 }
6837
6838 return total_shards > 1;
6839}
6840
6841// Parses the environment variable var as an Int32. If it is unset,
6842// returns default_val. If it is not an Int32, prints an error
6843// and aborts.
6844Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6845 const char* str_val = posix::GetEnv(var);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006846 if (str_val == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006847 return default_val;
6848 }
6849
6850 Int32 result;
6851 if (!ParseInt32(Message() << "The value of environment variable " << var,
6852 str_val, &result)) {
6853 exit(EXIT_FAILURE);
6854 }
6855 return result;
6856}
6857
6858// Given the total number of shards, the shard index, and the test id,
6859// returns true iff the test should be run on this shard. The test id is
6860// some arbitrary but unique non-negative integer assigned to each test
6861// method. Assumes that 0 <= shard_index < total_shards.
6862bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6863 return (test_id % total_shards) == shard_index;
6864}
6865
6866// Compares the name of each test with the user-specified filter to
6867// decide whether the test should be run, then records the result in
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006868// each TestSuite and TestInfo object.
Austin Schuh70cc9552019-01-21 19:46:48 -08006869// If shard_tests == true, further filters tests based on sharding
6870// variables in the environment - see
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006871// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6872// . Returns the number of tests that should run.
Austin Schuh70cc9552019-01-21 19:46:48 -08006873int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6874 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6875 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6876 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6877 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6878
6879 // num_runnable_tests are the number of tests that will
6880 // run across all shards (i.e., match filter and are not disabled).
6881 // num_selected_tests are the number of tests to be run on
6882 // this shard.
6883 int num_runnable_tests = 0;
6884 int num_selected_tests = 0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006885 for (auto* test_suite : test_suites_) {
6886 const std::string& test_suite_name = test_suite->name();
6887 test_suite->set_should_run(false);
Austin Schuh70cc9552019-01-21 19:46:48 -08006888
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006889 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6890 TestInfo* const test_info = test_suite->test_info_list()[j];
Austin Schuh70cc9552019-01-21 19:46:48 -08006891 const std::string test_name(test_info->name());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006892 // A test is disabled if test suite name or test name matches
Austin Schuh70cc9552019-01-21 19:46:48 -08006893 // kDisableTestFilter.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006894 const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
6895 test_suite_name, kDisableTestFilter) ||
6896 internal::UnitTestOptions::MatchesFilter(
6897 test_name, kDisableTestFilter);
Austin Schuh70cc9552019-01-21 19:46:48 -08006898 test_info->is_disabled_ = is_disabled;
6899
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006900 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
6901 test_suite_name, test_name);
Austin Schuh70cc9552019-01-21 19:46:48 -08006902 test_info->matches_filter_ = matches_filter;
6903
6904 const bool is_runnable =
6905 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6906 matches_filter;
6907
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006908 const bool is_in_another_shard =
6909 shard_tests != IGNORE_SHARDING_PROTOCOL &&
6910 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6911 test_info->is_in_another_shard_ = is_in_another_shard;
6912 const bool is_selected = is_runnable && !is_in_another_shard;
Austin Schuh70cc9552019-01-21 19:46:48 -08006913
6914 num_runnable_tests += is_runnable;
6915 num_selected_tests += is_selected;
6916
6917 test_info->should_run_ = is_selected;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006918 test_suite->set_should_run(test_suite->should_run() || is_selected);
Austin Schuh70cc9552019-01-21 19:46:48 -08006919 }
6920 }
6921 return num_selected_tests;
6922}
6923
6924// Prints the given C-string on a single line by replacing all '\n'
6925// characters with string "\\n". If the output takes more than
6926// max_length characters, only prints the first max_length characters
6927// and "...".
6928static void PrintOnOneLine(const char* str, int max_length) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006929 if (str != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006930 for (int i = 0; *str != '\0'; ++str) {
6931 if (i >= max_length) {
6932 printf("...");
6933 break;
6934 }
6935 if (*str == '\n') {
6936 printf("\\n");
6937 i += 2;
6938 } else {
6939 printf("%c", *str);
6940 ++i;
6941 }
6942 }
6943 }
6944}
6945
6946// Prints the names of the tests matching the user-specified filter flag.
6947void UnitTestImpl::ListTestsMatchingFilter() {
6948 // Print at most this many characters for each type/value parameter.
6949 const int kMaxParamLength = 250;
6950
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006951 for (auto* test_suite : test_suites_) {
6952 bool printed_test_suite_name = false;
Austin Schuh70cc9552019-01-21 19:46:48 -08006953
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006954 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6955 const TestInfo* const test_info = test_suite->test_info_list()[j];
Austin Schuh70cc9552019-01-21 19:46:48 -08006956 if (test_info->matches_filter_) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006957 if (!printed_test_suite_name) {
6958 printed_test_suite_name = true;
6959 printf("%s.", test_suite->name());
6960 if (test_suite->type_param() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006961 printf(" # %s = ", kTypeParamLabel);
6962 // We print the type parameter on a single line to make
6963 // the output easy to parse by a program.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006964 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
Austin Schuh70cc9552019-01-21 19:46:48 -08006965 }
6966 printf("\n");
6967 }
6968 printf(" %s", test_info->name());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006969 if (test_info->value_param() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006970 printf(" # %s = ", kValueParamLabel);
6971 // We print the value parameter on a single line to make the
6972 // output easy to parse by a program.
6973 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6974 }
6975 printf("\n");
6976 }
6977 }
6978 }
6979 fflush(stdout);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006980 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6981 if (output_format == "xml" || output_format == "json") {
6982 FILE* fileout = OpenFileForWriting(
6983 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6984 std::stringstream stream;
6985 if (output_format == "xml") {
6986 XmlUnitTestResultPrinter(
6987 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6988 .PrintXmlTestsList(&stream, test_suites_);
6989 } else if (output_format == "json") {
6990 JsonUnitTestResultPrinter(
6991 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6992 .PrintJsonTestList(&stream, test_suites_);
6993 }
6994 fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6995 fclose(fileout);
6996 }
Austin Schuh70cc9552019-01-21 19:46:48 -08006997}
6998
6999// Sets the OS stack trace getter.
7000//
7001// Does nothing if the input and the current OS stack trace getter are
7002// the same; otherwise, deletes the old getter and makes the input the
7003// current getter.
7004void UnitTestImpl::set_os_stack_trace_getter(
7005 OsStackTraceGetterInterface* getter) {
7006 if (os_stack_trace_getter_ != getter) {
7007 delete os_stack_trace_getter_;
7008 os_stack_trace_getter_ = getter;
7009 }
7010}
7011
7012// Returns the current OS stack trace getter if it is not NULL;
7013// otherwise, creates an OsStackTraceGetter, makes it the current
7014// getter, and returns it.
7015OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007016 if (os_stack_trace_getter_ == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007017#ifdef GTEST_OS_STACK_TRACE_GETTER_
7018 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
7019#else
7020 os_stack_trace_getter_ = new OsStackTraceGetter;
7021#endif // GTEST_OS_STACK_TRACE_GETTER_
7022 }
7023
7024 return os_stack_trace_getter_;
7025}
7026
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007027// Returns the most specific TestResult currently running.
Austin Schuh70cc9552019-01-21 19:46:48 -08007028TestResult* UnitTestImpl::current_test_result() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007029 if (current_test_info_ != nullptr) {
7030 return &current_test_info_->result_;
7031 }
7032 if (current_test_suite_ != nullptr) {
7033 return &current_test_suite_->ad_hoc_test_result_;
7034 }
7035 return &ad_hoc_test_result_;
Austin Schuh70cc9552019-01-21 19:46:48 -08007036}
7037
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007038// Shuffles all test suites, and the tests within each test suite,
Austin Schuh70cc9552019-01-21 19:46:48 -08007039// making sure that death tests are still run first.
7040void UnitTestImpl::ShuffleTests() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007041 // Shuffles the death test suites.
7042 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
Austin Schuh70cc9552019-01-21 19:46:48 -08007043
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007044 // Shuffles the non-death test suites.
7045 ShuffleRange(random(), last_death_test_suite_ + 1,
7046 static_cast<int>(test_suites_.size()), &test_suite_indices_);
Austin Schuh70cc9552019-01-21 19:46:48 -08007047
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007048 // Shuffles the tests inside each test suite.
7049 for (auto& test_suite : test_suites_) {
7050 test_suite->ShuffleTests(random());
Austin Schuh70cc9552019-01-21 19:46:48 -08007051 }
7052}
7053
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007054// Restores the test suites and tests to their order before the first shuffle.
Austin Schuh70cc9552019-01-21 19:46:48 -08007055void UnitTestImpl::UnshuffleTests() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007056 for (size_t i = 0; i < test_suites_.size(); i++) {
7057 // Unshuffles the tests in each test suite.
7058 test_suites_[i]->UnshuffleTests();
7059 // Resets the index of each test suite.
7060 test_suite_indices_[i] = static_cast<int>(i);
Austin Schuh70cc9552019-01-21 19:46:48 -08007061 }
7062}
7063
7064// Returns the current OS stack trace as an std::string.
7065//
7066// The maximum number of stack frames to be included is specified by
7067// the gtest_stack_trace_depth flag. The skip_count parameter
7068// specifies the number of top frames to be skipped, which doesn't
7069// count against the number of frames to be included.
7070//
7071// For example, if Foo() calls Bar(), which in turn calls
7072// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7073// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
7074std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7075 int skip_count) {
7076 // We pass skip_count + 1 to skip this wrapper function in addition
7077 // to what the user really wants to skip.
7078 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7079}
7080
7081// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7082// suppress unreachable code warnings.
7083namespace {
7084class ClassUniqueToAlwaysTrue {};
7085}
7086
7087bool IsTrue(bool condition) { return condition; }
7088
7089bool AlwaysTrue() {
7090#if GTEST_HAS_EXCEPTIONS
7091 // This condition is always false so AlwaysTrue() never actually throws,
7092 // but it makes the compiler think that it may throw.
7093 if (IsTrue(false))
7094 throw ClassUniqueToAlwaysTrue();
7095#endif // GTEST_HAS_EXCEPTIONS
7096 return true;
7097}
7098
7099// If *pstr starts with the given prefix, modifies *pstr to be right
7100// past the prefix and returns true; otherwise leaves *pstr unchanged
7101// and returns false. None of pstr, *pstr, and prefix can be NULL.
7102bool SkipPrefix(const char* prefix, const char** pstr) {
7103 const size_t prefix_len = strlen(prefix);
7104 if (strncmp(*pstr, prefix, prefix_len) == 0) {
7105 *pstr += prefix_len;
7106 return true;
7107 }
7108 return false;
7109}
7110
7111// Parses a string as a command line flag. The string should have
7112// the format "--flag=value". When def_optional is true, the "=value"
7113// part can be omitted.
7114//
7115// Returns the value of the flag, or NULL if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007116static const char* ParseFlagValue(const char* str, const char* flag,
7117 bool def_optional) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007118 // str and flag must not be NULL.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007119 if (str == nullptr || flag == nullptr) return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08007120
7121 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7122 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7123 const size_t flag_len = flag_str.length();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007124 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08007125
7126 // Skips the flag name.
7127 const char* flag_end = str + flag_len;
7128
7129 // When def_optional is true, it's OK to not have a "=value" part.
7130 if (def_optional && (flag_end[0] == '\0')) {
7131 return flag_end;
7132 }
7133
7134 // If def_optional is true and there are more characters after the
7135 // flag name, or if def_optional is false, there must be a '=' after
7136 // the flag name.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007137 if (flag_end[0] != '=') return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08007138
7139 // Returns the string after "=".
7140 return flag_end + 1;
7141}
7142
7143// Parses a string for a bool flag, in the form of either
7144// "--flag=value" or "--flag".
7145//
7146// In the former case, the value is taken as true as long as it does
7147// not start with '0', 'f', or 'F'.
7148//
7149// In the latter case, the value is taken as true.
7150//
7151// On success, stores the value of the flag in *value, and returns
7152// true. On failure, returns false without changing *value.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007153static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007154 // Gets the value of the flag as a string.
7155 const char* const value_str = ParseFlagValue(str, flag, true);
7156
7157 // Aborts if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007158 if (value_str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08007159
7160 // Converts the string value to a bool.
7161 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7162 return true;
7163}
7164
7165// Parses a string for an Int32 flag, in the form of
7166// "--flag=value".
7167//
7168// On success, stores the value of the flag in *value, and returns
7169// true. On failure, returns false without changing *value.
7170bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
7171 // Gets the value of the flag as a string.
7172 const char* const value_str = ParseFlagValue(str, flag, false);
7173
7174 // Aborts if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007175 if (value_str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08007176
7177 // Sets *value to the value of the flag.
7178 return ParseInt32(Message() << "The value of flag --" << flag,
7179 value_str, value);
7180}
7181
7182// Parses a string for a string flag, in the form of
7183// "--flag=value".
7184//
7185// On success, stores the value of the flag in *value, and returns
7186// true. On failure, returns false without changing *value.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007187template <typename String>
7188static bool ParseStringFlag(const char* str, const char* flag, String* value) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007189 // Gets the value of the flag as a string.
7190 const char* const value_str = ParseFlagValue(str, flag, false);
7191
7192 // Aborts if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007193 if (value_str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -08007194
7195 // Sets *value to the value of the flag.
7196 *value = value_str;
7197 return true;
7198}
7199
7200// Determines whether a string has a prefix that Google Test uses for its
7201// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7202// If Google Test detects that a command line flag has its prefix but is not
7203// recognized, it will print its help message. Flags starting with
7204// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7205// internal flags and do not trigger the help message.
7206static bool HasGoogleTestFlagPrefix(const char* str) {
7207 return (SkipPrefix("--", &str) ||
7208 SkipPrefix("-", &str) ||
7209 SkipPrefix("/", &str)) &&
7210 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7211 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7212 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7213}
7214
7215// Prints a string containing code-encoded text. The following escape
7216// sequences can be used in the string to control the text color:
7217//
7218// @@ prints a single '@' character.
7219// @R changes the color to red.
7220// @G changes the color to green.
7221// @Y changes the color to yellow.
7222// @D changes to the default terminal text color.
7223//
Austin Schuh70cc9552019-01-21 19:46:48 -08007224static void PrintColorEncoded(const char* str) {
7225 GTestColor color = COLOR_DEFAULT; // The current color.
7226
7227 // Conceptually, we split the string into segments divided by escape
7228 // sequences. Then we print one segment at a time. At the end of
7229 // each iteration, the str pointer advances to the beginning of the
7230 // next segment.
7231 for (;;) {
7232 const char* p = strchr(str, '@');
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007233 if (p == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007234 ColoredPrintf(color, "%s", str);
7235 return;
7236 }
7237
7238 ColoredPrintf(color, "%s", std::string(str, p).c_str());
7239
7240 const char ch = p[1];
7241 str = p + 2;
7242 if (ch == '@') {
7243 ColoredPrintf(color, "@");
7244 } else if (ch == 'D') {
7245 color = COLOR_DEFAULT;
7246 } else if (ch == 'R') {
7247 color = COLOR_RED;
7248 } else if (ch == 'G') {
7249 color = COLOR_GREEN;
7250 } else if (ch == 'Y') {
7251 color = COLOR_YELLOW;
7252 } else {
7253 --str;
7254 }
7255 }
7256}
7257
7258static const char kColorEncodedHelpMessage[] =
7259"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
7260"following command line flags to control its behavior:\n"
7261"\n"
7262"Test Selection:\n"
7263" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
7264" List the names of all tests instead of running them. The name of\n"
7265" TEST(Foo, Bar) is \"Foo.Bar\".\n"
7266" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
7267 "[@G-@YNEGATIVE_PATTERNS]@D\n"
7268" Run only the tests whose name matches one of the positive patterns but\n"
7269" none of the negative patterns. '?' matches any single character; '*'\n"
7270" matches any substring; ':' separates two patterns.\n"
7271" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
7272" Run all disabled tests too.\n"
7273"\n"
7274"Test Execution:\n"
7275" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
7276" Run the tests repeatedly; use a negative count to repeat forever.\n"
7277" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
7278" Randomize tests' orders on every iteration.\n"
7279" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
7280" Random number seed to use for shuffling test orders (between 1 and\n"
7281" 99999, or 0 to use a seed based on the current time).\n"
7282"\n"
7283"Test Output:\n"
7284" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7285" Enable/disable colored output. The default is @Gauto@D.\n"
7286" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
7287" Don't print the elapsed time of each test.\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007288" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
Austin Schuh70cc9552019-01-21 19:46:48 -08007289 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007290" Generate a JSON or XML report in the given directory or with the given\n"
7291" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
7292# if GTEST_CAN_STREAM_RESULTS_
Austin Schuh70cc9552019-01-21 19:46:48 -08007293" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
7294" Stream test results to the given server.\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007295# endif // GTEST_CAN_STREAM_RESULTS_
Austin Schuh70cc9552019-01-21 19:46:48 -08007296"\n"
7297"Assertion Behavior:\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007298# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
Austin Schuh70cc9552019-01-21 19:46:48 -08007299" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7300" Set the default death test style.\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007301# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
Austin Schuh70cc9552019-01-21 19:46:48 -08007302" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
7303" Turn assertion failures into debugger break-points.\n"
7304" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007305" Turn assertion failures into C++ exceptions for use by an external\n"
7306" test framework.\n"
Austin Schuh70cc9552019-01-21 19:46:48 -08007307" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
7308" Do not report exceptions as test failures. Instead, allow them\n"
7309" to crash the program or throw a pop-up (on Windows).\n"
7310"\n"
7311"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
7312 "the corresponding\n"
7313"environment variable of a flag (all letters in upper-case). For example, to\n"
7314"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
7315 "color=no@D or set\n"
7316"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
7317"\n"
7318"For more information, please read the " GTEST_NAME_ " documentation at\n"
7319"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
7320"(not one in your own code or tests), please report it to\n"
7321"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7322
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007323static bool ParseGoogleTestFlag(const char* const arg) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007324 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7325 &GTEST_FLAG(also_run_disabled_tests)) ||
7326 ParseBoolFlag(arg, kBreakOnFailureFlag,
7327 &GTEST_FLAG(break_on_failure)) ||
7328 ParseBoolFlag(arg, kCatchExceptionsFlag,
7329 &GTEST_FLAG(catch_exceptions)) ||
7330 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7331 ParseStringFlag(arg, kDeathTestStyleFlag,
7332 &GTEST_FLAG(death_test_style)) ||
7333 ParseBoolFlag(arg, kDeathTestUseFork,
7334 &GTEST_FLAG(death_test_use_fork)) ||
7335 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
7336 ParseStringFlag(arg, kInternalRunDeathTestFlag,
7337 &GTEST_FLAG(internal_run_death_test)) ||
7338 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
7339 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
7340 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007341 ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
Austin Schuh70cc9552019-01-21 19:46:48 -08007342 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
7343 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
7344 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
7345 ParseInt32Flag(arg, kStackTraceDepthFlag,
7346 &GTEST_FLAG(stack_trace_depth)) ||
7347 ParseStringFlag(arg, kStreamResultToFlag,
7348 &GTEST_FLAG(stream_result_to)) ||
7349 ParseBoolFlag(arg, kThrowOnFailureFlag,
7350 &GTEST_FLAG(throw_on_failure));
7351}
7352
7353#if GTEST_USE_OWN_FLAGFILE_FLAG_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007354static void LoadFlagsFromFile(const std::string& path) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007355 FILE* flagfile = posix::FOpen(path.c_str(), "r");
7356 if (!flagfile) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007357 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
7358 << "\"";
Austin Schuh70cc9552019-01-21 19:46:48 -08007359 }
7360 std::string contents(ReadEntireFile(flagfile));
7361 posix::FClose(flagfile);
7362 std::vector<std::string> lines;
7363 SplitString(contents, '\n', &lines);
7364 for (size_t i = 0; i < lines.size(); ++i) {
7365 if (lines[i].empty())
7366 continue;
7367 if (!ParseGoogleTestFlag(lines[i].c_str()))
7368 g_help_flag = true;
7369 }
7370}
7371#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7372
7373// Parses the command line for Google Test flags, without initializing
7374// other parts of Google Test. The type parameter CharType can be
7375// instantiated to either char or wchar_t.
7376template <typename CharType>
7377void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
7378 for (int i = 1; i < *argc; i++) {
7379 const std::string arg_string = StreamableToString(argv[i]);
7380 const char* const arg = arg_string.c_str();
7381
7382 using internal::ParseBoolFlag;
7383 using internal::ParseInt32Flag;
7384 using internal::ParseStringFlag;
7385
7386 bool remove_flag = false;
7387 if (ParseGoogleTestFlag(arg)) {
7388 remove_flag = true;
7389#if GTEST_USE_OWN_FLAGFILE_FLAG_
7390 } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
7391 LoadFlagsFromFile(GTEST_FLAG(flagfile));
7392 remove_flag = true;
7393#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7394 } else if (arg_string == "--help" || arg_string == "-h" ||
7395 arg_string == "-?" || arg_string == "/?" ||
7396 HasGoogleTestFlagPrefix(arg)) {
7397 // Both help flag and unrecognized Google Test flags (excluding
7398 // internal ones) trigger help display.
7399 g_help_flag = true;
7400 }
7401
7402 if (remove_flag) {
7403 // Shift the remainder of the argv list left by one. Note
7404 // that argv has (*argc + 1) elements, the last one always being
7405 // NULL. The following loop moves the trailing NULL element as
7406 // well.
7407 for (int j = i; j != *argc; j++) {
7408 argv[j] = argv[j + 1];
7409 }
7410
7411 // Decrements the argument count.
7412 (*argc)--;
7413
7414 // We also need to decrement the iterator as we just removed
7415 // an element.
7416 i--;
7417 }
7418 }
7419
7420 if (g_help_flag) {
7421 // We print the help here instead of in RUN_ALL_TESTS(), as the
7422 // latter may not be called at all if the user is using Google
7423 // Test with another testing framework.
7424 PrintColorEncoded(kColorEncodedHelpMessage);
7425 }
7426}
7427
7428// Parses the command line for Google Test flags, without initializing
7429// other parts of Google Test.
7430void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
7431 ParseGoogleTestFlagsOnlyImpl(argc, argv);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007432
7433 // Fix the value of *_NSGetArgc() on macOS, but iff
7434 // *_NSGetArgv() == argv
7435 // Only applicable to char** version of argv
7436#if GTEST_OS_MAC
7437#ifndef GTEST_OS_IOS
7438 if (*_NSGetArgv() == argv) {
7439 *_NSGetArgc() = *argc;
7440 }
7441#endif
7442#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08007443}
7444void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
7445 ParseGoogleTestFlagsOnlyImpl(argc, argv);
7446}
7447
7448// The internal implementation of InitGoogleTest().
7449//
7450// The type parameter CharType can be instantiated to either char or
7451// wchar_t.
7452template <typename CharType>
7453void InitGoogleTestImpl(int* argc, CharType** argv) {
7454 // We don't want to run the initialization code twice.
7455 if (GTestIsInitialized()) return;
7456
7457 if (*argc <= 0) return;
7458
7459 g_argvs.clear();
7460 for (int i = 0; i != *argc; i++) {
7461 g_argvs.push_back(StreamableToString(argv[i]));
7462 }
7463
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007464#if GTEST_HAS_ABSL
7465 absl::InitializeSymbolizer(g_argvs[0].c_str());
7466#endif // GTEST_HAS_ABSL
7467
Austin Schuh70cc9552019-01-21 19:46:48 -08007468 ParseGoogleTestFlagsOnly(argc, argv);
7469 GetUnitTestImpl()->PostFlagParsingInit();
7470}
7471
7472} // namespace internal
7473
7474// Initializes Google Test. This must be called before calling
7475// RUN_ALL_TESTS(). In particular, it parses a command line for the
7476// flags that Google Test recognizes. Whenever a Google Test flag is
7477// seen, it is removed from argv, and *argc is decremented.
7478//
7479// No value is returned. Instead, the Google Test flag variables are
7480// updated.
7481//
7482// Calling the function for the second time has no user-visible effect.
7483void InitGoogleTest(int* argc, char** argv) {
7484#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7485 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7486#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7487 internal::InitGoogleTestImpl(argc, argv);
7488#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7489}
7490
7491// This overloaded version can be used in Windows programs compiled in
7492// UNICODE mode.
7493void InitGoogleTest(int* argc, wchar_t** argv) {
7494#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7495 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7496#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7497 internal::InitGoogleTestImpl(argc, argv);
7498#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7499}
7500
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007501// This overloaded version can be used on Arduino/embedded platforms where
7502// there is no argc/argv.
7503void InitGoogleTest() {
7504 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
7505 int argc = 1;
7506 const auto arg0 = "dummy";
7507 char* argv0 = const_cast<char*>(arg0);
7508 char** argv = &argv0;
7509
7510#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7511 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
7512#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7513 internal::InitGoogleTestImpl(&argc, argv);
7514#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7515}
7516
7517std::string TempDir() {
7518#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7519 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7520#endif
7521
7522#if GTEST_OS_WINDOWS_MOBILE
7523 return "\\temp\\";
7524#elif GTEST_OS_WINDOWS
7525 const char* temp_dir = internal::posix::GetEnv("TEMP");
7526 if (temp_dir == nullptr || temp_dir[0] == '\0')
7527 return "\\temp\\";
7528 else if (temp_dir[strlen(temp_dir) - 1] == '\\')
7529 return temp_dir;
7530 else
7531 return std::string(temp_dir) + "\\";
7532#elif GTEST_OS_LINUX_ANDROID
7533 return "/sdcard/";
7534#else
7535 return "/tmp/";
7536#endif // GTEST_OS_WINDOWS_MOBILE
7537}
7538
7539// Class ScopedTrace
7540
7541// Pushes the given source file location and message onto a per-thread
7542// trace stack maintained by Google Test.
7543void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7544 internal::TraceInfo trace;
7545 trace.file = file;
7546 trace.line = line;
7547 trace.message.swap(message);
7548
7549 UnitTest::GetInstance()->PushGTestTrace(trace);
7550}
7551
7552// Pops the info pushed by the c'tor.
7553ScopedTrace::~ScopedTrace()
7554 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7555 UnitTest::GetInstance()->PopGTestTrace();
7556}
7557
Austin Schuh70cc9552019-01-21 19:46:48 -08007558} // namespace testing
7559// Copyright 2005, Google Inc.
7560// All rights reserved.
7561//
7562// Redistribution and use in source and binary forms, with or without
7563// modification, are permitted provided that the following conditions are
7564// met:
7565//
7566// * Redistributions of source code must retain the above copyright
7567// notice, this list of conditions and the following disclaimer.
7568// * Redistributions in binary form must reproduce the above
7569// copyright notice, this list of conditions and the following disclaimer
7570// in the documentation and/or other materials provided with the
7571// distribution.
7572// * Neither the name of Google Inc. nor the names of its
7573// contributors may be used to endorse or promote products derived from
7574// this software without specific prior written permission.
7575//
7576// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7577// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7578// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7579// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7580// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7581// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7582// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7583// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7584// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7585// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7586// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007587
Austin Schuh70cc9552019-01-21 19:46:48 -08007588//
7589// This file implements death tests.
7590
7591
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007592#include <utility>
7593
7594
Austin Schuh70cc9552019-01-21 19:46:48 -08007595#if GTEST_HAS_DEATH_TEST
7596
7597# if GTEST_OS_MAC
7598# include <crt_externs.h>
7599# endif // GTEST_OS_MAC
7600
7601# include <errno.h>
7602# include <fcntl.h>
7603# include <limits.h>
7604
7605# if GTEST_OS_LINUX
7606# include <signal.h>
7607# endif // GTEST_OS_LINUX
7608
7609# include <stdarg.h>
7610
7611# if GTEST_OS_WINDOWS
7612# include <windows.h>
7613# else
7614# include <sys/mman.h>
7615# include <sys/wait.h>
7616# endif // GTEST_OS_WINDOWS
7617
7618# if GTEST_OS_QNX
7619# include <spawn.h>
7620# endif // GTEST_OS_QNX
7621
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007622# if GTEST_OS_FUCHSIA
7623# include <lib/fdio/fd.h>
7624# include <lib/fdio/io.h>
7625# include <lib/fdio/spawn.h>
7626# include <lib/zx/port.h>
7627# include <lib/zx/process.h>
7628# include <lib/zx/socket.h>
7629# include <zircon/processargs.h>
7630# include <zircon/syscalls.h>
7631# include <zircon/syscalls/policy.h>
7632# include <zircon/syscalls/port.h>
7633# endif // GTEST_OS_FUCHSIA
7634
Austin Schuh70cc9552019-01-21 19:46:48 -08007635#endif // GTEST_HAS_DEATH_TEST
7636
7637
Austin Schuh70cc9552019-01-21 19:46:48 -08007638namespace testing {
7639
7640// Constants.
7641
7642// The default death test style.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007643//
7644// This is defined in internal/gtest-port.h as "fast", but can be overridden by
7645// a definition in internal/custom/gtest-port.h. The recommended value, which is
7646// used internally at Google, is "threadsafe".
7647static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
Austin Schuh70cc9552019-01-21 19:46:48 -08007648
7649GTEST_DEFINE_string_(
7650 death_test_style,
7651 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
7652 "Indicates how to run a death test in a forked child process: "
7653 "\"threadsafe\" (child process re-executes the test binary "
7654 "from the beginning, running only the specific death test) or "
7655 "\"fast\" (child process runs the death test immediately "
7656 "after forking).");
7657
7658GTEST_DEFINE_bool_(
7659 death_test_use_fork,
7660 internal::BoolFromGTestEnv("death_test_use_fork", false),
7661 "Instructs to use fork()/_exit() instead of clone() in death tests. "
7662 "Ignored and always uses fork() on POSIX systems where clone() is not "
7663 "implemented. Useful when running under valgrind or similar tools if "
7664 "those do not support clone(). Valgrind 3.3.1 will just fail if "
7665 "it sees an unsupported combination of clone() flags. "
7666 "It is not recommended to use this flag w/o valgrind though it will "
7667 "work in 99% of the cases. Once valgrind is fixed, this flag will "
7668 "most likely be removed.");
7669
7670namespace internal {
7671GTEST_DEFINE_string_(
7672 internal_run_death_test, "",
7673 "Indicates the file, line number, temporal index of "
7674 "the single death test to run, and a file descriptor to "
7675 "which a success code may be sent, all separated by "
7676 "the '|' characters. This flag is specified if and only if the current "
7677 "process is a sub-process launched for running a thread-safe "
7678 "death test. FOR INTERNAL USE ONLY.");
7679} // namespace internal
7680
7681#if GTEST_HAS_DEATH_TEST
7682
7683namespace internal {
7684
7685// Valid only for fast death tests. Indicates the code is running in the
7686// child process of a fast style death test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007687# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007688static bool g_in_fast_death_test_child = false;
7689# endif
7690
7691// Returns a Boolean value indicating whether the caller is currently
7692// executing in the context of the death test child process. Tools such as
7693// Valgrind heap checkers may need this to modify their behavior in death
7694// tests. IMPORTANT: This is an internal utility. Using it may break the
7695// implementation of death tests. User code MUST NOT use it.
7696bool InDeathTestChild() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007697# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007698
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007699 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
7700 // of the death_test_style flag.
Austin Schuh70cc9552019-01-21 19:46:48 -08007701 return !GTEST_FLAG(internal_run_death_test).empty();
7702
7703# else
7704
7705 if (GTEST_FLAG(death_test_style) == "threadsafe")
7706 return !GTEST_FLAG(internal_run_death_test).empty();
7707 else
7708 return g_in_fast_death_test_child;
7709#endif
7710}
7711
7712} // namespace internal
7713
7714// ExitedWithCode constructor.
7715ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
7716}
7717
7718// ExitedWithCode function-call operator.
7719bool ExitedWithCode::operator()(int exit_status) const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007720# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007721
7722 return exit_status == exit_code_;
7723
7724# else
7725
7726 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7727
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007728# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007729}
7730
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007731# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007732// KilledBySignal constructor.
7733KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7734}
7735
7736// KilledBySignal function-call operator.
7737bool KilledBySignal::operator()(int exit_status) const {
7738# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7739 {
7740 bool result;
7741 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7742 return result;
7743 }
7744 }
7745# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7746 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7747}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007748# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007749
7750namespace internal {
7751
7752// Utilities needed for death tests.
7753
7754// Generates a textual description of a given exit code, in the format
7755// specified by wait(2).
7756static std::string ExitSummary(int exit_code) {
7757 Message m;
7758
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007759# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007760
7761 m << "Exited with exit status " << exit_code;
7762
7763# else
7764
7765 if (WIFEXITED(exit_code)) {
7766 m << "Exited with exit status " << WEXITSTATUS(exit_code);
7767 } else if (WIFSIGNALED(exit_code)) {
7768 m << "Terminated by signal " << WTERMSIG(exit_code);
7769 }
7770# ifdef WCOREDUMP
7771 if (WCOREDUMP(exit_code)) {
7772 m << " (core dumped)";
7773 }
7774# endif
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007775# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007776
7777 return m.GetString();
7778}
7779
7780// Returns true if exit_status describes a process that was terminated
7781// by a signal, or exited normally with a nonzero exit code.
7782bool ExitedUnsuccessfully(int exit_status) {
7783 return !ExitedWithCode(0)(exit_status);
7784}
7785
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007786# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007787// Generates a textual failure message when a death test finds more than
7788// one thread running, or cannot determine the number of threads, prior
7789// to executing the given statement. It is the responsibility of the
7790// caller not to pass a thread_count of 1.
7791static std::string DeathTestThreadWarning(size_t thread_count) {
7792 Message msg;
7793 msg << "Death tests use fork(), which is unsafe particularly"
7794 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007795 if (thread_count == 0) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007796 msg << "couldn't detect the number of threads.";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007797 } else {
Austin Schuh70cc9552019-01-21 19:46:48 -08007798 msg << "detected " << thread_count << " threads.";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007799 }
7800 msg << " See "
7801 "https://github.com/google/googletest/blob/master/googletest/docs/"
7802 "advanced.md#death-tests-and-threads"
7803 << " for more explanation and suggested solutions, especially if"
7804 << " this is the last message you see before your test times out.";
Austin Schuh70cc9552019-01-21 19:46:48 -08007805 return msg.GetString();
7806}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007807# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08007808
7809// Flag characters for reporting a death test that did not die.
7810static const char kDeathTestLived = 'L';
7811static const char kDeathTestReturned = 'R';
7812static const char kDeathTestThrew = 'T';
7813static const char kDeathTestInternalError = 'I';
7814
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007815#if GTEST_OS_FUCHSIA
7816
7817// File descriptor used for the pipe in the child process.
7818static const int kFuchsiaReadPipeFd = 3;
7819
7820#endif
7821
Austin Schuh70cc9552019-01-21 19:46:48 -08007822// An enumeration describing all of the possible ways that a death test can
7823// conclude. DIED means that the process died while executing the test
7824// code; LIVED means that process lived beyond the end of the test code;
7825// RETURNED means that the test statement attempted to execute a return
7826// statement, which is not allowed; THREW means that the test statement
7827// returned control by throwing an exception. IN_PROGRESS means the test
7828// has not yet concluded.
Austin Schuh70cc9552019-01-21 19:46:48 -08007829enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7830
7831// Routine for aborting the program which is safe to call from an
7832// exec-style death test child process, in which case the error
7833// message is propagated back to the parent process. Otherwise, the
7834// message is simply printed to stderr. In either case, the program
7835// then exits with status 1.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007836static void DeathTestAbort(const std::string& message) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007837 // On a POSIX system, this function may be called from a threadsafe-style
7838 // death test child process, which operates on a very small stack. Use
7839 // the heap for any additional non-minuscule memory requirements.
7840 const InternalRunDeathTestFlag* const flag =
7841 GetUnitTestImpl()->internal_run_death_test_flag();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007842 if (flag != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007843 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7844 fputc(kDeathTestInternalError, parent);
7845 fprintf(parent, "%s", message.c_str());
7846 fflush(parent);
7847 _exit(1);
7848 } else {
7849 fprintf(stderr, "%s", message.c_str());
7850 fflush(stderr);
7851 posix::Abort();
7852 }
7853}
7854
7855// A replacement for CHECK that calls DeathTestAbort if the assertion
7856// fails.
7857# define GTEST_DEATH_TEST_CHECK_(expression) \
7858 do { \
7859 if (!::testing::internal::IsTrue(expression)) { \
7860 DeathTestAbort( \
7861 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7862 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7863 + #expression); \
7864 } \
7865 } while (::testing::internal::AlwaysFalse())
7866
7867// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7868// evaluating any system call that fulfills two conditions: it must return
7869// -1 on failure, and set errno to EINTR when it is interrupted and
7870// should be tried again. The macro expands to a loop that repeatedly
7871// evaluates the expression as long as it evaluates to -1 and sets
7872// errno to EINTR. If the expression evaluates to -1 but errno is
7873// something other than EINTR, DeathTestAbort is called.
7874# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7875 do { \
7876 int gtest_retval; \
7877 do { \
7878 gtest_retval = (expression); \
7879 } while (gtest_retval == -1 && errno == EINTR); \
7880 if (gtest_retval == -1) { \
7881 DeathTestAbort( \
7882 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7883 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7884 + #expression + " != -1"); \
7885 } \
7886 } while (::testing::internal::AlwaysFalse())
7887
7888// Returns the message describing the last system error in errno.
7889std::string GetLastErrnoDescription() {
7890 return errno == 0 ? "" : posix::StrError(errno);
7891}
7892
7893// This is called from a death test parent process to read a failure
7894// message from the death test child process and log it with the FATAL
7895// severity. On Windows, the message is read from a pipe handle. On other
7896// platforms, it is read from a file descriptor.
7897static void FailFromInternalError(int fd) {
7898 Message error;
7899 char buffer[256];
7900 int num_read;
7901
7902 do {
7903 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7904 buffer[num_read] = '\0';
7905 error << buffer;
7906 }
7907 } while (num_read == -1 && errno == EINTR);
7908
7909 if (num_read == 0) {
7910 GTEST_LOG_(FATAL) << error.GetString();
7911 } else {
7912 const int last_error = errno;
7913 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7914 << GetLastErrnoDescription() << " [" << last_error << "]";
7915 }
7916}
7917
7918// Death test constructor. Increments the running death test count
7919// for the current test.
7920DeathTest::DeathTest() {
7921 TestInfo* const info = GetUnitTestImpl()->current_test_info();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007922 if (info == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007923 DeathTestAbort("Cannot run a death test outside of a TEST or "
7924 "TEST_F construct");
7925 }
7926}
7927
7928// Creates and returns a death test by dispatching to the current
7929// death test factory.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007930bool DeathTest::Create(const char* statement,
7931 Matcher<const std::string&> matcher, const char* file,
7932 int line, DeathTest** test) {
Austin Schuh70cc9552019-01-21 19:46:48 -08007933 return GetUnitTestImpl()->death_test_factory()->Create(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007934 statement, std::move(matcher), file, line, test);
Austin Schuh70cc9552019-01-21 19:46:48 -08007935}
7936
7937const char* DeathTest::LastMessage() {
7938 return last_death_test_message_.c_str();
7939}
7940
7941void DeathTest::set_last_death_test_message(const std::string& message) {
7942 last_death_test_message_ = message;
7943}
7944
7945std::string DeathTest::last_death_test_message_;
7946
7947// Provides cross platform implementation for some death functionality.
7948class DeathTestImpl : public DeathTest {
7949 protected:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007950 DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
Austin Schuh70cc9552019-01-21 19:46:48 -08007951 : statement_(a_statement),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007952 matcher_(std::move(matcher)),
Austin Schuh70cc9552019-01-21 19:46:48 -08007953 spawned_(false),
7954 status_(-1),
7955 outcome_(IN_PROGRESS),
7956 read_fd_(-1),
7957 write_fd_(-1) {}
7958
7959 // read_fd_ is expected to be closed and cleared by a derived class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007960 ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
Austin Schuh70cc9552019-01-21 19:46:48 -08007961
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007962 void Abort(AbortReason reason) override;
7963 bool Passed(bool status_ok) override;
Austin Schuh70cc9552019-01-21 19:46:48 -08007964
7965 const char* statement() const { return statement_; }
Austin Schuh70cc9552019-01-21 19:46:48 -08007966 bool spawned() const { return spawned_; }
7967 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
7968 int status() const { return status_; }
7969 void set_status(int a_status) { status_ = a_status; }
7970 DeathTestOutcome outcome() const { return outcome_; }
7971 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7972 int read_fd() const { return read_fd_; }
7973 void set_read_fd(int fd) { read_fd_ = fd; }
7974 int write_fd() const { return write_fd_; }
7975 void set_write_fd(int fd) { write_fd_ = fd; }
7976
7977 // Called in the parent process only. Reads the result code of the death
7978 // test child process via a pipe, interprets it to set the outcome_
7979 // member, and closes read_fd_. Outputs diagnostics and terminates in
7980 // case of unexpected codes.
7981 void ReadAndInterpretStatusByte();
7982
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007983 // Returns stderr output from the child process.
7984 virtual std::string GetErrorLogs();
7985
Austin Schuh70cc9552019-01-21 19:46:48 -08007986 private:
7987 // The textual content of the code this object is testing. This class
7988 // doesn't own this string and should not attempt to delete it.
7989 const char* const statement_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007990 // A matcher that's expected to match the stderr output by the child process.
7991 Matcher<const std::string&> matcher_;
Austin Schuh70cc9552019-01-21 19:46:48 -08007992 // True if the death test child process has been successfully spawned.
7993 bool spawned_;
7994 // The exit status of the child process.
7995 int status_;
7996 // How the death test concluded.
7997 DeathTestOutcome outcome_;
7998 // Descriptor to the read end of the pipe to the child process. It is
7999 // always -1 in the child process. The child keeps its write end of the
8000 // pipe in write_fd_.
8001 int read_fd_;
8002 // Descriptor to the child's write end of the pipe to the parent process.
8003 // It is always -1 in the parent process. The parent keeps its end of the
8004 // pipe in read_fd_.
8005 int write_fd_;
8006};
8007
8008// Called in the parent process only. Reads the result code of the death
8009// test child process via a pipe, interprets it to set the outcome_
8010// member, and closes read_fd_. Outputs diagnostics and terminates in
8011// case of unexpected codes.
8012void DeathTestImpl::ReadAndInterpretStatusByte() {
8013 char flag;
8014 int bytes_read;
8015
8016 // The read() here blocks until data is available (signifying the
8017 // failure of the death test) or until the pipe is closed (signifying
8018 // its success), so it's okay to call this in the parent before
8019 // the child process has exited.
8020 do {
8021 bytes_read = posix::Read(read_fd(), &flag, 1);
8022 } while (bytes_read == -1 && errno == EINTR);
8023
8024 if (bytes_read == 0) {
8025 set_outcome(DIED);
8026 } else if (bytes_read == 1) {
8027 switch (flag) {
8028 case kDeathTestReturned:
8029 set_outcome(RETURNED);
8030 break;
8031 case kDeathTestThrew:
8032 set_outcome(THREW);
8033 break;
8034 case kDeathTestLived:
8035 set_outcome(LIVED);
8036 break;
8037 case kDeathTestInternalError:
8038 FailFromInternalError(read_fd()); // Does not return.
8039 break;
8040 default:
8041 GTEST_LOG_(FATAL) << "Death test child process reported "
8042 << "unexpected status byte ("
8043 << static_cast<unsigned int>(flag) << ")";
8044 }
8045 } else {
8046 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
8047 << GetLastErrnoDescription();
8048 }
8049 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
8050 set_read_fd(-1);
8051}
8052
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008053std::string DeathTestImpl::GetErrorLogs() {
8054 return GetCapturedStderr();
8055}
8056
Austin Schuh70cc9552019-01-21 19:46:48 -08008057// Signals that the death test code which should have exited, didn't.
8058// Should be called only in a death test child process.
8059// Writes a status byte to the child's status file descriptor, then
8060// calls _exit(1).
8061void DeathTestImpl::Abort(AbortReason reason) {
8062 // The parent process considers the death test to be a failure if
8063 // it finds any data in our pipe. So, here we write a single flag byte
8064 // to the pipe, then exit.
8065 const char status_ch =
8066 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8067 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8068
8069 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8070 // We are leaking the descriptor here because on some platforms (i.e.,
8071 // when built as Windows DLL), destructors of global objects will still
8072 // run after calling _exit(). On such systems, write_fd_ will be
8073 // indirectly closed from the destructor of UnitTestImpl, causing double
8074 // close if it is also closed here. On debug configurations, double close
8075 // may assert. As there are no in-process buffers to flush here, we are
8076 // relying on the OS to close the descriptor after the process terminates
8077 // when the destructors are not run.
8078 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
8079}
8080
8081// Returns an indented copy of stderr output for a death test.
8082// This makes distinguishing death test output lines from regular log lines
8083// much easier.
8084static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8085 ::std::string ret;
8086 for (size_t at = 0; ; ) {
8087 const size_t line_end = output.find('\n', at);
8088 ret += "[ DEATH ] ";
8089 if (line_end == ::std::string::npos) {
8090 ret += output.substr(at);
8091 break;
8092 }
8093 ret += output.substr(at, line_end + 1 - at);
8094 at = line_end + 1;
8095 }
8096 return ret;
8097}
8098
8099// Assesses the success or failure of a death test, using both private
8100// members which have previously been set, and one argument:
8101//
8102// Private data members:
8103// outcome: An enumeration describing how the death test
8104// concluded: DIED, LIVED, THREW, or RETURNED. The death test
8105// fails in the latter three cases.
8106// status: The exit status of the child process. On *nix, it is in the
8107// in the format specified by wait(2). On Windows, this is the
8108// value supplied to the ExitProcess() API or a numeric code
8109// of the exception that terminated the program.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008110// matcher_: A matcher that's expected to match the stderr output by the child
8111// process.
Austin Schuh70cc9552019-01-21 19:46:48 -08008112//
8113// Argument:
8114// status_ok: true if exit_status is acceptable in the context of
8115// this particular death test, which fails if it is false
8116//
8117// Returns true iff all of the above conditions are met. Otherwise, the
8118// first failing condition, in the order given above, is the one that is
8119// reported. Also sets the last death test message string.
8120bool DeathTestImpl::Passed(bool status_ok) {
8121 if (!spawned())
8122 return false;
8123
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008124 const std::string error_message = GetErrorLogs();
Austin Schuh70cc9552019-01-21 19:46:48 -08008125
8126 bool success = false;
8127 Message buffer;
8128
8129 buffer << "Death test: " << statement() << "\n";
8130 switch (outcome()) {
8131 case LIVED:
8132 buffer << " Result: failed to die.\n"
8133 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8134 break;
8135 case THREW:
8136 buffer << " Result: threw an exception.\n"
8137 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8138 break;
8139 case RETURNED:
8140 buffer << " Result: illegal return in test statement.\n"
8141 << " Error msg:\n" << FormatDeathTestOutput(error_message);
8142 break;
8143 case DIED:
8144 if (status_ok) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008145 if (matcher_.Matches(error_message)) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008146 success = true;
8147 } else {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008148 std::ostringstream stream;
8149 matcher_.DescribeTo(&stream);
Austin Schuh70cc9552019-01-21 19:46:48 -08008150 buffer << " Result: died but not with expected error.\n"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008151 << " Expected: " << stream.str() << "\n"
8152 << "Actual msg:\n"
8153 << FormatDeathTestOutput(error_message);
Austin Schuh70cc9552019-01-21 19:46:48 -08008154 }
8155 } else {
8156 buffer << " Result: died but not with expected exit code:\n"
8157 << " " << ExitSummary(status()) << "\n"
8158 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8159 }
8160 break;
8161 case IN_PROGRESS:
8162 default:
8163 GTEST_LOG_(FATAL)
8164 << "DeathTest::Passed somehow called before conclusion of test";
8165 }
8166
8167 DeathTest::set_last_death_test_message(buffer.GetString());
8168 return success;
8169}
8170
8171# if GTEST_OS_WINDOWS
8172// WindowsDeathTest implements death tests on Windows. Due to the
8173// specifics of starting new processes on Windows, death tests there are
8174// always threadsafe, and Google Test considers the
8175// --gtest_death_test_style=fast setting to be equivalent to
8176// --gtest_death_test_style=threadsafe there.
8177//
8178// A few implementation notes: Like the Linux version, the Windows
8179// implementation uses pipes for child-to-parent communication. But due to
8180// the specifics of pipes on Windows, some extra steps are required:
8181//
8182// 1. The parent creates a communication pipe and stores handles to both
8183// ends of it.
8184// 2. The parent starts the child and provides it with the information
8185// necessary to acquire the handle to the write end of the pipe.
8186// 3. The child acquires the write end of the pipe and signals the parent
8187// using a Windows event.
8188// 4. Now the parent can release the write end of the pipe on its side. If
8189// this is done before step 3, the object's reference count goes down to
8190// 0 and it is destroyed, preventing the child from acquiring it. The
8191// parent now has to release it, or read operations on the read end of
8192// the pipe will not return when the child terminates.
8193// 5. The parent reads child's output through the pipe (outcome code and
8194// any possible error messages) from the pipe, and its stderr and then
8195// determines whether to fail the test.
8196//
8197// Note: to distinguish Win32 API calls from the local method and function
8198// calls, the former are explicitly resolved in the global namespace.
8199//
8200class WindowsDeathTest : public DeathTestImpl {
8201 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008202 WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8203 const char* file, int line)
8204 : DeathTestImpl(a_statement, std::move(matcher)),
8205 file_(file),
8206 line_(line) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008207
8208 // All of these virtual functions are inherited from DeathTest.
8209 virtual int Wait();
8210 virtual TestRole AssumeRole();
8211
8212 private:
8213 // The name of the file in which the death test is located.
8214 const char* const file_;
8215 // The line number on which the death test is located.
8216 const int line_;
8217 // Handle to the write end of the pipe to the child process.
8218 AutoHandle write_handle_;
8219 // Child process handle.
8220 AutoHandle child_handle_;
8221 // Event the child process uses to signal the parent that it has
8222 // acquired the handle to the write end of the pipe. After seeing this
8223 // event the parent can release its own handles to make sure its
8224 // ReadFile() calls return when the child terminates.
8225 AutoHandle event_handle_;
8226};
8227
8228// Waits for the child in a death test to exit, returning its exit
8229// status, or 0 if no child process exists. As a side effect, sets the
8230// outcome data member.
8231int WindowsDeathTest::Wait() {
8232 if (!spawned())
8233 return 0;
8234
8235 // Wait until the child either signals that it has acquired the write end
8236 // of the pipe or it dies.
8237 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8238 switch (::WaitForMultipleObjects(2,
8239 wait_handles,
8240 FALSE, // Waits for any of the handles.
8241 INFINITE)) {
8242 case WAIT_OBJECT_0:
8243 case WAIT_OBJECT_0 + 1:
8244 break;
8245 default:
8246 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
8247 }
8248
8249 // The child has acquired the write end of the pipe or exited.
8250 // We release the handle on our side and continue.
8251 write_handle_.Reset();
8252 event_handle_.Reset();
8253
8254 ReadAndInterpretStatusByte();
8255
8256 // Waits for the child process to exit if it haven't already. This
8257 // returns immediately if the child has already exited, regardless of
8258 // whether previous calls to WaitForMultipleObjects synchronized on this
8259 // handle or not.
8260 GTEST_DEATH_TEST_CHECK_(
8261 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8262 INFINITE));
8263 DWORD status_code;
8264 GTEST_DEATH_TEST_CHECK_(
8265 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8266 child_handle_.Reset();
8267 set_status(static_cast<int>(status_code));
8268 return status();
8269}
8270
8271// The AssumeRole process for a Windows death test. It creates a child
8272// process with the same executable as the current process to run the
8273// death test. The child process is given the --gtest_filter and
8274// --gtest_internal_run_death_test flags such that it knows to run the
8275// current death test only.
8276DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8277 const UnitTestImpl* const impl = GetUnitTestImpl();
8278 const InternalRunDeathTestFlag* const flag =
8279 impl->internal_run_death_test_flag();
8280 const TestInfo* const info = impl->current_test_info();
8281 const int death_test_index = info->result()->death_test_count();
8282
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008283 if (flag != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008284 // ParseInternalRunDeathTestFlag() has performed all the necessary
8285 // processing.
8286 set_write_fd(flag->write_fd());
8287 return EXECUTE_TEST;
8288 }
8289
8290 // WindowsDeathTest uses an anonymous pipe to communicate results of
8291 // a death test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008292 SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
8293 nullptr, TRUE};
Austin Schuh70cc9552019-01-21 19:46:48 -08008294 HANDLE read_handle, write_handle;
8295 GTEST_DEATH_TEST_CHECK_(
8296 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8297 0) // Default buffer size.
8298 != FALSE);
8299 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8300 O_RDONLY));
8301 write_handle_.Reset(write_handle);
8302 event_handle_.Reset(::CreateEvent(
8303 &handles_are_inheritable,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008304 TRUE, // The event will automatically reset to non-signaled state.
8305 FALSE, // The initial state is non-signalled.
8306 nullptr)); // The even is unnamed.
8307 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
8308 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8309 kFilterFlag + "=" + info->test_suite_name() +
8310 "." + info->name();
Austin Schuh70cc9552019-01-21 19:46:48 -08008311 const std::string internal_flag =
8312 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8313 "=" + file_ + "|" + StreamableToString(line_) + "|" +
8314 StreamableToString(death_test_index) + "|" +
8315 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8316 // size_t has the same width as pointers on both 32-bit and 64-bit
8317 // Windows platforms.
8318 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8319 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
8320 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
8321
8322 char executable_path[_MAX_PATH + 1]; // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008323 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
8324 executable_path,
8325 _MAX_PATH));
Austin Schuh70cc9552019-01-21 19:46:48 -08008326
8327 std::string command_line =
8328 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
8329 internal_flag + "\"";
8330
8331 DeathTest::set_last_death_test_message("");
8332
8333 CaptureStderr();
8334 // Flush the log buffers since the log streams are shared with the child.
8335 FlushInfoLog();
8336
8337 // The child process will share the standard handles with the parent.
8338 STARTUPINFOA startup_info;
8339 memset(&startup_info, 0, sizeof(STARTUPINFO));
8340 startup_info.dwFlags = STARTF_USESTDHANDLES;
8341 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8342 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8343 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8344
8345 PROCESS_INFORMATION process_info;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008346 GTEST_DEATH_TEST_CHECK_(
8347 ::CreateProcessA(
8348 executable_path, const_cast<char*>(command_line.c_str()),
8349 nullptr, // Retuned process handle is not inheritable.
8350 nullptr, // Retuned thread handle is not inheritable.
8351 TRUE, // Child inherits all inheritable handles (for write_handle_).
8352 0x0, // Default creation flags.
8353 nullptr, // Inherit the parent's environment.
8354 UnitTest::GetInstance()->original_working_dir(), &startup_info,
8355 &process_info) != FALSE);
Austin Schuh70cc9552019-01-21 19:46:48 -08008356 child_handle_.Reset(process_info.hProcess);
8357 ::CloseHandle(process_info.hThread);
8358 set_spawned(true);
8359 return OVERSEE_TEST;
8360}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008361
8362# elif GTEST_OS_FUCHSIA
8363
8364class FuchsiaDeathTest : public DeathTestImpl {
8365 public:
8366 FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8367 const char* file, int line)
8368 : DeathTestImpl(a_statement, std::move(matcher)),
8369 file_(file),
8370 line_(line) {}
8371
8372 // All of these virtual functions are inherited from DeathTest.
8373 int Wait() override;
8374 TestRole AssumeRole() override;
8375 std::string GetErrorLogs() override;
8376
8377 private:
8378 // The name of the file in which the death test is located.
8379 const char* const file_;
8380 // The line number on which the death test is located.
8381 const int line_;
8382 // The stderr data captured by the child process.
8383 std::string captured_stderr_;
8384
8385 zx::process child_process_;
8386 zx::port port_;
8387 zx::socket stderr_socket_;
8388};
8389
8390// Utility class for accumulating command-line arguments.
8391class Arguments {
8392 public:
8393 Arguments() { args_.push_back(nullptr); }
8394
8395 ~Arguments() {
8396 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8397 ++i) {
8398 free(*i);
8399 }
8400 }
8401 void AddArgument(const char* argument) {
8402 args_.insert(args_.end() - 1, posix::StrDup(argument));
8403 }
8404
8405 template <typename Str>
8406 void AddArguments(const ::std::vector<Str>& arguments) {
8407 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8408 i != arguments.end();
8409 ++i) {
8410 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8411 }
8412 }
8413 char* const* Argv() {
8414 return &args_[0];
8415 }
8416
8417 int size() {
8418 return args_.size() - 1;
8419 }
8420
8421 private:
8422 std::vector<char*> args_;
8423};
8424
8425// Waits for the child in a death test to exit, returning its exit
8426// status, or 0 if no child process exists. As a side effect, sets the
8427// outcome data member.
8428int FuchsiaDeathTest::Wait() {
8429 const int kProcessKey = 0;
8430 const int kSocketKey = 1;
8431
8432 if (!spawned())
8433 return 0;
8434
8435 // Register to wait for the child process to terminate.
8436 zx_status_t status_zx;
8437 status_zx = child_process_.wait_async(
8438 port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
8439 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8440 // Register to wait for the socket to be readable or closed.
8441 status_zx = stderr_socket_.wait_async(
8442 port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
8443 ZX_WAIT_ASYNC_REPEATING);
8444 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8445
8446 bool process_terminated = false;
8447 bool socket_closed = false;
8448 do {
8449 zx_port_packet_t packet = {};
8450 status_zx = port_.wait(zx::time::infinite(), &packet);
8451 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8452
8453 if (packet.key == kProcessKey) {
8454 if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8455 // Process encountered an exception. Kill it directly rather than
8456 // letting other handlers process the event. We will get a second
8457 // kProcessKey event when the process actually terminates.
8458 status_zx = child_process_.kill();
8459 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8460 } else {
8461 // Process terminated.
8462 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8463 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8464 process_terminated = true;
8465 }
8466 } else if (packet.key == kSocketKey) {
8467 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type));
8468 if (packet.signal.observed & ZX_SOCKET_READABLE) {
8469 // Read data from the socket.
8470 constexpr size_t kBufferSize = 1024;
8471 do {
8472 size_t old_length = captured_stderr_.length();
8473 size_t bytes_read = 0;
8474 captured_stderr_.resize(old_length + kBufferSize);
8475 status_zx = stderr_socket_.read(
8476 0, &captured_stderr_.front() + old_length, kBufferSize,
8477 &bytes_read);
8478 captured_stderr_.resize(old_length + bytes_read);
8479 } while (status_zx == ZX_OK);
8480 if (status_zx == ZX_ERR_PEER_CLOSED) {
8481 socket_closed = true;
8482 } else {
8483 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
8484 }
8485 } else {
8486 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
8487 socket_closed = true;
8488 }
8489 }
8490 } while (!process_terminated && !socket_closed);
8491
8492 ReadAndInterpretStatusByte();
8493
8494 zx_info_process_t buffer;
8495 status_zx = child_process_.get_info(
8496 ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
8497 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8498
8499 GTEST_DEATH_TEST_CHECK_(buffer.exited);
8500 set_status(buffer.return_code);
8501 return status();
8502}
8503
8504// The AssumeRole process for a Fuchsia death test. It creates a child
8505// process with the same executable as the current process to run the
8506// death test. The child process is given the --gtest_filter and
8507// --gtest_internal_run_death_test flags such that it knows to run the
8508// current death test only.
8509DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8510 const UnitTestImpl* const impl = GetUnitTestImpl();
8511 const InternalRunDeathTestFlag* const flag =
8512 impl->internal_run_death_test_flag();
8513 const TestInfo* const info = impl->current_test_info();
8514 const int death_test_index = info->result()->death_test_count();
8515
8516 if (flag != nullptr) {
8517 // ParseInternalRunDeathTestFlag() has performed all the necessary
8518 // processing.
8519 set_write_fd(kFuchsiaReadPipeFd);
8520 return EXECUTE_TEST;
8521 }
8522
8523 // Flush the log buffers since the log streams are shared with the child.
8524 FlushInfoLog();
8525
8526 // Build the child process command line.
8527 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8528 kFilterFlag + "=" + info->test_suite_name() +
8529 "." + info->name();
8530 const std::string internal_flag =
8531 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8532 + file_ + "|"
8533 + StreamableToString(line_) + "|"
8534 + StreamableToString(death_test_index);
8535 Arguments args;
8536 args.AddArguments(GetInjectableArgvs());
8537 args.AddArgument(filter_flag.c_str());
8538 args.AddArgument(internal_flag.c_str());
8539
8540 // Build the pipe for communication with the child.
8541 zx_status_t status;
8542 zx_handle_t child_pipe_handle;
8543 uint32_t type;
8544 status = fdio_pipe_half(&child_pipe_handle, &type);
8545 GTEST_DEATH_TEST_CHECK_(status >= 0);
8546 set_read_fd(status);
8547
8548 // Set the pipe handle for the child.
8549 fdio_spawn_action_t spawn_actions[2] = {};
8550 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
8551 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8552 add_handle_action->h.id = PA_HND(type, kFuchsiaReadPipeFd);
8553 add_handle_action->h.handle = child_pipe_handle;
8554
8555 // Create a socket pair will be used to receive the child process' stderr.
8556 zx::socket stderr_producer_socket;
8557 status =
8558 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
8559 GTEST_DEATH_TEST_CHECK_(status >= 0);
8560 int stderr_producer_fd = -1;
8561 status =
8562 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
8563 GTEST_DEATH_TEST_CHECK_(status >= 0);
8564
8565 // Make the stderr socket nonblocking.
8566 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
8567
8568 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
8569 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
8570 add_stderr_action->fd.local_fd = stderr_producer_fd;
8571 add_stderr_action->fd.target_fd = STDERR_FILENO;
8572
8573 // Create a child job.
8574 zx_handle_t child_job = ZX_HANDLE_INVALID;
8575 status = zx_job_create(zx_job_default(), 0, & child_job);
8576 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8577 zx_policy_basic_t policy;
8578 policy.condition = ZX_POL_NEW_ANY;
8579 policy.policy = ZX_POL_ACTION_ALLOW;
8580 status = zx_job_set_policy(
8581 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
8582 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8583
8584 // Create an exception port and attach it to the |child_job|, to allow
8585 // us to suppress the system default exception handler from firing.
8586 status = zx::port::create(0, &port_);
8587 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8588 status = zx_task_bind_exception_port(
8589 child_job, port_.get(), 0 /* key */, 0 /*options */);
8590 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8591
8592 // Spawn the child process.
8593 status = fdio_spawn_etc(
8594 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
8595 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
8596 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8597
8598 set_spawned(true);
8599 return OVERSEE_TEST;
8600}
8601
8602std::string FuchsiaDeathTest::GetErrorLogs() {
8603 return captured_stderr_;
8604}
8605
8606#else // We are neither on Windows, nor on Fuchsia.
Austin Schuh70cc9552019-01-21 19:46:48 -08008607
8608// ForkingDeathTest provides implementations for most of the abstract
8609// methods of the DeathTest interface. Only the AssumeRole method is
8610// left undefined.
8611class ForkingDeathTest : public DeathTestImpl {
8612 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008613 ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
Austin Schuh70cc9552019-01-21 19:46:48 -08008614
8615 // All of these virtual functions are inherited from DeathTest.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008616 int Wait() override;
Austin Schuh70cc9552019-01-21 19:46:48 -08008617
8618 protected:
8619 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8620
8621 private:
8622 // PID of child process during death test; 0 in the child process itself.
8623 pid_t child_pid_;
8624};
8625
8626// Constructs a ForkingDeathTest.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008627ForkingDeathTest::ForkingDeathTest(const char* a_statement,
8628 Matcher<const std::string&> matcher)
8629 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008630
8631// Waits for the child in a death test to exit, returning its exit
8632// status, or 0 if no child process exists. As a side effect, sets the
8633// outcome data member.
8634int ForkingDeathTest::Wait() {
8635 if (!spawned())
8636 return 0;
8637
8638 ReadAndInterpretStatusByte();
8639
8640 int status_value;
8641 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8642 set_status(status_value);
8643 return status_value;
8644}
8645
8646// A concrete death test class that forks, then immediately runs the test
8647// in the child process.
8648class NoExecDeathTest : public ForkingDeathTest {
8649 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008650 NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
8651 : ForkingDeathTest(a_statement, std::move(matcher)) {}
8652 TestRole AssumeRole() override;
Austin Schuh70cc9552019-01-21 19:46:48 -08008653};
8654
8655// The AssumeRole process for a fork-and-run death test. It implements a
8656// straightforward fork, with a simple pipe to transmit the status byte.
8657DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8658 const size_t thread_count = GetThreadCount();
8659 if (thread_count != 1) {
8660 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8661 }
8662
8663 int pipe_fd[2];
8664 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8665
8666 DeathTest::set_last_death_test_message("");
8667 CaptureStderr();
8668 // When we fork the process below, the log file buffers are copied, but the
8669 // file descriptors are shared. We flush all log files here so that closing
8670 // the file descriptors in the child process doesn't throw off the
8671 // synchronization between descriptors and buffers in the parent process.
8672 // This is as close to the fork as possible to avoid a race condition in case
8673 // there are multiple threads running before the death test, and another
8674 // thread writes to the log file.
8675 FlushInfoLog();
8676
8677 const pid_t child_pid = fork();
8678 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8679 set_child_pid(child_pid);
8680 if (child_pid == 0) {
8681 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8682 set_write_fd(pipe_fd[1]);
8683 // Redirects all logging to stderr in the child process to prevent
8684 // concurrent writes to the log files. We capture stderr in the parent
8685 // process and append the child process' output to a log.
8686 LogToStderr();
8687 // Event forwarding to the listeners of event listener API mush be shut
8688 // down in death test subprocesses.
8689 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8690 g_in_fast_death_test_child = true;
8691 return EXECUTE_TEST;
8692 } else {
8693 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8694 set_read_fd(pipe_fd[0]);
8695 set_spawned(true);
8696 return OVERSEE_TEST;
8697 }
8698}
8699
8700// A concrete death test class that forks and re-executes the main
8701// program from the beginning, with command-line flags set that cause
8702// only this specific death test to be run.
8703class ExecDeathTest : public ForkingDeathTest {
8704 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008705 ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8706 const char* file, int line)
8707 : ForkingDeathTest(a_statement, std::move(matcher)),
8708 file_(file),
8709 line_(line) {}
8710 TestRole AssumeRole() override;
8711
Austin Schuh70cc9552019-01-21 19:46:48 -08008712 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008713 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8714 ::std::vector<std::string> args = GetInjectableArgvs();
Austin Schuh70cc9552019-01-21 19:46:48 -08008715# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008716 ::std::vector<std::string> extra_args =
Austin Schuh70cc9552019-01-21 19:46:48 -08008717 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8718 args.insert(args.end(), extra_args.begin(), extra_args.end());
8719# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8720 return args;
8721 }
8722 // The name of the file in which the death test is located.
8723 const char* const file_;
8724 // The line number on which the death test is located.
8725 const int line_;
8726};
8727
8728// Utility class for accumulating command-line arguments.
8729class Arguments {
8730 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008731 Arguments() { args_.push_back(nullptr); }
Austin Schuh70cc9552019-01-21 19:46:48 -08008732
8733 ~Arguments() {
8734 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8735 ++i) {
8736 free(*i);
8737 }
8738 }
8739 void AddArgument(const char* argument) {
8740 args_.insert(args_.end() - 1, posix::StrDup(argument));
8741 }
8742
8743 template <typename Str>
8744 void AddArguments(const ::std::vector<Str>& arguments) {
8745 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8746 i != arguments.end();
8747 ++i) {
8748 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8749 }
8750 }
8751 char* const* Argv() {
8752 return &args_[0];
8753 }
8754
8755 private:
8756 std::vector<char*> args_;
8757};
8758
8759// A struct that encompasses the arguments to the child process of a
8760// threadsafe-style death test process.
8761struct ExecDeathTestArgs {
8762 char* const* argv; // Command-line arguments for the child's call to exec
8763 int close_fd; // File descriptor to close; the read end of a pipe
8764};
8765
8766# if GTEST_OS_MAC
8767inline char** GetEnviron() {
8768 // When Google Test is built as a framework on MacOS X, the environ variable
8769 // is unavailable. Apple's documentation (man environ) recommends using
8770 // _NSGetEnviron() instead.
8771 return *_NSGetEnviron();
8772}
8773# else
8774// Some POSIX platforms expect you to declare environ. extern "C" makes
8775// it reside in the global namespace.
8776extern "C" char** environ;
8777inline char** GetEnviron() { return environ; }
8778# endif // GTEST_OS_MAC
8779
8780# if !GTEST_OS_QNX
8781// The main function for a threadsafe-style death test child process.
8782// This function is called in a clone()-ed process and thus must avoid
8783// any potentially unsafe operations like malloc or libc functions.
8784static int ExecDeathTestChildMain(void* child_arg) {
8785 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
8786 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8787
8788 // We need to execute the test program in the same environment where
8789 // it was originally invoked. Therefore we change to the original
8790 // working directory first.
8791 const char* const original_dir =
8792 UnitTest::GetInstance()->original_working_dir();
8793 // We can safely call chdir() as it's a direct system call.
8794 if (chdir(original_dir) != 0) {
8795 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8796 GetLastErrnoDescription());
8797 return EXIT_FAILURE;
8798 }
8799
8800 // We can safely call execve() as it's a direct system call. We
8801 // cannot use execvp() as it's a libc function and thus potentially
8802 // unsafe. Since execve() doesn't search the PATH, the user must
8803 // invoke the test program via a valid path that contains at least
8804 // one path separator.
8805 execve(args->argv[0], args->argv, GetEnviron());
8806 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
8807 original_dir + " failed: " +
8808 GetLastErrnoDescription());
8809 return EXIT_FAILURE;
8810}
8811# endif // !GTEST_OS_QNX
8812
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008813# if GTEST_HAS_CLONE
Austin Schuh70cc9552019-01-21 19:46:48 -08008814// Two utility routines that together determine the direction the stack
8815// grows.
8816// This could be accomplished more elegantly by a single recursive
8817// function, but we want to guard against the unlikely possibility of
8818// a smart compiler optimizing the recursion away.
8819//
8820// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
8821// StackLowerThanAddress into StackGrowsDown, which then doesn't give
8822// correct answer.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008823static void StackLowerThanAddress(const void* ptr,
8824 bool* result) GTEST_NO_INLINE_;
8825static void StackLowerThanAddress(const void* ptr, bool* result) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008826 int dummy;
8827 *result = (&dummy < ptr);
8828}
8829
8830// Make sure AddressSanitizer does not tamper with the stack here.
8831GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008832static bool StackGrowsDown() {
Austin Schuh70cc9552019-01-21 19:46:48 -08008833 int dummy;
8834 bool result;
8835 StackLowerThanAddress(&dummy, &result);
8836 return result;
8837}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008838# endif // GTEST_HAS_CLONE
Austin Schuh70cc9552019-01-21 19:46:48 -08008839
8840// Spawns a child process with the same executable as the current process in
8841// a thread-safe manner and instructs it to run the death test. The
8842// implementation uses fork(2) + exec. On systems where clone(2) is
8843// available, it is used instead, being slightly more thread-safe. On QNX,
8844// fork supports only single-threaded environments, so this function uses
8845// spawn(2) there instead. The function dies with an error message if
8846// anything goes wrong.
8847static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
8848 ExecDeathTestArgs args = { argv, close_fd };
8849 pid_t child_pid = -1;
8850
8851# if GTEST_OS_QNX
8852 // Obtains the current directory and sets it to be closed in the child
8853 // process.
8854 const int cwd_fd = open(".", O_RDONLY);
8855 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8856 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8857 // We need to execute the test program in the same environment where
8858 // it was originally invoked. Therefore we change to the original
8859 // working directory first.
8860 const char* const original_dir =
8861 UnitTest::GetInstance()->original_working_dir();
8862 // We can safely call chdir() as it's a direct system call.
8863 if (chdir(original_dir) != 0) {
8864 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8865 GetLastErrnoDescription());
8866 return EXIT_FAILURE;
8867 }
8868
8869 int fd_flags;
8870 // Set close_fd to be closed after spawn.
8871 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8872 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8873 fd_flags | FD_CLOEXEC));
8874 struct inheritance inherit = {0};
8875 // spawn is a system call.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008876 child_pid =
8877 spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
Austin Schuh70cc9552019-01-21 19:46:48 -08008878 // Restores the current working directory.
8879 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8880 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8881
8882# else // GTEST_OS_QNX
8883# if GTEST_OS_LINUX
8884 // When a SIGPROF signal is received while fork() or clone() are executing,
8885 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
8886 // it after the call to fork()/clone() is complete.
8887 struct sigaction saved_sigprof_action;
8888 struct sigaction ignore_sigprof_action;
8889 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
8890 sigemptyset(&ignore_sigprof_action.sa_mask);
8891 ignore_sigprof_action.sa_handler = SIG_IGN;
8892 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8893 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8894# endif // GTEST_OS_LINUX
8895
8896# if GTEST_HAS_CLONE
8897 const bool use_fork = GTEST_FLAG(death_test_use_fork);
8898
8899 if (!use_fork) {
8900 static const bool stack_grows_down = StackGrowsDown();
8901 const size_t stack_size = getpagesize();
8902 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008903 void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
Austin Schuh70cc9552019-01-21 19:46:48 -08008904 MAP_ANON | MAP_PRIVATE, -1, 0);
8905 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8906
8907 // Maximum stack alignment in bytes: For a downward-growing stack, this
8908 // amount is subtracted from size of the stack space to get an address
8909 // that is within the stack space and is aligned on all systems we care
8910 // about. As far as I know there is no ABI with stack alignment greater
8911 // than 64. We assume stack and stack_size already have alignment of
8912 // kMaxStackAlignment.
8913 const size_t kMaxStackAlignment = 64;
8914 void* const stack_top =
8915 static_cast<char*>(stack) +
8916 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8917 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8918 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8919
8920 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8921
8922 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8923 }
8924# else
8925 const bool use_fork = true;
8926# endif // GTEST_HAS_CLONE
8927
8928 if (use_fork && (child_pid = fork()) == 0) {
8929 ExecDeathTestChildMain(&args);
8930 _exit(0);
8931 }
8932# endif // GTEST_OS_QNX
8933# if GTEST_OS_LINUX
8934 GTEST_DEATH_TEST_CHECK_SYSCALL_(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008935 sigaction(SIGPROF, &saved_sigprof_action, nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -08008936# endif // GTEST_OS_LINUX
8937
8938 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8939 return child_pid;
8940}
8941
8942// The AssumeRole process for a fork-and-exec death test. It re-executes the
8943// main program from the beginning, setting the --gtest_filter
8944// and --gtest_internal_run_death_test flags to cause only the current
8945// death test to be re-run.
8946DeathTest::TestRole ExecDeathTest::AssumeRole() {
8947 const UnitTestImpl* const impl = GetUnitTestImpl();
8948 const InternalRunDeathTestFlag* const flag =
8949 impl->internal_run_death_test_flag();
8950 const TestInfo* const info = impl->current_test_info();
8951 const int death_test_index = info->result()->death_test_count();
8952
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008953 if (flag != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008954 set_write_fd(flag->write_fd());
8955 return EXECUTE_TEST;
8956 }
8957
8958 int pipe_fd[2];
8959 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8960 // Clear the close-on-exec flag on the write end of the pipe, lest
8961 // it be closed when the child process does an exec:
8962 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
8963
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008964 const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8965 kFilterFlag + "=" + info->test_suite_name() +
8966 "." + info->name();
Austin Schuh70cc9552019-01-21 19:46:48 -08008967 const std::string internal_flag =
8968 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8969 + file_ + "|" + StreamableToString(line_) + "|"
8970 + StreamableToString(death_test_index) + "|"
8971 + StreamableToString(pipe_fd[1]);
8972 Arguments args;
8973 args.AddArguments(GetArgvsForDeathTestChildProcess());
8974 args.AddArgument(filter_flag.c_str());
8975 args.AddArgument(internal_flag.c_str());
8976
8977 DeathTest::set_last_death_test_message("");
8978
8979 CaptureStderr();
8980 // See the comment in NoExecDeathTest::AssumeRole for why the next line
8981 // is necessary.
8982 FlushInfoLog();
8983
8984 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
8985 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8986 set_child_pid(child_pid);
8987 set_read_fd(pipe_fd[0]);
8988 set_spawned(true);
8989 return OVERSEE_TEST;
8990}
8991
8992# endif // !GTEST_OS_WINDOWS
8993
8994// Creates a concrete DeathTest-derived class that depends on the
8995// --gtest_death_test_style flag, and sets the pointer pointed to
8996// by the "test" argument to its address. If the test should be
8997// skipped, sets that pointer to NULL. Returns true, unless the
8998// flag is set to an invalid value.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008999bool DefaultDeathTestFactory::Create(const char* statement,
9000 Matcher<const std::string&> matcher,
Austin Schuh70cc9552019-01-21 19:46:48 -08009001 const char* file, int line,
9002 DeathTest** test) {
9003 UnitTestImpl* const impl = GetUnitTestImpl();
9004 const InternalRunDeathTestFlag* const flag =
9005 impl->internal_run_death_test_flag();
9006 const int death_test_index = impl->current_test_info()
9007 ->increment_death_test_count();
9008
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009009 if (flag != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08009010 if (death_test_index > flag->index()) {
9011 DeathTest::set_last_death_test_message(
9012 "Death test count (" + StreamableToString(death_test_index)
9013 + ") somehow exceeded expected maximum ("
9014 + StreamableToString(flag->index()) + ")");
9015 return false;
9016 }
9017
9018 if (!(flag->file() == file && flag->line() == line &&
9019 flag->index() == death_test_index)) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009020 *test = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08009021 return true;
9022 }
9023 }
9024
9025# if GTEST_OS_WINDOWS
9026
9027 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9028 GTEST_FLAG(death_test_style) == "fast") {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009029 *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
9030 }
9031
9032# elif GTEST_OS_FUCHSIA
9033
9034 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9035 GTEST_FLAG(death_test_style) == "fast") {
9036 *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
Austin Schuh70cc9552019-01-21 19:46:48 -08009037 }
9038
9039# else
9040
9041 if (GTEST_FLAG(death_test_style) == "threadsafe") {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009042 *test = new ExecDeathTest(statement, std::move(matcher), file, line);
Austin Schuh70cc9552019-01-21 19:46:48 -08009043 } else if (GTEST_FLAG(death_test_style) == "fast") {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009044 *test = new NoExecDeathTest(statement, std::move(matcher));
Austin Schuh70cc9552019-01-21 19:46:48 -08009045 }
9046
9047# endif // GTEST_OS_WINDOWS
9048
9049 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
9050 DeathTest::set_last_death_test_message(
9051 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
9052 + "\" encountered");
9053 return false;
9054 }
9055
9056 return true;
9057}
9058
9059# if GTEST_OS_WINDOWS
9060// Recreates the pipe and event handles from the provided parameters,
9061// signals the event, and returns a file descriptor wrapped around the pipe
9062// handle. This function is called in the child process only.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009063static int GetStatusFileDescriptor(unsigned int parent_process_id,
Austin Schuh70cc9552019-01-21 19:46:48 -08009064 size_t write_handle_as_size_t,
9065 size_t event_handle_as_size_t) {
9066 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9067 FALSE, // Non-inheritable.
9068 parent_process_id));
9069 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9070 DeathTestAbort("Unable to open parent process " +
9071 StreamableToString(parent_process_id));
9072 }
9073
Austin Schuh70cc9552019-01-21 19:46:48 -08009074 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
9075
9076 const HANDLE write_handle =
9077 reinterpret_cast<HANDLE>(write_handle_as_size_t);
9078 HANDLE dup_write_handle;
9079
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009080 // The newly initialized handle is accessible only in the parent
Austin Schuh70cc9552019-01-21 19:46:48 -08009081 // process. To obtain one accessible within the child, we need to use
9082 // DuplicateHandle.
9083 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9084 ::GetCurrentProcess(), &dup_write_handle,
9085 0x0, // Requested privileges ignored since
9086 // DUPLICATE_SAME_ACCESS is used.
9087 FALSE, // Request non-inheritable handler.
9088 DUPLICATE_SAME_ACCESS)) {
9089 DeathTestAbort("Unable to duplicate the pipe handle " +
9090 StreamableToString(write_handle_as_size_t) +
9091 " from the parent process " +
9092 StreamableToString(parent_process_id));
9093 }
9094
9095 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
9096 HANDLE dup_event_handle;
9097
9098 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9099 ::GetCurrentProcess(), &dup_event_handle,
9100 0x0,
9101 FALSE,
9102 DUPLICATE_SAME_ACCESS)) {
9103 DeathTestAbort("Unable to duplicate the event handle " +
9104 StreamableToString(event_handle_as_size_t) +
9105 " from the parent process " +
9106 StreamableToString(parent_process_id));
9107 }
9108
9109 const int write_fd =
9110 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9111 if (write_fd == -1) {
9112 DeathTestAbort("Unable to convert pipe handle " +
9113 StreamableToString(write_handle_as_size_t) +
9114 " to a file descriptor");
9115 }
9116
9117 // Signals the parent that the write end of the pipe has been acquired
9118 // so the parent can release its own write end.
9119 ::SetEvent(dup_event_handle);
9120
9121 return write_fd;
9122}
9123# endif // GTEST_OS_WINDOWS
9124
9125// Returns a newly created InternalRunDeathTestFlag object with fields
9126// initialized from the GTEST_FLAG(internal_run_death_test) flag if
9127// the flag is specified; otherwise returns NULL.
9128InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009129 if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08009130
9131 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9132 // can use it here.
9133 int line = -1;
9134 int index = -1;
9135 ::std::vector< ::std::string> fields;
9136 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9137 int write_fd = -1;
9138
9139# if GTEST_OS_WINDOWS
9140
9141 unsigned int parent_process_id = 0;
9142 size_t write_handle_as_size_t = 0;
9143 size_t event_handle_as_size_t = 0;
9144
9145 if (fields.size() != 6
9146 || !ParseNaturalNumber(fields[1], &line)
9147 || !ParseNaturalNumber(fields[2], &index)
9148 || !ParseNaturalNumber(fields[3], &parent_process_id)
9149 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9150 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9151 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9152 GTEST_FLAG(internal_run_death_test));
9153 }
9154 write_fd = GetStatusFileDescriptor(parent_process_id,
9155 write_handle_as_size_t,
9156 event_handle_as_size_t);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009157
9158# elif GTEST_OS_FUCHSIA
9159
9160 if (fields.size() != 3
9161 || !ParseNaturalNumber(fields[1], &line)
9162 || !ParseNaturalNumber(fields[2], &index)) {
9163 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9164 + GTEST_FLAG(internal_run_death_test));
9165 }
9166
Austin Schuh70cc9552019-01-21 19:46:48 -08009167# else
9168
9169 if (fields.size() != 4
9170 || !ParseNaturalNumber(fields[1], &line)
9171 || !ParseNaturalNumber(fields[2], &index)
9172 || !ParseNaturalNumber(fields[3], &write_fd)) {
9173 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9174 + GTEST_FLAG(internal_run_death_test));
9175 }
9176
9177# endif // GTEST_OS_WINDOWS
9178
9179 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9180}
9181
9182} // namespace internal
9183
9184#endif // GTEST_HAS_DEATH_TEST
9185
9186} // namespace testing
9187// Copyright 2008, Google Inc.
9188// All rights reserved.
9189//
9190// Redistribution and use in source and binary forms, with or without
9191// modification, are permitted provided that the following conditions are
9192// met:
9193//
9194// * Redistributions of source code must retain the above copyright
9195// notice, this list of conditions and the following disclaimer.
9196// * Redistributions in binary form must reproduce the above
9197// copyright notice, this list of conditions and the following disclaimer
9198// in the documentation and/or other materials provided with the
9199// distribution.
9200// * Neither the name of Google Inc. nor the names of its
9201// contributors may be used to endorse or promote products derived from
9202// this software without specific prior written permission.
9203//
9204// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9205// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9206// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9207// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9208// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9209// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9210// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9211// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9212// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9213// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9214// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh70cc9552019-01-21 19:46:48 -08009215
9216
9217#include <stdlib.h>
9218
9219#if GTEST_OS_WINDOWS_MOBILE
9220# include <windows.h>
9221#elif GTEST_OS_WINDOWS
9222# include <direct.h>
9223# include <io.h>
Austin Schuh70cc9552019-01-21 19:46:48 -08009224#else
9225# include <limits.h>
9226# include <climits> // Some Linux distributions define PATH_MAX here.
9227#endif // GTEST_OS_WINDOWS_MOBILE
9228
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009229
Austin Schuh70cc9552019-01-21 19:46:48 -08009230#if GTEST_OS_WINDOWS
9231# define GTEST_PATH_MAX_ _MAX_PATH
9232#elif defined(PATH_MAX)
9233# define GTEST_PATH_MAX_ PATH_MAX
9234#elif defined(_XOPEN_PATH_MAX)
9235# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9236#else
9237# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9238#endif // GTEST_OS_WINDOWS
9239
Austin Schuh70cc9552019-01-21 19:46:48 -08009240namespace testing {
9241namespace internal {
9242
9243#if GTEST_OS_WINDOWS
9244// On Windows, '\\' is the standard path separator, but many tools and the
9245// Windows API also accept '/' as an alternate path separator. Unless otherwise
9246// noted, a file path can contain either kind of path separators, or a mixture
9247// of them.
9248const char kPathSeparator = '\\';
9249const char kAlternatePathSeparator = '/';
9250const char kAlternatePathSeparatorString[] = "/";
9251# if GTEST_OS_WINDOWS_MOBILE
9252// Windows CE doesn't have a current directory. You should not use
9253// the current directory in tests on Windows CE, but this at least
9254// provides a reasonable fallback.
9255const char kCurrentDirectoryString[] = "\\";
9256// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9257const DWORD kInvalidFileAttributes = 0xffffffff;
9258# else
9259const char kCurrentDirectoryString[] = ".\\";
9260# endif // GTEST_OS_WINDOWS_MOBILE
9261#else
9262const char kPathSeparator = '/';
9263const char kCurrentDirectoryString[] = "./";
9264#endif // GTEST_OS_WINDOWS
9265
9266// Returns whether the given character is a valid path separator.
9267static bool IsPathSeparator(char c) {
9268#if GTEST_HAS_ALT_PATH_SEP_
9269 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9270#else
9271 return c == kPathSeparator;
9272#endif
9273}
9274
9275// Returns the current working directory, or "" if unsuccessful.
9276FilePath FilePath::GetCurrentDir() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009277#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
9278 GTEST_OS_WINDOWS_RT || ARDUINO
9279 // Windows CE and Arduino don't have a current directory, so we just return
Austin Schuh70cc9552019-01-21 19:46:48 -08009280 // something reasonable.
9281 return FilePath(kCurrentDirectoryString);
9282#elif GTEST_OS_WINDOWS
9283 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009284 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
Austin Schuh70cc9552019-01-21 19:46:48 -08009285#else
9286 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9287 char* result = getcwd(cwd, sizeof(cwd));
9288# if GTEST_OS_NACL
9289 // getcwd will likely fail in NaCl due to the sandbox, so return something
9290 // reasonable. The user may have provided a shim implementation for getcwd,
9291 // however, so fallback only when failure is detected.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009292 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
Austin Schuh70cc9552019-01-21 19:46:48 -08009293# endif // GTEST_OS_NACL
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009294 return FilePath(result == nullptr ? "" : cwd);
Austin Schuh70cc9552019-01-21 19:46:48 -08009295#endif // GTEST_OS_WINDOWS_MOBILE
9296}
9297
9298// Returns a copy of the FilePath with the case-insensitive extension removed.
9299// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9300// FilePath("dir/file"). If a case-insensitive extension is not
9301// found, returns a copy of the original FilePath.
9302FilePath FilePath::RemoveExtension(const char* extension) const {
9303 const std::string dot_extension = std::string(".") + extension;
9304 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9305 return FilePath(pathname_.substr(
9306 0, pathname_.length() - dot_extension.length()));
9307 }
9308 return *this;
9309}
9310
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009311// Returns a pointer to the last occurrence of a valid path separator in
Austin Schuh70cc9552019-01-21 19:46:48 -08009312// the FilePath. On Windows, for example, both '/' and '\' are valid path
9313// separators. Returns NULL if no path separator was found.
9314const char* FilePath::FindLastPathSeparator() const {
9315 const char* const last_sep = strrchr(c_str(), kPathSeparator);
9316#if GTEST_HAS_ALT_PATH_SEP_
9317 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9318 // Comparing two pointers of which only one is NULL is undefined.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009319 if (last_alt_sep != nullptr &&
9320 (last_sep == nullptr || last_alt_sep > last_sep)) {
Austin Schuh70cc9552019-01-21 19:46:48 -08009321 return last_alt_sep;
9322 }
9323#endif
9324 return last_sep;
9325}
9326
9327// Returns a copy of the FilePath with the directory part removed.
9328// Example: FilePath("path/to/file").RemoveDirectoryName() returns
9329// FilePath("file"). If there is no directory part ("just_a_file"), it returns
9330// the FilePath unmodified. If there is no file part ("just_a_dir/") it
9331// returns an empty FilePath ("").
9332// On Windows platform, '\' is the path separator, otherwise it is '/'.
9333FilePath FilePath::RemoveDirectoryName() const {
9334 const char* const last_sep = FindLastPathSeparator();
9335 return last_sep ? FilePath(last_sep + 1) : *this;
9336}
9337
9338// RemoveFileName returns the directory path with the filename removed.
9339// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
9340// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
9341// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
9342// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
9343// On Windows platform, '\' is the path separator, otherwise it is '/'.
9344FilePath FilePath::RemoveFileName() const {
9345 const char* const last_sep = FindLastPathSeparator();
9346 std::string dir;
9347 if (last_sep) {
9348 dir = std::string(c_str(), last_sep + 1 - c_str());
9349 } else {
9350 dir = kCurrentDirectoryString;
9351 }
9352 return FilePath(dir);
9353}
9354
9355// Helper functions for naming files in a directory for xml output.
9356
9357// Given directory = "dir", base_name = "test", number = 0,
9358// extension = "xml", returns "dir/test.xml". If number is greater
9359// than zero (e.g., 12), returns "dir/test_12.xml".
9360// On Windows platform, uses \ as the separator rather than /.
9361FilePath FilePath::MakeFileName(const FilePath& directory,
9362 const FilePath& base_name,
9363 int number,
9364 const char* extension) {
9365 std::string file;
9366 if (number == 0) {
9367 file = base_name.string() + "." + extension;
9368 } else {
9369 file = base_name.string() + "_" + StreamableToString(number)
9370 + "." + extension;
9371 }
9372 return ConcatPaths(directory, FilePath(file));
9373}
9374
9375// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
9376// On Windows, uses \ as the separator rather than /.
9377FilePath FilePath::ConcatPaths(const FilePath& directory,
9378 const FilePath& relative_path) {
9379 if (directory.IsEmpty())
9380 return relative_path;
9381 const FilePath dir(directory.RemoveTrailingPathSeparator());
9382 return FilePath(dir.string() + kPathSeparator + relative_path.string());
9383}
9384
9385// Returns true if pathname describes something findable in the file-system,
9386// either a file, directory, or whatever.
9387bool FilePath::FileOrDirectoryExists() const {
9388#if GTEST_OS_WINDOWS_MOBILE
9389 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9390 const DWORD attributes = GetFileAttributes(unicode);
9391 delete [] unicode;
9392 return attributes != kInvalidFileAttributes;
9393#else
9394 posix::StatStruct file_stat;
9395 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9396#endif // GTEST_OS_WINDOWS_MOBILE
9397}
9398
9399// Returns true if pathname describes a directory in the file-system
9400// that exists.
9401bool FilePath::DirectoryExists() const {
9402 bool result = false;
9403#if GTEST_OS_WINDOWS
9404 // Don't strip off trailing separator if path is a root directory on
9405 // Windows (like "C:\\").
9406 const FilePath& path(IsRootDirectory() ? *this :
9407 RemoveTrailingPathSeparator());
9408#else
9409 const FilePath& path(*this);
9410#endif
9411
9412#if GTEST_OS_WINDOWS_MOBILE
9413 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9414 const DWORD attributes = GetFileAttributes(unicode);
9415 delete [] unicode;
9416 if ((attributes != kInvalidFileAttributes) &&
9417 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9418 result = true;
9419 }
9420#else
9421 posix::StatStruct file_stat;
9422 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
9423 posix::IsDir(file_stat);
9424#endif // GTEST_OS_WINDOWS_MOBILE
9425
9426 return result;
9427}
9428
9429// Returns true if pathname describes a root directory. (Windows has one
9430// root directory per disk drive.)
9431bool FilePath::IsRootDirectory() const {
9432#if GTEST_OS_WINDOWS
Austin Schuh70cc9552019-01-21 19:46:48 -08009433 return pathname_.length() == 3 && IsAbsolutePath();
9434#else
9435 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9436#endif
9437}
9438
9439// Returns true if pathname describes an absolute path.
9440bool FilePath::IsAbsolutePath() const {
9441 const char* const name = pathname_.c_str();
9442#if GTEST_OS_WINDOWS
9443 return pathname_.length() >= 3 &&
9444 ((name[0] >= 'a' && name[0] <= 'z') ||
9445 (name[0] >= 'A' && name[0] <= 'Z')) &&
9446 name[1] == ':' &&
9447 IsPathSeparator(name[2]);
9448#else
9449 return IsPathSeparator(name[0]);
9450#endif
9451}
9452
9453// Returns a pathname for a file that does not currently exist. The pathname
9454// will be directory/base_name.extension or
9455// directory/base_name_<number>.extension if directory/base_name.extension
9456// already exists. The number will be incremented until a pathname is found
9457// that does not already exist.
9458// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
9459// There could be a race condition if two or more processes are calling this
9460// function at the same time -- they could both pick the same filename.
9461FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
9462 const FilePath& base_name,
9463 const char* extension) {
9464 FilePath full_pathname;
9465 int number = 0;
9466 do {
9467 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9468 } while (full_pathname.FileOrDirectoryExists());
9469 return full_pathname;
9470}
9471
9472// Returns true if FilePath ends with a path separator, which indicates that
9473// it is intended to represent a directory. Returns false otherwise.
9474// This does NOT check that a directory (or file) actually exists.
9475bool FilePath::IsDirectory() const {
9476 return !pathname_.empty() &&
9477 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9478}
9479
9480// Create directories so that path exists. Returns true if successful or if
9481// the directories already exist; returns false if unable to create directories
9482// for any reason.
9483bool FilePath::CreateDirectoriesRecursively() const {
9484 if (!this->IsDirectory()) {
9485 return false;
9486 }
9487
9488 if (pathname_.length() == 0 || this->DirectoryExists()) {
9489 return true;
9490 }
9491
9492 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9493 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9494}
9495
9496// Create the directory so that path exists. Returns true if successful or
9497// if the directory already exists; returns false if unable to create the
9498// directory for any reason, including if the parent directory does not
9499// exist. Not named "CreateDirectory" because that's a macro on Windows.
9500bool FilePath::CreateFolder() const {
9501#if GTEST_OS_WINDOWS_MOBILE
9502 FilePath removed_sep(this->RemoveTrailingPathSeparator());
9503 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009504 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
Austin Schuh70cc9552019-01-21 19:46:48 -08009505 delete [] unicode;
9506#elif GTEST_OS_WINDOWS
9507 int result = _mkdir(pathname_.c_str());
9508#else
9509 int result = mkdir(pathname_.c_str(), 0777);
9510#endif // GTEST_OS_WINDOWS_MOBILE
9511
9512 if (result == -1) {
9513 return this->DirectoryExists(); // An error is OK if the directory exists.
9514 }
9515 return true; // No error.
9516}
9517
9518// If input name has a trailing separator character, remove it and return the
9519// name, otherwise return the name string unmodified.
9520// On Windows platform, uses \ as the separator, other platforms use /.
9521FilePath FilePath::RemoveTrailingPathSeparator() const {
9522 return IsDirectory()
9523 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
9524 : *this;
9525}
9526
9527// Removes any redundant separators that might be in the pathname.
9528// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
9529// redundancies that might be in a pathname involving "." or "..".
Austin Schuh70cc9552019-01-21 19:46:48 -08009530void FilePath::Normalize() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009531 if (pathname_.c_str() == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08009532 pathname_ = "";
9533 return;
9534 }
9535 const char* src = pathname_.c_str();
9536 char* const dest = new char[pathname_.length() + 1];
9537 char* dest_ptr = dest;
9538 memset(dest_ptr, 0, pathname_.length() + 1);
9539
9540 while (*src != '\0') {
9541 *dest_ptr = *src;
9542 if (!IsPathSeparator(*src)) {
9543 src++;
9544 } else {
9545#if GTEST_HAS_ALT_PATH_SEP_
9546 if (*dest_ptr == kAlternatePathSeparator) {
9547 *dest_ptr = kPathSeparator;
9548 }
9549#endif
9550 while (IsPathSeparator(*src))
9551 src++;
9552 }
9553 dest_ptr++;
9554 }
9555 *dest_ptr = '\0';
9556 pathname_ = dest;
9557 delete[] dest;
9558}
9559
9560} // namespace internal
9561} // namespace testing
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009562// Copyright 2007, Google Inc.
9563// All rights reserved.
9564//
9565// Redistribution and use in source and binary forms, with or without
9566// modification, are permitted provided that the following conditions are
9567// met:
9568//
9569// * Redistributions of source code must retain the above copyright
9570// notice, this list of conditions and the following disclaimer.
9571// * Redistributions in binary form must reproduce the above
9572// copyright notice, this list of conditions and the following disclaimer
9573// in the documentation and/or other materials provided with the
9574// distribution.
9575// * Neither the name of Google Inc. nor the names of its
9576// contributors may be used to endorse or promote products derived from
9577// this software without specific prior written permission.
9578//
9579// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9580// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9581// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9582// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9583// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9584// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9585// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9586// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9587// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9588// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9589// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9590
9591// The Google C++ Testing and Mocking Framework (Google Test)
9592//
9593// This file implements just enough of the matcher interface to allow
9594// EXPECT_DEATH and friends to accept a matcher argument.
9595
9596
9597#include <string>
9598
9599namespace testing {
9600
9601// Constructs a matcher that matches a const std::string& whose value is
9602// equal to s.
9603Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
9604
9605#if GTEST_HAS_GLOBAL_STRING
9606// Constructs a matcher that matches a const std::string& whose value is
9607// equal to s.
9608Matcher<const std::string&>::Matcher(const ::string& s) {
9609 *this = Eq(static_cast<std::string>(s));
9610}
9611#endif // GTEST_HAS_GLOBAL_STRING
9612
9613// Constructs a matcher that matches a const std::string& whose value is
9614// equal to s.
9615Matcher<const std::string&>::Matcher(const char* s) {
9616 *this = Eq(std::string(s));
9617}
9618
9619// Constructs a matcher that matches a std::string whose value is equal to
9620// s.
9621Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
9622
9623#if GTEST_HAS_GLOBAL_STRING
9624// Constructs a matcher that matches a std::string whose value is equal to
9625// s.
9626Matcher<std::string>::Matcher(const ::string& s) {
9627 *this = Eq(static_cast<std::string>(s));
9628}
9629#endif // GTEST_HAS_GLOBAL_STRING
9630
9631// Constructs a matcher that matches a std::string whose value is equal to
9632// s.
9633Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
9634
9635#if GTEST_HAS_GLOBAL_STRING
9636// Constructs a matcher that matches a const ::string& whose value is
9637// equal to s.
9638Matcher<const ::string&>::Matcher(const std::string& s) {
9639 *this = Eq(static_cast<::string>(s));
9640}
9641
9642// Constructs a matcher that matches a const ::string& whose value is
9643// equal to s.
9644Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); }
9645
9646// Constructs a matcher that matches a const ::string& whose value is
9647// equal to s.
9648Matcher<const ::string&>::Matcher(const char* s) { *this = Eq(::string(s)); }
9649
9650// Constructs a matcher that matches a ::string whose value is equal to s.
9651Matcher<::string>::Matcher(const std::string& s) {
9652 *this = Eq(static_cast<::string>(s));
9653}
9654
9655// Constructs a matcher that matches a ::string whose value is equal to s.
9656Matcher<::string>::Matcher(const ::string& s) { *this = Eq(s); }
9657
9658// Constructs a matcher that matches a string whose value is equal to s.
9659Matcher<::string>::Matcher(const char* s) { *this = Eq(::string(s)); }
9660#endif // GTEST_HAS_GLOBAL_STRING
9661
9662#if GTEST_HAS_ABSL
9663// Constructs a matcher that matches a const absl::string_view& whose value is
9664// equal to s.
9665Matcher<const absl::string_view&>::Matcher(const std::string& s) {
9666 *this = Eq(s);
9667}
9668
9669#if GTEST_HAS_GLOBAL_STRING
9670// Constructs a matcher that matches a const absl::string_view& whose value is
9671// equal to s.
9672Matcher<const absl::string_view&>::Matcher(const ::string& s) { *this = Eq(s); }
9673#endif // GTEST_HAS_GLOBAL_STRING
9674
9675// Constructs a matcher that matches a const absl::string_view& whose value is
9676// equal to s.
9677Matcher<const absl::string_view&>::Matcher(const char* s) {
9678 *this = Eq(std::string(s));
9679}
9680
9681// Constructs a matcher that matches a const absl::string_view& whose value is
9682// equal to s.
9683Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
9684 *this = Eq(std::string(s));
9685}
9686
9687// Constructs a matcher that matches a absl::string_view whose value is equal to
9688// s.
9689Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
9690
9691#if GTEST_HAS_GLOBAL_STRING
9692// Constructs a matcher that matches a absl::string_view whose value is equal to
9693// s.
9694Matcher<absl::string_view>::Matcher(const ::string& s) { *this = Eq(s); }
9695#endif // GTEST_HAS_GLOBAL_STRING
9696
9697// Constructs a matcher that matches a absl::string_view whose value is equal to
9698// s.
9699Matcher<absl::string_view>::Matcher(const char* s) {
9700 *this = Eq(std::string(s));
9701}
9702
9703// Constructs a matcher that matches a absl::string_view whose value is equal to
9704// s.
9705Matcher<absl::string_view>::Matcher(absl::string_view s) {
9706 *this = Eq(std::string(s));
9707}
9708#endif // GTEST_HAS_ABSL
9709
9710} // namespace testing
Austin Schuh70cc9552019-01-21 19:46:48 -08009711// Copyright 2008, Google Inc.
9712// All rights reserved.
9713//
9714// Redistribution and use in source and binary forms, with or without
9715// modification, are permitted provided that the following conditions are
9716// met:
9717//
9718// * Redistributions of source code must retain the above copyright
9719// notice, this list of conditions and the following disclaimer.
9720// * Redistributions in binary form must reproduce the above
9721// copyright notice, this list of conditions and the following disclaimer
9722// in the documentation and/or other materials provided with the
9723// distribution.
9724// * Neither the name of Google Inc. nor the names of its
9725// contributors may be used to endorse or promote products derived from
9726// this software without specific prior written permission.
9727//
9728// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9729// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9730// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9731// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9732// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9733// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9734// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9735// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9736// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9737// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9738// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009739
Austin Schuh70cc9552019-01-21 19:46:48 -08009740
9741
9742#include <limits.h>
Austin Schuh70cc9552019-01-21 19:46:48 -08009743#include <stdio.h>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009744#include <stdlib.h>
Austin Schuh70cc9552019-01-21 19:46:48 -08009745#include <string.h>
9746#include <fstream>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009747#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -08009748
9749#if GTEST_OS_WINDOWS
9750# include <windows.h>
9751# include <io.h>
9752# include <sys/stat.h>
9753# include <map> // Used in ThreadLocal.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009754# ifdef _MSC_VER
9755# include <crtdbg.h>
9756# endif // _MSC_VER
Austin Schuh70cc9552019-01-21 19:46:48 -08009757#else
9758# include <unistd.h>
9759#endif // GTEST_OS_WINDOWS
9760
9761#if GTEST_OS_MAC
9762# include <mach/mach_init.h>
9763# include <mach/task.h>
9764# include <mach/vm_map.h>
9765#endif // GTEST_OS_MAC
9766
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009767#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
9768 GTEST_OS_NETBSD || GTEST_OS_OPENBSD
9769# include <sys/sysctl.h>
9770# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
9771# include <sys/user.h>
9772# endif
9773#endif
9774
Austin Schuh70cc9552019-01-21 19:46:48 -08009775#if GTEST_OS_QNX
9776# include <devctl.h>
9777# include <fcntl.h>
9778# include <sys/procfs.h>
9779#endif // GTEST_OS_QNX
9780
9781#if GTEST_OS_AIX
9782# include <procinfo.h>
9783# include <sys/types.h>
9784#endif // GTEST_OS_AIX
9785
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009786#if GTEST_OS_FUCHSIA
9787# include <zircon/process.h>
9788# include <zircon/syscalls.h>
9789#endif // GTEST_OS_FUCHSIA
Austin Schuh70cc9552019-01-21 19:46:48 -08009790
Austin Schuh70cc9552019-01-21 19:46:48 -08009791
9792namespace testing {
9793namespace internal {
9794
9795#if defined(_MSC_VER) || defined(__BORLANDC__)
9796// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
9797const int kStdOutFileno = 1;
9798const int kStdErrFileno = 2;
9799#else
9800const int kStdOutFileno = STDOUT_FILENO;
9801const int kStdErrFileno = STDERR_FILENO;
9802#endif // _MSC_VER
9803
9804#if GTEST_OS_LINUX
9805
9806namespace {
9807template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009808T ReadProcFileField(const std::string& filename, int field) {
Austin Schuh70cc9552019-01-21 19:46:48 -08009809 std::string dummy;
9810 std::ifstream file(filename.c_str());
9811 while (field-- > 0) {
9812 file >> dummy;
9813 }
9814 T output = 0;
9815 file >> output;
9816 return output;
9817}
9818} // namespace
9819
9820// Returns the number of active threads, or 0 when there is an error.
9821size_t GetThreadCount() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009822 const std::string filename =
Austin Schuh70cc9552019-01-21 19:46:48 -08009823 (Message() << "/proc/" << getpid() << "/stat").GetString();
9824 return ReadProcFileField<int>(filename, 19);
9825}
9826
9827#elif GTEST_OS_MAC
9828
9829size_t GetThreadCount() {
9830 const task_t task = mach_task_self();
9831 mach_msg_type_number_t thread_count;
9832 thread_act_array_t thread_list;
9833 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9834 if (status == KERN_SUCCESS) {
9835 // task_threads allocates resources in thread_list and we need to free them
9836 // to avoid leaks.
9837 vm_deallocate(task,
9838 reinterpret_cast<vm_address_t>(thread_list),
9839 sizeof(thread_t) * thread_count);
9840 return static_cast<size_t>(thread_count);
9841 } else {
9842 return 0;
9843 }
9844}
9845
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009846#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
9847 GTEST_OS_NETBSD
9848
9849#if GTEST_OS_NETBSD
9850#undef KERN_PROC
9851#define KERN_PROC KERN_PROC2
9852#define kinfo_proc kinfo_proc2
9853#endif
9854
9855#if GTEST_OS_DRAGONFLY
9856#define KP_NLWP(kp) (kp.kp_nthreads)
9857#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
9858#define KP_NLWP(kp) (kp.ki_numthreads)
9859#elif GTEST_OS_NETBSD
9860#define KP_NLWP(kp) (kp.p_nlwps)
9861#endif
9862
9863// Returns the number of threads running in the process, or 0 to indicate that
9864// we cannot detect it.
9865size_t GetThreadCount() {
9866 int mib[] = {
9867 CTL_KERN,
9868 KERN_PROC,
9869 KERN_PROC_PID,
9870 getpid(),
9871#if GTEST_OS_NETBSD
9872 sizeof(struct kinfo_proc),
9873 1,
9874#endif
9875 };
9876 u_int miblen = sizeof(mib) / sizeof(mib[0]);
9877 struct kinfo_proc info;
9878 size_t size = sizeof(info);
9879 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
9880 return 0;
9881 }
9882 return KP_NLWP(info);
9883}
9884#elif GTEST_OS_OPENBSD
9885
9886// Returns the number of threads running in the process, or 0 to indicate that
9887// we cannot detect it.
9888size_t GetThreadCount() {
9889 int mib[] = {
9890 CTL_KERN,
9891 KERN_PROC,
9892 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
9893 getpid(),
9894 sizeof(struct kinfo_proc),
9895 0,
9896 };
9897 u_int miblen = sizeof(mib) / sizeof(mib[0]);
9898
9899 // get number of structs
9900 size_t size;
9901 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
9902 return 0;
9903 }
9904 mib[5] = size / mib[4];
9905
9906 // populate array of structs
9907 struct kinfo_proc info[mib[5]];
9908 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
9909 return 0;
9910 }
9911
9912 // exclude empty members
9913 int nthreads = 0;
9914 for (int i = 0; i < size / mib[4]; i++) {
9915 if (info[i].p_tid != -1)
9916 nthreads++;
9917 }
9918 return nthreads;
9919}
9920
Austin Schuh70cc9552019-01-21 19:46:48 -08009921#elif GTEST_OS_QNX
9922
9923// Returns the number of threads running in the process, or 0 to indicate that
9924// we cannot detect it.
9925size_t GetThreadCount() {
9926 const int fd = open("/proc/self/as", O_RDONLY);
9927 if (fd < 0) {
9928 return 0;
9929 }
9930 procfs_info process_info;
9931 const int status =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009932 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08009933 close(fd);
9934 if (status == EOK) {
9935 return static_cast<size_t>(process_info.num_threads);
9936 } else {
9937 return 0;
9938 }
9939}
9940
9941#elif GTEST_OS_AIX
9942
9943size_t GetThreadCount() {
9944 struct procentry64 entry;
9945 pid_t pid = getpid();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009946 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
Austin Schuh70cc9552019-01-21 19:46:48 -08009947 if (status == 1) {
9948 return entry.pi_thcount;
9949 } else {
9950 return 0;
9951 }
9952}
9953
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009954#elif GTEST_OS_FUCHSIA
9955
9956size_t GetThreadCount() {
9957 int dummy_buffer;
9958 size_t avail;
9959 zx_status_t status = zx_object_get_info(
9960 zx_process_self(),
9961 ZX_INFO_PROCESS_THREADS,
9962 &dummy_buffer,
9963 0,
9964 nullptr,
9965 &avail);
9966 if (status == ZX_OK) {
9967 return avail;
9968 } else {
9969 return 0;
9970 }
9971}
9972
Austin Schuh70cc9552019-01-21 19:46:48 -08009973#else
9974
9975size_t GetThreadCount() {
9976 // There's no portable way to detect the number of threads, so we just
9977 // return 0 to indicate that we cannot detect it.
9978 return 0;
9979}
9980
9981#endif // GTEST_OS_LINUX
9982
9983#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9984
9985void SleepMilliseconds(int n) {
9986 ::Sleep(n);
9987}
9988
9989AutoHandle::AutoHandle()
9990 : handle_(INVALID_HANDLE_VALUE) {}
9991
9992AutoHandle::AutoHandle(Handle handle)
9993 : handle_(handle) {}
9994
9995AutoHandle::~AutoHandle() {
9996 Reset();
9997}
9998
9999AutoHandle::Handle AutoHandle::Get() const {
10000 return handle_;
10001}
10002
10003void AutoHandle::Reset() {
10004 Reset(INVALID_HANDLE_VALUE);
10005}
10006
10007void AutoHandle::Reset(HANDLE handle) {
10008 // Resetting with the same handle we already own is invalid.
10009 if (handle_ != handle) {
10010 if (IsCloseable()) {
10011 ::CloseHandle(handle_);
10012 }
10013 handle_ = handle;
10014 } else {
10015 GTEST_CHECK_(!IsCloseable())
10016 << "Resetting a valid handle to itself is likely a programmer error "
10017 "and thus not allowed.";
10018 }
10019}
10020
10021bool AutoHandle::IsCloseable() const {
10022 // Different Windows APIs may use either of these values to represent an
10023 // invalid handle.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010024 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
Austin Schuh70cc9552019-01-21 19:46:48 -080010025}
10026
10027Notification::Notification()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010028 : event_(::CreateEvent(nullptr, // Default security attributes.
10029 TRUE, // Do not reset automatically.
10030 FALSE, // Initially unset.
10031 nullptr)) { // Anonymous event.
10032 GTEST_CHECK_(event_.Get() != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -080010033}
10034
10035void Notification::Notify() {
10036 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
10037}
10038
10039void Notification::WaitForNotification() {
10040 GTEST_CHECK_(
10041 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
10042}
10043
10044Mutex::Mutex()
10045 : owner_thread_id_(0),
10046 type_(kDynamic),
10047 critical_section_init_phase_(0),
10048 critical_section_(new CRITICAL_SECTION) {
10049 ::InitializeCriticalSection(critical_section_);
10050}
10051
10052Mutex::~Mutex() {
10053 // Static mutexes are leaked intentionally. It is not thread-safe to try
10054 // to clean them up.
Austin Schuh70cc9552019-01-21 19:46:48 -080010055 if (type_ == kDynamic) {
10056 ::DeleteCriticalSection(critical_section_);
10057 delete critical_section_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010058 critical_section_ = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010059 }
10060}
10061
10062void Mutex::Lock() {
10063 ThreadSafeLazyInit();
10064 ::EnterCriticalSection(critical_section_);
10065 owner_thread_id_ = ::GetCurrentThreadId();
10066}
10067
10068void Mutex::Unlock() {
10069 ThreadSafeLazyInit();
10070 // We don't protect writing to owner_thread_id_ here, as it's the
10071 // caller's responsibility to ensure that the current thread holds the
10072 // mutex when this is called.
10073 owner_thread_id_ = 0;
10074 ::LeaveCriticalSection(critical_section_);
10075}
10076
10077// Does nothing if the current thread holds the mutex. Otherwise, crashes
10078// with high probability.
10079void Mutex::AssertHeld() {
10080 ThreadSafeLazyInit();
10081 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
10082 << "The current thread is not holding the mutex @" << this;
10083}
10084
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010085namespace {
10086
10087// Use the RAII idiom to flag mem allocs that are intentionally never
10088// deallocated. The motivation is to silence the false positive mem leaks
10089// that are reported by the debug version of MS's CRT which can only detect
10090// if an alloc is missing a matching deallocation.
10091// Example:
10092// MemoryIsNotDeallocated memory_is_not_deallocated;
10093// critical_section_ = new CRITICAL_SECTION;
10094//
10095class MemoryIsNotDeallocated
10096{
10097 public:
10098 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
10099#ifdef _MSC_VER
10100 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10101 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
10102 // doesn't report mem leak if there's no matching deallocation.
10103 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10104#endif // _MSC_VER
10105 }
10106
10107 ~MemoryIsNotDeallocated() {
10108#ifdef _MSC_VER
10109 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
10110 _CrtSetDbgFlag(old_crtdbg_flag_);
10111#endif // _MSC_VER
10112 }
10113
10114 private:
10115 int old_crtdbg_flag_;
10116
10117 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
10118};
10119
10120} // namespace
10121
Austin Schuh70cc9552019-01-21 19:46:48 -080010122// Initializes owner_thread_id_ and critical_section_ in static mutexes.
10123void Mutex::ThreadSafeLazyInit() {
10124 // Dynamic mutexes are initialized in the constructor.
10125 if (type_ == kStatic) {
10126 switch (
10127 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10128 case 0:
10129 // If critical_section_init_phase_ was 0 before the exchange, we
10130 // are the first to test it and need to perform the initialization.
10131 owner_thread_id_ = 0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010132 {
10133 // Use RAII to flag that following mem alloc is never deallocated.
10134 MemoryIsNotDeallocated memory_is_not_deallocated;
10135 critical_section_ = new CRITICAL_SECTION;
10136 }
Austin Schuh70cc9552019-01-21 19:46:48 -080010137 ::InitializeCriticalSection(critical_section_);
10138 // Updates the critical_section_init_phase_ to 2 to signal
10139 // initialization complete.
10140 GTEST_CHECK_(::InterlockedCompareExchange(
10141 &critical_section_init_phase_, 2L, 1L) ==
10142 1L);
10143 break;
10144 case 1:
10145 // Somebody else is already initializing the mutex; spin until they
10146 // are done.
10147 while (::InterlockedCompareExchange(&critical_section_init_phase_,
10148 2L,
10149 2L) != 2L) {
10150 // Possibly yields the rest of the thread's time slice to other
10151 // threads.
10152 ::Sleep(0);
10153 }
10154 break;
10155
10156 case 2:
10157 break; // The mutex is already initialized and ready for use.
10158
10159 default:
10160 GTEST_CHECK_(false)
10161 << "Unexpected value of critical_section_init_phase_ "
10162 << "while initializing a static mutex.";
10163 }
10164 }
10165}
10166
10167namespace {
10168
10169class ThreadWithParamSupport : public ThreadWithParamBase {
10170 public:
10171 static HANDLE CreateThread(Runnable* runnable,
10172 Notification* thread_can_start) {
10173 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
10174 DWORD thread_id;
Austin Schuh70cc9552019-01-21 19:46:48 -080010175 HANDLE thread_handle = ::CreateThread(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010176 nullptr, // Default security.
10177 0, // Default stack size.
Austin Schuh70cc9552019-01-21 19:46:48 -080010178 &ThreadWithParamSupport::ThreadMain,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010179 param, // Parameter to ThreadMainStatic
10180 0x0, // Default creation flags.
Austin Schuh70cc9552019-01-21 19:46:48 -080010181 &thread_id); // Need a valid pointer for the call to work under Win98.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010182 GTEST_CHECK_(thread_handle != nullptr)
10183 << "CreateThread failed with error " << ::GetLastError() << ".";
10184 if (thread_handle == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010185 delete param;
10186 }
10187 return thread_handle;
10188 }
10189
10190 private:
10191 struct ThreadMainParam {
10192 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10193 : runnable_(runnable),
10194 thread_can_start_(thread_can_start) {
10195 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010196 std::unique_ptr<Runnable> runnable_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010197 // Does not own.
10198 Notification* thread_can_start_;
10199 };
10200
10201 static DWORD WINAPI ThreadMain(void* ptr) {
10202 // Transfers ownership.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010203 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10204 if (param->thread_can_start_ != nullptr)
Austin Schuh70cc9552019-01-21 19:46:48 -080010205 param->thread_can_start_->WaitForNotification();
10206 param->runnable_->Run();
10207 return 0;
10208 }
10209
10210 // Prohibit instantiation.
10211 ThreadWithParamSupport();
10212
10213 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
10214};
10215
10216} // namespace
10217
10218ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10219 Notification* thread_can_start)
10220 : thread_(ThreadWithParamSupport::CreateThread(runnable,
10221 thread_can_start)) {
10222}
10223
10224ThreadWithParamBase::~ThreadWithParamBase() {
10225 Join();
10226}
10227
10228void ThreadWithParamBase::Join() {
10229 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10230 << "Failed to join the thread with error " << ::GetLastError() << ".";
10231}
10232
10233// Maps a thread to a set of ThreadIdToThreadLocals that have values
10234// instantiated on that thread and notifies them when the thread exits. A
10235// ThreadLocal instance is expected to persist until all threads it has
10236// values on have terminated.
10237class ThreadLocalRegistryImpl {
10238 public:
10239 // Registers thread_local_instance as having value on the current thread.
10240 // Returns a value that can be used to identify the thread from other threads.
10241 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10242 const ThreadLocalBase* thread_local_instance) {
10243 DWORD current_thread = ::GetCurrentThreadId();
10244 MutexLock lock(&mutex_);
10245 ThreadIdToThreadLocals* const thread_to_thread_locals =
10246 GetThreadLocalsMapLocked();
10247 ThreadIdToThreadLocals::iterator thread_local_pos =
10248 thread_to_thread_locals->find(current_thread);
10249 if (thread_local_pos == thread_to_thread_locals->end()) {
10250 thread_local_pos = thread_to_thread_locals->insert(
10251 std::make_pair(current_thread, ThreadLocalValues())).first;
10252 StartWatcherThreadFor(current_thread);
10253 }
10254 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10255 ThreadLocalValues::iterator value_pos =
10256 thread_local_values.find(thread_local_instance);
10257 if (value_pos == thread_local_values.end()) {
10258 value_pos =
10259 thread_local_values
10260 .insert(std::make_pair(
10261 thread_local_instance,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010262 std::shared_ptr<ThreadLocalValueHolderBase>(
Austin Schuh70cc9552019-01-21 19:46:48 -080010263 thread_local_instance->NewValueForCurrentThread())))
10264 .first;
10265 }
10266 return value_pos->second.get();
10267 }
10268
10269 static void OnThreadLocalDestroyed(
10270 const ThreadLocalBase* thread_local_instance) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010271 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
Austin Schuh70cc9552019-01-21 19:46:48 -080010272 // Clean up the ThreadLocalValues data structure while holding the lock, but
10273 // defer the destruction of the ThreadLocalValueHolderBases.
10274 {
10275 MutexLock lock(&mutex_);
10276 ThreadIdToThreadLocals* const thread_to_thread_locals =
10277 GetThreadLocalsMapLocked();
10278 for (ThreadIdToThreadLocals::iterator it =
10279 thread_to_thread_locals->begin();
10280 it != thread_to_thread_locals->end();
10281 ++it) {
10282 ThreadLocalValues& thread_local_values = it->second;
10283 ThreadLocalValues::iterator value_pos =
10284 thread_local_values.find(thread_local_instance);
10285 if (value_pos != thread_local_values.end()) {
10286 value_holders.push_back(value_pos->second);
10287 thread_local_values.erase(value_pos);
10288 // This 'if' can only be successful at most once, so theoretically we
10289 // could break out of the loop here, but we don't bother doing so.
10290 }
10291 }
10292 }
10293 // Outside the lock, let the destructor for 'value_holders' deallocate the
10294 // ThreadLocalValueHolderBases.
10295 }
10296
10297 static void OnThreadExit(DWORD thread_id) {
10298 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010299 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
Austin Schuh70cc9552019-01-21 19:46:48 -080010300 // Clean up the ThreadIdToThreadLocals data structure while holding the
10301 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
10302 {
10303 MutexLock lock(&mutex_);
10304 ThreadIdToThreadLocals* const thread_to_thread_locals =
10305 GetThreadLocalsMapLocked();
10306 ThreadIdToThreadLocals::iterator thread_local_pos =
10307 thread_to_thread_locals->find(thread_id);
10308 if (thread_local_pos != thread_to_thread_locals->end()) {
10309 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10310 for (ThreadLocalValues::iterator value_pos =
10311 thread_local_values.begin();
10312 value_pos != thread_local_values.end();
10313 ++value_pos) {
10314 value_holders.push_back(value_pos->second);
10315 }
10316 thread_to_thread_locals->erase(thread_local_pos);
10317 }
10318 }
10319 // Outside the lock, let the destructor for 'value_holders' deallocate the
10320 // ThreadLocalValueHolderBases.
10321 }
10322
10323 private:
10324 // In a particular thread, maps a ThreadLocal object to its value.
10325 typedef std::map<const ThreadLocalBase*,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010326 std::shared_ptr<ThreadLocalValueHolderBase> >
10327 ThreadLocalValues;
Austin Schuh70cc9552019-01-21 19:46:48 -080010328 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
10329 // thread's ID.
10330 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10331
10332 // Holds the thread id and thread handle that we pass from
10333 // StartWatcherThreadFor to WatcherThreadFunc.
10334 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10335
10336 static void StartWatcherThreadFor(DWORD thread_id) {
10337 // The returned handle will be kept in thread_map and closed by
10338 // watcher_thread in WatcherThreadFunc.
10339 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10340 FALSE,
10341 thread_id);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010342 GTEST_CHECK_(thread != nullptr);
10343 // We need to pass a valid thread ID pointer into CreateThread for it
Austin Schuh70cc9552019-01-21 19:46:48 -080010344 // to work correctly under Win98.
10345 DWORD watcher_thread_id;
10346 HANDLE watcher_thread = ::CreateThread(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010347 nullptr, // Default security.
10348 0, // Default stack size
Austin Schuh70cc9552019-01-21 19:46:48 -080010349 &ThreadLocalRegistryImpl::WatcherThreadFunc,
10350 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010351 CREATE_SUSPENDED, &watcher_thread_id);
10352 GTEST_CHECK_(watcher_thread != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -080010353 // Give the watcher thread the same priority as ours to avoid being
10354 // blocked by it.
10355 ::SetThreadPriority(watcher_thread,
10356 ::GetThreadPriority(::GetCurrentThread()));
10357 ::ResumeThread(watcher_thread);
10358 ::CloseHandle(watcher_thread);
10359 }
10360
10361 // Monitors exit from a given thread and notifies those
10362 // ThreadIdToThreadLocals about thread termination.
10363 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10364 const ThreadIdAndHandle* tah =
10365 reinterpret_cast<const ThreadIdAndHandle*>(param);
10366 GTEST_CHECK_(
10367 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10368 OnThreadExit(tah->first);
10369 ::CloseHandle(tah->second);
10370 delete tah;
10371 return 0;
10372 }
10373
10374 // Returns map of thread local instances.
10375 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
10376 mutex_.AssertHeld();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010377 MemoryIsNotDeallocated memory_is_not_deallocated;
10378 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
Austin Schuh70cc9552019-01-21 19:46:48 -080010379 return map;
10380 }
10381
10382 // Protects access to GetThreadLocalsMapLocked() and its return value.
10383 static Mutex mutex_;
10384 // Protects access to GetThreadMapLocked() and its return value.
10385 static Mutex thread_map_mutex_;
10386};
10387
10388Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10389Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10390
10391ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10392 const ThreadLocalBase* thread_local_instance) {
10393 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10394 thread_local_instance);
10395}
10396
10397void ThreadLocalRegistry::OnThreadLocalDestroyed(
10398 const ThreadLocalBase* thread_local_instance) {
10399 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10400}
10401
10402#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10403
10404#if GTEST_USES_POSIX_RE
10405
10406// Implements RE. Currently only needed for death tests.
10407
10408RE::~RE() {
10409 if (is_valid_) {
10410 // regfree'ing an invalid regex might crash because the content
10411 // of the regex is undefined. Since the regex's are essentially
10412 // the same, one cannot be valid (or invalid) without the other
10413 // being so too.
10414 regfree(&partial_regex_);
10415 regfree(&full_regex_);
10416 }
10417 free(const_cast<char*>(pattern_));
10418}
10419
10420// Returns true iff regular expression re matches the entire str.
10421bool RE::FullMatch(const char* str, const RE& re) {
10422 if (!re.is_valid_) return false;
10423
10424 regmatch_t match;
10425 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10426}
10427
10428// Returns true iff regular expression re matches a substring of str
10429// (including str itself).
10430bool RE::PartialMatch(const char* str, const RE& re) {
10431 if (!re.is_valid_) return false;
10432
10433 regmatch_t match;
10434 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10435}
10436
10437// Initializes an RE from its string representation.
10438void RE::Init(const char* regex) {
10439 pattern_ = posix::StrDup(regex);
10440
10441 // Reserves enough bytes to hold the regular expression used for a
10442 // full match.
10443 const size_t full_regex_len = strlen(regex) + 10;
10444 char* const full_pattern = new char[full_regex_len];
10445
10446 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
10447 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10448 // We want to call regcomp(&partial_regex_, ...) even if the
10449 // previous expression returns false. Otherwise partial_regex_ may
10450 // not be properly initialized can may cause trouble when it's
10451 // freed.
10452 //
10453 // Some implementation of POSIX regex (e.g. on at least some
10454 // versions of Cygwin) doesn't accept the empty string as a valid
10455 // regex. We change it to an equivalent form "()" to be safe.
10456 if (is_valid_) {
10457 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
10458 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10459 }
10460 EXPECT_TRUE(is_valid_)
10461 << "Regular expression \"" << regex
10462 << "\" is not a valid POSIX Extended regular expression.";
10463
10464 delete[] full_pattern;
10465}
10466
10467#elif GTEST_USES_SIMPLE_RE
10468
10469// Returns true iff ch appears anywhere in str (excluding the
10470// terminating '\0' character).
10471bool IsInSet(char ch, const char* str) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010472 return ch != '\0' && strchr(str, ch) != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010473}
10474
10475// Returns true iff ch belongs to the given classification. Unlike
10476// similar functions in <ctype.h>, these aren't affected by the
10477// current locale.
10478bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
10479bool IsAsciiPunct(char ch) {
10480 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10481}
10482bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
10483bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
10484bool IsAsciiWordChar(char ch) {
10485 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
10486 ('0' <= ch && ch <= '9') || ch == '_';
10487}
10488
10489// Returns true iff "\\c" is a supported escape sequence.
10490bool IsValidEscape(char c) {
10491 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
10492}
10493
10494// Returns true iff the given atom (specified by escaped and pattern)
10495// matches ch. The result is undefined if the atom is invalid.
10496bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
10497 if (escaped) { // "\\p" where p is pattern_char.
10498 switch (pattern_char) {
10499 case 'd': return IsAsciiDigit(ch);
10500 case 'D': return !IsAsciiDigit(ch);
10501 case 'f': return ch == '\f';
10502 case 'n': return ch == '\n';
10503 case 'r': return ch == '\r';
10504 case 's': return IsAsciiWhiteSpace(ch);
10505 case 'S': return !IsAsciiWhiteSpace(ch);
10506 case 't': return ch == '\t';
10507 case 'v': return ch == '\v';
10508 case 'w': return IsAsciiWordChar(ch);
10509 case 'W': return !IsAsciiWordChar(ch);
10510 }
10511 return IsAsciiPunct(pattern_char) && pattern_char == ch;
10512 }
10513
10514 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
10515}
10516
10517// Helper function used by ValidateRegex() to format error messages.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010518static std::string FormatRegexSyntaxError(const char* regex, int index) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010519 return (Message() << "Syntax error at index " << index
10520 << " in simple regular expression \"" << regex << "\": ").GetString();
10521}
10522
10523// Generates non-fatal failures and returns false if regex is invalid;
10524// otherwise returns true.
10525bool ValidateRegex(const char* regex) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010526 if (regex == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010527 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
10528 return false;
10529 }
10530
10531 bool is_valid = true;
10532
10533 // True iff ?, *, or + can follow the previous atom.
10534 bool prev_repeatable = false;
10535 for (int i = 0; regex[i]; i++) {
10536 if (regex[i] == '\\') { // An escape sequence
10537 i++;
10538 if (regex[i] == '\0') {
10539 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10540 << "'\\' cannot appear at the end.";
10541 return false;
10542 }
10543
10544 if (!IsValidEscape(regex[i])) {
10545 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10546 << "invalid escape sequence \"\\" << regex[i] << "\".";
10547 is_valid = false;
10548 }
10549 prev_repeatable = true;
10550 } else { // Not an escape sequence.
10551 const char ch = regex[i];
10552
10553 if (ch == '^' && i > 0) {
10554 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10555 << "'^' can only appear at the beginning.";
10556 is_valid = false;
10557 } else if (ch == '$' && regex[i + 1] != '\0') {
10558 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10559 << "'$' can only appear at the end.";
10560 is_valid = false;
10561 } else if (IsInSet(ch, "()[]{}|")) {
10562 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10563 << "'" << ch << "' is unsupported.";
10564 is_valid = false;
10565 } else if (IsRepeat(ch) && !prev_repeatable) {
10566 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10567 << "'" << ch << "' can only follow a repeatable token.";
10568 is_valid = false;
10569 }
10570
10571 prev_repeatable = !IsInSet(ch, "^$?*+");
10572 }
10573 }
10574
10575 return is_valid;
10576}
10577
10578// Matches a repeated regex atom followed by a valid simple regular
10579// expression. The regex atom is defined as c if escaped is false,
10580// or \c otherwise. repeat is the repetition meta character (?, *,
10581// or +). The behavior is undefined if str contains too many
10582// characters to be indexable by size_t, in which case the test will
10583// probably time out anyway. We are fine with this limitation as
10584// std::string has it too.
10585bool MatchRepetitionAndRegexAtHead(
10586 bool escaped, char c, char repeat, const char* regex,
10587 const char* str) {
10588 const size_t min_count = (repeat == '+') ? 1 : 0;
10589 const size_t max_count = (repeat == '?') ? 1 :
10590 static_cast<size_t>(-1) - 1;
10591 // We cannot call numeric_limits::max() as it conflicts with the
10592 // max() macro on Windows.
10593
10594 for (size_t i = 0; i <= max_count; ++i) {
10595 // We know that the atom matches each of the first i characters in str.
10596 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10597 // We have enough matches at the head, and the tail matches too.
10598 // Since we only care about *whether* the pattern matches str
10599 // (as opposed to *how* it matches), there is no need to find a
10600 // greedy match.
10601 return true;
10602 }
10603 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
10604 return false;
10605 }
10606 return false;
10607}
10608
10609// Returns true iff regex matches a prefix of str. regex must be a
10610// valid simple regular expression and not start with "^", or the
10611// result is undefined.
10612bool MatchRegexAtHead(const char* regex, const char* str) {
10613 if (*regex == '\0') // An empty regex matches a prefix of anything.
10614 return true;
10615
10616 // "$" only matches the end of a string. Note that regex being
10617 // valid guarantees that there's nothing after "$" in it.
10618 if (*regex == '$')
10619 return *str == '\0';
10620
10621 // Is the first thing in regex an escape sequence?
10622 const bool escaped = *regex == '\\';
10623 if (escaped)
10624 ++regex;
10625 if (IsRepeat(regex[1])) {
10626 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
10627 // here's an indirect recursion. It terminates as the regex gets
10628 // shorter in each recursion.
10629 return MatchRepetitionAndRegexAtHead(
10630 escaped, regex[0], regex[1], regex + 2, str);
10631 } else {
10632 // regex isn't empty, isn't "$", and doesn't start with a
10633 // repetition. We match the first atom of regex with the first
10634 // character of str and recurse.
10635 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
10636 MatchRegexAtHead(regex + 1, str + 1);
10637 }
10638}
10639
10640// Returns true iff regex matches any substring of str. regex must be
10641// a valid simple regular expression, or the result is undefined.
10642//
10643// The algorithm is recursive, but the recursion depth doesn't exceed
10644// the regex length, so we won't need to worry about running out of
10645// stack space normally. In rare cases the time complexity can be
10646// exponential with respect to the regex length + the string length,
10647// but usually it's must faster (often close to linear).
10648bool MatchRegexAnywhere(const char* regex, const char* str) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010649 if (regex == nullptr || str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -080010650
10651 if (*regex == '^')
10652 return MatchRegexAtHead(regex + 1, str);
10653
10654 // A successful match can be anywhere in str.
10655 do {
10656 if (MatchRegexAtHead(regex, str))
10657 return true;
10658 } while (*str++ != '\0');
10659 return false;
10660}
10661
10662// Implements the RE class.
10663
10664RE::~RE() {
10665 free(const_cast<char*>(pattern_));
10666 free(const_cast<char*>(full_pattern_));
10667}
10668
10669// Returns true iff regular expression re matches the entire str.
10670bool RE::FullMatch(const char* str, const RE& re) {
10671 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10672}
10673
10674// Returns true iff regular expression re matches a substring of str
10675// (including str itself).
10676bool RE::PartialMatch(const char* str, const RE& re) {
10677 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10678}
10679
10680// Initializes an RE from its string representation.
10681void RE::Init(const char* regex) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010682 pattern_ = full_pattern_ = nullptr;
10683 if (regex != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010684 pattern_ = posix::StrDup(regex);
10685 }
10686
10687 is_valid_ = ValidateRegex(regex);
10688 if (!is_valid_) {
10689 // No need to calculate the full pattern when the regex is invalid.
10690 return;
10691 }
10692
10693 const size_t len = strlen(regex);
10694 // Reserves enough bytes to hold the regular expression used for a
10695 // full match: we need space to prepend a '^', append a '$', and
10696 // terminate the string with '\0'.
10697 char* buffer = static_cast<char*>(malloc(len + 3));
10698 full_pattern_ = buffer;
10699
10700 if (*regex != '^')
10701 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
10702
10703 // We don't use snprintf or strncpy, as they trigger a warning when
10704 // compiled with VC++ 8.0.
10705 memcpy(buffer, regex, len);
10706 buffer += len;
10707
10708 if (len == 0 || regex[len - 1] != '$')
10709 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
10710
10711 *buffer = '\0';
10712}
10713
10714#endif // GTEST_USES_POSIX_RE
10715
10716const char kUnknownFile[] = "unknown file";
10717
10718// Formats a source file path and a line number as they would appear
10719// in an error message from the compiler used to compile this code.
10720GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010721 const std::string file_name(file == nullptr ? kUnknownFile : file);
Austin Schuh70cc9552019-01-21 19:46:48 -080010722
10723 if (line < 0) {
10724 return file_name + ":";
10725 }
10726#ifdef _MSC_VER
10727 return file_name + "(" + StreamableToString(line) + "):";
10728#else
10729 return file_name + ":" + StreamableToString(line) + ":";
10730#endif // _MSC_VER
10731}
10732
10733// Formats a file location for compiler-independent XML output.
10734// Although this function is not platform dependent, we put it next to
10735// FormatFileLocation in order to contrast the two functions.
10736// Note that FormatCompilerIndependentFileLocation() does NOT append colon
10737// to the file location it produces, unlike FormatFileLocation().
10738GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
10739 const char* file, int line) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010740 const std::string file_name(file == nullptr ? kUnknownFile : file);
Austin Schuh70cc9552019-01-21 19:46:48 -080010741
10742 if (line < 0)
10743 return file_name;
10744 else
10745 return file_name + ":" + StreamableToString(line);
10746}
10747
10748GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
10749 : severity_(severity) {
10750 const char* const marker =
10751 severity == GTEST_INFO ? "[ INFO ]" :
10752 severity == GTEST_WARNING ? "[WARNING]" :
10753 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
10754 GetStream() << ::std::endl << marker << " "
10755 << FormatFileLocation(file, line).c_str() << ": ";
10756}
10757
10758// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
10759GTestLog::~GTestLog() {
10760 GetStream() << ::std::endl;
10761 if (severity_ == GTEST_FATAL) {
10762 fflush(stderr);
10763 posix::Abort();
10764 }
10765}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010766
Austin Schuh70cc9552019-01-21 19:46:48 -080010767// Disable Microsoft deprecation warnings for POSIX functions called from
10768// this class (creat, dup, dup2, and close)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010769GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
Austin Schuh70cc9552019-01-21 19:46:48 -080010770
10771#if GTEST_HAS_STREAM_REDIRECTION
10772
10773// Object that captures an output stream (stdout/stderr).
10774class CapturedStream {
10775 public:
10776 // The ctor redirects the stream to a temporary file.
10777 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
10778# if GTEST_OS_WINDOWS
10779 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10780 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10781
10782 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
10783 const UINT success = ::GetTempFileNameA(temp_dir_path,
10784 "gtest_redir",
10785 0, // Generate unique file name.
10786 temp_file_path);
10787 GTEST_CHECK_(success != 0)
10788 << "Unable to create a temporary file in " << temp_dir_path;
10789 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10790 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
10791 << temp_file_path;
10792 filename_ = temp_file_path;
10793# else
10794 // There's no guarantee that a test has write access to the current
10795 // directory, so we create the temporary file in the /tmp directory
10796 // instead. We use /tmp on most systems, and /sdcard on Android.
10797 // That's because Android doesn't have /tmp.
10798# if GTEST_OS_LINUX_ANDROID
10799 // Note: Android applications are expected to call the framework's
10800 // Context.getExternalStorageDirectory() method through JNI to get
10801 // the location of the world-writable SD Card directory. However,
10802 // this requires a Context handle, which cannot be retrieved
10803 // globally from native code. Doing so also precludes running the
10804 // code as part of a regular standalone executable, which doesn't
10805 // run in a Dalvik process (e.g. when running it through 'adb shell').
10806 //
10807 // The location /sdcard is directly accessible from native code
10808 // and is the only location (unofficially) supported by the Android
10809 // team. It's generally a symlink to the real SD Card mount point
10810 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
10811 // other OEM-customized locations. Never rely on these, and always
10812 // use /sdcard.
10813 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
10814# else
10815 char name_template[] = "/tmp/captured_stream.XXXXXX";
10816# endif // GTEST_OS_LINUX_ANDROID
10817 const int captured_fd = mkstemp(name_template);
10818 filename_ = name_template;
10819# endif // GTEST_OS_WINDOWS
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010820 fflush(nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -080010821 dup2(captured_fd, fd_);
10822 close(captured_fd);
10823 }
10824
10825 ~CapturedStream() {
10826 remove(filename_.c_str());
10827 }
10828
10829 std::string GetCapturedString() {
10830 if (uncaptured_fd_ != -1) {
10831 // Restores the original stream.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010832 fflush(nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -080010833 dup2(uncaptured_fd_, fd_);
10834 close(uncaptured_fd_);
10835 uncaptured_fd_ = -1;
10836 }
10837
10838 FILE* const file = posix::FOpen(filename_.c_str(), "r");
10839 const std::string content = ReadEntireFile(file);
10840 posix::FClose(file);
10841 return content;
10842 }
10843
10844 private:
10845 const int fd_; // A stream to capture.
10846 int uncaptured_fd_;
10847 // Name of the temporary file holding the stderr output.
10848 ::std::string filename_;
10849
10850 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
10851};
10852
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010853GTEST_DISABLE_MSC_DEPRECATED_POP_()
Austin Schuh70cc9552019-01-21 19:46:48 -080010854
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010855static CapturedStream* g_captured_stderr = nullptr;
10856static CapturedStream* g_captured_stdout = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010857
10858// Starts capturing an output stream (stdout/stderr).
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010859static void CaptureStream(int fd, const char* stream_name,
10860 CapturedStream** stream) {
10861 if (*stream != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010862 GTEST_LOG_(FATAL) << "Only one " << stream_name
10863 << " capturer can exist at a time.";
10864 }
10865 *stream = new CapturedStream(fd);
10866}
10867
10868// Stops capturing the output stream and returns the captured string.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010869static std::string GetCapturedStream(CapturedStream** captured_stream) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010870 const std::string content = (*captured_stream)->GetCapturedString();
10871
10872 delete *captured_stream;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010873 *captured_stream = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010874
10875 return content;
10876}
10877
10878// Starts capturing stdout.
10879void CaptureStdout() {
10880 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
10881}
10882
10883// Starts capturing stderr.
10884void CaptureStderr() {
10885 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
10886}
10887
10888// Stops capturing stdout and returns the captured string.
10889std::string GetCapturedStdout() {
10890 return GetCapturedStream(&g_captured_stdout);
10891}
10892
10893// Stops capturing stderr and returns the captured string.
10894std::string GetCapturedStderr() {
10895 return GetCapturedStream(&g_captured_stderr);
10896}
10897
10898#endif // GTEST_HAS_STREAM_REDIRECTION
10899
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010900
10901
10902
Austin Schuh70cc9552019-01-21 19:46:48 -080010903
10904size_t GetFileSize(FILE* file) {
10905 fseek(file, 0, SEEK_END);
10906 return static_cast<size_t>(ftell(file));
10907}
10908
10909std::string ReadEntireFile(FILE* file) {
10910 const size_t file_size = GetFileSize(file);
10911 char* const buffer = new char[file_size];
10912
10913 size_t bytes_last_read = 0; // # of bytes read in the last fread()
10914 size_t bytes_read = 0; // # of bytes read so far
10915
10916 fseek(file, 0, SEEK_SET);
10917
10918 // Keeps reading the file until we cannot read further or the
10919 // pre-determined file size is reached.
10920 do {
10921 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10922 bytes_read += bytes_last_read;
10923 } while (bytes_last_read > 0 && bytes_read < file_size);
10924
10925 const std::string content(buffer, bytes_read);
10926 delete[] buffer;
10927
10928 return content;
10929}
10930
10931#if GTEST_HAS_DEATH_TEST
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010932static const std::vector<std::string>* g_injected_test_argvs =
10933 nullptr; // Owned.
Austin Schuh70cc9552019-01-21 19:46:48 -080010934
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010935std::vector<std::string> GetInjectableArgvs() {
10936 if (g_injected_test_argvs != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080010937 return *g_injected_test_argvs;
10938 }
10939 return GetArgvs();
10940}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010941
10942void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
10943 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
10944 g_injected_test_argvs = new_argvs;
10945}
10946
10947void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
10948 SetInjectableArgvs(
10949 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10950}
10951
10952#if GTEST_HAS_GLOBAL_STRING
10953void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
10954 SetInjectableArgvs(
10955 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10956}
10957#endif // GTEST_HAS_GLOBAL_STRING
10958
10959void ClearInjectableArgvs() {
10960 delete g_injected_test_argvs;
10961 g_injected_test_argvs = nullptr;
10962}
Austin Schuh70cc9552019-01-21 19:46:48 -080010963#endif // GTEST_HAS_DEATH_TEST
10964
10965#if GTEST_OS_WINDOWS_MOBILE
10966namespace posix {
10967void Abort() {
10968 DebugBreak();
10969 TerminateProcess(GetCurrentProcess(), 1);
10970}
10971} // namespace posix
10972#endif // GTEST_OS_WINDOWS_MOBILE
10973
10974// Returns the name of the environment variable corresponding to the
10975// given flag. For example, FlagToEnvVar("foo") will return
10976// "GTEST_FOO" in the open-source version.
10977static std::string FlagToEnvVar(const char* flag) {
10978 const std::string full_flag =
10979 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
10980
10981 Message env_var;
10982 for (size_t i = 0; i != full_flag.length(); i++) {
10983 env_var << ToUpper(full_flag.c_str()[i]);
10984 }
10985
10986 return env_var.GetString();
10987}
10988
10989// Parses 'str' for a 32-bit signed integer. If successful, writes
10990// the result to *value and returns true; otherwise leaves *value
10991// unchanged and returns false.
10992bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
10993 // Parses the environment variable as a decimal integer.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010994 char* end = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010995 const long long_value = strtol(str, &end, 10); // NOLINT
10996
10997 // Has strtol() consumed all characters in the string?
10998 if (*end != '\0') {
10999 // No - an invalid character was encountered.
11000 Message msg;
11001 msg << "WARNING: " << src_text
11002 << " is expected to be a 32-bit integer, but actually"
11003 << " has value \"" << str << "\".\n";
11004 printf("%s", msg.GetString().c_str());
11005 fflush(stdout);
11006 return false;
11007 }
11008
11009 // Is the parsed value in the range of an Int32?
11010 const Int32 result = static_cast<Int32>(long_value);
11011 if (long_value == LONG_MAX || long_value == LONG_MIN ||
11012 // The parsed value overflows as a long. (strtol() returns
11013 // LONG_MAX or LONG_MIN when the input overflows.)
11014 result != long_value
11015 // The parsed value overflows as an Int32.
11016 ) {
11017 Message msg;
11018 msg << "WARNING: " << src_text
11019 << " is expected to be a 32-bit integer, but actually"
11020 << " has value " << str << ", which overflows.\n";
11021 printf("%s", msg.GetString().c_str());
11022 fflush(stdout);
11023 return false;
11024 }
11025
11026 *value = result;
11027 return true;
11028}
11029
11030// Reads and returns the Boolean environment variable corresponding to
11031// the given flag; if it's not set, returns default_value.
11032//
11033// The value is considered true iff it's not "0".
11034bool BoolFromGTestEnv(const char* flag, bool default_value) {
11035#if defined(GTEST_GET_BOOL_FROM_ENV_)
11036 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011037#else
Austin Schuh70cc9552019-01-21 19:46:48 -080011038 const std::string env_var = FlagToEnvVar(flag);
11039 const char* const string_value = posix::GetEnv(env_var.c_str());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011040 return string_value == nullptr ? default_value
11041 : strcmp(string_value, "0") != 0;
11042#endif // defined(GTEST_GET_BOOL_FROM_ENV_)
Austin Schuh70cc9552019-01-21 19:46:48 -080011043}
11044
11045// Reads and returns a 32-bit integer stored in the environment
11046// variable corresponding to the given flag; if it isn't set or
11047// doesn't represent a valid 32-bit integer, returns default_value.
11048Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
11049#if defined(GTEST_GET_INT32_FROM_ENV_)
11050 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011051#else
Austin Schuh70cc9552019-01-21 19:46:48 -080011052 const std::string env_var = FlagToEnvVar(flag);
11053 const char* const string_value = posix::GetEnv(env_var.c_str());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011054 if (string_value == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011055 // The environment variable is not set.
11056 return default_value;
11057 }
11058
11059 Int32 result = default_value;
11060 if (!ParseInt32(Message() << "Environment variable " << env_var,
11061 string_value, &result)) {
11062 printf("The default value %s is used.\n",
11063 (Message() << default_value).GetString().c_str());
11064 fflush(stdout);
11065 return default_value;
11066 }
11067
11068 return result;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011069#endif // defined(GTEST_GET_INT32_FROM_ENV_)
11070}
11071
11072// As a special case for the 'output' flag, if GTEST_OUTPUT is not
11073// set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
11074// system. The value of XML_OUTPUT_FILE is a filename without the
11075// "xml:" prefix of GTEST_OUTPUT.
11076// Note that this is meant to be called at the call site so it does
11077// not check that the flag is 'output'
11078// In essence this checks an env variable called XML_OUTPUT_FILE
11079// and if it is set we prepend "xml:" to its value, if it not set we return ""
11080std::string OutputFlagAlsoCheckEnvVar(){
11081 std::string default_value_for_output_flag = "";
11082 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
11083 if (nullptr != xml_output_file_env) {
11084 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
11085 }
11086 return default_value_for_output_flag;
Austin Schuh70cc9552019-01-21 19:46:48 -080011087}
11088
11089// Reads and returns the string environment variable corresponding to
11090// the given flag; if it's not set, returns default_value.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011091const char* StringFromGTestEnv(const char* flag, const char* default_value) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011092#if defined(GTEST_GET_STRING_FROM_ENV_)
11093 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011094#else
Austin Schuh70cc9552019-01-21 19:46:48 -080011095 const std::string env_var = FlagToEnvVar(flag);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011096 const char* const value = posix::GetEnv(env_var.c_str());
11097 return value == nullptr ? default_value : value;
11098#endif // defined(GTEST_GET_STRING_FROM_ENV_)
Austin Schuh70cc9552019-01-21 19:46:48 -080011099}
11100
11101} // namespace internal
11102} // namespace testing
11103// Copyright 2007, Google Inc.
11104// All rights reserved.
11105//
11106// Redistribution and use in source and binary forms, with or without
11107// modification, are permitted provided that the following conditions are
11108// met:
11109//
11110// * Redistributions of source code must retain the above copyright
11111// notice, this list of conditions and the following disclaimer.
11112// * Redistributions in binary form must reproduce the above
11113// copyright notice, this list of conditions and the following disclaimer
11114// in the documentation and/or other materials provided with the
11115// distribution.
11116// * Neither the name of Google Inc. nor the names of its
11117// contributors may be used to endorse or promote products derived from
11118// this software without specific prior written permission.
11119//
11120// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11121// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11122// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11123// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11124// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11125// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11126// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11127// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11128// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11129// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11130// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh70cc9552019-01-21 19:46:48 -080011131
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011132
11133// Google Test - The Google C++ Testing and Mocking Framework
Austin Schuh70cc9552019-01-21 19:46:48 -080011134//
11135// This file implements a universal value printer that can print a
11136// value of any type T:
11137//
11138// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
11139//
11140// It uses the << operator when possible, and prints the bytes in the
11141// object otherwise. A user can override its behavior for a class
11142// type Foo by defining either operator<<(::std::ostream&, const Foo&)
11143// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
11144// defines Foo.
11145
Austin Schuh70cc9552019-01-21 19:46:48 -080011146#include <stdio.h>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011147#include <cctype>
Austin Schuh70cc9552019-01-21 19:46:48 -080011148#include <cwchar>
11149#include <ostream> // NOLINT
11150#include <string>
11151
11152namespace testing {
11153
11154namespace {
11155
11156using ::std::ostream;
11157
11158// Prints a segment of bytes in the given object.
11159GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11160GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11161GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
11162void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
11163 size_t count, ostream* os) {
11164 char text[5] = "";
11165 for (size_t i = 0; i != count; i++) {
11166 const size_t j = start + i;
11167 if (i != 0) {
11168 // Organizes the bytes into groups of 2 for easy parsing by
11169 // human.
11170 if ((j % 2) == 0)
11171 *os << ' ';
11172 else
11173 *os << '-';
11174 }
11175 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
11176 *os << text;
11177 }
11178}
11179
11180// Prints the bytes in the given value to the given ostream.
11181void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
11182 ostream* os) {
11183 // Tells the user how big the object is.
11184 *os << count << "-byte object <";
11185
11186 const size_t kThreshold = 132;
11187 const size_t kChunkSize = 64;
11188 // If the object size is bigger than kThreshold, we'll have to omit
11189 // some details by printing only the first and the last kChunkSize
11190 // bytes.
Austin Schuh70cc9552019-01-21 19:46:48 -080011191 if (count < kThreshold) {
11192 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
11193 } else {
11194 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11195 *os << " ... ";
11196 // Rounds up to 2-byte boundary.
11197 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
11198 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
11199 }
11200 *os << ">";
11201}
11202
11203} // namespace
11204
11205namespace internal2 {
11206
11207// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
11208// given object. The delegation simplifies the implementation, which
11209// uses the << operator and thus is easier done outside of the
11210// ::testing::internal namespace, which contains a << operator that
11211// sometimes conflicts with the one in STL.
11212void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
11213 ostream* os) {
11214 PrintBytesInObjectToImpl(obj_bytes, count, os);
11215}
11216
11217} // namespace internal2
11218
11219namespace internal {
11220
11221// Depending on the value of a char (or wchar_t), we print it in one
11222// of three formats:
11223// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011224// - as a hexadecimal escape sequence (e.g. '\x7F'), or
Austin Schuh70cc9552019-01-21 19:46:48 -080011225// - as a special escape sequence (e.g. '\r', '\n').
11226enum CharFormat {
11227 kAsIs,
11228 kHexEscape,
11229 kSpecialEscape
11230};
11231
11232// Returns true if c is a printable ASCII character. We test the
11233// value of c directly instead of calling isprint(), which is buggy on
11234// Windows Mobile.
11235inline bool IsPrintableAscii(wchar_t c) {
11236 return 0x20 <= c && c <= 0x7E;
11237}
11238
11239// Prints a wide or narrow char c as a character literal without the
11240// quotes, escaping it when necessary; returns how c was formatted.
11241// The template argument UnsignedChar is the unsigned version of Char,
11242// which is the type of c.
11243template <typename UnsignedChar, typename Char>
11244static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11245 switch (static_cast<wchar_t>(c)) {
11246 case L'\0':
11247 *os << "\\0";
11248 break;
11249 case L'\'':
11250 *os << "\\'";
11251 break;
11252 case L'\\':
11253 *os << "\\\\";
11254 break;
11255 case L'\a':
11256 *os << "\\a";
11257 break;
11258 case L'\b':
11259 *os << "\\b";
11260 break;
11261 case L'\f':
11262 *os << "\\f";
11263 break;
11264 case L'\n':
11265 *os << "\\n";
11266 break;
11267 case L'\r':
11268 *os << "\\r";
11269 break;
11270 case L'\t':
11271 *os << "\\t";
11272 break;
11273 case L'\v':
11274 *os << "\\v";
11275 break;
11276 default:
11277 if (IsPrintableAscii(c)) {
11278 *os << static_cast<char>(c);
11279 return kAsIs;
11280 } else {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011281 ostream::fmtflags flags = os->flags();
11282 *os << "\\x" << std::hex << std::uppercase
11283 << static_cast<int>(static_cast<UnsignedChar>(c));
11284 os->flags(flags);
Austin Schuh70cc9552019-01-21 19:46:48 -080011285 return kHexEscape;
11286 }
11287 }
11288 return kSpecialEscape;
11289}
11290
11291// Prints a wchar_t c as if it's part of a string literal, escaping it when
11292// necessary; returns how c was formatted.
11293static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
11294 switch (c) {
11295 case L'\'':
11296 *os << "'";
11297 return kAsIs;
11298 case L'"':
11299 *os << "\\\"";
11300 return kSpecialEscape;
11301 default:
11302 return PrintAsCharLiteralTo<wchar_t>(c, os);
11303 }
11304}
11305
11306// Prints a char c as if it's part of a string literal, escaping it when
11307// necessary; returns how c was formatted.
11308static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
11309 return PrintAsStringLiteralTo(
11310 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
11311}
11312
11313// Prints a wide or narrow character c and its code. '\0' is printed
11314// as "'\\0'", other unprintable characters are also properly escaped
11315// using the standard C++ escape sequence. The template argument
11316// UnsignedChar is the unsigned version of Char, which is the type of c.
11317template <typename UnsignedChar, typename Char>
11318void PrintCharAndCodeTo(Char c, ostream* os) {
11319 // First, print c as a literal in the most readable form we can find.
11320 *os << ((sizeof(c) > 1) ? "L'" : "'");
11321 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
11322 *os << "'";
11323
11324 // To aid user debugging, we also print c's code in decimal, unless
11325 // it's 0 (in which case c was printed as '\\0', making the code
11326 // obvious).
11327 if (c == 0)
11328 return;
11329 *os << " (" << static_cast<int>(c);
11330
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011331 // For more convenience, we print c's code again in hexadecimal,
Austin Schuh70cc9552019-01-21 19:46:48 -080011332 // unless c was already printed in the form '\x##' or the code is in
11333 // [1, 9].
11334 if (format == kHexEscape || (1 <= c && c <= 9)) {
11335 // Do nothing.
11336 } else {
11337 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
11338 }
11339 *os << ")";
11340}
11341
11342void PrintTo(unsigned char c, ::std::ostream* os) {
11343 PrintCharAndCodeTo<unsigned char>(c, os);
11344}
11345void PrintTo(signed char c, ::std::ostream* os) {
11346 PrintCharAndCodeTo<unsigned char>(c, os);
11347}
11348
11349// Prints a wchar_t as a symbol if it is printable or as its internal
11350// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
11351void PrintTo(wchar_t wc, ostream* os) {
11352 PrintCharAndCodeTo<wchar_t>(wc, os);
11353}
11354
11355// Prints the given array of characters to the ostream. CharType must be either
11356// char or wchar_t.
11357// The array starts at begin, the length is len, it may include '\0' characters
11358// and may not be NUL-terminated.
11359template <typename CharType>
11360GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11361GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11362GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011363static CharFormat PrintCharsAsStringTo(
Austin Schuh70cc9552019-01-21 19:46:48 -080011364 const CharType* begin, size_t len, ostream* os) {
11365 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
11366 *os << kQuoteBegin;
11367 bool is_previous_hex = false;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011368 CharFormat print_format = kAsIs;
Austin Schuh70cc9552019-01-21 19:46:48 -080011369 for (size_t index = 0; index < len; ++index) {
11370 const CharType cur = begin[index];
11371 if (is_previous_hex && IsXDigit(cur)) {
11372 // Previous character is of '\x..' form and this character can be
11373 // interpreted as another hexadecimal digit in its number. Break string to
11374 // disambiguate.
11375 *os << "\" " << kQuoteBegin;
11376 }
11377 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011378 // Remember if any characters required hex escaping.
11379 if (is_previous_hex) {
11380 print_format = kHexEscape;
11381 }
Austin Schuh70cc9552019-01-21 19:46:48 -080011382 }
11383 *os << "\"";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011384 return print_format;
Austin Schuh70cc9552019-01-21 19:46:48 -080011385}
11386
11387// Prints a (const) char/wchar_t array of 'len' elements, starting at address
11388// 'begin'. CharType must be either char or wchar_t.
11389template <typename CharType>
11390GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11391GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11392GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
11393static void UniversalPrintCharArray(
11394 const CharType* begin, size_t len, ostream* os) {
11395 // The code
11396 // const char kFoo[] = "foo";
11397 // generates an array of 4, not 3, elements, with the last one being '\0'.
11398 //
11399 // Therefore when printing a char array, we don't print the last element if
11400 // it's '\0', such that the output matches the string literal as it's
11401 // written in the source code.
11402 if (len > 0 && begin[len - 1] == '\0') {
11403 PrintCharsAsStringTo(begin, len - 1, os);
11404 return;
11405 }
11406
11407 // If, however, the last element in the array is not '\0', e.g.
11408 // const char kFoo[] = { 'f', 'o', 'o' };
11409 // we must print the entire array. We also print a message to indicate
11410 // that the array is not NUL-terminated.
11411 PrintCharsAsStringTo(begin, len, os);
11412 *os << " (no terminating NUL)";
11413}
11414
11415// Prints a (const) char array of 'len' elements, starting at address 'begin'.
11416void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
11417 UniversalPrintCharArray(begin, len, os);
11418}
11419
11420// Prints a (const) wchar_t array of 'len' elements, starting at address
11421// 'begin'.
11422void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
11423 UniversalPrintCharArray(begin, len, os);
11424}
11425
11426// Prints the given C string to the ostream.
11427void PrintTo(const char* s, ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011428 if (s == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011429 *os << "NULL";
11430 } else {
11431 *os << ImplicitCast_<const void*>(s) << " pointing to ";
11432 PrintCharsAsStringTo(s, strlen(s), os);
11433 }
11434}
11435
11436// MSVC compiler can be configured to define whar_t as a typedef
11437// of unsigned short. Defining an overload for const wchar_t* in that case
11438// would cause pointers to unsigned shorts be printed as wide strings,
11439// possibly accessing more memory than intended and causing invalid
11440// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
11441// wchar_t is implemented as a native type.
11442#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
11443// Prints the given wide C string to the ostream.
11444void PrintTo(const wchar_t* s, ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011445 if (s == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011446 *os << "NULL";
11447 } else {
11448 *os << ImplicitCast_<const void*>(s) << " pointing to ";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011449 PrintCharsAsStringTo(s, wcslen(s), os);
Austin Schuh70cc9552019-01-21 19:46:48 -080011450 }
11451}
11452#endif // wchar_t is native
11453
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011454namespace {
11455
11456bool ContainsUnprintableControlCodes(const char* str, size_t length) {
11457 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11458
11459 for (size_t i = 0; i < length; i++) {
11460 unsigned char ch = *s++;
11461 if (std::iscntrl(ch)) {
11462 switch (ch) {
11463 case '\t':
11464 case '\n':
11465 case '\r':
11466 break;
11467 default:
11468 return true;
11469 }
11470 }
11471 }
11472 return false;
11473}
11474
11475bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
11476
11477bool IsValidUTF8(const char* str, size_t length) {
11478 const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11479
11480 for (size_t i = 0; i < length;) {
11481 unsigned char lead = s[i++];
11482
11483 if (lead <= 0x7f) {
11484 continue; // single-byte character (ASCII) 0..7F
11485 }
11486 if (lead < 0xc2) {
11487 return false; // trail byte or non-shortest form
11488 } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11489 ++i; // 2-byte character
11490 } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11491 IsUTF8TrailByte(s[i]) &&
11492 IsUTF8TrailByte(s[i + 1]) &&
11493 // check for non-shortest form and surrogate
11494 (lead != 0xe0 || s[i] >= 0xa0) &&
11495 (lead != 0xed || s[i] < 0xa0)) {
11496 i += 2; // 3-byte character
11497 } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11498 IsUTF8TrailByte(s[i]) &&
11499 IsUTF8TrailByte(s[i + 1]) &&
11500 IsUTF8TrailByte(s[i + 2]) &&
11501 // check for non-shortest form
11502 (lead != 0xf0 || s[i] >= 0x90) &&
11503 (lead != 0xf4 || s[i] < 0x90)) {
11504 i += 3; // 4-byte character
11505 } else {
11506 return false;
11507 }
11508 }
11509 return true;
11510}
11511
11512void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
11513 if (!ContainsUnprintableControlCodes(str, length) &&
11514 IsValidUTF8(str, length)) {
11515 *os << "\n As Text: \"" << str << "\"";
11516 }
11517}
11518
11519} // anonymous namespace
11520
Austin Schuh70cc9552019-01-21 19:46:48 -080011521// Prints a ::string object.
11522#if GTEST_HAS_GLOBAL_STRING
11523void PrintStringTo(const ::string& s, ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011524 if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11525 if (GTEST_FLAG(print_utf8)) {
11526 ConditionalPrintAsText(s.data(), s.size(), os);
11527 }
11528 }
Austin Schuh70cc9552019-01-21 19:46:48 -080011529}
11530#endif // GTEST_HAS_GLOBAL_STRING
11531
11532void PrintStringTo(const ::std::string& s, ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011533 if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11534 if (GTEST_FLAG(print_utf8)) {
11535 ConditionalPrintAsText(s.data(), s.size(), os);
11536 }
11537 }
Austin Schuh70cc9552019-01-21 19:46:48 -080011538}
11539
11540// Prints a ::wstring object.
11541#if GTEST_HAS_GLOBAL_WSTRING
11542void PrintWideStringTo(const ::wstring& s, ostream* os) {
11543 PrintCharsAsStringTo(s.data(), s.size(), os);
11544}
11545#endif // GTEST_HAS_GLOBAL_WSTRING
11546
11547#if GTEST_HAS_STD_WSTRING
11548void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
11549 PrintCharsAsStringTo(s.data(), s.size(), os);
11550}
11551#endif // GTEST_HAS_STD_WSTRING
11552
11553} // namespace internal
11554
11555} // namespace testing
11556// Copyright 2008, Google Inc.
11557// All rights reserved.
11558//
11559// Redistribution and use in source and binary forms, with or without
11560// modification, are permitted provided that the following conditions are
11561// met:
11562//
11563// * Redistributions of source code must retain the above copyright
11564// notice, this list of conditions and the following disclaimer.
11565// * Redistributions in binary form must reproduce the above
11566// copyright notice, this list of conditions and the following disclaimer
11567// in the documentation and/or other materials provided with the
11568// distribution.
11569// * Neither the name of Google Inc. nor the names of its
11570// contributors may be used to endorse or promote products derived from
11571// this software without specific prior written permission.
11572//
11573// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11574// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11575// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11576// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11577// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11578// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11579// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11580// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11581// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11582// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11583// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh70cc9552019-01-21 19:46:48 -080011584
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011585//
11586// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -080011587
Austin Schuh70cc9552019-01-21 19:46:48 -080011588
11589namespace testing {
11590
11591using internal::GetUnitTestImpl;
11592
11593// Gets the summary of the failure message by omitting the stack trace
11594// in it.
11595std::string TestPartResult::ExtractSummary(const char* message) {
11596 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011597 return stack_trace == nullptr ? message : std::string(message, stack_trace);
Austin Schuh70cc9552019-01-21 19:46:48 -080011598}
11599
11600// Prints a TestPartResult object.
11601std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011602 return os << result.file_name() << ":" << result.line_number() << ": "
11603 << (result.type() == TestPartResult::kSuccess
11604 ? "Success"
11605 : result.type() == TestPartResult::kSkip
11606 ? "Skipped"
11607 : result.type() == TestPartResult::kFatalFailure
11608 ? "Fatal failure"
11609 : "Non-fatal failure")
11610 << ":\n"
11611 << result.message() << std::endl;
Austin Schuh70cc9552019-01-21 19:46:48 -080011612}
11613
11614// Appends a TestPartResult to the array.
11615void TestPartResultArray::Append(const TestPartResult& result) {
11616 array_.push_back(result);
11617}
11618
11619// Returns the TestPartResult at the given index (0-based).
11620const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
11621 if (index < 0 || index >= size()) {
11622 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
11623 internal::posix::Abort();
11624 }
11625
11626 return array_[index];
11627}
11628
11629// Returns the number of TestPartResult objects in the array.
11630int TestPartResultArray::size() const {
11631 return static_cast<int>(array_.size());
11632}
11633
11634namespace internal {
11635
11636HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11637 : has_new_fatal_failure_(false),
11638 original_reporter_(GetUnitTestImpl()->
11639 GetTestPartResultReporterForCurrentThread()) {
11640 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
11641}
11642
11643HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11644 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11645 original_reporter_);
11646}
11647
11648void HasNewFatalFailureHelper::ReportTestPartResult(
11649 const TestPartResult& result) {
11650 if (result.fatally_failed())
11651 has_new_fatal_failure_ = true;
11652 original_reporter_->ReportTestPartResult(result);
11653}
11654
11655} // namespace internal
11656
11657} // namespace testing
11658// Copyright 2008 Google Inc.
11659// All Rights Reserved.
11660//
11661// Redistribution and use in source and binary forms, with or without
11662// modification, are permitted provided that the following conditions are
11663// met:
11664//
11665// * Redistributions of source code must retain the above copyright
11666// notice, this list of conditions and the following disclaimer.
11667// * Redistributions in binary form must reproduce the above
11668// copyright notice, this list of conditions and the following disclaimer
11669// in the documentation and/or other materials provided with the
11670// distribution.
11671// * Neither the name of Google Inc. nor the names of its
11672// contributors may be used to endorse or promote products derived from
11673// this software without specific prior written permission.
11674//
11675// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11676// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11677// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11678// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11679// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11680// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11681// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11682// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11683// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11684// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11685// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011686
11687
Austin Schuh70cc9552019-01-21 19:46:48 -080011688
11689
11690namespace testing {
11691namespace internal {
11692
11693#if GTEST_HAS_TYPED_TEST_P
11694
11695// Skips to the first non-space char in str. Returns an empty string if str
11696// contains only whitespace characters.
11697static const char* SkipSpaces(const char* str) {
11698 while (IsSpace(*str))
11699 str++;
11700 return str;
11701}
11702
11703static std::vector<std::string> SplitIntoTestNames(const char* src) {
11704 std::vector<std::string> name_vec;
11705 src = SkipSpaces(src);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011706 for (; src != nullptr; src = SkipComma(src)) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011707 name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
11708 }
11709 return name_vec;
11710}
11711
11712// Verifies that registered_tests match the test names in
11713// registered_tests_; returns registered_tests if successful, or
11714// aborts the program otherwise.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011715const char* TypedTestSuitePState::VerifyRegisteredTestNames(
Austin Schuh70cc9552019-01-21 19:46:48 -080011716 const char* file, int line, const char* registered_tests) {
11717 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11718 registered_ = true;
11719
11720 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11721
11722 Message errors;
11723
11724 std::set<std::string> tests;
11725 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11726 name_it != name_vec.end(); ++name_it) {
11727 const std::string& name = *name_it;
11728 if (tests.count(name) != 0) {
11729 errors << "Test " << name << " is listed more than once.\n";
11730 continue;
11731 }
11732
11733 bool found = false;
11734 for (RegisteredTestIter it = registered_tests_.begin();
11735 it != registered_tests_.end();
11736 ++it) {
11737 if (name == it->first) {
11738 found = true;
11739 break;
11740 }
11741 }
11742
11743 if (found) {
11744 tests.insert(name);
11745 } else {
11746 errors << "No test named " << name
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011747 << " can be found in this test suite.\n";
Austin Schuh70cc9552019-01-21 19:46:48 -080011748 }
11749 }
11750
11751 for (RegisteredTestIter it = registered_tests_.begin();
11752 it != registered_tests_.end();
11753 ++it) {
11754 if (tests.count(it->first) == 0) {
11755 errors << "You forgot to list test " << it->first << ".\n";
11756 }
11757 }
11758
11759 const std::string& errors_str = errors.GetString();
11760 if (errors_str != "") {
11761 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
11762 errors_str.c_str());
11763 fflush(stderr);
11764 posix::Abort();
11765 }
11766
11767 return registered_tests;
11768}
11769
11770#endif // GTEST_HAS_TYPED_TEST_P
11771
11772} // namespace internal
11773} // namespace testing
11774// Copyright 2008, Google Inc.
11775// All rights reserved.
11776//
11777// Redistribution and use in source and binary forms, with or without
11778// modification, are permitted provided that the following conditions are
11779// met:
11780//
11781// * Redistributions of source code must retain the above copyright
11782// notice, this list of conditions and the following disclaimer.
11783// * Redistributions in binary form must reproduce the above
11784// copyright notice, this list of conditions and the following disclaimer
11785// in the documentation and/or other materials provided with the
11786// distribution.
11787// * Neither the name of Google Inc. nor the names of its
11788// contributors may be used to endorse or promote products derived from
11789// this software without specific prior written permission.
11790//
11791// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11792// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11793// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11794// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11795// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11796// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11797// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11798// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11799// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11800// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11801// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011802
Austin Schuh70cc9552019-01-21 19:46:48 -080011803//
11804// Google C++ Mocking Framework (Google Mock)
11805//
11806// This file #includes all Google Mock implementation .cc files. The
11807// purpose is to allow a user to build Google Mock by compiling this
11808// file alone.
11809
11810// This line ensures that gmock.h can be compiled on its own, even
11811// when it's fused.
11812#include "gmock/gmock.h"
11813
11814// The following lines pull in the real gmock *.cc files.
11815// Copyright 2007, Google Inc.
11816// All rights reserved.
11817//
11818// Redistribution and use in source and binary forms, with or without
11819// modification, are permitted provided that the following conditions are
11820// met:
11821//
11822// * Redistributions of source code must retain the above copyright
11823// notice, this list of conditions and the following disclaimer.
11824// * Redistributions in binary form must reproduce the above
11825// copyright notice, this list of conditions and the following disclaimer
11826// in the documentation and/or other materials provided with the
11827// distribution.
11828// * Neither the name of Google Inc. nor the names of its
11829// contributors may be used to endorse or promote products derived from
11830// this software without specific prior written permission.
11831//
11832// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11833// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11834// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11835// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11836// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11837// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11838// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11839// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11840// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11841// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11842// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011843
Austin Schuh70cc9552019-01-21 19:46:48 -080011844
11845// Google Mock - a framework for writing C++ mock classes.
11846//
11847// This file implements cardinalities.
11848
11849
11850#include <limits.h>
11851#include <ostream> // NOLINT
11852#include <sstream>
11853#include <string>
11854
11855namespace testing {
11856
11857namespace {
11858
11859// Implements the Between(m, n) cardinality.
11860class BetweenCardinalityImpl : public CardinalityInterface {
11861 public:
11862 BetweenCardinalityImpl(int min, int max)
11863 : min_(min >= 0 ? min : 0),
11864 max_(max >= min_ ? max : min_) {
11865 std::stringstream ss;
11866 if (min < 0) {
11867 ss << "The invocation lower bound must be >= 0, "
11868 << "but is actually " << min << ".";
11869 internal::Expect(false, __FILE__, __LINE__, ss.str());
11870 } else if (max < 0) {
11871 ss << "The invocation upper bound must be >= 0, "
11872 << "but is actually " << max << ".";
11873 internal::Expect(false, __FILE__, __LINE__, ss.str());
11874 } else if (min > max) {
11875 ss << "The invocation upper bound (" << max
11876 << ") must be >= the invocation lower bound (" << min
11877 << ").";
11878 internal::Expect(false, __FILE__, __LINE__, ss.str());
11879 }
11880 }
11881
11882 // Conservative estimate on the lower/upper bound of the number of
11883 // calls allowed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011884 int ConservativeLowerBound() const override { return min_; }
11885 int ConservativeUpperBound() const override { return max_; }
Austin Schuh70cc9552019-01-21 19:46:48 -080011886
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011887 bool IsSatisfiedByCallCount(int call_count) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -080011888 return min_ <= call_count && call_count <= max_;
11889 }
11890
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011891 bool IsSaturatedByCallCount(int call_count) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -080011892 return call_count >= max_;
11893 }
11894
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011895 void DescribeTo(::std::ostream* os) const override;
Austin Schuh70cc9552019-01-21 19:46:48 -080011896
11897 private:
11898 const int min_;
11899 const int max_;
11900
11901 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
11902};
11903
11904// Formats "n times" in a human-friendly way.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011905inline std::string FormatTimes(int n) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011906 if (n == 1) {
11907 return "once";
11908 } else if (n == 2) {
11909 return "twice";
11910 } else {
11911 std::stringstream ss;
11912 ss << n << " times";
11913 return ss.str();
11914 }
11915}
11916
11917// Describes the Between(m, n) cardinality in human-friendly text.
11918void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
11919 if (min_ == 0) {
11920 if (max_ == 0) {
11921 *os << "never called";
11922 } else if (max_ == INT_MAX) {
11923 *os << "called any number of times";
11924 } else {
11925 *os << "called at most " << FormatTimes(max_);
11926 }
11927 } else if (min_ == max_) {
11928 *os << "called " << FormatTimes(min_);
11929 } else if (max_ == INT_MAX) {
11930 *os << "called at least " << FormatTimes(min_);
11931 } else {
11932 // 0 < min_ < max_ < INT_MAX
11933 *os << "called between " << min_ << " and " << max_ << " times";
11934 }
11935}
11936
11937} // Unnamed namespace
11938
11939// Describes the given call count to an ostream.
11940void Cardinality::DescribeActualCallCountTo(int actual_call_count,
11941 ::std::ostream* os) {
11942 if (actual_call_count > 0) {
11943 *os << "called " << FormatTimes(actual_call_count);
11944 } else {
11945 *os << "never called";
11946 }
11947}
11948
11949// Creates a cardinality that allows at least n calls.
11950GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
11951
11952// Creates a cardinality that allows at most n calls.
11953GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
11954
11955// Creates a cardinality that allows any number of calls.
11956GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
11957
11958// Creates a cardinality that allows between min and max calls.
11959GTEST_API_ Cardinality Between(int min, int max) {
11960 return Cardinality(new BetweenCardinalityImpl(min, max));
11961}
11962
11963// Creates a cardinality that allows exactly n calls.
11964GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
11965
11966} // namespace testing
11967// Copyright 2007, Google Inc.
11968// All rights reserved.
11969//
11970// Redistribution and use in source and binary forms, with or without
11971// modification, are permitted provided that the following conditions are
11972// met:
11973//
11974// * Redistributions of source code must retain the above copyright
11975// notice, this list of conditions and the following disclaimer.
11976// * Redistributions in binary form must reproduce the above
11977// copyright notice, this list of conditions and the following disclaimer
11978// in the documentation and/or other materials provided with the
11979// distribution.
11980// * Neither the name of Google Inc. nor the names of its
11981// contributors may be used to endorse or promote products derived from
11982// this software without specific prior written permission.
11983//
11984// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11985// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11986// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11987// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11988// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11989// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11990// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11991// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11992// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11993// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11994// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011995
Austin Schuh70cc9552019-01-21 19:46:48 -080011996
11997// Google Mock - a framework for writing C++ mock classes.
11998//
11999// This file defines some utilities useful for implementing Google
12000// Mock. They are subject to change without notice, so please DO NOT
12001// USE THEM IN USER CODE.
12002
12003
12004#include <ctype.h>
12005#include <ostream> // NOLINT
12006#include <string>
12007
12008namespace testing {
12009namespace internal {
12010
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012011// Joins a vector of strings as if they are fields of a tuple; returns
12012// the joined string.
12013GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
12014 switch (fields.size()) {
12015 case 0:
12016 return "";
12017 case 1:
12018 return fields[0];
12019 default:
12020 std::string result = "(" + fields[0];
12021 for (size_t i = 1; i < fields.size(); i++) {
12022 result += ", ";
12023 result += fields[i];
12024 }
12025 result += ")";
12026 return result;
12027 }
12028}
12029
Austin Schuh70cc9552019-01-21 19:46:48 -080012030// Converts an identifier name to a space-separated list of lower-case
12031// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
12032// treated as one word. For example, both "FooBar123" and
12033// "foo_bar_123" are converted to "foo bar 123".
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012034GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
12035 std::string result;
Austin Schuh70cc9552019-01-21 19:46:48 -080012036 char prev_char = '\0';
12037 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
12038 // We don't care about the current locale as the input is
12039 // guaranteed to be a valid C++ identifier name.
12040 const bool starts_new_word = IsUpper(*p) ||
12041 (!IsAlpha(prev_char) && IsLower(*p)) ||
12042 (!IsDigit(prev_char) && IsDigit(*p));
12043
12044 if (IsAlNum(*p)) {
12045 if (starts_new_word && result != "")
12046 result += ' ';
12047 result += ToLower(*p);
12048 }
12049 }
12050 return result;
12051}
12052
12053// This class reports Google Mock failures as Google Test failures. A
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012054// user can define another class in a similar fashion if they intend to
Austin Schuh70cc9552019-01-21 19:46:48 -080012055// use Google Mock with a testing framework other than Google Test.
12056class GoogleTestFailureReporter : public FailureReporterInterface {
12057 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012058 void ReportFailure(FailureType type, const char* file, int line,
12059 const std::string& message) override {
Austin Schuh70cc9552019-01-21 19:46:48 -080012060 AssertHelper(type == kFatal ?
12061 TestPartResult::kFatalFailure :
12062 TestPartResult::kNonFatalFailure,
12063 file,
12064 line,
12065 message.c_str()) = Message();
12066 if (type == kFatal) {
12067 posix::Abort();
12068 }
12069 }
12070};
12071
12072// Returns the global failure reporter. Will create a
12073// GoogleTestFailureReporter and return it the first time called.
12074GTEST_API_ FailureReporterInterface* GetFailureReporter() {
12075 // Points to the global failure reporter used by Google Mock. gcc
12076 // guarantees that the following use of failure_reporter is
12077 // thread-safe. We may need to add additional synchronization to
12078 // protect failure_reporter if we port Google Mock to other
12079 // compilers.
12080 static FailureReporterInterface* const failure_reporter =
12081 new GoogleTestFailureReporter();
12082 return failure_reporter;
12083}
12084
12085// Protects global resources (stdout in particular) used by Log().
12086static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
12087
12088// Returns true iff a log with the given severity is visible according
12089// to the --gmock_verbose flag.
12090GTEST_API_ bool LogIsVisible(LogSeverity severity) {
12091 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
12092 // Always show the log if --gmock_verbose=info.
12093 return true;
12094 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
12095 // Always hide it if --gmock_verbose=error.
12096 return false;
12097 } else {
12098 // If --gmock_verbose is neither "info" nor "error", we treat it
12099 // as "warning" (its default value).
12100 return severity == kWarning;
12101 }
12102}
12103
12104// Prints the given message to stdout iff 'severity' >= the level
12105// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
12106// 0, also prints the stack trace excluding the top
12107// stack_frames_to_skip frames. In opt mode, any positive
12108// stack_frames_to_skip is treated as 0, since we don't know which
12109// function calls will be inlined by the compiler and need to be
12110// conservative.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012111GTEST_API_ void Log(LogSeverity severity, const std::string& message,
Austin Schuh70cc9552019-01-21 19:46:48 -080012112 int stack_frames_to_skip) {
12113 if (!LogIsVisible(severity))
12114 return;
12115
12116 // Ensures that logs from different threads don't interleave.
12117 MutexLock l(&g_log_mutex);
12118
Austin Schuh70cc9552019-01-21 19:46:48 -080012119 if (severity == kWarning) {
12120 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
12121 std::cout << "\nGMOCK WARNING:";
12122 }
12123 // Pre-pends a new-line to message if it doesn't start with one.
12124 if (message.empty() || message[0] != '\n') {
12125 std::cout << "\n";
12126 }
12127 std::cout << message;
12128 if (stack_frames_to_skip >= 0) {
12129#ifdef NDEBUG
12130 // In opt mode, we have to be conservative and skip no stack frame.
12131 const int actual_to_skip = 0;
12132#else
12133 // In dbg mode, we can do what the caller tell us to do (plus one
12134 // for skipping this function's stack frame).
12135 const int actual_to_skip = stack_frames_to_skip + 1;
12136#endif // NDEBUG
12137
12138 // Appends a new-line to message if it doesn't end with one.
12139 if (!message.empty() && *message.rbegin() != '\n') {
12140 std::cout << "\n";
12141 }
12142 std::cout << "Stack trace:\n"
12143 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
12144 ::testing::UnitTest::GetInstance(), actual_to_skip);
12145 }
12146 std::cout << ::std::flush;
12147}
12148
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012149GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
12150
12151GTEST_API_ void IllegalDoDefault(const char* file, int line) {
12152 internal::Assert(
12153 false, file, line,
12154 "You are using DoDefault() inside a composite action like "
12155 "DoAll() or WithArgs(). This is not supported for technical "
12156 "reasons. Please instead spell out the default action, or "
12157 "assign the default action to an Action variable and use "
12158 "the variable in various places.");
12159}
12160
Austin Schuh70cc9552019-01-21 19:46:48 -080012161} // namespace internal
12162} // namespace testing
12163// Copyright 2007, Google Inc.
12164// All rights reserved.
12165//
12166// Redistribution and use in source and binary forms, with or without
12167// modification, are permitted provided that the following conditions are
12168// met:
12169//
12170// * Redistributions of source code must retain the above copyright
12171// notice, this list of conditions and the following disclaimer.
12172// * Redistributions in binary form must reproduce the above
12173// copyright notice, this list of conditions and the following disclaimer
12174// in the documentation and/or other materials provided with the
12175// distribution.
12176// * Neither the name of Google Inc. nor the names of its
12177// contributors may be used to endorse or promote products derived from
12178// this software without specific prior written permission.
12179//
12180// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12181// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12182// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12183// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12184// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12185// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12186// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12187// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12188// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12189// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12190// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012191
Austin Schuh70cc9552019-01-21 19:46:48 -080012192
12193// Google Mock - a framework for writing C++ mock classes.
12194//
12195// This file implements Matcher<const string&>, Matcher<string>, and
12196// utilities for defining matchers.
12197
12198
12199#include <string.h>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012200#include <iostream>
Austin Schuh70cc9552019-01-21 19:46:48 -080012201#include <sstream>
12202#include <string>
12203
12204namespace testing {
Austin Schuh70cc9552019-01-21 19:46:48 -080012205namespace internal {
12206
Austin Schuh70cc9552019-01-21 19:46:48 -080012207// Returns the description for a matcher defined using the MATCHER*()
12208// macro where the user-supplied description string is "", if
12209// 'negation' is false; otherwise returns the description of the
12210// negation of the matcher. 'param_values' contains a list of strings
12211// that are the print-out of the matcher's parameters.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012212GTEST_API_ std::string FormatMatcherDescription(bool negation,
12213 const char* matcher_name,
12214 const Strings& param_values) {
12215 std::string result = ConvertIdentifierNameToWords(matcher_name);
12216 if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
Austin Schuh70cc9552019-01-21 19:46:48 -080012217 return negation ? "not (" + result + ")" : result;
12218}
12219
12220// FindMaxBipartiteMatching and its helper class.
12221//
12222// Uses the well-known Ford-Fulkerson max flow method to find a maximum
12223// bipartite matching. Flow is considered to be from left to right.
12224// There is an implicit source node that is connected to all of the left
12225// nodes, and an implicit sink node that is connected to all of the
12226// right nodes. All edges have unit capacity.
12227//
12228// Neither the flow graph nor the residual flow graph are represented
12229// explicitly. Instead, they are implied by the information in 'graph' and
12230// a vector<int> called 'left_' whose elements are initialized to the
12231// value kUnused. This represents the initial state of the algorithm,
12232// where the flow graph is empty, and the residual flow graph has the
12233// following edges:
12234// - An edge from source to each left_ node
12235// - An edge from each right_ node to sink
12236// - An edge from each left_ node to each right_ node, if the
12237// corresponding edge exists in 'graph'.
12238//
12239// When the TryAugment() method adds a flow, it sets left_[l] = r for some
12240// nodes l and r. This induces the following changes:
12241// - The edges (source, l), (l, r), and (r, sink) are added to the
12242// flow graph.
12243// - The same three edges are removed from the residual flow graph.
12244// - The reverse edges (l, source), (r, l), and (sink, r) are added
12245// to the residual flow graph, which is a directional graph
12246// representing unused flow capacity.
12247//
12248// When the method augments a flow (moving left_[l] from some r1 to some
12249// other r2), this can be thought of as "undoing" the above steps with
12250// respect to r1 and "redoing" them with respect to r2.
12251//
12252// It bears repeating that the flow graph and residual flow graph are
12253// never represented explicitly, but can be derived by looking at the
12254// information in 'graph' and in left_.
12255//
12256// As an optimization, there is a second vector<int> called right_ which
12257// does not provide any new information. Instead, it enables more
12258// efficient queries about edges entering or leaving the right-side nodes
12259// of the flow or residual flow graphs. The following invariants are
12260// maintained:
12261//
12262// left[l] == kUnused or right[left[l]] == l
12263// right[r] == kUnused or left[right[r]] == r
12264//
12265// . [ source ] .
12266// . ||| .
12267// . ||| .
12268// . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
12269// . || | | .
12270// . |\---> left[1]=-1 \--> right[1]=0 ---\| .
12271// . | || .
12272// . \----> left[2]=2 ------> right[2]=2 --\|| .
12273// . ||| .
12274// . elements matchers vvv .
12275// . [ sink ] .
12276//
12277// See Also:
12278// [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
12279// "Introduction to Algorithms (Second ed.)", pp. 651-664.
12280// [2] "Ford-Fulkerson algorithm", Wikipedia,
12281// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
12282class MaxBipartiteMatchState {
12283 public:
12284 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
12285 : graph_(&graph),
12286 left_(graph_->LhsSize(), kUnused),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012287 right_(graph_->RhsSize(), kUnused) {}
Austin Schuh70cc9552019-01-21 19:46:48 -080012288
12289 // Returns the edges of a maximal match, each in the form {left, right}.
12290 ElementMatcherPairs Compute() {
12291 // 'seen' is used for path finding { 0: unseen, 1: seen }.
12292 ::std::vector<char> seen;
12293 // Searches the residual flow graph for a path from each left node to
12294 // the sink in the residual flow graph, and if one is found, add flow
12295 // to the graph. It's okay to search through the left nodes once. The
12296 // edge from the implicit source node to each previously-visited left
12297 // node will have flow if that left node has any path to the sink
12298 // whatsoever. Subsequent augmentations can only add flow to the
12299 // network, and cannot take away that previous flow unit from the source.
12300 // Since the source-to-left edge can only carry one flow unit (or,
12301 // each element can be matched to only one matcher), there is no need
12302 // to visit the left nodes more than once looking for augmented paths.
12303 // The flow is known to be possible or impossible by looking at the
12304 // node once.
12305 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
12306 // Reset the path-marking vector and try to find a path from
12307 // source to sink starting at the left_[ilhs] node.
12308 GTEST_CHECK_(left_[ilhs] == kUnused)
12309 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
12310 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
12311 seen.assign(graph_->RhsSize(), 0);
12312 TryAugment(ilhs, &seen);
12313 }
12314 ElementMatcherPairs result;
12315 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
12316 size_t irhs = left_[ilhs];
12317 if (irhs == kUnused) continue;
12318 result.push_back(ElementMatcherPair(ilhs, irhs));
12319 }
12320 return result;
12321 }
12322
12323 private:
12324 static const size_t kUnused = static_cast<size_t>(-1);
12325
12326 // Perform a depth-first search from left node ilhs to the sink. If a
12327 // path is found, flow is added to the network by linking the left and
12328 // right vector elements corresponding each segment of the path.
12329 // Returns true if a path to sink was found, which means that a unit of
12330 // flow was added to the network. The 'seen' vector elements correspond
12331 // to right nodes and are marked to eliminate cycles from the search.
12332 //
12333 // Left nodes will only be explored at most once because they
12334 // are accessible from at most one right node in the residual flow
12335 // graph.
12336 //
12337 // Note that left_[ilhs] is the only element of left_ that TryAugment will
12338 // potentially transition from kUnused to another value. Any other
12339 // left_ element holding kUnused before TryAugment will be holding it
12340 // when TryAugment returns.
12341 //
12342 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
12343 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012344 if ((*seen)[irhs]) continue;
12345 if (!graph_->HasEdge(ilhs, irhs)) continue;
Austin Schuh70cc9552019-01-21 19:46:48 -080012346 // There's an available edge from ilhs to irhs.
12347 (*seen)[irhs] = 1;
12348 // Next a search is performed to determine whether
12349 // this edge is a dead end or leads to the sink.
12350 //
12351 // right_[irhs] == kUnused means that there is residual flow from
12352 // right node irhs to the sink, so we can use that to finish this
12353 // flow path and return success.
12354 //
12355 // Otherwise there is residual flow to some ilhs. We push flow
12356 // along that path and call ourselves recursively to see if this
12357 // ultimately leads to sink.
12358 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
12359 // Add flow from left_[ilhs] to right_[irhs].
12360 left_[ilhs] = irhs;
12361 right_[irhs] = ilhs;
12362 return true;
12363 }
12364 }
12365 return false;
12366 }
12367
12368 const MatchMatrix* graph_; // not owned
12369 // Each element of the left_ vector represents a left hand side node
12370 // (i.e. an element) and each element of right_ is a right hand side
12371 // node (i.e. a matcher). The values in the left_ vector indicate
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012372 // outflow from that node to a node on the right_ side. The values
Austin Schuh70cc9552019-01-21 19:46:48 -080012373 // in the right_ indicate inflow, and specify which left_ node is
12374 // feeding that right_ node, if any. For example, left_[3] == 1 means
12375 // there's a flow from element #3 to matcher #1. Such a flow would also
12376 // be redundantly represented in the right_ vector as right_[1] == 3.
12377 // Elements of left_ and right_ are either kUnused or mutually
12378 // referent. Mutually referent means that left_[right_[i]] = i and
12379 // right_[left_[i]] = i.
12380 ::std::vector<size_t> left_;
12381 ::std::vector<size_t> right_;
12382
12383 GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
12384};
12385
12386const size_t MaxBipartiteMatchState::kUnused;
12387
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012388GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
Austin Schuh70cc9552019-01-21 19:46:48 -080012389 return MaxBipartiteMatchState(g).Compute();
12390}
12391
12392static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
12393 ::std::ostream* stream) {
12394 typedef ElementMatcherPairs::const_iterator Iter;
12395 ::std::ostream& os = *stream;
12396 os << "{";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012397 const char* sep = "";
Austin Schuh70cc9552019-01-21 19:46:48 -080012398 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
12399 os << sep << "\n ("
12400 << "element #" << it->first << ", "
12401 << "matcher #" << it->second << ")";
12402 sep = ",";
12403 }
12404 os << "\n}";
12405}
12406
Austin Schuh70cc9552019-01-21 19:46:48 -080012407bool MatchMatrix::NextGraph() {
12408 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
12409 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
12410 char& b = matched_[SpaceIndex(ilhs, irhs)];
12411 if (!b) {
12412 b = 1;
12413 return true;
12414 }
12415 b = 0;
12416 }
12417 }
12418 return false;
12419}
12420
12421void MatchMatrix::Randomize() {
12422 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
12423 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
12424 char& b = matched_[SpaceIndex(ilhs, irhs)];
12425 b = static_cast<char>(rand() & 1); // NOLINT
12426 }
12427 }
12428}
12429
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012430std::string MatchMatrix::DebugString() const {
Austin Schuh70cc9552019-01-21 19:46:48 -080012431 ::std::stringstream ss;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012432 const char* sep = "";
Austin Schuh70cc9552019-01-21 19:46:48 -080012433 for (size_t i = 0; i < LhsSize(); ++i) {
12434 ss << sep;
12435 for (size_t j = 0; j < RhsSize(); ++j) {
12436 ss << HasEdge(i, j);
12437 }
12438 sep = ";";
12439 }
12440 return ss.str();
12441}
12442
12443void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
12444 ::std::ostream* os) const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012445 switch (match_flags()) {
12446 case UnorderedMatcherRequire::ExactMatch:
12447 if (matcher_describers_.empty()) {
12448 *os << "is empty";
12449 return;
12450 }
12451 if (matcher_describers_.size() == 1) {
12452 *os << "has " << Elements(1) << " and that element ";
12453 matcher_describers_[0]->DescribeTo(os);
12454 return;
12455 }
12456 *os << "has " << Elements(matcher_describers_.size())
12457 << " and there exists some permutation of elements such that:\n";
12458 break;
12459 case UnorderedMatcherRequire::Superset:
12460 *os << "a surjection from elements to requirements exists such that:\n";
12461 break;
12462 case UnorderedMatcherRequire::Subset:
12463 *os << "an injection from elements to requirements exists such that:\n";
12464 break;
Austin Schuh70cc9552019-01-21 19:46:48 -080012465 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012466
Austin Schuh70cc9552019-01-21 19:46:48 -080012467 const char* sep = "";
12468 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012469 *os << sep;
12470 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
12471 *os << " - element #" << i << " ";
12472 } else {
12473 *os << " - an element ";
12474 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012475 matcher_describers_[i]->DescribeTo(os);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012476 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
12477 sep = ", and\n";
12478 } else {
12479 sep = "\n";
12480 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012481 }
12482}
12483
12484void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
12485 ::std::ostream* os) const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012486 switch (match_flags()) {
12487 case UnorderedMatcherRequire::ExactMatch:
12488 if (matcher_describers_.empty()) {
12489 *os << "isn't empty";
12490 return;
12491 }
12492 if (matcher_describers_.size() == 1) {
12493 *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
12494 << " that ";
12495 matcher_describers_[0]->DescribeNegationTo(os);
12496 return;
12497 }
12498 *os << "doesn't have " << Elements(matcher_describers_.size())
12499 << ", or there exists no permutation of elements such that:\n";
12500 break;
12501 case UnorderedMatcherRequire::Superset:
12502 *os << "no surjection from elements to requirements exists such that:\n";
12503 break;
12504 case UnorderedMatcherRequire::Subset:
12505 *os << "no injection from elements to requirements exists such that:\n";
12506 break;
Austin Schuh70cc9552019-01-21 19:46:48 -080012507 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012508 const char* sep = "";
12509 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012510 *os << sep;
12511 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
12512 *os << " - element #" << i << " ";
12513 } else {
12514 *os << " - an element ";
12515 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012516 matcher_describers_[i]->DescribeTo(os);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012517 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
12518 sep = ", and\n";
12519 } else {
12520 sep = "\n";
12521 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012522 }
12523}
12524
12525// Checks that all matchers match at least one element, and that all
12526// elements match at least one matcher. This enables faster matching
12527// and better error reporting.
12528// Returns false, writing an explanation to 'listener', if and only
12529// if the success criteria are not met.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012530bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
12531 const ::std::vector<std::string>& element_printouts,
12532 const MatchMatrix& matrix, MatchResultListener* listener) const {
Austin Schuh70cc9552019-01-21 19:46:48 -080012533 bool result = true;
12534 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
12535 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
12536
12537 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
12538 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
12539 char matched = matrix.HasEdge(ilhs, irhs);
12540 element_matched[ilhs] |= matched;
12541 matcher_matched[irhs] |= matched;
12542 }
12543 }
12544
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012545 if (match_flags() & UnorderedMatcherRequire::Superset) {
Austin Schuh70cc9552019-01-21 19:46:48 -080012546 const char* sep =
12547 "where the following matchers don't match any elements:\n";
12548 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012549 if (matcher_matched[mi]) continue;
Austin Schuh70cc9552019-01-21 19:46:48 -080012550 result = false;
12551 if (listener->IsInterested()) {
12552 *listener << sep << "matcher #" << mi << ": ";
12553 matcher_describers_[mi]->DescribeTo(listener->stream());
12554 sep = ",\n";
12555 }
12556 }
12557 }
12558
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012559 if (match_flags() & UnorderedMatcherRequire::Subset) {
Austin Schuh70cc9552019-01-21 19:46:48 -080012560 const char* sep =
12561 "where the following elements don't match any matchers:\n";
12562 const char* outer_sep = "";
12563 if (!result) {
12564 outer_sep = "\nand ";
12565 }
12566 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012567 if (element_matched[ei]) continue;
Austin Schuh70cc9552019-01-21 19:46:48 -080012568 result = false;
12569 if (listener->IsInterested()) {
12570 *listener << outer_sep << sep << "element #" << ei << ": "
12571 << element_printouts[ei];
12572 sep = ",\n";
12573 outer_sep = "";
12574 }
12575 }
12576 }
12577 return result;
12578}
12579
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012580bool UnorderedElementsAreMatcherImplBase::FindPairing(
12581 const MatchMatrix& matrix, MatchResultListener* listener) const {
12582 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
12583
12584 size_t max_flow = matches.size();
12585 if ((match_flags() & UnorderedMatcherRequire::Superset) &&
12586 max_flow < matrix.RhsSize()) {
12587 if (listener->IsInterested()) {
12588 *listener << "where no permutation of the elements can satisfy all "
12589 "matchers, and the closest match is "
12590 << max_flow << " of " << matrix.RhsSize()
12591 << " matchers with the pairings:\n";
12592 LogElementMatcherPairVec(matches, listener->stream());
12593 }
12594 return false;
12595 }
12596 if ((match_flags() & UnorderedMatcherRequire::Subset) &&
12597 max_flow < matrix.LhsSize()) {
12598 if (listener->IsInterested()) {
12599 *listener
12600 << "where not all elements can be matched, and the closest match is "
12601 << max_flow << " of " << matrix.RhsSize()
12602 << " matchers with the pairings:\n";
12603 LogElementMatcherPairVec(matches, listener->stream());
12604 }
12605 return false;
12606 }
12607
12608 if (matches.size() > 1) {
12609 if (listener->IsInterested()) {
12610 const char* sep = "where:\n";
12611 for (size_t mi = 0; mi < matches.size(); ++mi) {
12612 *listener << sep << " - element #" << matches[mi].first
12613 << " is matched by matcher #" << matches[mi].second;
12614 sep = ",\n";
12615 }
12616 }
12617 }
12618 return true;
12619}
12620
Austin Schuh70cc9552019-01-21 19:46:48 -080012621} // namespace internal
12622} // namespace testing
12623// Copyright 2007, Google Inc.
12624// All rights reserved.
12625//
12626// Redistribution and use in source and binary forms, with or without
12627// modification, are permitted provided that the following conditions are
12628// met:
12629//
12630// * Redistributions of source code must retain the above copyright
12631// notice, this list of conditions and the following disclaimer.
12632// * Redistributions in binary form must reproduce the above
12633// copyright notice, this list of conditions and the following disclaimer
12634// in the documentation and/or other materials provided with the
12635// distribution.
12636// * Neither the name of Google Inc. nor the names of its
12637// contributors may be used to endorse or promote products derived from
12638// this software without specific prior written permission.
12639//
12640// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12641// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12642// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12643// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12644// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12645// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12646// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12647// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12648// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12649// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12650// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012651
Austin Schuh70cc9552019-01-21 19:46:48 -080012652
12653// Google Mock - a framework for writing C++ mock classes.
12654//
12655// This file implements the spec builder syntax (ON_CALL and
12656// EXPECT_CALL).
12657
12658
12659#include <stdlib.h>
12660#include <iostream> // NOLINT
12661#include <map>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012662#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -080012663#include <set>
12664#include <string>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012665#include <vector>
Austin Schuh70cc9552019-01-21 19:46:48 -080012666
12667#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
12668# include <unistd.h> // NOLINT
12669#endif
12670
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012671// Silence C4800 (C4800: 'int *const ': forcing value
12672// to bool 'true' or 'false') for MSVC 15
12673#ifdef _MSC_VER
12674#if _MSC_VER == 1900
12675# pragma warning(push)
12676# pragma warning(disable:4800)
12677#endif
12678#endif
12679
Austin Schuh70cc9552019-01-21 19:46:48 -080012680namespace testing {
12681namespace internal {
12682
12683// Protects the mock object registry (in class Mock), all function
12684// mockers, and all expectations.
12685GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
12686
12687// Logs a message including file and line number information.
12688GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
12689 const char* file, int line,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012690 const std::string& message) {
Austin Schuh70cc9552019-01-21 19:46:48 -080012691 ::std::ostringstream s;
12692 s << file << ":" << line << ": " << message << ::std::endl;
12693 Log(severity, s.str(), 0);
12694}
12695
12696// Constructs an ExpectationBase object.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012697ExpectationBase::ExpectationBase(const char* a_file, int a_line,
12698 const std::string& a_source_text)
Austin Schuh70cc9552019-01-21 19:46:48 -080012699 : file_(a_file),
12700 line_(a_line),
12701 source_text_(a_source_text),
12702 cardinality_specified_(false),
12703 cardinality_(Exactly(1)),
12704 call_count_(0),
12705 retired_(false),
12706 extra_matcher_specified_(false),
12707 repeated_action_specified_(false),
12708 retires_on_saturation_(false),
12709 last_clause_(kNone),
12710 action_count_checked_(false) {}
12711
12712// Destructs an ExpectationBase object.
12713ExpectationBase::~ExpectationBase() {}
12714
12715// Explicitly specifies the cardinality of this expectation. Used by
12716// the subclasses to implement the .Times() clause.
12717void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
12718 cardinality_specified_ = true;
12719 cardinality_ = a_cardinality;
12720}
12721
12722// Retires all pre-requisites of this expectation.
12723void ExpectationBase::RetireAllPreRequisites()
12724 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
12725 if (is_retired()) {
12726 // We can take this short-cut as we never retire an expectation
12727 // until we have retired all its pre-requisites.
12728 return;
12729 }
12730
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012731 ::std::vector<ExpectationBase*> expectations(1, this);
12732 while (!expectations.empty()) {
12733 ExpectationBase* exp = expectations.back();
12734 expectations.pop_back();
12735
12736 for (ExpectationSet::const_iterator it =
12737 exp->immediate_prerequisites_.begin();
12738 it != exp->immediate_prerequisites_.end(); ++it) {
12739 ExpectationBase* next = it->expectation_base().get();
12740 if (!next->is_retired()) {
12741 next->Retire();
12742 expectations.push_back(next);
12743 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012744 }
12745 }
12746}
12747
12748// Returns true iff all pre-requisites of this expectation have been
12749// satisfied.
12750bool ExpectationBase::AllPrerequisitesAreSatisfied() const
12751 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
12752 g_gmock_mutex.AssertHeld();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012753 ::std::vector<const ExpectationBase*> expectations(1, this);
12754 while (!expectations.empty()) {
12755 const ExpectationBase* exp = expectations.back();
12756 expectations.pop_back();
12757
12758 for (ExpectationSet::const_iterator it =
12759 exp->immediate_prerequisites_.begin();
12760 it != exp->immediate_prerequisites_.end(); ++it) {
12761 const ExpectationBase* next = it->expectation_base().get();
12762 if (!next->IsSatisfied()) return false;
12763 expectations.push_back(next);
12764 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012765 }
12766 return true;
12767}
12768
12769// Adds unsatisfied pre-requisites of this expectation to 'result'.
12770void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
12771 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
12772 g_gmock_mutex.AssertHeld();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012773 ::std::vector<const ExpectationBase*> expectations(1, this);
12774 while (!expectations.empty()) {
12775 const ExpectationBase* exp = expectations.back();
12776 expectations.pop_back();
12777
12778 for (ExpectationSet::const_iterator it =
12779 exp->immediate_prerequisites_.begin();
12780 it != exp->immediate_prerequisites_.end(); ++it) {
12781 const ExpectationBase* next = it->expectation_base().get();
12782
12783 if (next->IsSatisfied()) {
12784 // If *it is satisfied and has a call count of 0, some of its
12785 // pre-requisites may not be satisfied yet.
12786 if (next->call_count_ == 0) {
12787 expectations.push_back(next);
12788 }
12789 } else {
12790 // Now that we know next is unsatisfied, we are not so interested
12791 // in whether its pre-requisites are satisfied. Therefore we
12792 // don't iterate into it here.
12793 *result += *it;
Austin Schuh70cc9552019-01-21 19:46:48 -080012794 }
Austin Schuh70cc9552019-01-21 19:46:48 -080012795 }
12796 }
12797}
12798
12799// Describes how many times a function call matching this
12800// expectation has occurred.
12801void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
12802 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
12803 g_gmock_mutex.AssertHeld();
12804
12805 // Describes how many times the function is expected to be called.
12806 *os << " Expected: to be ";
12807 cardinality().DescribeTo(os);
12808 *os << "\n Actual: ";
12809 Cardinality::DescribeActualCallCountTo(call_count(), os);
12810
12811 // Describes the state of the expectation (e.g. is it satisfied?
12812 // is it active?).
12813 *os << " - " << (IsOverSaturated() ? "over-saturated" :
12814 IsSaturated() ? "saturated" :
12815 IsSatisfied() ? "satisfied" : "unsatisfied")
12816 << " and "
12817 << (is_retired() ? "retired" : "active");
12818}
12819
12820// Checks the action count (i.e. the number of WillOnce() and
12821// WillRepeatedly() clauses) against the cardinality if this hasn't
12822// been done before. Prints a warning if there are too many or too
12823// few actions.
12824void ExpectationBase::CheckActionCountIfNotDone() const
12825 GTEST_LOCK_EXCLUDED_(mutex_) {
12826 bool should_check = false;
12827 {
12828 MutexLock l(&mutex_);
12829 if (!action_count_checked_) {
12830 action_count_checked_ = true;
12831 should_check = true;
12832 }
12833 }
12834
12835 if (should_check) {
12836 if (!cardinality_specified_) {
12837 // The cardinality was inferred - no need to check the action
12838 // count against it.
12839 return;
12840 }
12841
12842 // The cardinality was explicitly specified.
12843 const int action_count = static_cast<int>(untyped_actions_.size());
12844 const int upper_bound = cardinality().ConservativeUpperBound();
12845 const int lower_bound = cardinality().ConservativeLowerBound();
12846 bool too_many; // True if there are too many actions, or false
12847 // if there are too few.
12848 if (action_count > upper_bound ||
12849 (action_count == upper_bound && repeated_action_specified_)) {
12850 too_many = true;
12851 } else if (0 < action_count && action_count < lower_bound &&
12852 !repeated_action_specified_) {
12853 too_many = false;
12854 } else {
12855 return;
12856 }
12857
12858 ::std::stringstream ss;
12859 DescribeLocationTo(&ss);
12860 ss << "Too " << (too_many ? "many" : "few")
12861 << " actions specified in " << source_text() << "...\n"
12862 << "Expected to be ";
12863 cardinality().DescribeTo(&ss);
12864 ss << ", but has " << (too_many ? "" : "only ")
12865 << action_count << " WillOnce()"
12866 << (action_count == 1 ? "" : "s");
12867 if (repeated_action_specified_) {
12868 ss << " and a WillRepeatedly()";
12869 }
12870 ss << ".";
12871 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
12872 }
12873}
12874
12875// Implements the .Times() clause.
12876void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
12877 if (last_clause_ == kTimes) {
12878 ExpectSpecProperty(false,
12879 ".Times() cannot appear "
12880 "more than once in an EXPECT_CALL().");
12881 } else {
12882 ExpectSpecProperty(last_clause_ < kTimes,
12883 ".Times() cannot appear after "
12884 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
12885 "or .RetiresOnSaturation().");
12886 }
12887 last_clause_ = kTimes;
12888
12889 SpecifyCardinality(a_cardinality);
12890}
12891
12892// Points to the implicit sequence introduced by a living InSequence
12893// object (if any) in the current thread or NULL.
12894GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
12895
12896// Reports an uninteresting call (whose description is in msg) in the
12897// manner specified by 'reaction'.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012898void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
Austin Schuh70cc9552019-01-21 19:46:48 -080012899 // Include a stack trace only if --gmock_verbose=info is specified.
12900 const int stack_frames_to_skip =
12901 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
12902 switch (reaction) {
12903 case kAllow:
12904 Log(kInfo, msg, stack_frames_to_skip);
12905 break;
12906 case kWarn:
12907 Log(kWarning,
12908 msg +
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012909 "\nNOTE: You can safely ignore the above warning unless this "
12910 "call should not happen. Do not suppress it by blindly adding "
12911 "an EXPECT_CALL() if you don't mean to enforce the call. "
12912 "See "
12913 "https://github.com/google/googletest/blob/master/googlemock/"
12914 "docs/CookBook.md#"
12915 "knowing-when-to-expect for details.\n",
Austin Schuh70cc9552019-01-21 19:46:48 -080012916 stack_frames_to_skip);
12917 break;
12918 default: // FAIL
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012919 Expect(false, nullptr, -1, msg);
Austin Schuh70cc9552019-01-21 19:46:48 -080012920 }
12921}
12922
12923UntypedFunctionMockerBase::UntypedFunctionMockerBase()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012924 : mock_obj_(nullptr), name_("") {}
Austin Schuh70cc9552019-01-21 19:46:48 -080012925
12926UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
12927
12928// Sets the mock object this mock method belongs to, and registers
12929// this information in the global mock registry. Will be called
12930// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
12931// method.
12932void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
12933 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
12934 {
12935 MutexLock l(&g_gmock_mutex);
12936 mock_obj_ = mock_obj;
12937 }
12938 Mock::Register(mock_obj, this);
12939}
12940
12941// Sets the mock object this mock method belongs to, and sets the name
12942// of the mock function. Will be called upon each invocation of this
12943// mock function.
12944void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
12945 const char* name)
12946 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
12947 // We protect name_ under g_gmock_mutex in case this mock function
12948 // is called from two threads concurrently.
12949 MutexLock l(&g_gmock_mutex);
12950 mock_obj_ = mock_obj;
12951 name_ = name;
12952}
12953
12954// Returns the name of the function being mocked. Must be called
12955// after RegisterOwner() or SetOwnerAndName() has been called.
12956const void* UntypedFunctionMockerBase::MockObject() const
12957 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
12958 const void* mock_obj;
12959 {
12960 // We protect mock_obj_ under g_gmock_mutex in case this mock
12961 // function is called from two threads concurrently.
12962 MutexLock l(&g_gmock_mutex);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012963 Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
Austin Schuh70cc9552019-01-21 19:46:48 -080012964 "MockObject() must not be called before RegisterOwner() or "
12965 "SetOwnerAndName() has been called.");
12966 mock_obj = mock_obj_;
12967 }
12968 return mock_obj;
12969}
12970
12971// Returns the name of this mock method. Must be called after
12972// SetOwnerAndName() has been called.
12973const char* UntypedFunctionMockerBase::Name() const
12974 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
12975 const char* name;
12976 {
12977 // We protect name_ under g_gmock_mutex in case this mock
12978 // function is called from two threads concurrently.
12979 MutexLock l(&g_gmock_mutex);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012980 Assert(name_ != nullptr, __FILE__, __LINE__,
Austin Schuh70cc9552019-01-21 19:46:48 -080012981 "Name() must not be called before SetOwnerAndName() has "
12982 "been called.");
12983 name = name_;
12984 }
12985 return name;
12986}
12987
12988// Calculates the result of invoking this mock function with the given
12989// arguments, prints it, and returns it. The caller is responsible
12990// for deleting the result.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012991UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
12992 void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
12993 // See the definition of untyped_expectations_ for why access to it
12994 // is unprotected here.
Austin Schuh70cc9552019-01-21 19:46:48 -080012995 if (untyped_expectations_.size() == 0) {
12996 // No expectation is set on this mock method - we have an
12997 // uninteresting call.
12998
12999 // We must get Google Mock's reaction on uninteresting calls
13000 // made on this mock object BEFORE performing the action,
13001 // because the action may DELETE the mock object and make the
13002 // following expression meaningless.
13003 const CallReaction reaction =
13004 Mock::GetReactionOnUninterestingCalls(MockObject());
13005
13006 // True iff we need to print this call's arguments and return
13007 // value. This definition must be kept in sync with
13008 // the behavior of ReportUninterestingCall().
13009 const bool need_to_report_uninteresting_call =
13010 // If the user allows this uninteresting call, we print it
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013011 // only when they want informational messages.
Austin Schuh70cc9552019-01-21 19:46:48 -080013012 reaction == kAllow ? LogIsVisible(kInfo) :
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013013 // If the user wants this to be a warning, we print
13014 // it only when they want to see warnings.
13015 reaction == kWarn
13016 ? LogIsVisible(kWarning)
13017 :
13018 // Otherwise, the user wants this to be an error, and we
13019 // should always print detailed information in the error.
13020 true;
Austin Schuh70cc9552019-01-21 19:46:48 -080013021
13022 if (!need_to_report_uninteresting_call) {
13023 // Perform the action without printing the call information.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013024 return this->UntypedPerformDefaultAction(
13025 untyped_args, "Function call: " + std::string(Name()));
Austin Schuh70cc9552019-01-21 19:46:48 -080013026 }
13027
13028 // Warns about the uninteresting call.
13029 ::std::stringstream ss;
13030 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
13031
13032 // Calculates the function result.
13033 UntypedActionResultHolderBase* const result =
13034 this->UntypedPerformDefaultAction(untyped_args, ss.str());
13035
13036 // Prints the function result.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013037 if (result != nullptr) result->PrintAsActionResult(&ss);
Austin Schuh70cc9552019-01-21 19:46:48 -080013038
13039 ReportUninterestingCall(reaction, ss.str());
13040 return result;
13041 }
13042
13043 bool is_excessive = false;
13044 ::std::stringstream ss;
13045 ::std::stringstream why;
13046 ::std::stringstream loc;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013047 const void* untyped_action = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080013048
13049 // The UntypedFindMatchingExpectation() function acquires and
13050 // releases g_gmock_mutex.
13051 const ExpectationBase* const untyped_expectation =
13052 this->UntypedFindMatchingExpectation(
13053 untyped_args, &untyped_action, &is_excessive,
13054 &ss, &why);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013055 const bool found = untyped_expectation != nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080013056
13057 // True iff we need to print the call's arguments and return value.
13058 // This definition must be kept in sync with the uses of Expect()
13059 // and Log() in this function.
13060 const bool need_to_report_call =
13061 !found || is_excessive || LogIsVisible(kInfo);
13062 if (!need_to_report_call) {
13063 // Perform the action without printing the call information.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013064 return untyped_action == nullptr
13065 ? this->UntypedPerformDefaultAction(untyped_args, "")
13066 : this->UntypedPerformAction(untyped_action, untyped_args);
Austin Schuh70cc9552019-01-21 19:46:48 -080013067 }
13068
13069 ss << " Function call: " << Name();
13070 this->UntypedPrintArgs(untyped_args, &ss);
13071
13072 // In case the action deletes a piece of the expectation, we
13073 // generate the message beforehand.
13074 if (found && !is_excessive) {
13075 untyped_expectation->DescribeLocationTo(&loc);
13076 }
13077
13078 UntypedActionResultHolderBase* const result =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013079 untyped_action == nullptr
13080 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
13081 : this->UntypedPerformAction(untyped_action, untyped_args);
13082 if (result != nullptr) result->PrintAsActionResult(&ss);
Austin Schuh70cc9552019-01-21 19:46:48 -080013083 ss << "\n" << why.str();
13084
13085 if (!found) {
13086 // No expectation matches this call - reports a failure.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013087 Expect(false, nullptr, -1, ss.str());
Austin Schuh70cc9552019-01-21 19:46:48 -080013088 } else if (is_excessive) {
13089 // We had an upper-bound violation and the failure message is in ss.
13090 Expect(false, untyped_expectation->file(),
13091 untyped_expectation->line(), ss.str());
13092 } else {
13093 // We had an expected call and the matching expectation is
13094 // described in ss.
13095 Log(kInfo, loc.str() + ss.str(), 2);
13096 }
13097
13098 return result;
13099}
13100
13101// Returns an Expectation object that references and co-owns exp,
13102// which must be an expectation on this mock function.
13103Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013104 // See the definition of untyped_expectations_ for why access to it
13105 // is unprotected here.
Austin Schuh70cc9552019-01-21 19:46:48 -080013106 for (UntypedExpectations::const_iterator it =
13107 untyped_expectations_.begin();
13108 it != untyped_expectations_.end(); ++it) {
13109 if (it->get() == exp) {
13110 return Expectation(*it);
13111 }
13112 }
13113
13114 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
13115 return Expectation();
13116 // The above statement is just to make the code compile, and will
13117 // never be executed.
13118}
13119
13120// Verifies that all expectations on this mock function have been
13121// satisfied. Reports one or more Google Test non-fatal failures
13122// and returns false if not.
13123bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
13124 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
13125 g_gmock_mutex.AssertHeld();
13126 bool expectations_met = true;
13127 for (UntypedExpectations::const_iterator it =
13128 untyped_expectations_.begin();
13129 it != untyped_expectations_.end(); ++it) {
13130 ExpectationBase* const untyped_expectation = it->get();
13131 if (untyped_expectation->IsOverSaturated()) {
13132 // There was an upper-bound violation. Since the error was
13133 // already reported when it occurred, there is no need to do
13134 // anything here.
13135 expectations_met = false;
13136 } else if (!untyped_expectation->IsSatisfied()) {
13137 expectations_met = false;
13138 ::std::stringstream ss;
13139 ss << "Actual function call count doesn't match "
13140 << untyped_expectation->source_text() << "...\n";
13141 // No need to show the source file location of the expectation
13142 // in the description, as the Expect() call that follows already
13143 // takes care of it.
13144 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
13145 untyped_expectation->DescribeCallCountTo(&ss);
13146 Expect(false, untyped_expectation->file(),
13147 untyped_expectation->line(), ss.str());
13148 }
13149 }
13150
13151 // Deleting our expectations may trigger other mock objects to be deleted, for
13152 // example if an action contains a reference counted smart pointer to that
13153 // mock object, and that is the last reference. So if we delete our
13154 // expectations within the context of the global mutex we may deadlock when
13155 // this method is called again. Instead, make a copy of the set of
13156 // expectations to delete, clear our set within the mutex, and then clear the
13157 // copied set outside of it.
13158 UntypedExpectations expectations_to_delete;
13159 untyped_expectations_.swap(expectations_to_delete);
13160
13161 g_gmock_mutex.Unlock();
13162 expectations_to_delete.clear();
13163 g_gmock_mutex.Lock();
13164
13165 return expectations_met;
13166}
13167
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013168CallReaction intToCallReaction(int mock_behavior) {
13169 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
13170 return static_cast<internal::CallReaction>(mock_behavior);
13171 }
13172 return kWarn;
13173}
13174
Austin Schuh70cc9552019-01-21 19:46:48 -080013175} // namespace internal
13176
13177// Class Mock.
13178
13179namespace {
13180
13181typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
13182
13183// The current state of a mock object. Such information is needed for
13184// detecting leaked mock objects and explicitly verifying a mock's
13185// expectations.
13186struct MockObjectState {
13187 MockObjectState()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013188 : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
Austin Schuh70cc9552019-01-21 19:46:48 -080013189
13190 // Where in the source file an ON_CALL or EXPECT_CALL is first
13191 // invoked on this mock object.
13192 const char* first_used_file;
13193 int first_used_line;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013194 ::std::string first_used_test_suite;
Austin Schuh70cc9552019-01-21 19:46:48 -080013195 ::std::string first_used_test;
13196 bool leakable; // true iff it's OK to leak the object.
13197 FunctionMockers function_mockers; // All registered methods of the object.
13198};
13199
13200// A global registry holding the state of all mock objects that are
13201// alive. A mock object is added to this registry the first time
13202// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
13203// is removed from the registry in the mock object's destructor.
13204class MockObjectRegistry {
13205 public:
13206 // Maps a mock object (identified by its address) to its state.
13207 typedef std::map<const void*, MockObjectState> StateMap;
13208
13209 // This destructor will be called when a program exits, after all
13210 // tests in it have been run. By then, there should be no mock
13211 // object alive. Therefore we report any living object as test
13212 // failure, unless the user explicitly asked us to ignore it.
13213 ~MockObjectRegistry() {
Austin Schuh70cc9552019-01-21 19:46:48 -080013214 if (!GMOCK_FLAG(catch_leaked_mocks))
13215 return;
13216
13217 int leaked_count = 0;
13218 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
13219 ++it) {
13220 if (it->second.leakable) // The user said it's fine to leak this object.
13221 continue;
13222
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013223 // FIXME: Print the type of the leaked object.
Austin Schuh70cc9552019-01-21 19:46:48 -080013224 // This can help the user identify the leaked object.
13225 std::cout << "\n";
13226 const MockObjectState& state = it->second;
13227 std::cout << internal::FormatFileLocation(state.first_used_file,
13228 state.first_used_line);
13229 std::cout << " ERROR: this mock object";
13230 if (state.first_used_test != "") {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013231 std::cout << " (used in test " << state.first_used_test_suite << "."
13232 << state.first_used_test << ")";
Austin Schuh70cc9552019-01-21 19:46:48 -080013233 }
13234 std::cout << " should be deleted but never is. Its address is @"
13235 << it->first << ".";
13236 leaked_count++;
13237 }
13238 if (leaked_count > 0) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013239 std::cout << "\nERROR: " << leaked_count << " leaked mock "
13240 << (leaked_count == 1 ? "object" : "objects")
13241 << " found at program exit. Expectations on a mock object is "
13242 "verified when the object is destructed. Leaking a mock "
13243 "means that its expectations aren't verified, which is "
13244 "usually a test bug. If you really intend to leak a mock, "
13245 "you can suppress this error using "
13246 "testing::Mock::AllowLeak(mock_object), or you may use a "
13247 "fake or stub instead of a mock.\n";
Austin Schuh70cc9552019-01-21 19:46:48 -080013248 std::cout.flush();
13249 ::std::cerr.flush();
13250 // RUN_ALL_TESTS() has already returned when this destructor is
13251 // called. Therefore we cannot use the normal Google Test
13252 // failure reporting mechanism.
13253 _exit(1); // We cannot call exit() as it is not reentrant and
13254 // may already have been called.
13255 }
13256 }
13257
13258 StateMap& states() { return states_; }
13259
13260 private:
13261 StateMap states_;
13262};
13263
13264// Protected by g_gmock_mutex.
13265MockObjectRegistry g_mock_object_registry;
13266
13267// Maps a mock object to the reaction Google Mock should have when an
13268// uninteresting method is called. Protected by g_gmock_mutex.
13269std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
13270
13271// Sets the reaction Google Mock should have when an uninteresting
13272// method of the given mock object is called.
13273void SetReactionOnUninterestingCalls(const void* mock_obj,
13274 internal::CallReaction reaction)
13275 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13276 internal::MutexLock l(&internal::g_gmock_mutex);
13277 g_uninteresting_call_reaction[mock_obj] = reaction;
13278}
13279
13280} // namespace
13281
13282// Tells Google Mock to allow uninteresting calls on the given mock
13283// object.
13284void Mock::AllowUninterestingCalls(const void* mock_obj)
13285 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13286 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
13287}
13288
13289// Tells Google Mock to warn the user about uninteresting calls on the
13290// given mock object.
13291void Mock::WarnUninterestingCalls(const void* mock_obj)
13292 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13293 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
13294}
13295
13296// Tells Google Mock to fail uninteresting calls on the given mock
13297// object.
13298void Mock::FailUninterestingCalls(const void* mock_obj)
13299 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13300 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
13301}
13302
13303// Tells Google Mock the given mock object is being destroyed and its
13304// entry in the call-reaction table should be removed.
13305void Mock::UnregisterCallReaction(const void* mock_obj)
13306 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13307 internal::MutexLock l(&internal::g_gmock_mutex);
13308 g_uninteresting_call_reaction.erase(mock_obj);
13309}
13310
13311// Returns the reaction Google Mock will have on uninteresting calls
13312// made on the given mock object.
13313internal::CallReaction Mock::GetReactionOnUninterestingCalls(
13314 const void* mock_obj)
13315 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13316 internal::MutexLock l(&internal::g_gmock_mutex);
13317 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013318 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
13319 g_uninteresting_call_reaction[mock_obj];
Austin Schuh70cc9552019-01-21 19:46:48 -080013320}
13321
13322// Tells Google Mock to ignore mock_obj when checking for leaked mock
13323// objects.
13324void Mock::AllowLeak(const void* mock_obj)
13325 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13326 internal::MutexLock l(&internal::g_gmock_mutex);
13327 g_mock_object_registry.states()[mock_obj].leakable = true;
13328}
13329
13330// Verifies and clears all expectations on the given mock object. If
13331// the expectations aren't satisfied, generates one or more Google
13332// Test non-fatal failures and returns false.
13333bool Mock::VerifyAndClearExpectations(void* mock_obj)
13334 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13335 internal::MutexLock l(&internal::g_gmock_mutex);
13336 return VerifyAndClearExpectationsLocked(mock_obj);
13337}
13338
13339// Verifies all expectations on the given mock object and clears its
13340// default actions and expectations. Returns true iff the
13341// verification was successful.
13342bool Mock::VerifyAndClear(void* mock_obj)
13343 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13344 internal::MutexLock l(&internal::g_gmock_mutex);
13345 ClearDefaultActionsLocked(mock_obj);
13346 return VerifyAndClearExpectationsLocked(mock_obj);
13347}
13348
13349// Verifies and clears all expectations on the given mock object. If
13350// the expectations aren't satisfied, generates one or more Google
13351// Test non-fatal failures and returns false.
13352bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
13353 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
13354 internal::g_gmock_mutex.AssertHeld();
13355 if (g_mock_object_registry.states().count(mock_obj) == 0) {
13356 // No EXPECT_CALL() was set on the given mock object.
13357 return true;
13358 }
13359
13360 // Verifies and clears the expectations on each mock method in the
13361 // given mock object.
13362 bool expectations_met = true;
13363 FunctionMockers& mockers =
13364 g_mock_object_registry.states()[mock_obj].function_mockers;
13365 for (FunctionMockers::const_iterator it = mockers.begin();
13366 it != mockers.end(); ++it) {
13367 if (!(*it)->VerifyAndClearExpectationsLocked()) {
13368 expectations_met = false;
13369 }
13370 }
13371
13372 // We don't clear the content of mockers, as they may still be
13373 // needed by ClearDefaultActionsLocked().
13374 return expectations_met;
13375}
13376
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013377bool Mock::IsNaggy(void* mock_obj)
13378 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13379 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
13380}
13381bool Mock::IsNice(void* mock_obj)
13382 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13383 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
13384}
13385bool Mock::IsStrict(void* mock_obj)
13386 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13387 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
13388}
13389
Austin Schuh70cc9552019-01-21 19:46:48 -080013390// Registers a mock object and a mock method it owns.
13391void Mock::Register(const void* mock_obj,
13392 internal::UntypedFunctionMockerBase* mocker)
13393 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13394 internal::MutexLock l(&internal::g_gmock_mutex);
13395 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
13396}
13397
13398// Tells Google Mock where in the source code mock_obj is used in an
13399// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
13400// information helps the user identify which object it is.
13401void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
13402 const char* file, int line)
13403 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
13404 internal::MutexLock l(&internal::g_gmock_mutex);
13405 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013406 if (state.first_used_file == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080013407 state.first_used_file = file;
13408 state.first_used_line = line;
13409 const TestInfo* const test_info =
13410 UnitTest::GetInstance()->current_test_info();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013411 if (test_info != nullptr) {
13412 state.first_used_test_suite = test_info->test_suite_name();
Austin Schuh70cc9552019-01-21 19:46:48 -080013413 state.first_used_test = test_info->name();
13414 }
13415 }
13416}
13417
13418// Unregisters a mock method; removes the owning mock object from the
13419// registry when the last mock method associated with it has been
13420// unregistered. This is called only in the destructor of
13421// FunctionMockerBase.
13422void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
13423 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
13424 internal::g_gmock_mutex.AssertHeld();
13425 for (MockObjectRegistry::StateMap::iterator it =
13426 g_mock_object_registry.states().begin();
13427 it != g_mock_object_registry.states().end(); ++it) {
13428 FunctionMockers& mockers = it->second.function_mockers;
13429 if (mockers.erase(mocker) > 0) {
13430 // mocker was in mockers and has been just removed.
13431 if (mockers.empty()) {
13432 g_mock_object_registry.states().erase(it);
13433 }
13434 return;
13435 }
13436 }
13437}
13438
13439// Clears all ON_CALL()s set on the given mock object.
13440void Mock::ClearDefaultActionsLocked(void* mock_obj)
13441 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
13442 internal::g_gmock_mutex.AssertHeld();
13443
13444 if (g_mock_object_registry.states().count(mock_obj) == 0) {
13445 // No ON_CALL() was set on the given mock object.
13446 return;
13447 }
13448
13449 // Clears the default actions for each mock method in the given mock
13450 // object.
13451 FunctionMockers& mockers =
13452 g_mock_object_registry.states()[mock_obj].function_mockers;
13453 for (FunctionMockers::const_iterator it = mockers.begin();
13454 it != mockers.end(); ++it) {
13455 (*it)->ClearDefaultActionsLocked();
13456 }
13457
13458 // We don't clear the content of mockers, as they may still be
13459 // needed by VerifyAndClearExpectationsLocked().
13460}
13461
13462Expectation::Expectation() {}
13463
13464Expectation::Expectation(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013465 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
Austin Schuh70cc9552019-01-21 19:46:48 -080013466 : expectation_base_(an_expectation_base) {}
13467
13468Expectation::~Expectation() {}
13469
13470// Adds an expectation to a sequence.
13471void Sequence::AddExpectation(const Expectation& expectation) const {
13472 if (*last_expectation_ != expectation) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013473 if (last_expectation_->expectation_base() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080013474 expectation.expectation_base()->immediate_prerequisites_
13475 += *last_expectation_;
13476 }
13477 *last_expectation_ = expectation;
13478 }
13479}
13480
13481// Creates the implicit sequence if there isn't one.
13482InSequence::InSequence() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013483 if (internal::g_gmock_implicit_sequence.get() == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080013484 internal::g_gmock_implicit_sequence.set(new Sequence);
13485 sequence_created_ = true;
13486 } else {
13487 sequence_created_ = false;
13488 }
13489}
13490
13491// Deletes the implicit sequence if it was created by the constructor
13492// of this object.
13493InSequence::~InSequence() {
13494 if (sequence_created_) {
13495 delete internal::g_gmock_implicit_sequence.get();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013496 internal::g_gmock_implicit_sequence.set(nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -080013497 }
13498}
13499
13500} // namespace testing
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013501
13502#ifdef _MSC_VER
13503#if _MSC_VER == 1900
13504# pragma warning(pop)
13505#endif
13506#endif
Austin Schuh70cc9552019-01-21 19:46:48 -080013507// Copyright 2008, Google Inc.
13508// All rights reserved.
13509//
13510// Redistribution and use in source and binary forms, with or without
13511// modification, are permitted provided that the following conditions are
13512// met:
13513//
13514// * Redistributions of source code must retain the above copyright
13515// notice, this list of conditions and the following disclaimer.
13516// * Redistributions in binary form must reproduce the above
13517// copyright notice, this list of conditions and the following disclaimer
13518// in the documentation and/or other materials provided with the
13519// distribution.
13520// * Neither the name of Google Inc. nor the names of its
13521// contributors may be used to endorse or promote products derived from
13522// this software without specific prior written permission.
13523//
13524// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
13525// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
13526// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
13527// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
13528// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
13529// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
13530// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
13531// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13532// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13533// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13534// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013535
Austin Schuh70cc9552019-01-21 19:46:48 -080013536
13537
13538namespace testing {
13539
Austin Schuh70cc9552019-01-21 19:46:48 -080013540GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
13541 "true iff Google Mock should report leaked mock objects "
13542 "as failures.");
13543
13544GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
13545 "Controls how verbose Google Mock's output is."
13546 " Valid values:\n"
13547 " info - prints all messages.\n"
13548 " warning - prints warnings and errors.\n"
13549 " error - prints errors only.");
13550
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013551GMOCK_DEFINE_int32_(default_mock_behavior, 1,
13552 "Controls the default behavior of mocks."
13553 " Valid values:\n"
13554 " 0 - by default, mocks act as NiceMocks.\n"
13555 " 1 - by default, mocks act as NaggyMocks.\n"
13556 " 2 - by default, mocks act as StrictMocks.");
13557
Austin Schuh70cc9552019-01-21 19:46:48 -080013558namespace internal {
13559
13560// Parses a string as a command line flag. The string should have the
13561// format "--gmock_flag=value". When def_optional is true, the
13562// "=value" part can be omitted.
13563//
13564// Returns the value of the flag, or NULL if the parsing failed.
13565static const char* ParseGoogleMockFlagValue(const char* str,
13566 const char* flag,
13567 bool def_optional) {
13568 // str and flag must not be NULL.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013569 if (str == nullptr || flag == nullptr) return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080013570
13571 // The flag must start with "--gmock_".
13572 const std::string flag_str = std::string("--gmock_") + flag;
13573 const size_t flag_len = flag_str.length();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013574 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080013575
13576 // Skips the flag name.
13577 const char* flag_end = str + flag_len;
13578
13579 // When def_optional is true, it's OK to not have a "=value" part.
13580 if (def_optional && (flag_end[0] == '\0')) {
13581 return flag_end;
13582 }
13583
13584 // If def_optional is true and there are more characters after the
13585 // flag name, or if def_optional is false, there must be a '=' after
13586 // the flag name.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013587 if (flag_end[0] != '=') return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080013588
13589 // Returns the string after "=".
13590 return flag_end + 1;
13591}
13592
13593// Parses a string for a Google Mock bool flag, in the form of
13594// "--gmock_flag=value".
13595//
13596// On success, stores the value of the flag in *value, and returns
13597// true. On failure, returns false without changing *value.
13598static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
13599 bool* value) {
13600 // Gets the value of the flag as a string.
13601 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
13602
13603 // Aborts if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013604 if (value_str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -080013605
13606 // Converts the string value to a bool.
13607 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
13608 return true;
13609}
13610
13611// Parses a string for a Google Mock string flag, in the form of
13612// "--gmock_flag=value".
13613//
13614// On success, stores the value of the flag in *value, and returns
13615// true. On failure, returns false without changing *value.
13616template <typename String>
13617static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
13618 String* value) {
13619 // Gets the value of the flag as a string.
13620 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
13621
13622 // Aborts if the parsing failed.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013623 if (value_str == nullptr) return false;
Austin Schuh70cc9552019-01-21 19:46:48 -080013624
13625 // Sets *value to the value of the flag.
13626 *value = value_str;
13627 return true;
13628}
13629
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013630static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
13631 int* value) {
13632 // Gets the value of the flag as a string.
13633 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
13634
13635 // Aborts if the parsing failed.
13636 if (value_str == nullptr) return false;
13637
13638 // Sets *value to the value of the flag.
13639 return ParseInt32(Message() << "The value of flag --" << flag,
13640 value_str, value);
13641}
13642
Austin Schuh70cc9552019-01-21 19:46:48 -080013643// The internal implementation of InitGoogleMock().
13644//
13645// The type parameter CharType can be instantiated to either char or
13646// wchar_t.
13647template <typename CharType>
13648void InitGoogleMockImpl(int* argc, CharType** argv) {
13649 // Makes sure Google Test is initialized. InitGoogleTest() is
13650 // idempotent, so it's fine if the user has already called it.
13651 InitGoogleTest(argc, argv);
13652 if (*argc <= 0) return;
13653
13654 for (int i = 1; i != *argc; i++) {
13655 const std::string arg_string = StreamableToString(argv[i]);
13656 const char* const arg = arg_string.c_str();
13657
13658 // Do we see a Google Mock flag?
13659 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
13660 &GMOCK_FLAG(catch_leaked_mocks)) ||
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013661 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
13662 ParseGoogleMockIntFlag(arg, "default_mock_behavior",
13663 &GMOCK_FLAG(default_mock_behavior))) {
Austin Schuh70cc9552019-01-21 19:46:48 -080013664 // Yes. Shift the remainder of the argv list left by one. Note
13665 // that argv has (*argc + 1) elements, the last one always being
13666 // NULL. The following loop moves the trailing NULL element as
13667 // well.
13668 for (int j = i; j != *argc; j++) {
13669 argv[j] = argv[j + 1];
13670 }
13671
13672 // Decrements the argument count.
13673 (*argc)--;
13674
13675 // We also need to decrement the iterator as we just removed
13676 // an element.
13677 i--;
13678 }
13679 }
13680}
13681
13682} // namespace internal
13683
13684// Initializes Google Mock. This must be called before running the
13685// tests. In particular, it parses a command line for the flags that
13686// Google Mock recognizes. Whenever a Google Mock flag is seen, it is
13687// removed from argv, and *argc is decremented.
13688//
13689// No value is returned. Instead, the Google Mock flag variables are
13690// updated.
13691//
13692// Since Google Test is needed for Google Mock to work, this function
13693// also initializes Google Test and parses its flags, if that hasn't
13694// been done.
13695GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
13696 internal::InitGoogleMockImpl(argc, argv);
13697}
13698
13699// This overloaded version can be used in Windows programs compiled in
13700// UNICODE mode.
13701GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
13702 internal::InitGoogleMockImpl(argc, argv);
13703}
13704
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080013705// This overloaded version can be used on Arduino/embedded platforms where
13706// there is no argc/argv.
13707GTEST_API_ void InitGoogleMock() {
13708 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
13709 int argc = 1;
13710 const auto arg0 = "dummy";
13711 char* argv0 = const_cast<char*>(arg0);
13712 char** argv = &argv0;
13713
13714 internal::InitGoogleMockImpl(&argc, argv);
13715}
13716
Austin Schuh70cc9552019-01-21 19:46:48 -080013717} // namespace testing