1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // The Google C++ Testing and Mocking Framework (Google Test)
33 #include "gtest/gtest.h"
34 #include "gtest/internal/custom/gtest.h"
35 #include "gtest/gtest-spi.h"
46 #include <chrono> // NOLINT
53 #include <ostream> // NOLINT
59 # include <fcntl.h> // NOLINT
60 # include <limits.h> // NOLINT
61 # include <sched.h> // NOLINT
62 // Declares vsnprintf(). This header is not available on Windows.
63 # include <strings.h> // NOLINT
64 # include <sys/mman.h> // NOLINT
65 # include <sys/time.h> // NOLINT
66 # include <unistd.h> // NOLINT
70 # include <sys/time.h> // NOLINT
72 // On z/OS we additionally need strings.h for strcasecmp.
73 # include <strings.h> // NOLINT
75 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
77 # include <windows.h> // NOLINT
80 #elif GTEST_OS_WINDOWS // We are on Windows proper.
82 # include <windows.h> // NOLINT
86 # include <crtdbg.h> // NOLINT
89 # include <io.h> // NOLINT
90 # include <sys/timeb.h> // NOLINT
91 # include <sys/types.h> // NOLINT
92 # include <sys/stat.h> // NOLINT
94 # if GTEST_OS_WINDOWS_MINGW
95 # include <sys/time.h> // NOLINT
96 # endif // GTEST_OS_WINDOWS_MINGW
100 // cpplint thinks that the header is already included, so we want to
102 # include <sys/time.h> // NOLINT
103 # include <unistd.h> // NOLINT
105 #endif // GTEST_OS_LINUX
107 #if GTEST_HAS_EXCEPTIONS
108 # include <stdexcept>
111 #if GTEST_CAN_STREAM_RESULTS_
112 # include <arpa/inet.h> // NOLINT
113 # include <netdb.h> // NOLINT
114 # include <sys/socket.h> // NOLINT
115 # include <sys/types.h> // NOLINT
118 #include "src/gtest-internal-inl.h"
121 # define vsnprintf _vsnprintf
122 #endif // GTEST_OS_WINDOWS
126 #include <crt_externs.h>
131 #include "absl/debugging/failure_signal_handler.h"
132 #include "absl/debugging/stacktrace.h"
133 #include "absl/debugging/symbolize.h"
134 #include "absl/strings/str_cat.h"
135 #endif // GTEST_HAS_ABSL
139 using internal::CountIf
;
140 using internal::ForEach
;
141 using internal::GetElementOr
;
142 using internal::Shuffle
;
146 // A test whose test suite name or test name matches this filter is
147 // disabled and not run.
148 static const char kDisableTestFilter
[] = "DISABLED_*:*/DISABLED_*";
150 // A test suite whose name matches this filter is considered a death
151 // test suite and will be run before test suites whose name doesn't
152 // match this filter.
153 static const char kDeathTestSuiteFilter
[] = "*DeathTest:*DeathTest/*";
155 // A test filter that matches everything.
156 static const char kUniversalFilter
[] = "*";
158 // The default output format.
159 static const char kDefaultOutputFormat
[] = "xml";
160 // The default output file.
161 static const char kDefaultOutputFile
[] = "test_detail";
163 // The environment variable name for the test shard index.
164 static const char kTestShardIndex
[] = "GTEST_SHARD_INDEX";
165 // The environment variable name for the total number of test shards.
166 static const char kTestTotalShards
[] = "GTEST_TOTAL_SHARDS";
167 // The environment variable name for the test shard status file.
168 static const char kTestShardStatusFile
[] = "GTEST_SHARD_STATUS_FILE";
172 // The text used in failure messages to indicate the start of the
174 const char kStackTraceMarker
[] = "\nStack trace:\n";
176 // g_help_flag is true if and only if the --help flag or an equivalent form
177 // is specified on the command line.
178 bool g_help_flag
= false;
180 // Utilty function to Open File for Writing
181 static FILE* OpenFileForWriting(const std::string
& output_file
) {
182 FILE* fileout
= nullptr;
183 FilePath
output_file_path(output_file
);
184 FilePath
output_dir(output_file_path
.RemoveFileName());
186 if (output_dir
.CreateDirectoriesRecursively()) {
187 fileout
= posix::FOpen(output_file
.c_str(), "w");
189 if (fileout
== nullptr) {
190 GTEST_LOG_(FATAL
) << "Unable to open file \"" << output_file
<< "\"";
195 } // namespace internal
197 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
198 // environment variable.
199 static const char* GetDefaultFilter() {
200 const char* const testbridge_test_only
=
201 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
202 if (testbridge_test_only
!= nullptr) {
203 return testbridge_test_only
;
205 return kUniversalFilter
;
208 // Bazel passes in the argument to '--test_runner_fail_fast' via the
209 // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
210 static bool GetDefaultFailFast() {
211 const char* const testbridge_test_runner_fail_fast
=
212 internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
213 if (testbridge_test_runner_fail_fast
!= nullptr) {
214 return strcmp(testbridge_test_runner_fail_fast
, "1") == 0;
220 fail_fast
, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
221 "True if and only if a test failure should stop further test execution.");
224 also_run_disabled_tests
,
225 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
226 "Run disabled tests too, in addition to the tests normally being run.");
229 break_on_failure
, internal::BoolFromGTestEnv("break_on_failure", false),
230 "True if and only if a failed assertion should be a debugger "
233 GTEST_DEFINE_bool_(catch_exceptions
,
234 internal::BoolFromGTestEnv("catch_exceptions", true),
235 "True if and only if " GTEST_NAME_
236 " should catch exceptions and treat them as test failures.");
238 GTEST_DEFINE_string_(
240 internal::StringFromGTestEnv("color", "auto"),
241 "Whether to use colors in the output. Valid values: yes, no, "
242 "and auto. 'auto' means to use colors if the output is "
243 "being sent to a terminal and the TERM environment variable "
244 "is set to a terminal type that supports colors.");
246 GTEST_DEFINE_string_(
248 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
249 "A colon-separated list of glob (not regex) patterns "
250 "for filtering the tests to run, optionally followed by a "
251 "'-' and a : separated list of negative patterns (tests to "
252 "exclude). A test is run if it matches one of the positive "
253 "patterns and does not match any of the negative patterns.");
256 install_failure_signal_handler
,
257 internal::BoolFromGTestEnv("install_failure_signal_handler", false),
258 "If true and supported on the current platform, " GTEST_NAME_
" should "
259 "install a signal handler that dumps debugging information when fatal "
260 "signals are raised.");
262 GTEST_DEFINE_bool_(list_tests
, false,
263 "List all tests without running them.");
265 // The net priority order after flag processing is thus:
266 // --gtest_output command line flag
267 // GTEST_OUTPUT environment variable
268 // XML_OUTPUT_FILE environment variable
270 GTEST_DEFINE_string_(
272 internal::StringFromGTestEnv("output",
273 internal::OutputFlagAlsoCheckEnvVar().c_str()),
274 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
275 "optionally followed by a colon and an output file name or directory. "
276 "A directory is indicated by a trailing pathname separator. "
277 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
278 "If a directory is specified, output files will be created "
279 "within that directory, with file-names based on the test "
280 "executable's name and, if necessary, made unique by adding "
284 brief
, internal::BoolFromGTestEnv("brief", false),
285 "True if only test failures should be displayed in text output.");
287 GTEST_DEFINE_bool_(print_time
, internal::BoolFromGTestEnv("print_time", true),
288 "True if and only if " GTEST_NAME_
289 " should display elapsed time in text output.");
291 GTEST_DEFINE_bool_(print_utf8
, internal::BoolFromGTestEnv("print_utf8", true),
292 "True if and only if " GTEST_NAME_
293 " prints UTF8 characters as text.");
297 internal::Int32FromGTestEnv("random_seed", 0),
298 "Random number seed to use when shuffling test orders. Must be in range "
299 "[1, 99999], or 0 to use a seed based on the current time.");
303 internal::Int32FromGTestEnv("repeat", 1),
304 "How many times to repeat each test. Specify a negative number "
305 "for repeating forever. Useful for shaking out flaky tests.");
307 GTEST_DEFINE_bool_(show_internal_stack_frames
, false,
308 "True if and only if " GTEST_NAME_
309 " should include internal stack frames when "
310 "printing test failure stack traces.");
312 GTEST_DEFINE_bool_(shuffle
, internal::BoolFromGTestEnv("shuffle", false),
313 "True if and only if " GTEST_NAME_
314 " should randomize tests' order on every run.");
318 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth
),
319 "The maximum number of stack frames to print when an "
320 "assertion fails. The valid range is 0 through 100, inclusive.");
322 GTEST_DEFINE_string_(
324 internal::StringFromGTestEnv("stream_result_to", ""),
325 "This flag specifies the host name and the port number on which to stream "
326 "test results. Example: \"localhost:555\". The flag is effective only on "
331 internal::BoolFromGTestEnv("throw_on_failure", false),
332 "When this flag is specified, a failed assertion will throw an exception "
333 "if exceptions are enabled or exit the program with a non-zero code "
334 "otherwise. For use with an external test framework.");
336 #if GTEST_USE_OWN_FLAGFILE_FLAG_
337 GTEST_DEFINE_string_(
339 internal::StringFromGTestEnv("flagfile", ""),
340 "This flag specifies the flagfile to read command-line flags from.");
341 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
345 // Generates a random number from [0, range), using a Linear
346 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
348 uint32_t Random::Generate(uint32_t range
) {
349 // These constants are the same as are used in glibc's rand(3).
350 // Use wider types than necessary to prevent unsigned overflow diagnostics.
351 state_
= static_cast<uint32_t>(1103515245ULL*state_
+ 12345U) % kMaxRange
;
353 GTEST_CHECK_(range
> 0)
354 << "Cannot generate a number in the range [0, 0).";
355 GTEST_CHECK_(range
<= kMaxRange
)
356 << "Generation of a number in [0, " << range
<< ") was requested, "
357 << "but this can only generate numbers in [0, " << kMaxRange
<< ").";
359 // Converting via modulus introduces a bit of downward bias, but
360 // it's simple, and a linear congruential generator isn't too good
362 return state_
% range
;
365 // GTestIsInitialized() returns true if and only if the user has initialized
366 // Google Test. Useful for catching the user mistake of not initializing
367 // Google Test before calling RUN_ALL_TESTS().
368 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
370 // Iterates over a vector of TestSuites, keeping a running sum of the
371 // results of calling a given int-returning method on each.
373 static int SumOverTestSuiteList(const std::vector
<TestSuite
*>& case_list
,
374 int (TestSuite::*method
)() const) {
376 for (size_t i
= 0; i
< case_list
.size(); i
++) {
377 sum
+= (case_list
[i
]->*method
)();
382 // Returns true if and only if the test suite passed.
383 static bool TestSuitePassed(const TestSuite
* test_suite
) {
384 return test_suite
->should_run() && test_suite
->Passed();
387 // Returns true if and only if the test suite failed.
388 static bool TestSuiteFailed(const TestSuite
* test_suite
) {
389 return test_suite
->should_run() && test_suite
->Failed();
392 // Returns true if and only if test_suite contains at least one test that
394 static bool ShouldRunTestSuite(const TestSuite
* test_suite
) {
395 return test_suite
->should_run();
398 // AssertHelper constructor.
399 AssertHelper::AssertHelper(TestPartResult::Type type
,
403 : data_(new AssertHelperData(type
, file
, line
, message
)) {
406 AssertHelper::~AssertHelper() {
410 // Message assignment, for assertion streaming support.
411 void AssertHelper::operator=(const Message
& message
) const {
412 UnitTest::GetInstance()->
413 AddTestPartResult(data_
->type
, data_
->file
, data_
->line
,
414 AppendUserMessage(data_
->message
, message
),
415 UnitTest::GetInstance()->impl()
416 ->CurrentOsStackTraceExceptTop(1)
417 // Skips the stack frame for this function itself.
423 // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
424 // to creates test cases for it, a syntetic test case is
425 // inserted to report ether an error or a log message.
427 // This configuration bit will likely be removed at some point.
428 constexpr bool kErrorOnUninstantiatedParameterizedTest
= true;
429 constexpr bool kErrorOnUninstantiatedTypeParameterizedTest
= true;
431 // A test that fails at a given file/line location with a given message.
432 class FailureTest
: public Test
{
434 explicit FailureTest(const CodeLocation
& loc
, std::string error_message
,
437 error_message_(std::move(error_message
)),
438 as_error_(as_error
) {}
440 void TestBody() override
{
442 AssertHelper(TestPartResult::kNonFatalFailure
, loc_
.file
.c_str(),
443 loc_
.line
, "") = Message() << error_message_
;
445 std::cout
<< error_message_
<< std::endl
;
450 const CodeLocation loc_
;
451 const std::string error_message_
;
452 const bool as_error_
;
458 std::set
<std::string
>* GetIgnoredParameterizedTestSuites() {
459 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
462 // Add a given test_suit to the list of them allow to go un-instantiated.
463 MarkAsIgnored::MarkAsIgnored(const char* test_suite
) {
464 GetIgnoredParameterizedTestSuites()->insert(test_suite
);
467 // If this parameterized test suite has no instantiations (and that
468 // has not been marked as okay), emit a test case reporting that.
469 void InsertSyntheticTestCase(const std::string
& name
, CodeLocation location
,
471 const auto& ignored
= *GetIgnoredParameterizedTestSuites();
472 if (ignored
.find(name
) != ignored
.end()) return;
474 const char kMissingInstantiation
[] = //
475 " is defined via TEST_P, but never instantiated. None of the test cases "
476 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
477 "ones provided expand to nothing."
479 "Ideally, TEST_P definitions should only ever be included as part of "
480 "binaries that intend to use them. (As opposed to, for example, being "
481 "placed in a library that may be linked in to get other utilities.)";
483 const char kMissingTestCase
[] = //
484 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
485 "defined via TEST_P . No test cases will run."
487 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
488 "code that always depend on code that provides TEST_P. Failing to do "
489 "so is often an indication of dead code, e.g. the last TEST_P was "
490 "removed but the rest got left behind.";
492 std::string message
=
493 "Parameterized test suite " + name
+
494 (has_test_p
? kMissingInstantiation
: kMissingTestCase
) +
496 "To suppress this error for this test suite, insert the following line "
497 "(in a non-header) in the namespace it is defined in:"
499 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name
+ ");";
501 std::string full_name
= "UninstantiatedParameterizedTestSuite<" + name
+ ">";
503 "GoogleTestVerification", full_name
.c_str(),
504 nullptr, // No type parameter.
505 nullptr, // No value parameter.
506 location
.file
.c_str(), location
.line
, [message
, location
] {
507 return new FailureTest(location
, message
,
508 kErrorOnUninstantiatedParameterizedTest
);
512 void RegisterTypeParameterizedTestSuite(const char* test_suite_name
,
513 CodeLocation code_location
) {
514 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
515 test_suite_name
, code_location
);
518 void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name
) {
520 ->type_parameterized_test_registry()
521 .RegisterInstantiation(case_name
);
524 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
525 const char* test_suite_name
, CodeLocation code_location
) {
526 suites_
.emplace(std::string(test_suite_name
),
527 TypeParameterizedTestSuiteInfo(code_location
));
530 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
531 const char* test_suite_name
) {
532 auto it
= suites_
.find(std::string(test_suite_name
));
533 if (it
!= suites_
.end()) {
534 it
->second
.instantiated
= true;
536 GTEST_LOG_(ERROR
) << "Unknown type parameterized test suit '"
537 << test_suite_name
<< "'";
541 void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
542 const auto& ignored
= *GetIgnoredParameterizedTestSuites();
543 for (const auto& testcase
: suites_
) {
544 if (testcase
.second
.instantiated
) continue;
545 if (ignored
.find(testcase
.first
) != ignored
.end()) continue;
547 std::string message
=
548 "Type parameterized test suite " + testcase
.first
+
549 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
550 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
552 "Ideally, TYPED_TEST_P definitions should only ever be included as "
553 "part of binaries that intend to use them. (As opposed to, for "
554 "example, being placed in a library that may be linked in to get other "
557 "To suppress this error for this test suite, insert the following line "
558 "(in a non-header) in the namespace it is defined in:"
560 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
561 testcase
.first
+ ");";
563 std::string full_name
=
564 "UninstantiatedTypeParameterizedTestSuite<" + testcase
.first
+ ">";
566 "GoogleTestVerification", full_name
.c_str(),
567 nullptr, // No type parameter.
568 nullptr, // No value parameter.
569 testcase
.second
.code_location
.file
.c_str(),
570 testcase
.second
.code_location
.line
, [message
, testcase
] {
571 return new FailureTest(testcase
.second
.code_location
, message
,
572 kErrorOnUninstantiatedTypeParameterizedTest
);
577 // A copy of all command line arguments. Set by InitGoogleTest().
578 static ::std::vector
<std::string
> g_argvs
;
580 ::std::vector
<std::string
> GetArgvs() {
581 #if defined(GTEST_CUSTOM_GET_ARGVS_)
582 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
583 // ::string. This code converts it to the appropriate type.
584 const auto& custom
= GTEST_CUSTOM_GET_ARGVS_();
585 return ::std::vector
<std::string
>(custom
.begin(), custom
.end());
586 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
588 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
591 // Returns the current application's name, removing directory path if that
593 FilePath
GetCurrentExecutableName() {
596 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
597 result
.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
599 result
.Set(FilePath(GetArgvs()[0]));
600 #endif // GTEST_OS_WINDOWS
602 return result
.RemoveDirectoryName();
605 // Functions for processing the gtest_output flag.
607 // Returns the output format, or "" for normal printed output.
608 std::string
UnitTestOptions::GetOutputFormat() {
609 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
610 const char* const colon
= strchr(gtest_output_flag
, ':');
611 return (colon
== nullptr)
612 ? std::string(gtest_output_flag
)
613 : std::string(gtest_output_flag
,
614 static_cast<size_t>(colon
- gtest_output_flag
));
617 // Returns the name of the requested output file, or the default if none
618 // was explicitly specified.
619 std::string
UnitTestOptions::GetAbsolutePathToOutputFile() {
620 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
622 std::string format
= GetOutputFormat();
624 format
= std::string(kDefaultOutputFormat
);
626 const char* const colon
= strchr(gtest_output_flag
, ':');
627 if (colon
== nullptr)
628 return internal::FilePath::MakeFileName(
630 UnitTest::GetInstance()->original_working_dir()),
631 internal::FilePath(kDefaultOutputFile
), 0,
632 format
.c_str()).string();
634 internal::FilePath
output_name(colon
+ 1);
635 if (!output_name
.IsAbsolutePath())
636 output_name
= internal::FilePath::ConcatPaths(
637 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
638 internal::FilePath(colon
+ 1));
640 if (!output_name
.IsDirectory())
641 return output_name
.string();
643 internal::FilePath
result(internal::FilePath::GenerateUniqueFileName(
644 output_name
, internal::GetCurrentExecutableName(),
645 GetOutputFormat().c_str()));
646 return result
.string();
649 // Returns true if and only if the wildcard pattern matches the string.
650 // The first ':' or '\0' character in pattern marks the end of it.
652 // This recursive algorithm isn't very efficient, but is clear and
653 // works well enough for matching test names, which are short.
654 bool UnitTestOptions::PatternMatchesString(const char *pattern
,
658 case ':': // Either ':' or '\0' marks the end of the pattern.
660 case '?': // Matches any single character.
661 return *str
!= '\0' && PatternMatchesString(pattern
+ 1, str
+ 1);
662 case '*': // Matches any string (possibly empty) of characters.
663 return (*str
!= '\0' && PatternMatchesString(pattern
, str
+ 1)) ||
664 PatternMatchesString(pattern
+ 1, str
);
665 default: // Non-special character. Matches itself.
666 return *pattern
== *str
&&
667 PatternMatchesString(pattern
+ 1, str
+ 1);
671 bool UnitTestOptions::MatchesFilter(
672 const std::string
& name
, const char* filter
) {
673 const char *cur_pattern
= filter
;
675 if (PatternMatchesString(cur_pattern
, name
.c_str())) {
679 // Finds the next pattern in the filter.
680 cur_pattern
= strchr(cur_pattern
, ':');
682 // Returns if no more pattern can be found.
683 if (cur_pattern
== nullptr) {
687 // Skips the pattern separater (the ':' character).
692 // Returns true if and only if the user-specified filter matches the test
693 // suite name and the test name.
694 bool UnitTestOptions::FilterMatchesTest(const std::string
& test_suite_name
,
695 const std::string
& test_name
) {
696 const std::string
& full_name
= test_suite_name
+ "." + test_name
.c_str();
698 // Split --gtest_filter at '-', if there is one, to separate into
699 // positive filter and negative filter portions
700 const char* const p
= GTEST_FLAG(filter
).c_str();
701 const char* const dash
= strchr(p
, '-');
702 std::string positive
;
703 std::string negative
;
704 if (dash
== nullptr) {
705 positive
= GTEST_FLAG(filter
).c_str(); // Whole string is a positive filter
708 positive
= std::string(p
, dash
); // Everything up to the dash
709 negative
= std::string(dash
+ 1); // Everything after the dash
710 if (positive
.empty()) {
711 // Treat '-test1' as the same as '*-test1'
712 positive
= kUniversalFilter
;
716 // A filter is a colon-separated list of patterns. It matches a
717 // test if any pattern in it matches the test.
718 return (MatchesFilter(full_name
, positive
.c_str()) &&
719 !MatchesFilter(full_name
, negative
.c_str()));
723 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
724 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
725 // This function is useful as an __except condition.
726 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code
) {
727 // Google Test should handle a SEH exception if:
728 // 1. the user wants it to, AND
729 // 2. this is not a breakpoint exception, AND
730 // 3. this is not a C++ exception (VC++ implements them via SEH,
733 // SEH exception code for C++ exceptions.
734 // (see http://support.microsoft.com/kb/185294 for more information).
735 const DWORD kCxxExceptionCode
= 0xe06d7363;
737 bool should_handle
= true;
739 if (!GTEST_FLAG(catch_exceptions
))
740 should_handle
= false;
741 else if (exception_code
== EXCEPTION_BREAKPOINT
)
742 should_handle
= false;
743 else if (exception_code
== kCxxExceptionCode
)
744 should_handle
= false;
746 return should_handle
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
;
748 #endif // GTEST_HAS_SEH
750 } // namespace internal
752 // The c'tor sets this object as the test part result reporter used by
753 // Google Test. The 'result' parameter specifies where to report the
754 // results. Intercepts only failures from the current thread.
755 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
756 TestPartResultArray
* result
)
757 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD
),
762 // The c'tor sets this object as the test part result reporter used by
763 // Google Test. The 'result' parameter specifies where to report the
765 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
766 InterceptMode intercept_mode
, TestPartResultArray
* result
)
767 : intercept_mode_(intercept_mode
),
772 void ScopedFakeTestPartResultReporter::Init() {
773 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
774 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
775 old_reporter_
= impl
->GetGlobalTestPartResultReporter();
776 impl
->SetGlobalTestPartResultReporter(this);
778 old_reporter_
= impl
->GetTestPartResultReporterForCurrentThread();
779 impl
->SetTestPartResultReporterForCurrentThread(this);
783 // The d'tor restores the test part result reporter used by Google Test
785 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
786 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
787 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
788 impl
->SetGlobalTestPartResultReporter(old_reporter_
);
790 impl
->SetTestPartResultReporterForCurrentThread(old_reporter_
);
794 // Increments the test part result count and remembers the result.
795 // This method is from the TestPartResultReporterInterface interface.
796 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
797 const TestPartResult
& result
) {
798 result_
->Append(result
);
803 // Returns the type ID of ::testing::Test. We should always call this
804 // instead of GetTypeId< ::testing::Test>() to get the type ID of
805 // testing::Test. This is to work around a suspected linker bug when
806 // using Google Test as a framework on Mac OS X. The bug causes
807 // GetTypeId< ::testing::Test>() to return different values depending
808 // on whether the call is from the Google Test framework itself or
809 // from user test code. GetTestTypeId() is guaranteed to always
810 // return the same value, as it always calls GetTypeId<>() from the
811 // gtest.cc, which is within the Google Test framework.
812 TypeId
GetTestTypeId() {
813 return GetTypeId
<Test
>();
816 // The value of GetTestTypeId() as seen from within the Google Test
817 // library. This is solely for testing GetTestTypeId().
818 extern const TypeId kTestTypeIdInGoogleTest
= GetTestTypeId();
820 // This predicate-formatter checks that 'results' contains a test part
821 // failure of the given type and that the failure message contains the
823 static AssertionResult
HasOneFailure(const char* /* results_expr */,
824 const char* /* type_expr */,
825 const char* /* substr_expr */,
826 const TestPartResultArray
& results
,
827 TestPartResult::Type type
,
828 const std::string
& substr
) {
829 const std::string
expected(type
== TestPartResult::kFatalFailure
?
831 "1 non-fatal failure");
833 if (results
.size() != 1) {
834 msg
<< "Expected: " << expected
<< "\n"
835 << " Actual: " << results
.size() << " failures";
836 for (int i
= 0; i
< results
.size(); i
++) {
837 msg
<< "\n" << results
.GetTestPartResult(i
);
839 return AssertionFailure() << msg
;
842 const TestPartResult
& r
= results
.GetTestPartResult(0);
843 if (r
.type() != type
) {
844 return AssertionFailure() << "Expected: " << expected
<< "\n"
849 if (strstr(r
.message(), substr
.c_str()) == nullptr) {
850 return AssertionFailure() << "Expected: " << expected
<< " containing \""
856 return AssertionSuccess();
859 // The constructor of SingleFailureChecker remembers where to look up
860 // test part results, what type of failure we expect, and what
861 // substring the failure message should contain.
862 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray
* results
,
863 TestPartResult::Type type
,
864 const std::string
& substr
)
865 : results_(results
), type_(type
), substr_(substr
) {}
867 // The destructor of SingleFailureChecker verifies that the given
868 // TestPartResultArray contains exactly one failure that has the given
869 // type and contains the given substring. If that's not the case, a
870 // non-fatal failure will be generated.
871 SingleFailureChecker::~SingleFailureChecker() {
872 EXPECT_PRED_FORMAT3(HasOneFailure
, *results_
, type_
, substr_
);
875 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
876 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
878 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
879 const TestPartResult
& result
) {
880 unit_test_
->current_test_result()->AddTestPartResult(result
);
881 unit_test_
->listeners()->repeater()->OnTestPartResult(result
);
884 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
885 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
887 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
888 const TestPartResult
& result
) {
889 unit_test_
->GetGlobalTestPartResultReporter()->ReportTestPartResult(result
);
892 // Returns the global test part result reporter.
893 TestPartResultReporterInterface
*
894 UnitTestImpl::GetGlobalTestPartResultReporter() {
895 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
896 return global_test_part_result_repoter_
;
899 // Sets the global test part result reporter.
900 void UnitTestImpl::SetGlobalTestPartResultReporter(
901 TestPartResultReporterInterface
* reporter
) {
902 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
903 global_test_part_result_repoter_
= reporter
;
906 // Returns the test part result reporter for the current thread.
907 TestPartResultReporterInterface
*
908 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
909 return per_thread_test_part_result_reporter_
.get();
912 // Sets the test part result reporter for the current thread.
913 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
914 TestPartResultReporterInterface
* reporter
) {
915 per_thread_test_part_result_reporter_
.set(reporter
);
918 // Gets the number of successful test suites.
919 int UnitTestImpl::successful_test_suite_count() const {
920 return CountIf(test_suites_
, TestSuitePassed
);
923 // Gets the number of failed test suites.
924 int UnitTestImpl::failed_test_suite_count() const {
925 return CountIf(test_suites_
, TestSuiteFailed
);
928 // Gets the number of all test suites.
929 int UnitTestImpl::total_test_suite_count() const {
930 return static_cast<int>(test_suites_
.size());
933 // Gets the number of all test suites that contain at least one test
935 int UnitTestImpl::test_suite_to_run_count() const {
936 return CountIf(test_suites_
, ShouldRunTestSuite
);
939 // Gets the number of successful tests.
940 int UnitTestImpl::successful_test_count() const {
941 return SumOverTestSuiteList(test_suites_
, &TestSuite::successful_test_count
);
944 // Gets the number of skipped tests.
945 int UnitTestImpl::skipped_test_count() const {
946 return SumOverTestSuiteList(test_suites_
, &TestSuite::skipped_test_count
);
949 // Gets the number of failed tests.
950 int UnitTestImpl::failed_test_count() const {
951 return SumOverTestSuiteList(test_suites_
, &TestSuite::failed_test_count
);
954 // Gets the number of disabled tests that will be reported in the XML report.
955 int UnitTestImpl::reportable_disabled_test_count() const {
956 return SumOverTestSuiteList(test_suites_
,
957 &TestSuite::reportable_disabled_test_count
);
960 // Gets the number of disabled tests.
961 int UnitTestImpl::disabled_test_count() const {
962 return SumOverTestSuiteList(test_suites_
, &TestSuite::disabled_test_count
);
965 // Gets the number of tests to be printed in the XML report.
966 int UnitTestImpl::reportable_test_count() const {
967 return SumOverTestSuiteList(test_suites_
, &TestSuite::reportable_test_count
);
970 // Gets the number of all tests.
971 int UnitTestImpl::total_test_count() const {
972 return SumOverTestSuiteList(test_suites_
, &TestSuite::total_test_count
);
975 // Gets the number of tests that should run.
976 int UnitTestImpl::test_to_run_count() const {
977 return SumOverTestSuiteList(test_suites_
, &TestSuite::test_to_run_count
);
980 // Returns the current OS stack trace as an std::string.
982 // The maximum number of stack frames to be included is specified by
983 // the gtest_stack_trace_depth flag. The skip_count parameter
984 // specifies the number of top frames to be skipped, which doesn't
985 // count against the number of frames to be included.
987 // For example, if Foo() calls Bar(), which in turn calls
988 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
989 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
990 std::string
UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count
) {
991 return os_stack_trace_getter()->CurrentStackTrace(
992 static_cast<int>(GTEST_FLAG(stack_trace_depth
)),
994 // Skips the user-specified number of frames plus this function
999 // Returns the current time in milliseconds.
1000 TimeInMillis
GetTimeInMillis() {
1001 return std::chrono::duration_cast
<std::chrono::milliseconds
>(
1002 std::chrono::system_clock::now() -
1003 std::chrono::system_clock::from_time_t(0))
1011 #if GTEST_OS_WINDOWS_MOBILE
1012 // Creates a UTF-16 wide string from the given ANSI string, allocating
1013 // memory using new. The caller is responsible for deleting the return
1014 // value using delete[]. Returns the wide string, or NULL if the
1016 LPCWSTR
String::AnsiToUtf16(const char* ansi
) {
1017 if (!ansi
) return nullptr;
1018 const int length
= strlen(ansi
);
1019 const int unicode_length
=
1020 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
, nullptr, 0);
1021 WCHAR
* unicode
= new WCHAR
[unicode_length
+ 1];
1022 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
,
1023 unicode
, unicode_length
);
1024 unicode
[unicode_length
] = 0;
1028 // Creates an ANSI string from the given wide string, allocating
1029 // memory using new. The caller is responsible for deleting the return
1030 // value using delete[]. Returns the ANSI string, or NULL if the
1032 const char* String::Utf16ToAnsi(LPCWSTR utf16_str
) {
1033 if (!utf16_str
) return nullptr;
1034 const int ansi_length
= WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, nullptr,
1035 0, nullptr, nullptr);
1036 char* ansi
= new char[ansi_length
+ 1];
1037 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, ansi
, ansi_length
, nullptr,
1039 ansi
[ansi_length
] = 0;
1043 #endif // GTEST_OS_WINDOWS_MOBILE
1045 // Compares two C strings. Returns true if and only if they have the same
1048 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
1049 // C string is considered different to any non-NULL C string,
1050 // including the empty string.
1051 bool String::CStringEquals(const char * lhs
, const char * rhs
) {
1052 if (lhs
== nullptr) return rhs
== nullptr;
1054 if (rhs
== nullptr) return false;
1056 return strcmp(lhs
, rhs
) == 0;
1059 #if GTEST_HAS_STD_WSTRING
1061 // Converts an array of wide chars to a narrow string using the UTF-8
1062 // encoding, and streams the result to the given Message object.
1063 static void StreamWideCharsToMessage(const wchar_t* wstr
, size_t length
,
1065 for (size_t i
= 0; i
!= length
; ) { // NOLINT
1066 if (wstr
[i
] != L
'\0') {
1067 *msg
<< WideStringToUtf8(wstr
+ i
, static_cast<int>(length
- i
));
1068 while (i
!= length
&& wstr
[i
] != L
'\0')
1077 #endif // GTEST_HAS_STD_WSTRING
1079 void SplitString(const ::std::string
& str
, char delimiter
,
1080 ::std::vector
< ::std::string
>* dest
) {
1081 ::std::vector
< ::std::string
> parsed
;
1082 ::std::string::size_type pos
= 0;
1083 while (::testing::internal::AlwaysTrue()) {
1084 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
1085 if (colon
== ::std::string::npos
) {
1086 parsed
.push_back(str
.substr(pos
));
1089 parsed
.push_back(str
.substr(pos
, colon
- pos
));
1096 } // namespace internal
1098 // Constructs an empty Message.
1099 // We allocate the stringstream separately because otherwise each use of
1100 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
1101 // stack frame leading to huge stack frames in some cases; gcc does not reuse
1103 Message::Message() : ss_(new ::std::stringstream
) {
1104 // By default, we want there to be enough precision when printing
1105 // a double to a Message.
1106 *ss_
<< std::setprecision(std::numeric_limits
<double>::digits10
+ 2);
1109 // These two overloads allow streaming a wide C string to a Message
1110 // using the UTF-8 encoding.
1111 Message
& Message::operator <<(const wchar_t* wide_c_str
) {
1112 return *this << internal::String::ShowWideCString(wide_c_str
);
1114 Message
& Message::operator <<(wchar_t* wide_c_str
) {
1115 return *this << internal::String::ShowWideCString(wide_c_str
);
1118 #if GTEST_HAS_STD_WSTRING
1119 // Converts the given wide string to a narrow string using the UTF-8
1120 // encoding, and streams the result to this Message object.
1121 Message
& Message::operator <<(const ::std::wstring
& wstr
) {
1122 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
1125 #endif // GTEST_HAS_STD_WSTRING
1127 // Gets the text streamed to this object so far as an std::string.
1128 // Each '\0' character in the buffer is replaced with "\\0".
1129 std::string
Message::GetString() const {
1130 return internal::StringStreamToString(ss_
.get());
1133 // AssertionResult constructors.
1134 // Used in EXPECT_TRUE/FALSE(assertion_result).
1135 AssertionResult::AssertionResult(const AssertionResult
& other
)
1136 : success_(other
.success_
),
1137 message_(other
.message_
.get() != nullptr
1138 ? new ::std::string(*other
.message_
)
1139 : static_cast< ::std::string
*>(nullptr)) {}
1141 // Swaps two AssertionResults.
1142 void AssertionResult::swap(AssertionResult
& other
) {
1144 swap(success_
, other
.success_
);
1145 swap(message_
, other
.message_
);
1148 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1149 AssertionResult
AssertionResult::operator!() const {
1150 AssertionResult
negation(!success_
);
1151 if (message_
.get() != nullptr) negation
<< *message_
;
1155 // Makes a successful assertion result.
1156 AssertionResult
AssertionSuccess() {
1157 return AssertionResult(true);
1160 // Makes a failed assertion result.
1161 AssertionResult
AssertionFailure() {
1162 return AssertionResult(false);
1165 // Makes a failed assertion result with the given failure message.
1166 // Deprecated; use AssertionFailure() << message.
1167 AssertionResult
AssertionFailure(const Message
& message
) {
1168 return AssertionFailure() << message
;
1171 namespace internal
{
1173 namespace edit_distance
{
1174 std::vector
<EditType
> CalculateOptimalEdits(const std::vector
<size_t>& left
,
1175 const std::vector
<size_t>& right
) {
1176 std::vector
<std::vector
<double> > costs(
1177 left
.size() + 1, std::vector
<double>(right
.size() + 1));
1178 std::vector
<std::vector
<EditType
> > best_move(
1179 left
.size() + 1, std::vector
<EditType
>(right
.size() + 1));
1181 // Populate for empty right.
1182 for (size_t l_i
= 0; l_i
< costs
.size(); ++l_i
) {
1183 costs
[l_i
][0] = static_cast<double>(l_i
);
1184 best_move
[l_i
][0] = kRemove
;
1186 // Populate for empty left.
1187 for (size_t r_i
= 1; r_i
< costs
[0].size(); ++r_i
) {
1188 costs
[0][r_i
] = static_cast<double>(r_i
);
1189 best_move
[0][r_i
] = kAdd
;
1192 for (size_t l_i
= 0; l_i
< left
.size(); ++l_i
) {
1193 for (size_t r_i
= 0; r_i
< right
.size(); ++r_i
) {
1194 if (left
[l_i
] == right
[r_i
]) {
1195 // Found a match. Consume it.
1196 costs
[l_i
+ 1][r_i
+ 1] = costs
[l_i
][r_i
];
1197 best_move
[l_i
+ 1][r_i
+ 1] = kMatch
;
1201 const double add
= costs
[l_i
+ 1][r_i
];
1202 const double remove
= costs
[l_i
][r_i
+ 1];
1203 const double replace
= costs
[l_i
][r_i
];
1204 if (add
< remove
&& add
< replace
) {
1205 costs
[l_i
+ 1][r_i
+ 1] = add
+ 1;
1206 best_move
[l_i
+ 1][r_i
+ 1] = kAdd
;
1207 } else if (remove
< add
&& remove
< replace
) {
1208 costs
[l_i
+ 1][r_i
+ 1] = remove
+ 1;
1209 best_move
[l_i
+ 1][r_i
+ 1] = kRemove
;
1211 // We make replace a little more expensive than add/remove to lower
1213 costs
[l_i
+ 1][r_i
+ 1] = replace
+ 1.00001;
1214 best_move
[l_i
+ 1][r_i
+ 1] = kReplace
;
1219 // Reconstruct the best path. We do it in reverse order.
1220 std::vector
<EditType
> best_path
;
1221 for (size_t l_i
= left
.size(), r_i
= right
.size(); l_i
> 0 || r_i
> 0;) {
1222 EditType move
= best_move
[l_i
][r_i
];
1223 best_path
.push_back(move
);
1224 l_i
-= move
!= kAdd
;
1225 r_i
-= move
!= kRemove
;
1227 std::reverse(best_path
.begin(), best_path
.end());
1233 // Helper class to convert string into ids with deduplication.
1234 class InternalStrings
{
1236 size_t GetId(const std::string
& str
) {
1237 IdMap::iterator it
= ids_
.find(str
);
1238 if (it
!= ids_
.end()) return it
->second
;
1239 size_t id
= ids_
.size();
1240 return ids_
[str
] = id
;
1244 typedef std::map
<std::string
, size_t> IdMap
;
1250 std::vector
<EditType
> CalculateOptimalEdits(
1251 const std::vector
<std::string
>& left
,
1252 const std::vector
<std::string
>& right
) {
1253 std::vector
<size_t> left_ids
, right_ids
;
1255 InternalStrings intern_table
;
1256 for (size_t i
= 0; i
< left
.size(); ++i
) {
1257 left_ids
.push_back(intern_table
.GetId(left
[i
]));
1259 for (size_t i
= 0; i
< right
.size(); ++i
) {
1260 right_ids
.push_back(intern_table
.GetId(right
[i
]));
1263 return CalculateOptimalEdits(left_ids
, right_ids
);
1268 // Helper class that holds the state for one hunk and prints it out to the
1270 // It reorders adds/removes when possible to group all removes before all
1271 // adds. It also adds the hunk header before printint into the stream.
1274 Hunk(size_t left_start
, size_t right_start
)
1275 : left_start_(left_start
),
1276 right_start_(right_start
),
1281 void PushLine(char edit
, const char* line
) {
1286 hunk_
.push_back(std::make_pair(' ', line
));
1290 hunk_removes_
.push_back(std::make_pair('-', line
));
1294 hunk_adds_
.push_back(std::make_pair('+', line
));
1299 void PrintTo(std::ostream
* os
) {
1302 for (std::list
<std::pair
<char, const char*> >::const_iterator it
=
1304 it
!= hunk_
.end(); ++it
) {
1305 *os
<< it
->first
<< it
->second
<< "\n";
1309 bool has_edits() const { return adds_
|| removes_
; }
1313 hunk_
.splice(hunk_
.end(), hunk_removes_
);
1314 hunk_
.splice(hunk_
.end(), hunk_adds_
);
1317 // Print a unified diff header for one hunk.
1319 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1320 // where the left/right parts are omitted if unnecessary.
1321 void PrintHeader(std::ostream
* ss
) const {
1324 *ss
<< "-" << left_start_
<< "," << (removes_
+ common_
);
1326 if (removes_
&& adds_
) {
1330 *ss
<< "+" << right_start_
<< "," << (adds_
+ common_
);
1335 size_t left_start_
, right_start_
;
1336 size_t adds_
, removes_
, common_
;
1337 std::list
<std::pair
<char, const char*> > hunk_
, hunk_adds_
, hunk_removes_
;
1342 // Create a list of diff hunks in Unified diff format.
1343 // Each hunk has a header generated by PrintHeader above plus a body with
1344 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
1346 // 'context' represents the desired unchanged prefix/suffix around the diff.
1347 // If two hunks are close enough that their contexts overlap, then they are
1348 // joined into one hunk.
1349 std::string
CreateUnifiedDiff(const std::vector
<std::string
>& left
,
1350 const std::vector
<std::string
>& right
,
1352 const std::vector
<EditType
> edits
= CalculateOptimalEdits(left
, right
);
1354 size_t l_i
= 0, r_i
= 0, edit_i
= 0;
1355 std::stringstream ss
;
1356 while (edit_i
< edits
.size()) {
1358 while (edit_i
< edits
.size() && edits
[edit_i
] == kMatch
) {
1364 // Find the first line to include in the hunk.
1365 const size_t prefix_context
= std::min(l_i
, context
);
1366 Hunk
hunk(l_i
- prefix_context
+ 1, r_i
- prefix_context
+ 1);
1367 for (size_t i
= prefix_context
; i
> 0; --i
) {
1368 hunk
.PushLine(' ', left
[l_i
- i
].c_str());
1371 // Iterate the edits until we found enough suffix for the hunk or the input
1373 size_t n_suffix
= 0;
1374 for (; edit_i
< edits
.size(); ++edit_i
) {
1375 if (n_suffix
>= context
) {
1376 // Continue only if the next hunk is very close.
1377 auto it
= edits
.begin() + static_cast<int>(edit_i
);
1378 while (it
!= edits
.end() && *it
== kMatch
) ++it
;
1379 if (it
== edits
.end() ||
1380 static_cast<size_t>(it
- edits
.begin()) - edit_i
>= context
) {
1381 // There is no next edit or it is too far away.
1386 EditType edit
= edits
[edit_i
];
1387 // Reset count when a non match is found.
1388 n_suffix
= edit
== kMatch
? n_suffix
+ 1 : 0;
1390 if (edit
== kMatch
|| edit
== kRemove
|| edit
== kReplace
) {
1391 hunk
.PushLine(edit
== kMatch
? ' ' : '-', left
[l_i
].c_str());
1393 if (edit
== kAdd
|| edit
== kReplace
) {
1394 hunk
.PushLine('+', right
[r_i
].c_str());
1397 // Advance indices, depending on edit type.
1398 l_i
+= edit
!= kAdd
;
1399 r_i
+= edit
!= kRemove
;
1402 if (!hunk
.has_edits()) {
1403 // We are done. We don't want this hunk.
1412 } // namespace edit_distance
1416 // The string representation of the values received in EqFailure() are already
1417 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1418 // characters the same.
1419 std::vector
<std::string
> SplitEscapedString(const std::string
& str
) {
1420 std::vector
<std::string
> lines
;
1421 size_t start
= 0, end
= str
.size();
1422 if (end
> 2 && str
[0] == '"' && str
[end
- 1] == '"') {
1426 bool escaped
= false;
1427 for (size_t i
= start
; i
+ 1 < end
; ++i
) {
1430 if (str
[i
] == 'n') {
1431 lines
.push_back(str
.substr(start
, i
- start
- 1));
1435 escaped
= str
[i
] == '\\';
1438 lines
.push_back(str
.substr(start
, end
- start
));
1444 // Constructs and returns the message for an equality assertion
1445 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1447 // The first four parameters are the expressions used in the assertion
1448 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1449 // where foo is 5 and bar is 6, we have:
1451 // lhs_expression: "foo"
1452 // rhs_expression: "bar"
1456 // The ignoring_case parameter is true if and only if the assertion is a
1457 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
1458 // be inserted into the message.
1459 AssertionResult
EqFailure(const char* lhs_expression
,
1460 const char* rhs_expression
,
1461 const std::string
& lhs_value
,
1462 const std::string
& rhs_value
,
1463 bool ignoring_case
) {
1465 msg
<< "Expected equality of these values:";
1466 msg
<< "\n " << lhs_expression
;
1467 if (lhs_value
!= lhs_expression
) {
1468 msg
<< "\n Which is: " << lhs_value
;
1470 msg
<< "\n " << rhs_expression
;
1471 if (rhs_value
!= rhs_expression
) {
1472 msg
<< "\n Which is: " << rhs_value
;
1475 if (ignoring_case
) {
1476 msg
<< "\nIgnoring case";
1479 if (!lhs_value
.empty() && !rhs_value
.empty()) {
1480 const std::vector
<std::string
> lhs_lines
=
1481 SplitEscapedString(lhs_value
);
1482 const std::vector
<std::string
> rhs_lines
=
1483 SplitEscapedString(rhs_value
);
1484 if (lhs_lines
.size() > 1 || rhs_lines
.size() > 1) {
1485 msg
<< "\nWith diff:\n"
1486 << edit_distance::CreateUnifiedDiff(lhs_lines
, rhs_lines
);
1490 return AssertionFailure() << msg
;
1493 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1494 std::string
GetBoolAssertionFailureMessage(
1495 const AssertionResult
& assertion_result
,
1496 const char* expression_text
,
1497 const char* actual_predicate_value
,
1498 const char* expected_predicate_value
) {
1499 const char* actual_message
= assertion_result
.message();
1501 msg
<< "Value of: " << expression_text
1502 << "\n Actual: " << actual_predicate_value
;
1503 if (actual_message
[0] != '\0')
1504 msg
<< " (" << actual_message
<< ")";
1505 msg
<< "\nExpected: " << expected_predicate_value
;
1506 return msg
.GetString();
1509 // Helper function for implementing ASSERT_NEAR.
1510 AssertionResult
DoubleNearPredFormat(const char* expr1
,
1512 const char* abs_error_expr
,
1516 const double diff
= fabs(val1
- val2
);
1517 if (diff
<= abs_error
) return AssertionSuccess();
1519 // Find the value which is closest to zero.
1520 const double min_abs
= std::min(fabs(val1
), fabs(val2
));
1521 // Find the distance to the next double from that value.
1522 const double epsilon
=
1523 nextafter(min_abs
, std::numeric_limits
<double>::infinity()) - min_abs
;
1524 // Detect the case where abs_error is so small that EXPECT_NEAR is
1525 // effectively the same as EXPECT_EQUAL, and give an informative error
1526 // message so that the situation can be more easily understood without
1527 // requiring exotic floating-point knowledge.
1528 // Don't do an epsilon check if abs_error is zero because that implies
1529 // that an equality check was actually intended.
1530 if (!(std::isnan
)(val1
) && !(std::isnan
)(val2
) && abs_error
> 0 &&
1531 abs_error
< epsilon
) {
1532 return AssertionFailure()
1533 << "The difference between " << expr1
<< " and " << expr2
<< " is "
1534 << diff
<< ", where\n"
1535 << expr1
<< " evaluates to " << val1
<< ",\n"
1536 << expr2
<< " evaluates to " << val2
<< ".\nThe abs_error parameter "
1537 << abs_error_expr
<< " evaluates to " << abs_error
1538 << " which is smaller than the minimum distance between doubles for "
1539 "numbers of this magnitude which is "
1541 << ", thus making this EXPECT_NEAR check equivalent to "
1542 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1544 return AssertionFailure()
1545 << "The difference between " << expr1
<< " and " << expr2
1546 << " is " << diff
<< ", which exceeds " << abs_error_expr
<< ", where\n"
1547 << expr1
<< " evaluates to " << val1
<< ",\n"
1548 << expr2
<< " evaluates to " << val2
<< ", and\n"
1549 << abs_error_expr
<< " evaluates to " << abs_error
<< ".";
1553 // Helper template for implementing FloatLE() and DoubleLE().
1554 template <typename RawType
>
1555 AssertionResult
FloatingPointLE(const char* expr1
,
1559 // Returns success if val1 is less than val2,
1561 return AssertionSuccess();
1564 // or if val1 is almost equal to val2.
1565 const FloatingPoint
<RawType
> lhs(val1
), rhs(val2
);
1566 if (lhs
.AlmostEquals(rhs
)) {
1567 return AssertionSuccess();
1570 // Note that the above two checks will both fail if either val1 or
1571 // val2 is NaN, as the IEEE floating-point standard requires that
1572 // any predicate involving a NaN must return false.
1574 ::std::stringstream val1_ss
;
1575 val1_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
1578 ::std::stringstream val2_ss
;
1579 val2_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
1582 return AssertionFailure()
1583 << "Expected: (" << expr1
<< ") <= (" << expr2
<< ")\n"
1584 << " Actual: " << StringStreamToString(&val1_ss
) << " vs "
1585 << StringStreamToString(&val2_ss
);
1588 } // namespace internal
1590 // Asserts that val1 is less than, or almost equal to, val2. Fails
1591 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1592 AssertionResult
FloatLE(const char* expr1
, const char* expr2
,
1593 float val1
, float val2
) {
1594 return internal::FloatingPointLE
<float>(expr1
, expr2
, val1
, val2
);
1597 // Asserts that val1 is less than, or almost equal to, val2. Fails
1598 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1599 AssertionResult
DoubleLE(const char* expr1
, const char* expr2
,
1600 double val1
, double val2
) {
1601 return internal::FloatingPointLE
<double>(expr1
, expr2
, val1
, val2
);
1604 namespace internal
{
1606 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
1608 AssertionResult
CmpHelperEQ(const char* lhs_expression
,
1609 const char* rhs_expression
,
1613 return AssertionSuccess();
1616 return EqFailure(lhs_expression
,
1618 FormatForComparisonFailureMessage(lhs
, rhs
),
1619 FormatForComparisonFailureMessage(rhs
, lhs
),
1623 // A macro for implementing the helper functions needed to implement
1624 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1625 // just to avoid copy-and-paste of similar code.
1626 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1627 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1628 BiggestInt val1, BiggestInt val2) {\
1629 if (val1 op val2) {\
1630 return AssertionSuccess();\
1632 return AssertionFailure() \
1633 << "Expected: (" << expr1 << ") " #op " (" << expr2\
1634 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1635 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1639 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
1641 GTEST_IMPL_CMP_HELPER_(NE
, !=)
1642 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
1644 GTEST_IMPL_CMP_HELPER_(LE
, <=)
1645 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
1647 GTEST_IMPL_CMP_HELPER_(LT
, < )
1648 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
1650 GTEST_IMPL_CMP_HELPER_(GE
, >=)
1651 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
1653 GTEST_IMPL_CMP_HELPER_(GT
, > )
1655 #undef GTEST_IMPL_CMP_HELPER_
1657 // The helper function for {ASSERT|EXPECT}_STREQ.
1658 AssertionResult
CmpHelperSTREQ(const char* lhs_expression
,
1659 const char* rhs_expression
,
1662 if (String::CStringEquals(lhs
, rhs
)) {
1663 return AssertionSuccess();
1666 return EqFailure(lhs_expression
,
1673 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1674 AssertionResult
CmpHelperSTRCASEEQ(const char* lhs_expression
,
1675 const char* rhs_expression
,
1678 if (String::CaseInsensitiveCStringEquals(lhs
, rhs
)) {
1679 return AssertionSuccess();
1682 return EqFailure(lhs_expression
,
1689 // The helper function for {ASSERT|EXPECT}_STRNE.
1690 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
1691 const char* s2_expression
,
1694 if (!String::CStringEquals(s1
, s2
)) {
1695 return AssertionSuccess();
1697 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
1698 << s2_expression
<< "), actual: \""
1699 << s1
<< "\" vs \"" << s2
<< "\"";
1703 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1704 AssertionResult
CmpHelperSTRCASENE(const char* s1_expression
,
1705 const char* s2_expression
,
1708 if (!String::CaseInsensitiveCStringEquals(s1
, s2
)) {
1709 return AssertionSuccess();
1711 return AssertionFailure()
1712 << "Expected: (" << s1_expression
<< ") != ("
1713 << s2_expression
<< ") (ignoring case), actual: \""
1714 << s1
<< "\" vs \"" << s2
<< "\"";
1718 } // namespace internal
1722 // Helper functions for implementing IsSubString() and IsNotSubstring().
1724 // This group of overloaded functions return true if and only if needle
1725 // is a substring of haystack. NULL is considered a substring of
1728 bool IsSubstringPred(const char* needle
, const char* haystack
) {
1729 if (needle
== nullptr || haystack
== nullptr) return needle
== haystack
;
1731 return strstr(haystack
, needle
) != nullptr;
1734 bool IsSubstringPred(const wchar_t* needle
, const wchar_t* haystack
) {
1735 if (needle
== nullptr || haystack
== nullptr) return needle
== haystack
;
1737 return wcsstr(haystack
, needle
) != nullptr;
1740 // StringType here can be either ::std::string or ::std::wstring.
1741 template <typename StringType
>
1742 bool IsSubstringPred(const StringType
& needle
,
1743 const StringType
& haystack
) {
1744 return haystack
.find(needle
) != StringType::npos
;
1747 // This function implements either IsSubstring() or IsNotSubstring(),
1748 // depending on the value of the expected_to_be_substring parameter.
1749 // StringType here can be const char*, const wchar_t*, ::std::string,
1750 // or ::std::wstring.
1751 template <typename StringType
>
1752 AssertionResult
IsSubstringImpl(
1753 bool expected_to_be_substring
,
1754 const char* needle_expr
, const char* haystack_expr
,
1755 const StringType
& needle
, const StringType
& haystack
) {
1756 if (IsSubstringPred(needle
, haystack
) == expected_to_be_substring
)
1757 return AssertionSuccess();
1759 const bool is_wide_string
= sizeof(needle
[0]) > 1;
1760 const char* const begin_string_quote
= is_wide_string
? "L\"" : "\"";
1761 return AssertionFailure()
1762 << "Value of: " << needle_expr
<< "\n"
1763 << " Actual: " << begin_string_quote
<< needle
<< "\"\n"
1764 << "Expected: " << (expected_to_be_substring
? "" : "not ")
1765 << "a substring of " << haystack_expr
<< "\n"
1766 << "Which is: " << begin_string_quote
<< haystack
<< "\"";
1771 // IsSubstring() and IsNotSubstring() check whether needle is a
1772 // substring of haystack (NULL is considered a substring of itself
1773 // only), and return an appropriate error message when they fail.
1775 AssertionResult
IsSubstring(
1776 const char* needle_expr
, const char* haystack_expr
,
1777 const char* needle
, const char* haystack
) {
1778 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1781 AssertionResult
IsSubstring(
1782 const char* needle_expr
, const char* haystack_expr
,
1783 const wchar_t* needle
, const wchar_t* haystack
) {
1784 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1787 AssertionResult
IsNotSubstring(
1788 const char* needle_expr
, const char* haystack_expr
,
1789 const char* needle
, const char* haystack
) {
1790 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1793 AssertionResult
IsNotSubstring(
1794 const char* needle_expr
, const char* haystack_expr
,
1795 const wchar_t* needle
, const wchar_t* haystack
) {
1796 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1799 AssertionResult
IsSubstring(
1800 const char* needle_expr
, const char* haystack_expr
,
1801 const ::std::string
& needle
, const ::std::string
& haystack
) {
1802 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1805 AssertionResult
IsNotSubstring(
1806 const char* needle_expr
, const char* haystack_expr
,
1807 const ::std::string
& needle
, const ::std::string
& haystack
) {
1808 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1811 #if GTEST_HAS_STD_WSTRING
1812 AssertionResult
IsSubstring(
1813 const char* needle_expr
, const char* haystack_expr
,
1814 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
1815 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
1818 AssertionResult
IsNotSubstring(
1819 const char* needle_expr
, const char* haystack_expr
,
1820 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
1821 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
1823 #endif // GTEST_HAS_STD_WSTRING
1825 namespace internal
{
1827 #if GTEST_OS_WINDOWS
1831 // Helper function for IsHRESULT{SuccessFailure} predicates
1832 AssertionResult
HRESULTFailureHelper(const char* expr
,
1833 const char* expected
,
1834 long hr
) { // NOLINT
1835 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1837 // Windows CE doesn't support FormatMessage.
1838 const char error_text
[] = "";
1842 // Looks up the human-readable system message for the HRESULT code
1843 // and since we're not passing any params to FormatMessage, we don't
1844 // want inserts expanded.
1845 const DWORD kFlags
= FORMAT_MESSAGE_FROM_SYSTEM
|
1846 FORMAT_MESSAGE_IGNORE_INSERTS
;
1847 const DWORD kBufSize
= 4096;
1848 // Gets the system's human readable message string for this HRESULT.
1849 char error_text
[kBufSize
] = { '\0' };
1850 DWORD message_length
= ::FormatMessageA(kFlags
,
1851 0, // no source, we're asking system
1852 static_cast<DWORD
>(hr
), // the error
1853 0, // no line width restrictions
1854 error_text
, // output buffer
1855 kBufSize
, // buf size
1856 nullptr); // no arguments for inserts
1857 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1858 for (; message_length
&& IsSpace(error_text
[message_length
- 1]);
1860 error_text
[message_length
- 1] = '\0';
1863 # endif // GTEST_OS_WINDOWS_MOBILE
1865 const std::string
error_hex("0x" + String::FormatHexInt(hr
));
1866 return ::testing::AssertionFailure()
1867 << "Expected: " << expr
<< " " << expected
<< ".\n"
1868 << " Actual: " << error_hex
<< " " << error_text
<< "\n";
1873 AssertionResult
IsHRESULTSuccess(const char* expr
, long hr
) { // NOLINT
1874 if (SUCCEEDED(hr
)) {
1875 return AssertionSuccess();
1877 return HRESULTFailureHelper(expr
, "succeeds", hr
);
1880 AssertionResult
IsHRESULTFailure(const char* expr
, long hr
) { // NOLINT
1882 return AssertionSuccess();
1884 return HRESULTFailureHelper(expr
, "fails", hr
);
1887 #endif // GTEST_OS_WINDOWS
1889 // Utility functions for encoding Unicode text (wide strings) in
1892 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1895 // Code-point length Encoding
1896 // 0 - 7 bits 0xxxxxxx
1897 // 8 - 11 bits 110xxxxx 10xxxxxx
1898 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1899 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1901 // The maximum code-point a one-byte UTF-8 sequence can represent.
1902 constexpr uint32_t kMaxCodePoint1
= (static_cast<uint32_t>(1) << 7) - 1;
1904 // The maximum code-point a two-byte UTF-8 sequence can represent.
1905 constexpr uint32_t kMaxCodePoint2
= (static_cast<uint32_t>(1) << (5 + 6)) - 1;
1907 // The maximum code-point a three-byte UTF-8 sequence can represent.
1908 constexpr uint32_t kMaxCodePoint3
= (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
1910 // The maximum code-point a four-byte UTF-8 sequence can represent.
1911 constexpr uint32_t kMaxCodePoint4
= (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
1913 // Chops off the n lowest bits from a bit pattern. Returns the n
1914 // lowest bits. As a side effect, the original bit pattern will be
1915 // shifted to the right by n bits.
1916 inline uint32_t ChopLowBits(uint32_t* bits
, int n
) {
1917 const uint32_t low_bits
= *bits
& ((static_cast<uint32_t>(1) << n
) - 1);
1922 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
1923 // code_point parameter is of type uint32_t because wchar_t may not be
1924 // wide enough to contain a code point.
1925 // If the code_point is not a valid Unicode code point
1926 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1927 // to "(Invalid Unicode 0xXXXXXXXX)".
1928 std::string
CodePointToUtf8(uint32_t code_point
) {
1929 if (code_point
> kMaxCodePoint4
) {
1930 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point
) + ")";
1933 char str
[5]; // Big enough for the largest valid code point.
1934 if (code_point
<= kMaxCodePoint1
) {
1936 str
[0] = static_cast<char>(code_point
); // 0xxxxxxx
1937 } else if (code_point
<= kMaxCodePoint2
) {
1939 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1940 str
[0] = static_cast<char>(0xC0 | code_point
); // 110xxxxx
1941 } else if (code_point
<= kMaxCodePoint3
) {
1943 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1944 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1945 str
[0] = static_cast<char>(0xE0 | code_point
); // 1110xxxx
1946 } else { // code_point <= kMaxCodePoint4
1948 str
[3] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1949 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1950 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
1951 str
[0] = static_cast<char>(0xF0 | code_point
); // 11110xxx
1956 // The following two functions only make sense if the system
1957 // uses UTF-16 for wide string encoding. All supported systems
1958 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
1960 // Determines if the arguments constitute UTF-16 surrogate pair
1961 // and thus should be combined into a single Unicode code point
1962 // using CreateCodePointFromUtf16SurrogatePair.
1963 inline bool IsUtf16SurrogatePair(wchar_t first
, wchar_t second
) {
1964 return sizeof(wchar_t) == 2 &&
1965 (first
& 0xFC00) == 0xD800 && (second
& 0xFC00) == 0xDC00;
1968 // Creates a Unicode code point from UTF16 surrogate pair.
1969 inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first
,
1971 const auto first_u
= static_cast<uint32_t>(first
);
1972 const auto second_u
= static_cast<uint32_t>(second
);
1973 const uint32_t mask
= (1 << 10) - 1;
1974 return (sizeof(wchar_t) == 2)
1975 ? (((first_u
& mask
) << 10) | (second_u
& mask
)) + 0x10000
1977 // This function should not be called when the condition is
1978 // false, but we provide a sensible default in case it is.
1982 // Converts a wide string to a narrow string in UTF-8 encoding.
1983 // The wide string is assumed to have the following encoding:
1984 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
1985 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1986 // Parameter str points to a null-terminated wide string.
1987 // Parameter num_chars may additionally limit the number
1988 // of wchar_t characters processed. -1 is used when the entire string
1989 // should be processed.
1990 // If the string contains code points that are not valid Unicode code points
1991 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1992 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1993 // and contains invalid UTF-16 surrogate pairs, values in those pairs
1994 // will be encoded as individual Unicode characters from Basic Normal Plane.
1995 std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
) {
1996 if (num_chars
== -1)
1997 num_chars
= static_cast<int>(wcslen(str
));
1999 ::std::stringstream stream
;
2000 for (int i
= 0; i
< num_chars
; ++i
) {
2001 uint32_t unicode_code_point
;
2003 if (str
[i
] == L
'\0') {
2005 } else if (i
+ 1 < num_chars
&& IsUtf16SurrogatePair(str
[i
], str
[i
+ 1])) {
2006 unicode_code_point
= CreateCodePointFromUtf16SurrogatePair(str
[i
],
2010 unicode_code_point
= static_cast<uint32_t>(str
[i
]);
2013 stream
<< CodePointToUtf8(unicode_code_point
);
2015 return StringStreamToString(&stream
);
2018 // Converts a wide C string to an std::string using the UTF-8 encoding.
2019 // NULL will be converted to "(null)".
2020 std::string
String::ShowWideCString(const wchar_t * wide_c_str
) {
2021 if (wide_c_str
== nullptr) return "(null)";
2023 return internal::WideStringToUtf8(wide_c_str
, -1);
2026 // Compares two wide C strings. Returns true if and only if they have the
2029 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2030 // C string is considered different to any non-NULL C string,
2031 // including the empty string.
2032 bool String::WideCStringEquals(const wchar_t * lhs
, const wchar_t * rhs
) {
2033 if (lhs
== nullptr) return rhs
== nullptr;
2035 if (rhs
== nullptr) return false;
2037 return wcscmp(lhs
, rhs
) == 0;
2040 // Helper function for *_STREQ on wide strings.
2041 AssertionResult
CmpHelperSTREQ(const char* lhs_expression
,
2042 const char* rhs_expression
,
2044 const wchar_t* rhs
) {
2045 if (String::WideCStringEquals(lhs
, rhs
)) {
2046 return AssertionSuccess();
2049 return EqFailure(lhs_expression
,
2056 // Helper function for *_STRNE on wide strings.
2057 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
2058 const char* s2_expression
,
2060 const wchar_t* s2
) {
2061 if (!String::WideCStringEquals(s1
, s2
)) {
2062 return AssertionSuccess();
2065 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
2066 << s2_expression
<< "), actual: "
2067 << PrintToString(s1
)
2068 << " vs " << PrintToString(s2
);
2071 // Compares two C strings, ignoring case. Returns true if and only if they have
2072 // the same content.
2074 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2075 // NULL C string is considered different to any non-NULL C string,
2076 // including the empty string.
2077 bool String::CaseInsensitiveCStringEquals(const char * lhs
, const char * rhs
) {
2078 if (lhs
== nullptr) return rhs
== nullptr;
2079 if (rhs
== nullptr) return false;
2080 return posix::StrCaseCmp(lhs
, rhs
) == 0;
2083 // Compares two wide C strings, ignoring case. Returns true if and only if they
2084 // have the same content.
2086 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2087 // A NULL C string is considered different to any non-NULL wide C string,
2088 // including the empty string.
2089 // NB: The implementations on different platforms slightly differ.
2090 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2091 // environment variable. On GNU platform this method uses wcscasecmp
2092 // which compares according to LC_CTYPE category of the current locale.
2093 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2095 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs
,
2096 const wchar_t* rhs
) {
2097 if (lhs
== nullptr) return rhs
== nullptr;
2099 if (rhs
== nullptr) return false;
2101 #if GTEST_OS_WINDOWS
2102 return _wcsicmp(lhs
, rhs
) == 0;
2103 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2104 return wcscasecmp(lhs
, rhs
) == 0;
2106 // Android, Mac OS X and Cygwin don't define wcscasecmp.
2107 // Other unknown OSes may not define it either.
2110 left
= towlower(static_cast<wint_t>(*lhs
++));
2111 right
= towlower(static_cast<wint_t>(*rhs
++));
2112 } while (left
&& left
== right
);
2113 return left
== right
;
2114 #endif // OS selector
2117 // Returns true if and only if str ends with the given suffix, ignoring case.
2118 // Any string is considered to end with an empty suffix.
2119 bool String::EndsWithCaseInsensitive(
2120 const std::string
& str
, const std::string
& suffix
) {
2121 const size_t str_len
= str
.length();
2122 const size_t suffix_len
= suffix
.length();
2123 return (str_len
>= suffix_len
) &&
2124 CaseInsensitiveCStringEquals(str
.c_str() + str_len
- suffix_len
,
2128 // Formats an int value as "%02d".
2129 std::string
String::FormatIntWidth2(int value
) {
2130 return FormatIntWidthN(value
, 2);
2133 // Formats an int value to given width with leading zeros.
2134 std::string
String::FormatIntWidthN(int value
, int width
) {
2135 std::stringstream ss
;
2136 ss
<< std::setfill('0') << std::setw(width
) << value
;
2140 // Formats an int value as "%X".
2141 std::string
String::FormatHexUInt32(uint32_t value
) {
2142 std::stringstream ss
;
2143 ss
<< std::hex
<< std::uppercase
<< value
;
2147 // Formats an int value as "%X".
2148 std::string
String::FormatHexInt(int value
) {
2149 return FormatHexUInt32(static_cast<uint32_t>(value
));
2152 // Formats a byte as "%02X".
2153 std::string
String::FormatByte(unsigned char value
) {
2154 std::stringstream ss
;
2155 ss
<< std::setfill('0') << std::setw(2) << std::hex
<< std::uppercase
2156 << static_cast<unsigned int>(value
);
2160 // Converts the buffer in a stringstream to an std::string, converting NUL
2161 // bytes to "\\0" along the way.
2162 std::string
StringStreamToString(::std::stringstream
* ss
) {
2163 const ::std::string
& str
= ss
->str();
2164 const char* const start
= str
.c_str();
2165 const char* const end
= start
+ str
.length();
2168 result
.reserve(static_cast<size_t>(2 * (end
- start
)));
2169 for (const char* ch
= start
; ch
!= end
; ++ch
) {
2171 result
+= "\\0"; // Replaces NUL with "\\0";
2180 // Appends the user-supplied message to the Google-Test-generated message.
2181 std::string
AppendUserMessage(const std::string
& gtest_msg
,
2182 const Message
& user_msg
) {
2183 // Appends the user message if it's non-empty.
2184 const std::string user_msg_string
= user_msg
.GetString();
2185 if (user_msg_string
.empty()) {
2188 if (gtest_msg
.empty()) {
2189 return user_msg_string
;
2191 return gtest_msg
+ "\n" + user_msg_string
;
2194 } // namespace internal
2198 // Creates an empty TestResult.
2199 TestResult::TestResult()
2200 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2203 TestResult::~TestResult() {
2206 // Returns the i-th test part result among all the results. i can
2207 // range from 0 to total_part_count() - 1. If i is not in that range,
2208 // aborts the program.
2209 const TestPartResult
& TestResult::GetTestPartResult(int i
) const {
2210 if (i
< 0 || i
>= total_part_count())
2211 internal::posix::Abort();
2212 return test_part_results_
.at(static_cast<size_t>(i
));
2215 // Returns the i-th test property. i can range from 0 to
2216 // test_property_count() - 1. If i is not in that range, aborts the
2218 const TestProperty
& TestResult::GetTestProperty(int i
) const {
2219 if (i
< 0 || i
>= test_property_count())
2220 internal::posix::Abort();
2221 return test_properties_
.at(static_cast<size_t>(i
));
2224 // Clears the test part results.
2225 void TestResult::ClearTestPartResults() {
2226 test_part_results_
.clear();
2229 // Adds a test part result to the list.
2230 void TestResult::AddTestPartResult(const TestPartResult
& test_part_result
) {
2231 test_part_results_
.push_back(test_part_result
);
2234 // Adds a test property to the list. If a property with the same key as the
2235 // supplied property is already represented, the value of this test_property
2236 // replaces the old value for that key.
2237 void TestResult::RecordProperty(const std::string
& xml_element
,
2238 const TestProperty
& test_property
) {
2239 if (!ValidateTestProperty(xml_element
, test_property
)) {
2242 internal::MutexLock
lock(&test_properites_mutex_
);
2243 const std::vector
<TestProperty
>::iterator property_with_matching_key
=
2244 std::find_if(test_properties_
.begin(), test_properties_
.end(),
2245 internal::TestPropertyKeyIs(test_property
.key()));
2246 if (property_with_matching_key
== test_properties_
.end()) {
2247 test_properties_
.push_back(test_property
);
2250 property_with_matching_key
->SetValue(test_property
.value());
2253 // The list of reserved attributes used in the <testsuites> element of XML
2255 static const char* const kReservedTestSuitesAttributes
[] = {
2266 // The list of reserved attributes used in the <testsuite> element of XML
2268 static const char* const kReservedTestSuiteAttributes
[] = {
2269 "disabled", "errors", "failures", "name",
2270 "tests", "time", "timestamp", "skipped"};
2272 // The list of reserved attributes used in the <testcase> element of XML output.
2273 static const char* const kReservedTestCaseAttributes
[] = {
2274 "classname", "name", "status", "time", "type_param",
2275 "value_param", "file", "line"};
2277 // Use a slightly different set for allowed output to ensure existing tests can
2278 // still RecordProperty("result") or "RecordProperty(timestamp")
2279 static const char* const kReservedOutputTestCaseAttributes
[] = {
2280 "classname", "name", "status", "time", "type_param",
2281 "value_param", "file", "line", "result", "timestamp"};
2283 template <size_t kSize
>
2284 std::vector
<std::string
> ArrayAsVector(const char* const (&array
)[kSize
]) {
2285 return std::vector
<std::string
>(array
, array
+ kSize
);
2288 static std::vector
<std::string
> GetReservedAttributesForElement(
2289 const std::string
& xml_element
) {
2290 if (xml_element
== "testsuites") {
2291 return ArrayAsVector(kReservedTestSuitesAttributes
);
2292 } else if (xml_element
== "testsuite") {
2293 return ArrayAsVector(kReservedTestSuiteAttributes
);
2294 } else if (xml_element
== "testcase") {
2295 return ArrayAsVector(kReservedTestCaseAttributes
);
2297 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
2299 // This code is unreachable but some compilers may not realizes that.
2300 return std::vector
<std::string
>();
2303 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
2304 static std::vector
<std::string
> GetReservedOutputAttributesForElement(
2305 const std::string
& xml_element
) {
2306 if (xml_element
== "testsuites") {
2307 return ArrayAsVector(kReservedTestSuitesAttributes
);
2308 } else if (xml_element
== "testsuite") {
2309 return ArrayAsVector(kReservedTestSuiteAttributes
);
2310 } else if (xml_element
== "testcase") {
2311 return ArrayAsVector(kReservedOutputTestCaseAttributes
);
2313 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
2315 // This code is unreachable but some compilers may not realizes that.
2316 return std::vector
<std::string
>();
2319 static std::string
FormatWordList(const std::vector
<std::string
>& words
) {
2321 for (size_t i
= 0; i
< words
.size(); ++i
) {
2322 if (i
> 0 && words
.size() > 2) {
2325 if (i
== words
.size() - 1) {
2326 word_list
<< "and ";
2328 word_list
<< "'" << words
[i
] << "'";
2330 return word_list
.GetString();
2333 static bool ValidateTestPropertyName(
2334 const std::string
& property_name
,
2335 const std::vector
<std::string
>& reserved_names
) {
2336 if (std::find(reserved_names
.begin(), reserved_names
.end(), property_name
) !=
2337 reserved_names
.end()) {
2338 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2339 << " (" << FormatWordList(reserved_names
)
2340 << " are reserved by " << GTEST_NAME_
<< ")";
2346 // Adds a failure if the key is a reserved attribute of the element named
2347 // xml_element. Returns true if the property is valid.
2348 bool TestResult::ValidateTestProperty(const std::string
& xml_element
,
2349 const TestProperty
& test_property
) {
2350 return ValidateTestPropertyName(test_property
.key(),
2351 GetReservedAttributesForElement(xml_element
));
2354 // Clears the object.
2355 void TestResult::Clear() {
2356 test_part_results_
.clear();
2357 test_properties_
.clear();
2358 death_test_count_
= 0;
2362 // Returns true off the test part was skipped.
2363 static bool TestPartSkipped(const TestPartResult
& result
) {
2364 return result
.skipped();
2367 // Returns true if and only if the test was skipped.
2368 bool TestResult::Skipped() const {
2369 return !Failed() && CountIf(test_part_results_
, TestPartSkipped
) > 0;
2372 // Returns true if and only if the test failed.
2373 bool TestResult::Failed() const {
2374 for (int i
= 0; i
< total_part_count(); ++i
) {
2375 if (GetTestPartResult(i
).failed())
2381 // Returns true if and only if the test part fatally failed.
2382 static bool TestPartFatallyFailed(const TestPartResult
& result
) {
2383 return result
.fatally_failed();
2386 // Returns true if and only if the test fatally failed.
2387 bool TestResult::HasFatalFailure() const {
2388 return CountIf(test_part_results_
, TestPartFatallyFailed
) > 0;
2391 // Returns true if and only if the test part non-fatally failed.
2392 static bool TestPartNonfatallyFailed(const TestPartResult
& result
) {
2393 return result
.nonfatally_failed();
2396 // Returns true if and only if the test has a non-fatal failure.
2397 bool TestResult::HasNonfatalFailure() const {
2398 return CountIf(test_part_results_
, TestPartNonfatallyFailed
) > 0;
2401 // Gets the number of all test parts. This is the sum of the number
2402 // of successful test parts and the number of failed test parts.
2403 int TestResult::total_part_count() const {
2404 return static_cast<int>(test_part_results_
.size());
2407 // Returns the number of the test properties.
2408 int TestResult::test_property_count() const {
2409 return static_cast<int>(test_properties_
.size());
2414 // Creates a Test object.
2416 // The c'tor saves the states of all flags.
2418 : gtest_flag_saver_(new GTEST_FLAG_SAVER_
) {
2421 // The d'tor restores the states of all flags. The actual work is
2422 // done by the d'tor of the gtest_flag_saver_ field, and thus not
2427 // Sets up the test fixture.
2429 // A sub-class may override this.
2430 void Test::SetUp() {
2433 // Tears down the test fixture.
2435 // A sub-class may override this.
2436 void Test::TearDown() {
2439 // Allows user supplied key value pairs to be recorded for later output.
2440 void Test::RecordProperty(const std::string
& key
, const std::string
& value
) {
2441 UnitTest::GetInstance()->RecordProperty(key
, value
);
2444 // Allows user supplied key value pairs to be recorded for later output.
2445 void Test::RecordProperty(const std::string
& key
, int value
) {
2446 Message value_message
;
2447 value_message
<< value
;
2448 RecordProperty(key
, value_message
.GetString().c_str());
2451 namespace internal
{
2453 void ReportFailureInUnknownLocation(TestPartResult::Type result_type
,
2454 const std::string
& message
) {
2455 // This function is a friend of UnitTest and as such has access to
2456 // AddTestPartResult.
2457 UnitTest::GetInstance()->AddTestPartResult(
2459 nullptr, // No info about the source file where the exception occurred.
2460 -1, // We have no info on which line caused the exception.
2462 ""); // No stack trace, either.
2465 } // namespace internal
2467 // Google Test requires all tests in the same test suite to use the same test
2468 // fixture class. This function checks if the current test has the
2469 // same fixture class as the first test in the current test suite. If
2470 // yes, it returns true; otherwise it generates a Google Test failure and
2472 bool Test::HasSameFixtureClass() {
2473 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2474 const TestSuite
* const test_suite
= impl
->current_test_suite();
2476 // Info about the first test in the current test suite.
2477 const TestInfo
* const first_test_info
= test_suite
->test_info_list()[0];
2478 const internal::TypeId first_fixture_id
= first_test_info
->fixture_class_id_
;
2479 const char* const first_test_name
= first_test_info
->name();
2481 // Info about the current test.
2482 const TestInfo
* const this_test_info
= impl
->current_test_info();
2483 const internal::TypeId this_fixture_id
= this_test_info
->fixture_class_id_
;
2484 const char* const this_test_name
= this_test_info
->name();
2486 if (this_fixture_id
!= first_fixture_id
) {
2487 // Is the first test defined using TEST?
2488 const bool first_is_TEST
= first_fixture_id
== internal::GetTestTypeId();
2489 // Is this test defined using TEST?
2490 const bool this_is_TEST
= this_fixture_id
== internal::GetTestTypeId();
2492 if (first_is_TEST
|| this_is_TEST
) {
2493 // Both TEST and TEST_F appear in same test suite, which is incorrect.
2494 // Tell the user how to fix this.
2496 // Gets the name of the TEST and the name of the TEST_F. Note
2497 // that first_is_TEST and this_is_TEST cannot both be true, as
2498 // the fixture IDs are different for the two tests.
2499 const char* const TEST_name
=
2500 first_is_TEST
? first_test_name
: this_test_name
;
2501 const char* const TEST_F_name
=
2502 first_is_TEST
? this_test_name
: first_test_name
;
2505 << "All tests in the same test suite must use the same test fixture\n"
2506 << "class, so mixing TEST_F and TEST in the same test suite is\n"
2507 << "illegal. In test suite " << this_test_info
->test_suite_name()
2509 << "test " << TEST_F_name
<< " is defined using TEST_F but\n"
2510 << "test " << TEST_name
<< " is defined using TEST. You probably\n"
2511 << "want to change the TEST to TEST_F or move it to another test\n"
2514 // Two fixture classes with the same name appear in two different
2515 // namespaces, which is not allowed. Tell the user how to fix this.
2517 << "All tests in the same test suite must use the same test fixture\n"
2518 << "class. However, in test suite "
2519 << this_test_info
->test_suite_name() << ",\n"
2520 << "you defined test " << first_test_name
<< " and test "
2521 << this_test_name
<< "\n"
2522 << "using two different test fixture classes. This can happen if\n"
2523 << "the two classes are from different namespaces or translation\n"
2524 << "units and have the same name. You should probably rename one\n"
2525 << "of the classes to put the tests into different test suites.";
2535 // Adds an "exception thrown" fatal failure to the current test. This
2536 // function returns its result via an output parameter pointer because VC++
2537 // prohibits creation of objects with destructors on stack in functions
2538 // using __try (see error C2712).
2539 static std::string
* FormatSehExceptionMessage(DWORD exception_code
,
2540 const char* location
) {
2542 message
<< "SEH exception with code 0x" << std::setbase(16) <<
2543 exception_code
<< std::setbase(10) << " thrown in " << location
<< ".";
2545 return new std::string(message
.GetString());
2548 #endif // GTEST_HAS_SEH
2550 namespace internal
{
2552 #if GTEST_HAS_EXCEPTIONS
2554 // Adds an "exception thrown" fatal failure to the current test.
2555 static std::string
FormatCxxExceptionMessage(const char* description
,
2556 const char* location
) {
2558 if (description
!= nullptr) {
2559 message
<< "C++ exception with description \"" << description
<< "\"";
2561 message
<< "Unknown C++ exception";
2563 message
<< " thrown in " << location
<< ".";
2565 return message
.GetString();
2568 static std::string
PrintTestPartResultToString(
2569 const TestPartResult
& test_part_result
);
2571 GoogleTestFailureException::GoogleTestFailureException(
2572 const TestPartResult
& failure
)
2573 : ::std::runtime_error(PrintTestPartResultToString(failure
).c_str()) {}
2575 #endif // GTEST_HAS_EXCEPTIONS
2577 // We put these helper functions in the internal namespace as IBM's xlC
2578 // compiler rejects the code if they were declared static.
2580 // Runs the given method and handles SEH exceptions it throws, when
2581 // SEH is supported; returns the 0-value for type Result in case of an
2582 // SEH exception. (Microsoft compilers cannot handle SEH and C++
2583 // exceptions in the same function. Therefore, we provide a separate
2584 // wrapper function for handling SEH exceptions.)
2585 template <class T
, typename Result
>
2586 Result
HandleSehExceptionsInMethodIfSupported(
2587 T
* object
, Result (T::*method
)(), const char* location
) {
2590 return (object
->*method
)();
2591 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
2592 GetExceptionCode())) {
2593 // We create the exception message on the heap because VC++ prohibits
2594 // creation of objects with destructors on stack in functions using __try
2595 // (see error C2712).
2596 std::string
* exception_message
= FormatSehExceptionMessage(
2597 GetExceptionCode(), location
);
2598 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure
,
2599 *exception_message
);
2600 delete exception_message
;
2601 return static_cast<Result
>(0);
2605 return (object
->*method
)();
2606 #endif // GTEST_HAS_SEH
2609 // Runs the given method and catches and reports C++ and/or SEH-style
2610 // exceptions, if they are supported; returns the 0-value for type
2611 // Result in case of an SEH exception.
2612 template <class T
, typename Result
>
2613 Result
HandleExceptionsInMethodIfSupported(
2614 T
* object
, Result (T::*method
)(), const char* location
) {
2615 // NOTE: The user code can affect the way in which Google Test handles
2616 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2617 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2618 // after the exception is caught and either report or re-throw the
2619 // exception based on the flag's value:
2622 // // Perform the test method.
2624 // if (GTEST_FLAG(catch_exceptions))
2625 // // Report the exception as failure.
2627 // throw; // Re-throws the original exception.
2630 // However, the purpose of this flag is to allow the program to drop into
2631 // the debugger when the exception is thrown. On most platforms, once the
2632 // control enters the catch block, the exception origin information is
2633 // lost and the debugger will stop the program at the point of the
2634 // re-throw in this function -- instead of at the point of the original
2635 // throw statement in the code under test. For this reason, we perform
2636 // the check early, sacrificing the ability to affect Google Test's
2637 // exception handling in the method where the exception is thrown.
2638 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2639 #if GTEST_HAS_EXCEPTIONS
2641 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
2642 } catch (const AssertionException
&) { // NOLINT
2643 // This failure was reported already.
2644 } catch (const internal::GoogleTestFailureException
&) { // NOLINT
2645 // This exception type can only be thrown by a failed Google
2646 // Test assertion with the intention of letting another testing
2647 // framework catch it. Therefore we just re-throw it.
2649 } catch (const std::exception
& e
) { // NOLINT
2650 internal::ReportFailureInUnknownLocation(
2651 TestPartResult::kFatalFailure
,
2652 FormatCxxExceptionMessage(e
.what(), location
));
2653 } catch (...) { // NOLINT
2654 internal::ReportFailureInUnknownLocation(
2655 TestPartResult::kFatalFailure
,
2656 FormatCxxExceptionMessage(nullptr, location
));
2658 return static_cast<Result
>(0);
2660 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
2661 #endif // GTEST_HAS_EXCEPTIONS
2663 return (object
->*method
)();
2667 } // namespace internal
2669 // Runs the test and updates the test result.
2671 if (!HasSameFixtureClass()) return;
2673 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2674 impl
->os_stack_trace_getter()->UponLeavingGTest();
2675 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp
, "SetUp()");
2676 // We will run the test only if SetUp() was successful and didn't call
2678 if (!HasFatalFailure() && !IsSkipped()) {
2679 impl
->os_stack_trace_getter()->UponLeavingGTest();
2680 internal::HandleExceptionsInMethodIfSupported(
2681 this, &Test::TestBody
, "the test body");
2684 // However, we want to clean up as much as possible. Hence we will
2685 // always call TearDown(), even if SetUp() or the test body has
2687 impl
->os_stack_trace_getter()->UponLeavingGTest();
2688 internal::HandleExceptionsInMethodIfSupported(
2689 this, &Test::TearDown
, "TearDown()");
2692 // Returns true if and only if the current test has a fatal failure.
2693 bool Test::HasFatalFailure() {
2694 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2697 // Returns true if and only if the current test has a non-fatal failure.
2698 bool Test::HasNonfatalFailure() {
2699 return internal::GetUnitTestImpl()->current_test_result()->
2700 HasNonfatalFailure();
2703 // Returns true if and only if the current test was skipped.
2704 bool Test::IsSkipped() {
2705 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2710 // Constructs a TestInfo object. It assumes ownership of the test factory
2712 TestInfo::TestInfo(const std::string
& a_test_suite_name
,
2713 const std::string
& a_name
, const char* a_type_param
,
2714 const char* a_value_param
,
2715 internal::CodeLocation a_code_location
,
2716 internal::TypeId fixture_class_id
,
2717 internal::TestFactoryBase
* factory
)
2718 : test_suite_name_(a_test_suite_name
),
2720 type_param_(a_type_param
? new std::string(a_type_param
) : nullptr),
2721 value_param_(a_value_param
? new std::string(a_value_param
) : nullptr),
2722 location_(a_code_location
),
2723 fixture_class_id_(fixture_class_id
),
2725 is_disabled_(false),
2726 matches_filter_(false),
2730 // Destructs a TestInfo object.
2731 TestInfo::~TestInfo() { delete factory_
; }
2733 namespace internal
{
2735 // Creates a new TestInfo object and registers it with Google Test;
2736 // returns the created object.
2740 // test_suite_name: name of the test suite
2741 // name: name of the test
2742 // type_param: the name of the test's type parameter, or NULL if
2743 // this is not a typed or a type-parameterized test.
2744 // value_param: text representation of the test's value parameter,
2745 // or NULL if this is not a value-parameterized test.
2746 // code_location: code location where the test is defined
2747 // fixture_class_id: ID of the test fixture class
2748 // set_up_tc: pointer to the function that sets up the test suite
2749 // tear_down_tc: pointer to the function that tears down the test suite
2750 // factory: pointer to the factory that creates a test object.
2751 // The newly created TestInfo instance will assume
2752 // ownership of the factory object.
2753 TestInfo
* MakeAndRegisterTestInfo(
2754 const char* test_suite_name
, const char* name
, const char* type_param
,
2755 const char* value_param
, CodeLocation code_location
,
2756 TypeId fixture_class_id
, SetUpTestSuiteFunc set_up_tc
,
2757 TearDownTestSuiteFunc tear_down_tc
, TestFactoryBase
* factory
) {
2758 TestInfo
* const test_info
=
2759 new TestInfo(test_suite_name
, name
, type_param
, value_param
,
2760 code_location
, fixture_class_id
, factory
);
2761 GetUnitTestImpl()->AddTestInfo(set_up_tc
, tear_down_tc
, test_info
);
2765 void ReportInvalidTestSuiteType(const char* test_suite_name
,
2766 CodeLocation code_location
) {
2769 << "Attempted redefinition of test suite " << test_suite_name
<< ".\n"
2770 << "All tests in the same test suite must use the same test fixture\n"
2771 << "class. However, in test suite " << test_suite_name
<< ", you tried\n"
2772 << "to define a test using a fixture class different from the one\n"
2773 << "used earlier. This can happen if the two fixture classes are\n"
2774 << "from different namespaces and have the same name. You should\n"
2775 << "probably rename one of the classes to put the tests into different\n"
2778 GTEST_LOG_(ERROR
) << FormatFileLocation(code_location
.file
.c_str(),
2780 << " " << errors
.GetString();
2782 } // namespace internal
2786 // A predicate that checks the test name of a TestInfo against a known
2789 // This is used for implementation of the TestSuite class only. We put
2790 // it in the anonymous namespace to prevent polluting the outer
2793 // TestNameIs is copyable.
2798 // TestNameIs has NO default constructor.
2799 explicit TestNameIs(const char* name
)
2802 // Returns true if and only if the test name of test_info matches name_.
2803 bool operator()(const TestInfo
* test_info
) const {
2804 return test_info
&& test_info
->name() == name_
;
2813 namespace internal
{
2815 // This method expands all parameterized tests registered with macros TEST_P
2816 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
2817 // This will be done just once during the program runtime.
2818 void UnitTestImpl::RegisterParameterizedTests() {
2819 if (!parameterized_tests_registered_
) {
2820 parameterized_test_registry_
.RegisterTests();
2821 type_parameterized_test_registry_
.CheckForInstantiations();
2822 parameterized_tests_registered_
= true;
2826 } // namespace internal
2828 // Creates the test object, runs it, records its result, and then
2830 void TestInfo::Run() {
2831 if (!should_run_
) return;
2833 // Tells UnitTest where to store test result.
2834 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2835 impl
->set_current_test_info(this);
2837 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
2839 // Notifies the unit test event listeners that a test is about to start.
2840 repeater
->OnTestStart(*this);
2842 const TimeInMillis start
= internal::GetTimeInMillis();
2844 impl
->os_stack_trace_getter()->UponLeavingGTest();
2846 // Creates the test object.
2847 Test
* const test
= internal::HandleExceptionsInMethodIfSupported(
2848 factory_
, &internal::TestFactoryBase::CreateTest
,
2849 "the test fixture's constructor");
2851 // Runs the test if the constructor didn't generate a fatal failure or invoke
2853 // Note that the object will not be null
2854 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2855 // This doesn't throw as all user code that can throw are wrapped into
2856 // exception handling code.
2860 if (test
!= nullptr) {
2861 // Deletes the test object.
2862 impl
->os_stack_trace_getter()->UponLeavingGTest();
2863 internal::HandleExceptionsInMethodIfSupported(
2864 test
, &Test::DeleteSelf_
, "the test fixture's destructor");
2867 result_
.set_start_timestamp(start
);
2868 result_
.set_elapsed_time(internal::GetTimeInMillis() - start
);
2870 // Notifies the unit test event listener that a test has just finished.
2871 repeater
->OnTestEnd(*this);
2873 // Tells UnitTest to stop associating assertion results to this
2875 impl
->set_current_test_info(nullptr);
2878 // Skip and records a skipped test result for this object.
2879 void TestInfo::Skip() {
2880 if (!should_run_
) return;
2882 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2883 impl
->set_current_test_info(this);
2885 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
2887 // Notifies the unit test event listeners that a test is about to start.
2888 repeater
->OnTestStart(*this);
2890 const TestPartResult test_part_result
=
2891 TestPartResult(TestPartResult::kSkip
, this->file(), this->line(), "");
2892 impl
->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
2895 // Notifies the unit test event listener that a test has just finished.
2896 repeater
->OnTestEnd(*this);
2897 impl
->set_current_test_info(nullptr);
2902 // Gets the number of successful tests in this test suite.
2903 int TestSuite::successful_test_count() const {
2904 return CountIf(test_info_list_
, TestPassed
);
2907 // Gets the number of successful tests in this test suite.
2908 int TestSuite::skipped_test_count() const {
2909 return CountIf(test_info_list_
, TestSkipped
);
2912 // Gets the number of failed tests in this test suite.
2913 int TestSuite::failed_test_count() const {
2914 return CountIf(test_info_list_
, TestFailed
);
2917 // Gets the number of disabled tests that will be reported in the XML report.
2918 int TestSuite::reportable_disabled_test_count() const {
2919 return CountIf(test_info_list_
, TestReportableDisabled
);
2922 // Gets the number of disabled tests in this test suite.
2923 int TestSuite::disabled_test_count() const {
2924 return CountIf(test_info_list_
, TestDisabled
);
2927 // Gets the number of tests to be printed in the XML report.
2928 int TestSuite::reportable_test_count() const {
2929 return CountIf(test_info_list_
, TestReportable
);
2932 // Get the number of tests in this test suite that should run.
2933 int TestSuite::test_to_run_count() const {
2934 return CountIf(test_info_list_
, ShouldRunTest
);
2937 // Gets the number of all tests.
2938 int TestSuite::total_test_count() const {
2939 return static_cast<int>(test_info_list_
.size());
2942 // Creates a TestSuite with the given name.
2946 // name: name of the test suite
2947 // a_type_param: the name of the test suite's type parameter, or NULL if
2948 // this is not a typed or a type-parameterized test suite.
2949 // set_up_tc: pointer to the function that sets up the test suite
2950 // tear_down_tc: pointer to the function that tears down the test suite
2951 TestSuite::TestSuite(const char* a_name
, const char* a_type_param
,
2952 internal::SetUpTestSuiteFunc set_up_tc
,
2953 internal::TearDownTestSuiteFunc tear_down_tc
)
2955 type_param_(a_type_param
? new std::string(a_type_param
) : nullptr),
2956 set_up_tc_(set_up_tc
),
2957 tear_down_tc_(tear_down_tc
),
2959 start_timestamp_(0),
2962 // Destructor of TestSuite.
2963 TestSuite::~TestSuite() {
2964 // Deletes every Test in the collection.
2965 ForEach(test_info_list_
, internal::Delete
<TestInfo
>);
2968 // Returns the i-th test among all the tests. i can range from 0 to
2969 // total_test_count() - 1. If i is not in that range, returns NULL.
2970 const TestInfo
* TestSuite::GetTestInfo(int i
) const {
2971 const int index
= GetElementOr(test_indices_
, i
, -1);
2972 return index
< 0 ? nullptr : test_info_list_
[static_cast<size_t>(index
)];
2975 // Returns the i-th test among all the tests. i can range from 0 to
2976 // total_test_count() - 1. If i is not in that range, returns NULL.
2977 TestInfo
* TestSuite::GetMutableTestInfo(int i
) {
2978 const int index
= GetElementOr(test_indices_
, i
, -1);
2979 return index
< 0 ? nullptr : test_info_list_
[static_cast<size_t>(index
)];
2982 // Adds a test to this test suite. Will delete the test upon
2983 // destruction of the TestSuite object.
2984 void TestSuite::AddTestInfo(TestInfo
* test_info
) {
2985 test_info_list_
.push_back(test_info
);
2986 test_indices_
.push_back(static_cast<int>(test_indices_
.size()));
2989 // Runs every test in this TestSuite.
2990 void TestSuite::Run() {
2991 if (!should_run_
) return;
2993 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2994 impl
->set_current_test_suite(this);
2996 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
2998 // Call both legacy and the new API
2999 repeater
->OnTestSuiteStart(*this);
3000 // Legacy API is deprecated but still available
3001 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3002 repeater
->OnTestCaseStart(*this);
3003 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3005 impl
->os_stack_trace_getter()->UponLeavingGTest();
3006 internal::HandleExceptionsInMethodIfSupported(
3007 this, &TestSuite::RunSetUpTestSuite
, "SetUpTestSuite()");
3009 start_timestamp_
= internal::GetTimeInMillis();
3010 for (int i
= 0; i
< total_test_count(); i
++) {
3011 GetMutableTestInfo(i
)->Run();
3012 if (GTEST_FLAG(fail_fast
) && GetMutableTestInfo(i
)->result()->Failed()) {
3013 for (int j
= i
+ 1; j
< total_test_count(); j
++) {
3014 GetMutableTestInfo(j
)->Skip();
3019 elapsed_time_
= internal::GetTimeInMillis() - start_timestamp_
;
3021 impl
->os_stack_trace_getter()->UponLeavingGTest();
3022 internal::HandleExceptionsInMethodIfSupported(
3023 this, &TestSuite::RunTearDownTestSuite
, "TearDownTestSuite()");
3025 // Call both legacy and the new API
3026 repeater
->OnTestSuiteEnd(*this);
3027 // Legacy API is deprecated but still available
3028 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3029 repeater
->OnTestCaseEnd(*this);
3030 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3032 impl
->set_current_test_suite(nullptr);
3035 // Skips all tests under this TestSuite.
3036 void TestSuite::Skip() {
3037 if (!should_run_
) return;
3039 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3040 impl
->set_current_test_suite(this);
3042 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
3044 // Call both legacy and the new API
3045 repeater
->OnTestSuiteStart(*this);
3046 // Legacy API is deprecated but still available
3047 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3048 repeater
->OnTestCaseStart(*this);
3049 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3051 for (int i
= 0; i
< total_test_count(); i
++) {
3052 GetMutableTestInfo(i
)->Skip();
3055 // Call both legacy and the new API
3056 repeater
->OnTestSuiteEnd(*this);
3057 // Legacy API is deprecated but still available
3058 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3059 repeater
->OnTestCaseEnd(*this);
3060 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3062 impl
->set_current_test_suite(nullptr);
3065 // Clears the results of all tests in this test suite.
3066 void TestSuite::ClearResult() {
3067 ad_hoc_test_result_
.Clear();
3068 ForEach(test_info_list_
, TestInfo::ClearTestResult
);
3071 // Shuffles the tests in this test suite.
3072 void TestSuite::ShuffleTests(internal::Random
* random
) {
3073 Shuffle(random
, &test_indices_
);
3076 // Restores the test order to before the first shuffle.
3077 void TestSuite::UnshuffleTests() {
3078 for (size_t i
= 0; i
< test_indices_
.size(); i
++) {
3079 test_indices_
[i
] = static_cast<int>(i
);
3083 // Formats a countable noun. Depending on its quantity, either the
3084 // singular form or the plural form is used. e.g.
3086 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3087 // FormatCountableNoun(5, "book", "books") returns "5 books".
3088 static std::string
FormatCountableNoun(int count
,
3089 const char * singular_form
,
3090 const char * plural_form
) {
3091 return internal::StreamableToString(count
) + " " +
3092 (count
== 1 ? singular_form
: plural_form
);
3095 // Formats the count of tests.
3096 static std::string
FormatTestCount(int test_count
) {
3097 return FormatCountableNoun(test_count
, "test", "tests");
3100 // Formats the count of test suites.
3101 static std::string
FormatTestSuiteCount(int test_suite_count
) {
3102 return FormatCountableNoun(test_suite_count
, "test suite", "test suites");
3105 // Converts a TestPartResult::Type enum to human-friendly string
3106 // representation. Both kNonFatalFailure and kFatalFailure are translated
3107 // to "Failure", as the user usually doesn't care about the difference
3108 // between the two when viewing the test result.
3109 static const char * TestPartResultTypeToString(TestPartResult::Type type
) {
3111 case TestPartResult::kSkip
:
3113 case TestPartResult::kSuccess
:
3116 case TestPartResult::kNonFatalFailure
:
3117 case TestPartResult::kFatalFailure
:
3124 return "Unknown result type";
3128 namespace internal
{
3130 enum class GTestColor
{ kDefault
, kRed
, kGreen
, kYellow
};
3133 // Prints a TestPartResult to an std::string.
3134 static std::string
PrintTestPartResultToString(
3135 const TestPartResult
& test_part_result
) {
3137 << internal::FormatFileLocation(test_part_result
.file_name(),
3138 test_part_result
.line_number())
3139 << " " << TestPartResultTypeToString(test_part_result
.type())
3140 << test_part_result
.message()).GetString();
3143 // Prints a TestPartResult.
3144 static void PrintTestPartResult(const TestPartResult
& test_part_result
) {
3145 const std::string
& result
=
3146 PrintTestPartResultToString(test_part_result
);
3147 printf("%s\n", result
.c_str());
3149 // If the test program runs in Visual Studio or a debugger, the
3150 // following statements add the test part result message to the Output
3151 // window such that the user can double-click on it to jump to the
3152 // corresponding source code location; otherwise they do nothing.
3153 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3154 // We don't call OutputDebugString*() on Windows Mobile, as printing
3155 // to stdout is done by OutputDebugString() there already - we don't
3156 // want the same message printed twice.
3157 ::OutputDebugStringA(result
.c_str());
3158 ::OutputDebugStringA("\n");
3162 // class PrettyUnitTestResultPrinter
3163 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3164 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3166 // Returns the character attribute for the given color.
3167 static WORD
GetColorAttribute(GTestColor color
) {
3169 case GTestColor::kRed
:
3170 return FOREGROUND_RED
;
3171 case GTestColor::kGreen
:
3172 return FOREGROUND_GREEN
;
3173 case GTestColor::kYellow
:
3174 return FOREGROUND_RED
| FOREGROUND_GREEN
;
3179 static int GetBitOffset(WORD color_mask
) {
3180 if (color_mask
== 0) return 0;
3183 while ((color_mask
& 1) == 0) {
3190 static WORD
GetNewColor(GTestColor color
, WORD old_color_attrs
) {
3191 // Let's reuse the BG
3192 static const WORD background_mask
= BACKGROUND_BLUE
| BACKGROUND_GREEN
|
3193 BACKGROUND_RED
| BACKGROUND_INTENSITY
;
3194 static const WORD foreground_mask
= FOREGROUND_BLUE
| FOREGROUND_GREEN
|
3195 FOREGROUND_RED
| FOREGROUND_INTENSITY
;
3196 const WORD existing_bg
= old_color_attrs
& background_mask
;
3199 GetColorAttribute(color
) | existing_bg
| FOREGROUND_INTENSITY
;
3200 static const int bg_bitOffset
= GetBitOffset(background_mask
);
3201 static const int fg_bitOffset
= GetBitOffset(foreground_mask
);
3203 if (((new_color
& background_mask
) >> bg_bitOffset
) ==
3204 ((new_color
& foreground_mask
) >> fg_bitOffset
)) {
3205 new_color
^= FOREGROUND_INTENSITY
; // invert intensity
3212 // Returns the ANSI color code for the given color. GTestColor::kDefault is
3213 // an invalid input.
3214 static const char* GetAnsiColorCode(GTestColor color
) {
3216 case GTestColor::kRed
:
3218 case GTestColor::kGreen
:
3220 case GTestColor::kYellow
:
3227 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3229 // Returns true if and only if Google Test should use colors in the output.
3230 bool ShouldUseColor(bool stdout_is_tty
) {
3231 const char* const gtest_color
= GTEST_FLAG(color
).c_str();
3233 if (String::CaseInsensitiveCStringEquals(gtest_color
, "auto")) {
3234 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
3235 // On Windows the TERM variable is usually not set, but the
3236 // console there does support colors.
3237 return stdout_is_tty
;
3239 // On non-Windows platforms, we rely on the TERM variable.
3240 const char* const term
= posix::GetEnv("TERM");
3241 const bool term_supports_color
=
3242 String::CStringEquals(term
, "xterm") ||
3243 String::CStringEquals(term
, "xterm-color") ||
3244 String::CStringEquals(term
, "xterm-256color") ||
3245 String::CStringEquals(term
, "screen") ||
3246 String::CStringEquals(term
, "screen-256color") ||
3247 String::CStringEquals(term
, "tmux") ||
3248 String::CStringEquals(term
, "tmux-256color") ||
3249 String::CStringEquals(term
, "rxvt-unicode") ||
3250 String::CStringEquals(term
, "rxvt-unicode-256color") ||
3251 String::CStringEquals(term
, "linux") ||
3252 String::CStringEquals(term
, "cygwin");
3253 return stdout_is_tty
&& term_supports_color
;
3254 #endif // GTEST_OS_WINDOWS
3257 return String::CaseInsensitiveCStringEquals(gtest_color
, "yes") ||
3258 String::CaseInsensitiveCStringEquals(gtest_color
, "true") ||
3259 String::CaseInsensitiveCStringEquals(gtest_color
, "t") ||
3260 String::CStringEquals(gtest_color
, "1");
3261 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3262 // value is neither one of these nor "auto", we treat it as "no" to
3266 // Helpers for printing colored strings to stdout. Note that on Windows, we
3267 // cannot simply emit special characters and have the terminal change colors.
3268 // This routine must actually emit the characters rather than return a string
3269 // that would be colored when printed, as can be done on Linux.
3271 static void ColoredPrintf(GTestColor color
, const char* fmt
, ...) {
3273 va_start(args
, fmt
);
3275 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
3276 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
3277 const bool use_color
= AlwaysFalse();
3279 static const bool in_color_mode
=
3280 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout
)) != 0);
3281 const bool use_color
= in_color_mode
&& (color
!= GTestColor::kDefault
);
3282 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
3290 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3291 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3292 const HANDLE stdout_handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
3294 // Gets the current text color.
3295 CONSOLE_SCREEN_BUFFER_INFO buffer_info
;
3296 GetConsoleScreenBufferInfo(stdout_handle
, &buffer_info
);
3297 const WORD old_color_attrs
= buffer_info
.wAttributes
;
3298 const WORD new_color
= GetNewColor(color
, old_color_attrs
);
3300 // We need to flush the stream buffers into the console before each
3301 // SetConsoleTextAttribute call lest it affect the text that is already
3302 // printed but has not yet reached the console.
3304 SetConsoleTextAttribute(stdout_handle
, new_color
);
3309 // Restores the text color.
3310 SetConsoleTextAttribute(stdout_handle
, old_color_attrs
);
3312 printf("\033[0;3%sm", GetAnsiColorCode(color
));
3314 printf("\033[m"); // Resets the terminal to default.
3315 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3319 // Text printed in Google Test's text output and --gtest_list_tests
3320 // output to label the type parameter and value parameter for a test.
3321 static const char kTypeParamLabel
[] = "TypeParam";
3322 static const char kValueParamLabel
[] = "GetParam()";
3324 static void PrintFullTestCommentIfPresent(const TestInfo
& test_info
) {
3325 const char* const type_param
= test_info
.type_param();
3326 const char* const value_param
= test_info
.value_param();
3328 if (type_param
!= nullptr || value_param
!= nullptr) {
3330 if (type_param
!= nullptr) {
3331 printf("%s = %s", kTypeParamLabel
, type_param
);
3332 if (value_param
!= nullptr) printf(" and ");
3334 if (value_param
!= nullptr) {
3335 printf("%s = %s", kValueParamLabel
, value_param
);
3340 // This class implements the TestEventListener interface.
3342 // Class PrettyUnitTestResultPrinter is copyable.
3343 class PrettyUnitTestResultPrinter
: public TestEventListener
{
3345 PrettyUnitTestResultPrinter() {}
3346 static void PrintTestName(const char* test_suite
, const char* test
) {
3347 printf("%s.%s", test_suite
, test
);
3350 // The following methods override what's in the TestEventListener class.
3351 void OnTestProgramStart(const UnitTest
& /*unit_test*/) override
{}
3352 void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
) override
;
3353 void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
) override
;
3354 void OnEnvironmentsSetUpEnd(const UnitTest
& /*unit_test*/) override
{}
3355 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3356 void OnTestCaseStart(const TestCase
& test_case
) override
;
3358 void OnTestSuiteStart(const TestSuite
& test_suite
) override
;
3359 #endif // OnTestCaseStart
3361 void OnTestStart(const TestInfo
& test_info
) override
;
3363 void OnTestPartResult(const TestPartResult
& result
) override
;
3364 void OnTestEnd(const TestInfo
& test_info
) override
;
3365 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3366 void OnTestCaseEnd(const TestCase
& test_case
) override
;
3368 void OnTestSuiteEnd(const TestSuite
& test_suite
) override
;
3369 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3371 void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
) override
;
3372 void OnEnvironmentsTearDownEnd(const UnitTest
& /*unit_test*/) override
{}
3373 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3374 void OnTestProgramEnd(const UnitTest
& /*unit_test*/) override
{}
3377 static void PrintFailedTests(const UnitTest
& unit_test
);
3378 static void PrintFailedTestSuites(const UnitTest
& unit_test
);
3379 static void PrintSkippedTests(const UnitTest
& unit_test
);
3382 // Fired before each iteration of tests starts.
3383 void PrettyUnitTestResultPrinter::OnTestIterationStart(
3384 const UnitTest
& unit_test
, int iteration
) {
3385 if (GTEST_FLAG(repeat
) != 1)
3386 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration
+ 1);
3388 const char* const filter
= GTEST_FLAG(filter
).c_str();
3390 // Prints the filter if it's not *. This reminds the user that some
3391 // tests may be skipped.
3392 if (!String::CStringEquals(filter
, kUniversalFilter
)) {
3393 ColoredPrintf(GTestColor::kYellow
, "Note: %s filter = %s\n", GTEST_NAME_
,
3397 if (internal::ShouldShard(kTestTotalShards
, kTestShardIndex
, false)) {
3398 const int32_t shard_index
= Int32FromEnvOrDie(kTestShardIndex
, -1);
3399 ColoredPrintf(GTestColor::kYellow
, "Note: This is test shard %d of %s.\n",
3400 static_cast<int>(shard_index
) + 1,
3401 internal::posix::GetEnv(kTestTotalShards
));
3404 if (GTEST_FLAG(shuffle
)) {
3405 ColoredPrintf(GTestColor::kYellow
,
3406 "Note: Randomizing tests' orders with a seed of %d .\n",
3407 unit_test
.random_seed());
3410 ColoredPrintf(GTestColor::kGreen
, "[==========] ");
3411 printf("Running %s from %s.\n",
3412 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
3413 FormatTestSuiteCount(unit_test
.test_suite_to_run_count()).c_str());
3417 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3418 const UnitTest
& /*unit_test*/) {
3419 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3420 printf("Global test environment set-up.\n");
3424 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3425 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase
& test_case
) {
3426 const std::string counts
=
3427 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
3428 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3429 printf("%s from %s", counts
.c_str(), test_case
.name());
3430 if (test_case
.type_param() == nullptr) {
3433 printf(", where %s = %s\n", kTypeParamLabel
, test_case
.type_param());
3438 void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3439 const TestSuite
& test_suite
) {
3440 const std::string counts
=
3441 FormatCountableNoun(test_suite
.test_to_run_count(), "test", "tests");
3442 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3443 printf("%s from %s", counts
.c_str(), test_suite
.name());
3444 if (test_suite
.type_param() == nullptr) {
3447 printf(", where %s = %s\n", kTypeParamLabel
, test_suite
.type_param());
3451 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3453 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo
& test_info
) {
3454 ColoredPrintf(GTestColor::kGreen
, "[ RUN ] ");
3455 PrintTestName(test_info
.test_suite_name(), test_info
.name());
3460 // Called after an assertion failure.
3461 void PrettyUnitTestResultPrinter::OnTestPartResult(
3462 const TestPartResult
& result
) {
3463 switch (result
.type()) {
3464 // If the test part succeeded, we don't need to do anything.
3465 case TestPartResult::kSuccess
:
3468 // Print failure message from the assertion
3469 // (e.g. expected this and got that).
3470 PrintTestPartResult(result
);
3475 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo
& test_info
) {
3476 if (test_info
.result()->Passed()) {
3477 ColoredPrintf(GTestColor::kGreen
, "[ OK ] ");
3478 } else if (test_info
.result()->Skipped()) {
3479 ColoredPrintf(GTestColor::kGreen
, "[ SKIPPED ] ");
3481 ColoredPrintf(GTestColor::kRed
, "[ FAILED ] ");
3483 PrintTestName(test_info
.test_suite_name(), test_info
.name());
3484 if (test_info
.result()->Failed())
3485 PrintFullTestCommentIfPresent(test_info
);
3487 if (GTEST_FLAG(print_time
)) {
3488 printf(" (%s ms)\n", internal::StreamableToString(
3489 test_info
.result()->elapsed_time()).c_str());
3496 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3497 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase
& test_case
) {
3498 if (!GTEST_FLAG(print_time
)) return;
3500 const std::string counts
=
3501 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
3502 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3503 printf("%s from %s (%s ms total)\n\n", counts
.c_str(), test_case
.name(),
3504 internal::StreamableToString(test_case
.elapsed_time()).c_str());
3508 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite
& test_suite
) {
3509 if (!GTEST_FLAG(print_time
)) return;
3511 const std::string counts
=
3512 FormatCountableNoun(test_suite
.test_to_run_count(), "test", "tests");
3513 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3514 printf("%s from %s (%s ms total)\n\n", counts
.c_str(), test_suite
.name(),
3515 internal::StreamableToString(test_suite
.elapsed_time()).c_str());
3518 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3520 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3521 const UnitTest
& /*unit_test*/) {
3522 ColoredPrintf(GTestColor::kGreen
, "[----------] ");
3523 printf("Global test environment tear-down\n");
3527 // Internal helper for printing the list of failed tests.
3528 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest
& unit_test
) {
3529 const int failed_test_count
= unit_test
.failed_test_count();
3530 ColoredPrintf(GTestColor::kRed
, "[ FAILED ] ");
3531 printf("%s, listed below:\n", FormatTestCount(failed_test_count
).c_str());
3533 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3534 const TestSuite
& test_suite
= *unit_test
.GetTestSuite(i
);
3535 if (!test_suite
.should_run() || (test_suite
.failed_test_count() == 0)) {
3538 for (int j
= 0; j
< test_suite
.total_test_count(); ++j
) {
3539 const TestInfo
& test_info
= *test_suite
.GetTestInfo(j
);
3540 if (!test_info
.should_run() || !test_info
.result()->Failed()) {
3543 ColoredPrintf(GTestColor::kRed
, "[ FAILED ] ");
3544 printf("%s.%s", test_suite
.name(), test_info
.name());
3545 PrintFullTestCommentIfPresent(test_info
);
3549 printf("\n%2d FAILED %s\n", failed_test_count
,
3550 failed_test_count
== 1 ? "TEST" : "TESTS");
3553 // Internal helper for printing the list of test suite failures not covered by
3554 // PrintFailedTests.
3555 void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3556 const UnitTest
& unit_test
) {
3557 int suite_failure_count
= 0;
3558 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3559 const TestSuite
& test_suite
= *unit_test
.GetTestSuite(i
);
3560 if (!test_suite
.should_run()) {
3563 if (test_suite
.ad_hoc_test_result().Failed()) {
3564 ColoredPrintf(GTestColor::kRed
, "[ FAILED ] ");
3565 printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite
.name());
3566 ++suite_failure_count
;
3569 if (suite_failure_count
> 0) {
3570 printf("\n%2d FAILED TEST %s\n", suite_failure_count
,
3571 suite_failure_count
== 1 ? "SUITE" : "SUITES");
3575 // Internal helper for printing the list of skipped tests.
3576 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest
& unit_test
) {
3577 const int skipped_test_count
= unit_test
.skipped_test_count();
3578 if (skipped_test_count
== 0) {
3582 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
3583 const TestSuite
& test_suite
= *unit_test
.GetTestSuite(i
);
3584 if (!test_suite
.should_run() || (test_suite
.skipped_test_count() == 0)) {
3587 for (int j
= 0; j
< test_suite
.total_test_count(); ++j
) {
3588 const TestInfo
& test_info
= *test_suite
.GetTestInfo(j
);
3589 if (!test_info
.should_run() || !test_info
.result()->Skipped()) {
3592 ColoredPrintf(GTestColor::kGreen
, "[ SKIPPED ] ");
3593 printf("%s.%s", test_suite
.name(), test_info
.name());
3599 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
3600 int /*iteration*/) {
3601 ColoredPrintf(GTestColor::kGreen
, "[==========] ");
3602 printf("%s from %s ran.",
3603 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
3604 FormatTestSuiteCount(unit_test
.test_suite_to_run_count()).c_str());
3605 if (GTEST_FLAG(print_time
)) {
3606 printf(" (%s ms total)",
3607 internal::StreamableToString(unit_test
.elapsed_time()).c_str());
3610 ColoredPrintf(GTestColor::kGreen
, "[ PASSED ] ");
3611 printf("%s.\n", FormatTestCount(unit_test
.successful_test_count()).c_str());
3613 const int skipped_test_count
= unit_test
.skipped_test_count();
3614 if (skipped_test_count
> 0) {
3615 ColoredPrintf(GTestColor::kGreen
, "[ SKIPPED ] ");
3616 printf("%s, listed below:\n", FormatTestCount(skipped_test_count
).c_str());
3617 PrintSkippedTests(unit_test
);
3620 if (!unit_test
.Passed()) {
3621 PrintFailedTests(unit_test
);
3622 PrintFailedTestSuites(unit_test
);
3625 int num_disabled
= unit_test
.reportable_disabled_test_count();
3626 if (num_disabled
&& !GTEST_FLAG(also_run_disabled_tests
)) {
3627 if (unit_test
.Passed()) {
3628 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3630 ColoredPrintf(GTestColor::kYellow
, " YOU HAVE %d DISABLED %s\n\n",
3631 num_disabled
, num_disabled
== 1 ? "TEST" : "TESTS");
3633 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3637 // End PrettyUnitTestResultPrinter
3639 // This class implements the TestEventListener interface.
3641 // Class BriefUnitTestResultPrinter is copyable.
3642 class BriefUnitTestResultPrinter
: public TestEventListener
{
3644 BriefUnitTestResultPrinter() {}
3645 static void PrintTestName(const char* test_suite
, const char* test
) {
3646 printf("%s.%s", test_suite
, test
);
3649 // The following methods override what's in the TestEventListener class.
3650 void OnTestProgramStart(const UnitTest
& /*unit_test*/) override
{}
3651 void OnTestIterationStart(const UnitTest
& /*unit_test*/,
3652 int /*iteration*/) override
{}
3653 void OnEnvironmentsSetUpStart(const UnitTest
& /*unit_test*/) override
{}
3654 void OnEnvironmentsSetUpEnd(const UnitTest
& /*unit_test*/) override
{}
3655 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3656 void OnTestCaseStart(const TestCase
& /*test_case*/) override
{}
3658 void OnTestSuiteStart(const TestSuite
& /*test_suite*/) override
{}
3659 #endif // OnTestCaseStart
3661 void OnTestStart(const TestInfo
& /*test_info*/) override
{}
3663 void OnTestPartResult(const TestPartResult
& result
) override
;
3664 void OnTestEnd(const TestInfo
& test_info
) override
;
3665 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3666 void OnTestCaseEnd(const TestCase
& /*test_case*/) override
{}
3668 void OnTestSuiteEnd(const TestSuite
& /*test_suite*/) override
{}
3669 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3671 void OnEnvironmentsTearDownStart(const UnitTest
& /*unit_test*/) override
{}
3672 void OnEnvironmentsTearDownEnd(const UnitTest
& /*unit_test*/) override
{}
3673 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3674 void OnTestProgramEnd(const UnitTest
& /*unit_test*/) override
{}
3677 // Called after an assertion failure.
3678 void BriefUnitTestResultPrinter::OnTestPartResult(
3679 const TestPartResult
& result
) {
3680 switch (result
.type()) {
3681 // If the test part succeeded, we don't need to do anything.
3682 case TestPartResult::kSuccess
:
3685 // Print failure message from the assertion
3686 // (e.g. expected this and got that).
3687 PrintTestPartResult(result
);
3692 void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo
& test_info
) {
3693 if (test_info
.result()->Failed()) {
3694 ColoredPrintf(GTestColor::kRed
, "[ FAILED ] ");
3695 PrintTestName(test_info
.test_suite_name(), test_info
.name());
3696 PrintFullTestCommentIfPresent(test_info
);
3698 if (GTEST_FLAG(print_time
)) {
3699 printf(" (%s ms)\n",
3700 internal::StreamableToString(test_info
.result()->elapsed_time())
3709 void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
3710 int /*iteration*/) {
3711 ColoredPrintf(GTestColor::kGreen
, "[==========] ");
3712 printf("%s from %s ran.",
3713 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
3714 FormatTestSuiteCount(unit_test
.test_suite_to_run_count()).c_str());
3715 if (GTEST_FLAG(print_time
)) {
3716 printf(" (%s ms total)",
3717 internal::StreamableToString(unit_test
.elapsed_time()).c_str());
3720 ColoredPrintf(GTestColor::kGreen
, "[ PASSED ] ");
3721 printf("%s.\n", FormatTestCount(unit_test
.successful_test_count()).c_str());
3723 const int skipped_test_count
= unit_test
.skipped_test_count();
3724 if (skipped_test_count
> 0) {
3725 ColoredPrintf(GTestColor::kGreen
, "[ SKIPPED ] ");
3726 printf("%s.\n", FormatTestCount(skipped_test_count
).c_str());
3729 int num_disabled
= unit_test
.reportable_disabled_test_count();
3730 if (num_disabled
&& !GTEST_FLAG(also_run_disabled_tests
)) {
3731 if (unit_test
.Passed()) {
3732 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3734 ColoredPrintf(GTestColor::kYellow
, " YOU HAVE %d DISABLED %s\n\n",
3735 num_disabled
, num_disabled
== 1 ? "TEST" : "TESTS");
3737 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3741 // End BriefUnitTestResultPrinter
3743 // class TestEventRepeater
3745 // This class forwards events to other event listeners.
3746 class TestEventRepeater
: public TestEventListener
{
3748 TestEventRepeater() : forwarding_enabled_(true) {}
3749 ~TestEventRepeater() override
;
3750 void Append(TestEventListener
*listener
);
3751 TestEventListener
* Release(TestEventListener
* listener
);
3753 // Controls whether events will be forwarded to listeners_. Set to false
3754 // in death test child processes.
3755 bool forwarding_enabled() const { return forwarding_enabled_
; }
3756 void set_forwarding_enabled(bool enable
) { forwarding_enabled_
= enable
; }
3758 void OnTestProgramStart(const UnitTest
& unit_test
) override
;
3759 void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
) override
;
3760 void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
) override
;
3761 void OnEnvironmentsSetUpEnd(const UnitTest
& unit_test
) override
;
3762 // Legacy API is deprecated but still available
3763 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3764 void OnTestCaseStart(const TestSuite
& parameter
) override
;
3765 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3766 void OnTestSuiteStart(const TestSuite
& parameter
) override
;
3767 void OnTestStart(const TestInfo
& test_info
) override
;
3768 void OnTestPartResult(const TestPartResult
& result
) override
;
3769 void OnTestEnd(const TestInfo
& test_info
) override
;
3770 // Legacy API is deprecated but still available
3771 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3772 void OnTestCaseEnd(const TestCase
& parameter
) override
;
3773 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3774 void OnTestSuiteEnd(const TestSuite
& parameter
) override
;
3775 void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
) override
;
3776 void OnEnvironmentsTearDownEnd(const UnitTest
& unit_test
) override
;
3777 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3778 void OnTestProgramEnd(const UnitTest
& unit_test
) override
;
3781 // Controls whether events will be forwarded to listeners_. Set to false
3782 // in death test child processes.
3783 bool forwarding_enabled_
;
3784 // The list of listeners that receive events.
3785 std::vector
<TestEventListener
*> listeners_
;
3787 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater
);
3790 TestEventRepeater::~TestEventRepeater() {
3791 ForEach(listeners_
, Delete
<TestEventListener
>);
3794 void TestEventRepeater::Append(TestEventListener
*listener
) {
3795 listeners_
.push_back(listener
);
3798 TestEventListener
* TestEventRepeater::Release(TestEventListener
*listener
) {
3799 for (size_t i
= 0; i
< listeners_
.size(); ++i
) {
3800 if (listeners_
[i
] == listener
) {
3801 listeners_
.erase(listeners_
.begin() + static_cast<int>(i
));
3809 // Since most methods are very similar, use macros to reduce boilerplate.
3810 // This defines a member that forwards the call to all listeners.
3811 #define GTEST_REPEATER_METHOD_(Name, Type) \
3812 void TestEventRepeater::Name(const Type& parameter) { \
3813 if (forwarding_enabled_) { \
3814 for (size_t i = 0; i < listeners_.size(); i++) { \
3815 listeners_[i]->Name(parameter); \
3819 // This defines a member that forwards the call to all listeners in reverse
3821 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3822 void TestEventRepeater::Name(const Type& parameter) { \
3823 if (forwarding_enabled_) { \
3824 for (size_t i = listeners_.size(); i != 0; i--) { \
3825 listeners_[i - 1]->Name(parameter); \
3830 GTEST_REPEATER_METHOD_(OnTestProgramStart
, UnitTest
)
3831 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart
, UnitTest
)
3832 // Legacy API is deprecated but still available
3833 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3834 GTEST_REPEATER_METHOD_(OnTestCaseStart
, TestSuite
)
3835 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3836 GTEST_REPEATER_METHOD_(OnTestSuiteStart
, TestSuite
)
3837 GTEST_REPEATER_METHOD_(OnTestStart
, TestInfo
)
3838 GTEST_REPEATER_METHOD_(OnTestPartResult
, TestPartResult
)
3839 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart
, UnitTest
)
3840 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd
, UnitTest
)
3841 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd
, UnitTest
)
3842 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd
, TestInfo
)
3843 // Legacy API is deprecated but still available
3844 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3845 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd
, TestSuite
)
3846 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3847 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd
, TestSuite
)
3848 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd
, UnitTest
)
3850 #undef GTEST_REPEATER_METHOD_
3851 #undef GTEST_REVERSE_REPEATER_METHOD_
3853 void TestEventRepeater::OnTestIterationStart(const UnitTest
& unit_test
,
3855 if (forwarding_enabled_
) {
3856 for (size_t i
= 0; i
< listeners_
.size(); i
++) {
3857 listeners_
[i
]->OnTestIterationStart(unit_test
, iteration
);
3862 void TestEventRepeater::OnTestIterationEnd(const UnitTest
& unit_test
,
3864 if (forwarding_enabled_
) {
3865 for (size_t i
= listeners_
.size(); i
> 0; i
--) {
3866 listeners_
[i
- 1]->OnTestIterationEnd(unit_test
, iteration
);
3871 // End TestEventRepeater
3873 // This class generates an XML output file.
3874 class XmlUnitTestResultPrinter
: public EmptyTestEventListener
{
3876 explicit XmlUnitTestResultPrinter(const char* output_file
);
3878 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
3879 void ListTestsMatchingFilter(const std::vector
<TestSuite
*>& test_suites
);
3881 // Prints an XML summary of all unit tests.
3882 static void PrintXmlTestsList(std::ostream
* stream
,
3883 const std::vector
<TestSuite
*>& test_suites
);
3886 // Is c a whitespace character that is normalized to a space character
3887 // when it appears in an XML attribute value?
3888 static bool IsNormalizableWhitespace(char c
) {
3889 return c
== 0x9 || c
== 0xA || c
== 0xD;
3892 // May c appear in a well-formed XML document?
3893 static bool IsValidXmlCharacter(char c
) {
3894 return IsNormalizableWhitespace(c
) || c
>= 0x20;
3897 // Returns an XML-escaped copy of the input string str. If
3898 // is_attribute is true, the text is meant to appear as an attribute
3899 // value, and normalizable whitespace is preserved by replacing it
3900 // with character references.
3901 static std::string
EscapeXml(const std::string
& str
, bool is_attribute
);
3903 // Returns the given string with all characters invalid in XML removed.
3904 static std::string
RemoveInvalidXmlCharacters(const std::string
& str
);
3906 // Convenience wrapper around EscapeXml when str is an attribute value.
3907 static std::string
EscapeXmlAttribute(const std::string
& str
) {
3908 return EscapeXml(str
, true);
3911 // Convenience wrapper around EscapeXml when str is not an attribute value.
3912 static std::string
EscapeXmlText(const char* str
) {
3913 return EscapeXml(str
, false);
3916 // Verifies that the given attribute belongs to the given element and
3917 // streams the attribute as XML.
3918 static void OutputXmlAttribute(std::ostream
* stream
,
3919 const std::string
& element_name
,
3920 const std::string
& name
,
3921 const std::string
& value
);
3923 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3924 static void OutputXmlCDataSection(::std::ostream
* stream
, const char* data
);
3926 // Streams an XML representation of a TestInfo object.
3927 static void OutputXmlTestInfo(::std::ostream
* stream
,
3928 const char* test_suite_name
,
3929 const TestInfo
& test_info
);
3931 // Prints an XML representation of a TestSuite object
3932 static void PrintXmlTestSuite(::std::ostream
* stream
,
3933 const TestSuite
& test_suite
);
3935 // Prints an XML summary of unit_test to output stream out.
3936 static void PrintXmlUnitTest(::std::ostream
* stream
,
3937 const UnitTest
& unit_test
);
3939 // Produces a string representing the test properties in a result as space
3940 // delimited XML attributes based on the property key="value" pairs.
3941 // When the std::string is not empty, it includes a space at the beginning,
3942 // to delimit this attribute from prior attributes.
3943 static std::string
TestPropertiesAsXmlAttributes(const TestResult
& result
);
3945 // Streams an XML representation of the test properties of a TestResult
3947 static void OutputXmlTestProperties(std::ostream
* stream
,
3948 const TestResult
& result
);
3951 const std::string output_file_
;
3953 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter
);
3956 // Creates a new XmlUnitTestResultPrinter.
3957 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file
)
3958 : output_file_(output_file
) {
3959 if (output_file_
.empty()) {
3960 GTEST_LOG_(FATAL
) << "XML output file may not be null";
3964 // Called after the unit test ends.
3965 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
3966 int /*iteration*/) {
3967 FILE* xmlout
= OpenFileForWriting(output_file_
);
3968 std::stringstream stream
;
3969 PrintXmlUnitTest(&stream
, unit_test
);
3970 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
3974 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
3975 const std::vector
<TestSuite
*>& test_suites
) {
3976 FILE* xmlout
= OpenFileForWriting(output_file_
);
3977 std::stringstream stream
;
3978 PrintXmlTestsList(&stream
, test_suites
);
3979 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
3983 // Returns an XML-escaped copy of the input string str. If is_attribute
3984 // is true, the text is meant to appear as an attribute value, and
3985 // normalizable whitespace is preserved by replacing it with character
3988 // Invalid XML characters in str, if any, are stripped from the output.
3989 // It is expected that most, if not all, of the text processed by this
3990 // module will consist of ordinary English text.
3991 // If this module is ever modified to produce version 1.1 XML output,
3992 // most invalid characters can be retained using character references.
3993 std::string
XmlUnitTestResultPrinter::EscapeXml(
3994 const std::string
& str
, bool is_attribute
) {
3997 for (size_t i
= 0; i
< str
.size(); ++i
) {
3998 const char ch
= str
[i
];
4022 if (IsValidXmlCharacter(ch
)) {
4023 if (is_attribute
&& IsNormalizableWhitespace(ch
))
4024 m
<< "&#x" << String::FormatByte(static_cast<unsigned char>(ch
))
4033 return m
.GetString();
4036 // Returns the given string with all characters invalid in XML removed.
4037 // Currently invalid characters are dropped from the string. An
4038 // alternative is to replace them with certain characters such as . or ?.
4039 std::string
XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4040 const std::string
& str
) {
4042 output
.reserve(str
.size());
4043 for (std::string::const_iterator it
= str
.begin(); it
!= str
.end(); ++it
)
4044 if (IsValidXmlCharacter(*it
))
4045 output
.push_back(*it
);
4050 // The following routines generate an XML representation of a UnitTest
4052 // GOOGLETEST_CM0009 DO NOT DELETE
4054 // This is how Google Test concepts map to the DTD:
4056 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4057 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
4058 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4059 // <failure message="...">...</failure>
4060 // <failure message="...">...</failure>
4061 // <failure message="...">...</failure>
4062 // <-- individual assertion failures
4067 // Formats the given time in milliseconds as seconds.
4068 std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
) {
4069 ::std::stringstream ss
;
4070 ss
<< (static_cast<double>(ms
) * 1e-3);
4074 static bool PortableLocaltime(time_t seconds
, struct tm
* out
) {
4075 #if defined(_MSC_VER)
4076 return localtime_s(out
, &seconds
) == 0;
4077 #elif defined(__MINGW32__) || defined(__MINGW64__)
4078 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
4079 // Windows' localtime(), which has a thread-local tm buffer.
4080 struct tm
* tm_ptr
= localtime(&seconds
); // NOLINT
4081 if (tm_ptr
== nullptr) return false;
4085 return localtime_r(&seconds
, out
) != nullptr;
4089 // Converts the given epoch time in milliseconds to a date string in the ISO
4090 // 8601 format, without the timezone information.
4091 std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
) {
4092 struct tm time_struct
;
4093 if (!PortableLocaltime(static_cast<time_t>(ms
/ 1000), &time_struct
))
4095 // YYYY-MM-DDThh:mm:ss.sss
4096 return StreamableToString(time_struct
.tm_year
+ 1900) + "-" +
4097 String::FormatIntWidth2(time_struct
.tm_mon
+ 1) + "-" +
4098 String::FormatIntWidth2(time_struct
.tm_mday
) + "T" +
4099 String::FormatIntWidth2(time_struct
.tm_hour
) + ":" +
4100 String::FormatIntWidth2(time_struct
.tm_min
) + ":" +
4101 String::FormatIntWidth2(time_struct
.tm_sec
) + "." +
4102 String::FormatIntWidthN(static_cast<int>(ms
% 1000), 3);
4105 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4106 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream
* stream
,
4108 const char* segment
= data
;
4109 *stream
<< "<![CDATA[";
4111 const char* const next_segment
= strstr(segment
, "]]>");
4112 if (next_segment
!= nullptr) {
4114 segment
, static_cast<std::streamsize
>(next_segment
- segment
));
4115 *stream
<< "]]>]]><![CDATA[";
4116 segment
= next_segment
+ strlen("]]>");
4125 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4126 std::ostream
* stream
,
4127 const std::string
& element_name
,
4128 const std::string
& name
,
4129 const std::string
& value
) {
4130 const std::vector
<std::string
>& allowed_names
=
4131 GetReservedOutputAttributesForElement(element_name
);
4133 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4134 allowed_names
.end())
4135 << "Attribute " << name
<< " is not allowed for element <" << element_name
4138 *stream
<< " " << name
<< "=\"" << EscapeXmlAttribute(value
) << "\"";
4141 // Prints an XML representation of a TestInfo object.
4142 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream
* stream
,
4143 const char* test_suite_name
,
4144 const TestInfo
& test_info
) {
4145 const TestResult
& result
= *test_info
.result();
4146 const std::string kTestsuite
= "testcase";
4148 if (test_info
.is_in_another_shard()) {
4152 *stream
<< " <testcase";
4153 OutputXmlAttribute(stream
, kTestsuite
, "name", test_info
.name());
4155 if (test_info
.value_param() != nullptr) {
4156 OutputXmlAttribute(stream
, kTestsuite
, "value_param",
4157 test_info
.value_param());
4159 if (test_info
.type_param() != nullptr) {
4160 OutputXmlAttribute(stream
, kTestsuite
, "type_param",
4161 test_info
.type_param());
4163 if (GTEST_FLAG(list_tests
)) {
4164 OutputXmlAttribute(stream
, kTestsuite
, "file", test_info
.file());
4165 OutputXmlAttribute(stream
, kTestsuite
, "line",
4166 StreamableToString(test_info
.line()));
4171 OutputXmlAttribute(stream
, kTestsuite
, "status",
4172 test_info
.should_run() ? "run" : "notrun");
4173 OutputXmlAttribute(stream
, kTestsuite
, "result",
4174 test_info
.should_run()
4175 ? (result
.Skipped() ? "skipped" : "completed")
4177 OutputXmlAttribute(stream
, kTestsuite
, "time",
4178 FormatTimeInMillisAsSeconds(result
.elapsed_time()));
4180 stream
, kTestsuite
, "timestamp",
4181 FormatEpochTimeInMillisAsIso8601(result
.start_timestamp()));
4182 OutputXmlAttribute(stream
, kTestsuite
, "classname", test_suite_name
);
4186 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
4187 const TestPartResult
& part
= result
.GetTestPartResult(i
);
4188 if (part
.failed()) {
4189 if (++failures
== 1 && skips
== 0) {
4192 const std::string location
=
4193 internal::FormatCompilerIndependentFileLocation(part
.file_name(),
4194 part
.line_number());
4195 const std::string summary
= location
+ "\n" + part
.summary();
4196 *stream
<< " <failure message=\""
4197 << EscapeXmlAttribute(summary
)
4199 const std::string detail
= location
+ "\n" + part
.message();
4200 OutputXmlCDataSection(stream
, RemoveInvalidXmlCharacters(detail
).c_str());
4201 *stream
<< "</failure>\n";
4202 } else if (part
.skipped()) {
4203 if (++skips
== 1 && failures
== 0) {
4206 const std::string location
=
4207 internal::FormatCompilerIndependentFileLocation(part
.file_name(),
4208 part
.line_number());
4209 const std::string summary
= location
+ "\n" + part
.summary();
4210 *stream
<< " <skipped message=\""
4211 << EscapeXmlAttribute(summary
.c_str()) << "\">";
4212 const std::string detail
= location
+ "\n" + part
.message();
4213 OutputXmlCDataSection(stream
, RemoveInvalidXmlCharacters(detail
).c_str());
4214 *stream
<< "</skipped>\n";
4218 if (failures
== 0 && skips
== 0 && result
.test_property_count() == 0) {
4221 if (failures
== 0 && skips
== 0) {
4224 OutputXmlTestProperties(stream
, result
);
4225 *stream
<< " </testcase>\n";
4229 // Prints an XML representation of a TestSuite object
4230 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream
* stream
,
4231 const TestSuite
& test_suite
) {
4232 const std::string kTestsuite
= "testsuite";
4233 *stream
<< " <" << kTestsuite
;
4234 OutputXmlAttribute(stream
, kTestsuite
, "name", test_suite
.name());
4235 OutputXmlAttribute(stream
, kTestsuite
, "tests",
4236 StreamableToString(test_suite
.reportable_test_count()));
4237 if (!GTEST_FLAG(list_tests
)) {
4238 OutputXmlAttribute(stream
, kTestsuite
, "failures",
4239 StreamableToString(test_suite
.failed_test_count()));
4241 stream
, kTestsuite
, "disabled",
4242 StreamableToString(test_suite
.reportable_disabled_test_count()));
4243 OutputXmlAttribute(stream
, kTestsuite
, "skipped",
4244 StreamableToString(test_suite
.skipped_test_count()));
4246 OutputXmlAttribute(stream
, kTestsuite
, "errors", "0");
4248 OutputXmlAttribute(stream
, kTestsuite
, "time",
4249 FormatTimeInMillisAsSeconds(test_suite
.elapsed_time()));
4251 stream
, kTestsuite
, "timestamp",
4252 FormatEpochTimeInMillisAsIso8601(test_suite
.start_timestamp()));
4253 *stream
<< TestPropertiesAsXmlAttributes(test_suite
.ad_hoc_test_result());
4256 for (int i
= 0; i
< test_suite
.total_test_count(); ++i
) {
4257 if (test_suite
.GetTestInfo(i
)->is_reportable())
4258 OutputXmlTestInfo(stream
, test_suite
.name(), *test_suite
.GetTestInfo(i
));
4260 *stream
<< " </" << kTestsuite
<< ">\n";
4263 // Prints an XML summary of unit_test to output stream out.
4264 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream
* stream
,
4265 const UnitTest
& unit_test
) {
4266 const std::string kTestsuites
= "testsuites";
4268 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4269 *stream
<< "<" << kTestsuites
;
4271 OutputXmlAttribute(stream
, kTestsuites
, "tests",
4272 StreamableToString(unit_test
.reportable_test_count()));
4273 OutputXmlAttribute(stream
, kTestsuites
, "failures",
4274 StreamableToString(unit_test
.failed_test_count()));
4276 stream
, kTestsuites
, "disabled",
4277 StreamableToString(unit_test
.reportable_disabled_test_count()));
4278 OutputXmlAttribute(stream
, kTestsuites
, "errors", "0");
4279 OutputXmlAttribute(stream
, kTestsuites
, "time",
4280 FormatTimeInMillisAsSeconds(unit_test
.elapsed_time()));
4282 stream
, kTestsuites
, "timestamp",
4283 FormatEpochTimeInMillisAsIso8601(unit_test
.start_timestamp()));
4285 if (GTEST_FLAG(shuffle
)) {
4286 OutputXmlAttribute(stream
, kTestsuites
, "random_seed",
4287 StreamableToString(unit_test
.random_seed()));
4289 *stream
<< TestPropertiesAsXmlAttributes(unit_test
.ad_hoc_test_result());
4291 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
4294 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
4295 if (unit_test
.GetTestSuite(i
)->reportable_test_count() > 0)
4296 PrintXmlTestSuite(stream
, *unit_test
.GetTestSuite(i
));
4298 *stream
<< "</" << kTestsuites
<< ">\n";
4301 void XmlUnitTestResultPrinter::PrintXmlTestsList(
4302 std::ostream
* stream
, const std::vector
<TestSuite
*>& test_suites
) {
4303 const std::string kTestsuites
= "testsuites";
4305 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4306 *stream
<< "<" << kTestsuites
;
4308 int total_tests
= 0;
4309 for (auto test_suite
: test_suites
) {
4310 total_tests
+= test_suite
->total_test_count();
4312 OutputXmlAttribute(stream
, kTestsuites
, "tests",
4313 StreamableToString(total_tests
));
4314 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
4317 for (auto test_suite
: test_suites
) {
4318 PrintXmlTestSuite(stream
, *test_suite
);
4320 *stream
<< "</" << kTestsuites
<< ">\n";
4323 // Produces a string representing the test properties in a result as space
4324 // delimited XML attributes based on the property key="value" pairs.
4325 std::string
XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4326 const TestResult
& result
) {
4328 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4329 const TestProperty
& property
= result
.GetTestProperty(i
);
4330 attributes
<< " " << property
.key() << "="
4331 << "\"" << EscapeXmlAttribute(property
.value()) << "\"";
4333 return attributes
.GetString();
4336 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4337 std::ostream
* stream
, const TestResult
& result
) {
4338 const std::string kProperties
= "properties";
4339 const std::string kProperty
= "property";
4341 if (result
.test_property_count() <= 0) {
4345 *stream
<< "<" << kProperties
<< ">\n";
4346 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4347 const TestProperty
& property
= result
.GetTestProperty(i
);
4348 *stream
<< "<" << kProperty
;
4349 *stream
<< " name=\"" << EscapeXmlAttribute(property
.key()) << "\"";
4350 *stream
<< " value=\"" << EscapeXmlAttribute(property
.value()) << "\"";
4353 *stream
<< "</" << kProperties
<< ">\n";
4356 // End XmlUnitTestResultPrinter
4358 // This class generates an JSON output file.
4359 class JsonUnitTestResultPrinter
: public EmptyTestEventListener
{
4361 explicit JsonUnitTestResultPrinter(const char* output_file
);
4363 void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
) override
;
4365 // Prints an JSON summary of all unit tests.
4366 static void PrintJsonTestList(::std::ostream
* stream
,
4367 const std::vector
<TestSuite
*>& test_suites
);
4370 // Returns an JSON-escaped copy of the input string str.
4371 static std::string
EscapeJson(const std::string
& str
);
4373 //// Verifies that the given attribute belongs to the given element and
4374 //// streams the attribute as JSON.
4375 static void OutputJsonKey(std::ostream
* stream
,
4376 const std::string
& element_name
,
4377 const std::string
& name
,
4378 const std::string
& value
,
4379 const std::string
& indent
,
4381 static void OutputJsonKey(std::ostream
* stream
,
4382 const std::string
& element_name
,
4383 const std::string
& name
,
4385 const std::string
& indent
,
4388 // Streams a JSON representation of a TestInfo object.
4389 static void OutputJsonTestInfo(::std::ostream
* stream
,
4390 const char* test_suite_name
,
4391 const TestInfo
& test_info
);
4393 // Prints a JSON representation of a TestSuite object
4394 static void PrintJsonTestSuite(::std::ostream
* stream
,
4395 const TestSuite
& test_suite
);
4397 // Prints a JSON summary of unit_test to output stream out.
4398 static void PrintJsonUnitTest(::std::ostream
* stream
,
4399 const UnitTest
& unit_test
);
4401 // Produces a string representing the test properties in a result as
4402 // a JSON dictionary.
4403 static std::string
TestPropertiesAsJson(const TestResult
& result
,
4404 const std::string
& indent
);
4407 const std::string output_file_
;
4409 GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter
);
4412 // Creates a new JsonUnitTestResultPrinter.
4413 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file
)
4414 : output_file_(output_file
) {
4415 if (output_file_
.empty()) {
4416 GTEST_LOG_(FATAL
) << "JSON output file may not be null";
4420 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4421 int /*iteration*/) {
4422 FILE* jsonout
= OpenFileForWriting(output_file_
);
4423 std::stringstream stream
;
4424 PrintJsonUnitTest(&stream
, unit_test
);
4425 fprintf(jsonout
, "%s", StringStreamToString(&stream
).c_str());
4429 // Returns an JSON-escaped copy of the input string str.
4430 std::string
JsonUnitTestResultPrinter::EscapeJson(const std::string
& str
) {
4433 for (size_t i
= 0; i
< str
.size(); ++i
) {
4434 const char ch
= str
[i
];
4458 m
<< "\\u00" << String::FormatByte(static_cast<unsigned char>(ch
));
4466 return m
.GetString();
4469 // The following routines generate an JSON representation of a UnitTest
4472 // Formats the given time in milliseconds as seconds.
4473 static std::string
FormatTimeInMillisAsDuration(TimeInMillis ms
) {
4474 ::std::stringstream ss
;
4475 ss
<< (static_cast<double>(ms
) * 1e-3) << "s";
4479 // Converts the given epoch time in milliseconds to a date string in the
4480 // RFC3339 format, without the timezone information.
4481 static std::string
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms
) {
4482 struct tm time_struct
;
4483 if (!PortableLocaltime(static_cast<time_t>(ms
/ 1000), &time_struct
))
4485 // YYYY-MM-DDThh:mm:ss
4486 return StreamableToString(time_struct
.tm_year
+ 1900) + "-" +
4487 String::FormatIntWidth2(time_struct
.tm_mon
+ 1) + "-" +
4488 String::FormatIntWidth2(time_struct
.tm_mday
) + "T" +
4489 String::FormatIntWidth2(time_struct
.tm_hour
) + ":" +
4490 String::FormatIntWidth2(time_struct
.tm_min
) + ":" +
4491 String::FormatIntWidth2(time_struct
.tm_sec
) + "Z";
4494 static inline std::string
Indent(size_t width
) {
4495 return std::string(width
, ' ');
4498 void JsonUnitTestResultPrinter::OutputJsonKey(
4499 std::ostream
* stream
,
4500 const std::string
& element_name
,
4501 const std::string
& name
,
4502 const std::string
& value
,
4503 const std::string
& indent
,
4505 const std::vector
<std::string
>& allowed_names
=
4506 GetReservedOutputAttributesForElement(element_name
);
4508 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4509 allowed_names
.end())
4510 << "Key \"" << name
<< "\" is not allowed for value \"" << element_name
4513 *stream
<< indent
<< "\"" << name
<< "\": \"" << EscapeJson(value
) << "\"";
4518 void JsonUnitTestResultPrinter::OutputJsonKey(
4519 std::ostream
* stream
,
4520 const std::string
& element_name
,
4521 const std::string
& name
,
4523 const std::string
& indent
,
4525 const std::vector
<std::string
>& allowed_names
=
4526 GetReservedOutputAttributesForElement(element_name
);
4528 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4529 allowed_names
.end())
4530 << "Key \"" << name
<< "\" is not allowed for value \"" << element_name
4533 *stream
<< indent
<< "\"" << name
<< "\": " << StreamableToString(value
);
4538 // Prints a JSON representation of a TestInfo object.
4539 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream
* stream
,
4540 const char* test_suite_name
,
4541 const TestInfo
& test_info
) {
4542 const TestResult
& result
= *test_info
.result();
4543 const std::string kTestsuite
= "testcase";
4544 const std::string kIndent
= Indent(10);
4546 *stream
<< Indent(8) << "{\n";
4547 OutputJsonKey(stream
, kTestsuite
, "name", test_info
.name(), kIndent
);
4549 if (test_info
.value_param() != nullptr) {
4550 OutputJsonKey(stream
, kTestsuite
, "value_param", test_info
.value_param(),
4553 if (test_info
.type_param() != nullptr) {
4554 OutputJsonKey(stream
, kTestsuite
, "type_param", test_info
.type_param(),
4557 if (GTEST_FLAG(list_tests
)) {
4558 OutputJsonKey(stream
, kTestsuite
, "file", test_info
.file(), kIndent
);
4559 OutputJsonKey(stream
, kTestsuite
, "line", test_info
.line(), kIndent
, false);
4560 *stream
<< "\n" << Indent(8) << "}";
4564 OutputJsonKey(stream
, kTestsuite
, "status",
4565 test_info
.should_run() ? "RUN" : "NOTRUN", kIndent
);
4566 OutputJsonKey(stream
, kTestsuite
, "result",
4567 test_info
.should_run()
4568 ? (result
.Skipped() ? "SKIPPED" : "COMPLETED")
4571 OutputJsonKey(stream
, kTestsuite
, "timestamp",
4572 FormatEpochTimeInMillisAsRFC3339(result
.start_timestamp()),
4574 OutputJsonKey(stream
, kTestsuite
, "time",
4575 FormatTimeInMillisAsDuration(result
.elapsed_time()), kIndent
);
4576 OutputJsonKey(stream
, kTestsuite
, "classname", test_suite_name
, kIndent
,
4578 *stream
<< TestPropertiesAsJson(result
, kIndent
);
4581 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
4582 const TestPartResult
& part
= result
.GetTestPartResult(i
);
4583 if (part
.failed()) {
4585 if (++failures
== 1) {
4586 *stream
<< kIndent
<< "\"" << "failures" << "\": [\n";
4588 const std::string location
=
4589 internal::FormatCompilerIndependentFileLocation(part
.file_name(),
4590 part
.line_number());
4591 const std::string message
= EscapeJson(location
+ "\n" + part
.message());
4592 *stream
<< kIndent
<< " {\n"
4593 << kIndent
<< " \"failure\": \"" << message
<< "\",\n"
4594 << kIndent
<< " \"type\": \"\"\n"
4600 *stream
<< "\n" << kIndent
<< "]";
4601 *stream
<< "\n" << Indent(8) << "}";
4604 // Prints an JSON representation of a TestSuite object
4605 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4606 std::ostream
* stream
, const TestSuite
& test_suite
) {
4607 const std::string kTestsuite
= "testsuite";
4608 const std::string kIndent
= Indent(6);
4610 *stream
<< Indent(4) << "{\n";
4611 OutputJsonKey(stream
, kTestsuite
, "name", test_suite
.name(), kIndent
);
4612 OutputJsonKey(stream
, kTestsuite
, "tests", test_suite
.reportable_test_count(),
4614 if (!GTEST_FLAG(list_tests
)) {
4615 OutputJsonKey(stream
, kTestsuite
, "failures",
4616 test_suite
.failed_test_count(), kIndent
);
4617 OutputJsonKey(stream
, kTestsuite
, "disabled",
4618 test_suite
.reportable_disabled_test_count(), kIndent
);
4619 OutputJsonKey(stream
, kTestsuite
, "errors", 0, kIndent
);
4621 stream
, kTestsuite
, "timestamp",
4622 FormatEpochTimeInMillisAsRFC3339(test_suite
.start_timestamp()),
4624 OutputJsonKey(stream
, kTestsuite
, "time",
4625 FormatTimeInMillisAsDuration(test_suite
.elapsed_time()),
4627 *stream
<< TestPropertiesAsJson(test_suite
.ad_hoc_test_result(), kIndent
)
4631 *stream
<< kIndent
<< "\"" << kTestsuite
<< "\": [\n";
4634 for (int i
= 0; i
< test_suite
.total_test_count(); ++i
) {
4635 if (test_suite
.GetTestInfo(i
)->is_reportable()) {
4641 OutputJsonTestInfo(stream
, test_suite
.name(), *test_suite
.GetTestInfo(i
));
4644 *stream
<< "\n" << kIndent
<< "]\n" << Indent(4) << "}";
4647 // Prints a JSON summary of unit_test to output stream out.
4648 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream
* stream
,
4649 const UnitTest
& unit_test
) {
4650 const std::string kTestsuites
= "testsuites";
4651 const std::string kIndent
= Indent(2);
4654 OutputJsonKey(stream
, kTestsuites
, "tests", unit_test
.reportable_test_count(),
4656 OutputJsonKey(stream
, kTestsuites
, "failures", unit_test
.failed_test_count(),
4658 OutputJsonKey(stream
, kTestsuites
, "disabled",
4659 unit_test
.reportable_disabled_test_count(), kIndent
);
4660 OutputJsonKey(stream
, kTestsuites
, "errors", 0, kIndent
);
4661 if (GTEST_FLAG(shuffle
)) {
4662 OutputJsonKey(stream
, kTestsuites
, "random_seed", unit_test
.random_seed(),
4665 OutputJsonKey(stream
, kTestsuites
, "timestamp",
4666 FormatEpochTimeInMillisAsRFC3339(unit_test
.start_timestamp()),
4668 OutputJsonKey(stream
, kTestsuites
, "time",
4669 FormatTimeInMillisAsDuration(unit_test
.elapsed_time()), kIndent
,
4672 *stream
<< TestPropertiesAsJson(unit_test
.ad_hoc_test_result(), kIndent
)
4675 OutputJsonKey(stream
, kTestsuites
, "name", "AllTests", kIndent
);
4676 *stream
<< kIndent
<< "\"" << kTestsuites
<< "\": [\n";
4679 for (int i
= 0; i
< unit_test
.total_test_suite_count(); ++i
) {
4680 if (unit_test
.GetTestSuite(i
)->reportable_test_count() > 0) {
4686 PrintJsonTestSuite(stream
, *unit_test
.GetTestSuite(i
));
4690 *stream
<< "\n" << kIndent
<< "]\n" << "}\n";
4693 void JsonUnitTestResultPrinter::PrintJsonTestList(
4694 std::ostream
* stream
, const std::vector
<TestSuite
*>& test_suites
) {
4695 const std::string kTestsuites
= "testsuites";
4696 const std::string kIndent
= Indent(2);
4698 int total_tests
= 0;
4699 for (auto test_suite
: test_suites
) {
4700 total_tests
+= test_suite
->total_test_count();
4702 OutputJsonKey(stream
, kTestsuites
, "tests", total_tests
, kIndent
);
4704 OutputJsonKey(stream
, kTestsuites
, "name", "AllTests", kIndent
);
4705 *stream
<< kIndent
<< "\"" << kTestsuites
<< "\": [\n";
4707 for (size_t i
= 0; i
< test_suites
.size(); ++i
) {
4711 PrintJsonTestSuite(stream
, *test_suites
[i
]);
4718 // Produces a string representing the test properties in a result as
4719 // a JSON dictionary.
4720 std::string
JsonUnitTestResultPrinter::TestPropertiesAsJson(
4721 const TestResult
& result
, const std::string
& indent
) {
4723 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4724 const TestProperty
& property
= result
.GetTestProperty(i
);
4725 attributes
<< ",\n" << indent
<< "\"" << property
.key() << "\": "
4726 << "\"" << EscapeJson(property
.value()) << "\"";
4728 return attributes
.GetString();
4731 // End JsonUnitTestResultPrinter
4733 #if GTEST_CAN_STREAM_RESULTS_
4735 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4736 // replaces them by "%xx" where xx is their hexadecimal value. For
4737 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4738 // in both time and space -- important as the input str may contain an
4739 // arbitrarily long test failure message and stack trace.
4740 std::string
StreamingListener::UrlEncode(const char* str
) {
4742 result
.reserve(strlen(str
) + 1);
4743 for (char ch
= *str
; ch
!= '\0'; ch
= *++str
) {
4749 result
.append("%" + String::FormatByte(static_cast<unsigned char>(ch
)));
4752 result
.push_back(ch
);
4759 void StreamingListener::SocketWriter::MakeConnection() {
4760 GTEST_CHECK_(sockfd_
== -1)
4761 << "MakeConnection() can't be called when there is already a connection.";
4764 memset(&hints
, 0, sizeof(hints
));
4765 hints
.ai_family
= AF_UNSPEC
; // To allow both IPv4 and IPv6 addresses.
4766 hints
.ai_socktype
= SOCK_STREAM
;
4767 addrinfo
* servinfo
= nullptr;
4769 // Use the getaddrinfo() to get a linked list of IP addresses for
4770 // the given host name.
4771 const int error_num
= getaddrinfo(
4772 host_name_
.c_str(), port_num_
.c_str(), &hints
, &servinfo
);
4773 if (error_num
!= 0) {
4774 GTEST_LOG_(WARNING
) << "stream_result_to: getaddrinfo() failed: "
4775 << gai_strerror(error_num
);
4778 // Loop through all the results and connect to the first we can.
4779 for (addrinfo
* cur_addr
= servinfo
; sockfd_
== -1 && cur_addr
!= nullptr;
4780 cur_addr
= cur_addr
->ai_next
) {
4782 cur_addr
->ai_family
, cur_addr
->ai_socktype
, cur_addr
->ai_protocol
);
4783 if (sockfd_
!= -1) {
4784 // Connect the client socket to the server socket.
4785 if (connect(sockfd_
, cur_addr
->ai_addr
, cur_addr
->ai_addrlen
) == -1) {
4792 freeaddrinfo(servinfo
); // all done with this structure
4794 if (sockfd_
== -1) {
4795 GTEST_LOG_(WARNING
) << "stream_result_to: failed to connect to "
4796 << host_name_
<< ":" << port_num_
;
4800 // End of class Streaming Listener
4801 #endif // GTEST_CAN_STREAM_RESULTS__
4803 // class OsStackTraceGetter
4805 const char* const OsStackTraceGetterInterface::kElidedFramesMarker
=
4806 "... " GTEST_NAME_
" internal frames ...";
4808 std::string
OsStackTraceGetter::CurrentStackTrace(int max_depth
, int skip_count
)
4809 GTEST_LOCK_EXCLUDED_(mutex_
) {
4813 if (max_depth
<= 0) {
4817 max_depth
= std::min(max_depth
, kMaxStackTraceDepth
);
4819 std::vector
<void*> raw_stack(max_depth
);
4820 // Skips the frames requested by the caller, plus this function.
4821 const int raw_stack_size
=
4822 absl::GetStackTrace(&raw_stack
[0], max_depth
, skip_count
+ 1);
4824 void* caller_frame
= nullptr;
4826 MutexLock
lock(&mutex_
);
4827 caller_frame
= caller_frame_
;
4830 for (int i
= 0; i
< raw_stack_size
; ++i
) {
4831 if (raw_stack
[i
] == caller_frame
&&
4832 !GTEST_FLAG(show_internal_stack_frames
)) {
4833 // Add a marker to the trace and stop adding frames.
4834 absl::StrAppend(&result
, kElidedFramesMarker
, "\n");
4839 const char* symbol
= "(unknown)";
4840 if (absl::Symbolize(raw_stack
[i
], tmp
, sizeof(tmp
))) {
4845 snprintf(line
, sizeof(line
), " %p: %s\n", raw_stack
[i
], symbol
);
4851 #else // !GTEST_HAS_ABSL
4852 static_cast<void>(max_depth
);
4853 static_cast<void>(skip_count
);
4855 #endif // GTEST_HAS_ABSL
4858 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_
) {
4860 void* caller_frame
= nullptr;
4861 if (absl::GetStackTrace(&caller_frame
, 1, 3) <= 0) {
4862 caller_frame
= nullptr;
4865 MutexLock
lock(&mutex_
);
4866 caller_frame_
= caller_frame
;
4867 #endif // GTEST_HAS_ABSL
4870 // A helper class that creates the premature-exit file in its
4871 // constructor and deletes the file in its destructor.
4872 class ScopedPrematureExitFile
{
4874 explicit ScopedPrematureExitFile(const char* premature_exit_filepath
)
4875 : premature_exit_filepath_(premature_exit_filepath
?
4876 premature_exit_filepath
: "") {
4877 // If a path to the premature-exit file is specified...
4878 if (!premature_exit_filepath_
.empty()) {
4879 // create the file with a single "0" character in it. I/O
4880 // errors are ignored as there's nothing better we can do and we
4881 // don't want to fail the test because of this.
4882 FILE* pfile
= posix::FOpen(premature_exit_filepath
, "w");
4883 fwrite("0", 1, 1, pfile
);
4888 ~ScopedPrematureExitFile() {
4889 #if !defined GTEST_OS_ESP8266
4890 if (!premature_exit_filepath_
.empty()) {
4891 int retval
= remove(premature_exit_filepath_
.c_str());
4893 GTEST_LOG_(ERROR
) << "Failed to remove premature exit filepath \""
4894 << premature_exit_filepath_
<< "\" with error "
4902 const std::string premature_exit_filepath_
;
4904 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile
);
4907 } // namespace internal
4909 // class TestEventListeners
4911 TestEventListeners::TestEventListeners()
4912 : repeater_(new internal::TestEventRepeater()),
4913 default_result_printer_(nullptr),
4914 default_xml_generator_(nullptr) {}
4916 TestEventListeners::~TestEventListeners() { delete repeater_
; }
4918 // Returns the standard listener responsible for the default console
4919 // output. Can be removed from the listeners list to shut down default
4920 // console output. Note that removing this object from the listener list
4921 // with Release transfers its ownership to the user.
4922 void TestEventListeners::Append(TestEventListener
* listener
) {
4923 repeater_
->Append(listener
);
4926 // Removes the given event listener from the list and returns it. It then
4927 // becomes the caller's responsibility to delete the listener. Returns
4928 // NULL if the listener is not found in the list.
4929 TestEventListener
* TestEventListeners::Release(TestEventListener
* listener
) {
4930 if (listener
== default_result_printer_
)
4931 default_result_printer_
= nullptr;
4932 else if (listener
== default_xml_generator_
)
4933 default_xml_generator_
= nullptr;
4934 return repeater_
->Release(listener
);
4937 // Returns repeater that broadcasts the TestEventListener events to all
4939 TestEventListener
* TestEventListeners::repeater() { return repeater_
; }
4941 // Sets the default_result_printer attribute to the provided listener.
4942 // The listener is also added to the listener list and previous
4943 // default_result_printer is removed from it and deleted. The listener can
4944 // also be NULL in which case it will not be added to the list. Does
4945 // nothing if the previous and the current listener objects are the same.
4946 void TestEventListeners::SetDefaultResultPrinter(TestEventListener
* listener
) {
4947 if (default_result_printer_
!= listener
) {
4948 // It is an error to pass this method a listener that is already in the
4950 delete Release(default_result_printer_
);
4951 default_result_printer_
= listener
;
4952 if (listener
!= nullptr) Append(listener
);
4956 // Sets the default_xml_generator attribute to the provided listener. The
4957 // listener is also added to the listener list and previous
4958 // default_xml_generator is removed from it and deleted. The listener can
4959 // also be NULL in which case it will not be added to the list. Does
4960 // nothing if the previous and the current listener objects are the same.
4961 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener
* listener
) {
4962 if (default_xml_generator_
!= listener
) {
4963 // It is an error to pass this method a listener that is already in the
4965 delete Release(default_xml_generator_
);
4966 default_xml_generator_
= listener
;
4967 if (listener
!= nullptr) Append(listener
);
4971 // Controls whether events will be forwarded by the repeater to the
4972 // listeners in the list.
4973 bool TestEventListeners::EventForwardingEnabled() const {
4974 return repeater_
->forwarding_enabled();
4977 void TestEventListeners::SuppressEventForwarding() {
4978 repeater_
->set_forwarding_enabled(false);
4983 // Gets the singleton UnitTest object. The first time this method is
4984 // called, a UnitTest object is constructed and returned. Consecutive
4985 // calls will return the same object.
4987 // We don't protect this under mutex_ as a user is not supposed to
4988 // call this before main() starts, from which point on the return
4989 // value will never change.
4990 UnitTest
* UnitTest::GetInstance() {
4991 // CodeGear C++Builder insists on a public destructor for the
4992 // default implementation. Use this implementation to keep good OO
4993 // design with private destructor.
4995 #if defined(__BORLANDC__)
4996 static UnitTest
* const instance
= new UnitTest
;
4999 static UnitTest instance
;
5001 #endif // defined(__BORLANDC__)
5004 // Gets the number of successful test suites.
5005 int UnitTest::successful_test_suite_count() const {
5006 return impl()->successful_test_suite_count();
5009 // Gets the number of failed test suites.
5010 int UnitTest::failed_test_suite_count() const {
5011 return impl()->failed_test_suite_count();
5014 // Gets the number of all test suites.
5015 int UnitTest::total_test_suite_count() const {
5016 return impl()->total_test_suite_count();
5019 // Gets the number of all test suites that contain at least one test
5021 int UnitTest::test_suite_to_run_count() const {
5022 return impl()->test_suite_to_run_count();
5025 // Legacy API is deprecated but still available
5026 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5027 int UnitTest::successful_test_case_count() const {
5028 return impl()->successful_test_suite_count();
5030 int UnitTest::failed_test_case_count() const {
5031 return impl()->failed_test_suite_count();
5033 int UnitTest::total_test_case_count() const {
5034 return impl()->total_test_suite_count();
5036 int UnitTest::test_case_to_run_count() const {
5037 return impl()->test_suite_to_run_count();
5039 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5041 // Gets the number of successful tests.
5042 int UnitTest::successful_test_count() const {
5043 return impl()->successful_test_count();
5046 // Gets the number of skipped tests.
5047 int UnitTest::skipped_test_count() const {
5048 return impl()->skipped_test_count();
5051 // Gets the number of failed tests.
5052 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5054 // Gets the number of disabled tests that will be reported in the XML report.
5055 int UnitTest::reportable_disabled_test_count() const {
5056 return impl()->reportable_disabled_test_count();
5059 // Gets the number of disabled tests.
5060 int UnitTest::disabled_test_count() const {
5061 return impl()->disabled_test_count();
5064 // Gets the number of tests to be printed in the XML report.
5065 int UnitTest::reportable_test_count() const {
5066 return impl()->reportable_test_count();
5069 // Gets the number of all tests.
5070 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5072 // Gets the number of tests that should run.
5073 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5075 // Gets the time of the test program start, in ms from the start of the
5077 internal::TimeInMillis
UnitTest::start_timestamp() const {
5078 return impl()->start_timestamp();
5081 // Gets the elapsed time, in milliseconds.
5082 internal::TimeInMillis
UnitTest::elapsed_time() const {
5083 return impl()->elapsed_time();
5086 // Returns true if and only if the unit test passed (i.e. all test suites
5088 bool UnitTest::Passed() const { return impl()->Passed(); }
5090 // Returns true if and only if the unit test failed (i.e. some test suite
5091 // failed or something outside of all tests failed).
5092 bool UnitTest::Failed() const { return impl()->Failed(); }
5094 // Gets the i-th test suite among all the test suites. i can range from 0 to
5095 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
5096 const TestSuite
* UnitTest::GetTestSuite(int i
) const {
5097 return impl()->GetTestSuite(i
);
5100 // Legacy API is deprecated but still available
5101 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5102 const TestCase
* UnitTest::GetTestCase(int i
) const {
5103 return impl()->GetTestCase(i
);
5105 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5107 // Returns the TestResult containing information on test failures and
5108 // properties logged outside of individual test suites.
5109 const TestResult
& UnitTest::ad_hoc_test_result() const {
5110 return *impl()->ad_hoc_test_result();
5113 // Gets the i-th test suite among all the test suites. i can range from 0 to
5114 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
5115 TestSuite
* UnitTest::GetMutableTestSuite(int i
) {
5116 return impl()->GetMutableSuiteCase(i
);
5119 // Returns the list of event listeners that can be used to track events
5120 // inside Google Test.
5121 TestEventListeners
& UnitTest::listeners() {
5122 return *impl()->listeners();
5125 // Registers and returns a global test environment. When a test
5126 // program is run, all global test environments will be set-up in the
5127 // order they were registered. After all tests in the program have
5128 // finished, all global test environments will be torn-down in the
5129 // *reverse* order they were registered.
5131 // The UnitTest object takes ownership of the given environment.
5133 // We don't protect this under mutex_, as we only support calling it
5134 // from the main thread.
5135 Environment
* UnitTest::AddEnvironment(Environment
* env
) {
5136 if (env
== nullptr) {
5140 impl_
->environments().push_back(env
);
5144 // Adds a TestPartResult to the current TestResult object. All Google Test
5145 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5146 // this to report their results. The user code should use the
5147 // assertion macros instead of calling this directly.
5148 void UnitTest::AddTestPartResult(
5149 TestPartResult::Type result_type
,
5150 const char* file_name
,
5152 const std::string
& message
,
5153 const std::string
& os_stack_trace
) GTEST_LOCK_EXCLUDED_(mutex_
) {
5157 internal::MutexLock
lock(&mutex_
);
5158 if (impl_
->gtest_trace_stack().size() > 0) {
5159 msg
<< "\n" << GTEST_NAME_
<< " trace:";
5161 for (size_t i
= impl_
->gtest_trace_stack().size(); i
> 0; --i
) {
5162 const internal::TraceInfo
& trace
= impl_
->gtest_trace_stack()[i
- 1];
5163 msg
<< "\n" << internal::FormatFileLocation(trace
.file
, trace
.line
)
5164 << " " << trace
.message
;
5168 if (os_stack_trace
.c_str() != nullptr && !os_stack_trace
.empty()) {
5169 msg
<< internal::kStackTraceMarker
<< os_stack_trace
;
5172 const TestPartResult result
= TestPartResult(
5173 result_type
, file_name
, line_number
, msg
.GetString().c_str());
5174 impl_
->GetTestPartResultReporterForCurrentThread()->
5175 ReportTestPartResult(result
);
5177 if (result_type
!= TestPartResult::kSuccess
&&
5178 result_type
!= TestPartResult::kSkip
) {
5179 // gtest_break_on_failure takes precedence over
5180 // gtest_throw_on_failure. This allows a user to set the latter
5181 // in the code (perhaps in order to use Google Test assertions
5182 // with another testing framework) and specify the former on the
5183 // command line for debugging.
5184 if (GTEST_FLAG(break_on_failure
)) {
5185 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5186 // Using DebugBreak on Windows allows gtest to still break into a debugger
5187 // when a failure happens and both the --gtest_break_on_failure and
5188 // the --gtest_catch_exceptions flags are specified.
5190 #elif (!defined(__native_client__)) && \
5191 ((defined(__clang__) || defined(__GNUC__)) && \
5192 (defined(__x86_64__) || defined(__i386__)))
5193 // with clang/gcc we can achieve the same effect on x86 by invoking int3
5196 // Dereference nullptr through a volatile pointer to prevent the compiler
5197 // from removing. We use this rather than abort() or __builtin_trap() for
5198 // portability: some debuggers don't correctly trap abort().
5199 *static_cast<volatile int*>(nullptr) = 1;
5200 #endif // GTEST_OS_WINDOWS
5201 } else if (GTEST_FLAG(throw_on_failure
)) {
5202 #if GTEST_HAS_EXCEPTIONS
5203 throw internal::GoogleTestFailureException(result
);
5205 // We cannot call abort() as it generates a pop-up in debug mode
5206 // that cannot be suppressed in VC 7.1 or below.
5213 // Adds a TestProperty to the current TestResult object when invoked from
5214 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
5215 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
5216 // when invoked elsewhere. If the result already contains a property with
5217 // the same key, the value will be updated.
5218 void UnitTest::RecordProperty(const std::string
& key
,
5219 const std::string
& value
) {
5220 impl_
->RecordProperty(TestProperty(key
, value
));
5223 // Runs all tests in this UnitTest object and prints the result.
5224 // Returns 0 if successful, or 1 otherwise.
5226 // We don't protect this under mutex_, as we only support calling it
5227 // from the main thread.
5228 int UnitTest::Run() {
5229 const bool in_death_test_child_process
=
5230 internal::GTEST_FLAG(internal_run_death_test
).length() > 0;
5232 // Google Test implements this protocol for catching that a test
5233 // program exits before returning control to Google Test:
5235 // 1. Upon start, Google Test creates a file whose absolute path
5236 // is specified by the environment variable
5237 // TEST_PREMATURE_EXIT_FILE.
5238 // 2. When Google Test has finished its work, it deletes the file.
5240 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5241 // running a Google-Test-based test program and check the existence
5242 // of the file at the end of the test execution to see if it has
5243 // exited prematurely.
5245 // If we are in the child process of a death test, don't
5246 // create/delete the premature exit file, as doing so is unnecessary
5247 // and will confuse the parent process. Otherwise, create/delete
5248 // the file upon entering/leaving this function. If the program
5249 // somehow exits before this function has a chance to return, the
5250 // premature-exit file will be left undeleted, causing a test runner
5251 // that understands the premature-exit-file protocol to report the
5252 // test as having failed.
5253 const internal::ScopedPrematureExitFile
premature_exit_file(
5254 in_death_test_child_process
5256 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5258 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5259 // used for the duration of the program.
5260 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions
));
5262 #if GTEST_OS_WINDOWS
5263 // Either the user wants Google Test to catch exceptions thrown by the
5264 // tests or this is executing in the context of death test child
5265 // process. In either case the user does not want to see pop-up dialogs
5266 // about crashes - they are expected.
5267 if (impl()->catch_exceptions() || in_death_test_child_process
) {
5268 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5269 // SetErrorMode doesn't exist on CE.
5270 SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOALIGNMENTFAULTEXCEPT
|
5271 SEM_NOGPFAULTERRORBOX
| SEM_NOOPENFILEERRORBOX
);
5272 # endif // !GTEST_OS_WINDOWS_MOBILE
5274 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5275 // Death test children can be terminated with _abort(). On Windows,
5276 // _abort() can show a dialog with a warning message. This forces the
5277 // abort message to go to stderr instead.
5278 _set_error_mode(_OUT_TO_STDERR
);
5281 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
5282 // In the debug version, Visual Studio pops up a separate dialog
5283 // offering a choice to debug the aborted program. We need to suppress
5284 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5285 // executed. Google Test will notify the user of any unexpected
5286 // failure via stderr.
5287 if (!GTEST_FLAG(break_on_failure
))
5288 _set_abort_behavior(
5289 0x0, // Clear the following flags:
5290 _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
); // pop-up window, core dump.
5292 // In debug mode, the Windows CRT can crash with an assertion over invalid
5293 // input (e.g. passing an invalid file descriptor). The default handling
5294 // for these assertions is to pop up a dialog and wait for user input.
5295 // Instead ask the CRT to dump such assertions to stderr non-interactively.
5296 if (!IsDebuggerPresent()) {
5297 (void)_CrtSetReportMode(_CRT_ASSERT
,
5298 _CRTDBG_MODE_FILE
| _CRTDBG_MODE_DEBUG
);
5299 (void)_CrtSetReportFile(_CRT_ASSERT
, _CRTDBG_FILE_STDERR
);
5303 #endif // GTEST_OS_WINDOWS
5305 return internal::HandleExceptionsInMethodIfSupported(
5307 &internal::UnitTestImpl::RunAllTests
,
5308 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5311 // Returns the working directory when the first TEST() or TEST_F() was
5313 const char* UnitTest::original_working_dir() const {
5314 return impl_
->original_working_dir_
.c_str();
5317 // Returns the TestSuite object for the test that's currently running,
5318 // or NULL if no test is running.
5319 const TestSuite
* UnitTest::current_test_suite() const
5320 GTEST_LOCK_EXCLUDED_(mutex_
) {
5321 internal::MutexLock
lock(&mutex_
);
5322 return impl_
->current_test_suite();
5325 // Legacy API is still available but deprecated
5326 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5327 const TestCase
* UnitTest::current_test_case() const
5328 GTEST_LOCK_EXCLUDED_(mutex_
) {
5329 internal::MutexLock
lock(&mutex_
);
5330 return impl_
->current_test_suite();
5334 // Returns the TestInfo object for the test that's currently running,
5335 // or NULL if no test is running.
5336 const TestInfo
* UnitTest::current_test_info() const
5337 GTEST_LOCK_EXCLUDED_(mutex_
) {
5338 internal::MutexLock
lock(&mutex_
);
5339 return impl_
->current_test_info();
5342 // Returns the random seed used at the start of the current test run.
5343 int UnitTest::random_seed() const { return impl_
->random_seed(); }
5345 // Returns ParameterizedTestSuiteRegistry object used to keep track of
5346 // value-parameterized tests and instantiate and register them.
5347 internal::ParameterizedTestSuiteRegistry
&
5348 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_
) {
5349 return impl_
->parameterized_test_registry();
5352 // Creates an empty UnitTest.
5353 UnitTest::UnitTest() {
5354 impl_
= new internal::UnitTestImpl(this);
5357 // Destructor of UnitTest.
5358 UnitTest::~UnitTest() {
5362 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5363 // Google Test trace stack.
5364 void UnitTest::PushGTestTrace(const internal::TraceInfo
& trace
)
5365 GTEST_LOCK_EXCLUDED_(mutex_
) {
5366 internal::MutexLock
lock(&mutex_
);
5367 impl_
->gtest_trace_stack().push_back(trace
);
5370 // Pops a trace from the per-thread Google Test trace stack.
5371 void UnitTest::PopGTestTrace()
5372 GTEST_LOCK_EXCLUDED_(mutex_
) {
5373 internal::MutexLock
lock(&mutex_
);
5374 impl_
->gtest_trace_stack().pop_back();
5377 namespace internal
{
5379 UnitTestImpl::UnitTestImpl(UnitTest
* parent
)
5381 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5382 default_global_test_part_result_reporter_(this),
5383 default_per_thread_test_part_result_reporter_(this),
5384 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
5385 &default_global_test_part_result_reporter_
),
5386 per_thread_test_part_result_reporter_(
5387 &default_per_thread_test_part_result_reporter_
),
5388 parameterized_test_registry_(),
5389 parameterized_tests_registered_(false),
5390 last_death_test_suite_(-1),
5391 current_test_suite_(nullptr),
5392 current_test_info_(nullptr),
5393 ad_hoc_test_result_(),
5394 os_stack_trace_getter_(nullptr),
5395 post_flag_parse_init_performed_(false),
5396 random_seed_(0), // Will be overridden by the flag before first use.
5397 random_(0), // Will be reseeded before first use.
5398 start_timestamp_(0),
5400 #if GTEST_HAS_DEATH_TEST
5401 death_test_factory_(new DefaultDeathTestFactory
),
5403 // Will be overridden by the flag before first use.
5404 catch_exceptions_(false) {
5405 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter
);
5408 UnitTestImpl::~UnitTestImpl() {
5409 // Deletes every TestSuite.
5410 ForEach(test_suites_
, internal::Delete
<TestSuite
>);
5412 // Deletes every Environment.
5413 ForEach(environments_
, internal::Delete
<Environment
>);
5415 delete os_stack_trace_getter_
;
5418 // Adds a TestProperty to the current TestResult object when invoked in a
5419 // context of a test, to current test suite's ad_hoc_test_result when invoke
5420 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
5421 // otherwise. If the result already contains a property with the same key,
5422 // the value will be updated.
5423 void UnitTestImpl::RecordProperty(const TestProperty
& test_property
) {
5424 std::string xml_element
;
5425 TestResult
* test_result
; // TestResult appropriate for property recording.
5427 if (current_test_info_
!= nullptr) {
5428 xml_element
= "testcase";
5429 test_result
= &(current_test_info_
->result_
);
5430 } else if (current_test_suite_
!= nullptr) {
5431 xml_element
= "testsuite";
5432 test_result
= &(current_test_suite_
->ad_hoc_test_result_
);
5434 xml_element
= "testsuites";
5435 test_result
= &ad_hoc_test_result_
;
5437 test_result
->RecordProperty(xml_element
, test_property
);
5440 #if GTEST_HAS_DEATH_TEST
5441 // Disables event forwarding if the control is currently in a death test
5442 // subprocess. Must not be called before InitGoogleTest.
5443 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5444 if (internal_run_death_test_flag_
.get() != nullptr)
5445 listeners()->SuppressEventForwarding();
5447 #endif // GTEST_HAS_DEATH_TEST
5449 // Initializes event listeners performing XML output as specified by
5450 // UnitTestOptions. Must not be called before InitGoogleTest.
5451 void UnitTestImpl::ConfigureXmlOutput() {
5452 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5453 if (output_format
== "xml") {
5454 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5455 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5456 } else if (output_format
== "json") {
5457 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
5458 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5459 } else if (output_format
!= "") {
5460 GTEST_LOG_(WARNING
) << "WARNING: unrecognized output format \""
5461 << output_format
<< "\" ignored.";
5465 #if GTEST_CAN_STREAM_RESULTS_
5466 // Initializes event listeners for streaming test results in string form.
5467 // Must not be called before InitGoogleTest.
5468 void UnitTestImpl::ConfigureStreamingOutput() {
5469 const std::string
& target
= GTEST_FLAG(stream_result_to
);
5470 if (!target
.empty()) {
5471 const size_t pos
= target
.find(':');
5472 if (pos
!= std::string::npos
) {
5473 listeners()->Append(new StreamingListener(target
.substr(0, pos
),
5474 target
.substr(pos
+1)));
5476 GTEST_LOG_(WARNING
) << "unrecognized streaming target \"" << target
5481 #endif // GTEST_CAN_STREAM_RESULTS_
5483 // Performs initialization dependent upon flag values obtained in
5484 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5485 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5486 // this function is also called from RunAllTests. Since this function can be
5487 // called more than once, it has to be idempotent.
5488 void UnitTestImpl::PostFlagParsingInit() {
5489 // Ensures that this function does not execute more than once.
5490 if (!post_flag_parse_init_performed_
) {
5491 post_flag_parse_init_performed_
= true;
5493 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5494 // Register to send notifications about key process state changes.
5495 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5496 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5498 #if GTEST_HAS_DEATH_TEST
5499 InitDeathTestSubprocessControlInfo();
5500 SuppressTestEventsIfInSubprocess();
5501 #endif // GTEST_HAS_DEATH_TEST
5503 // Registers parameterized tests. This makes parameterized tests
5504 // available to the UnitTest reflection API without running
5506 RegisterParameterizedTests();
5508 // Configures listeners for XML output. This makes it possible for users
5509 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5510 ConfigureXmlOutput();
5512 if (GTEST_FLAG(brief
)) {
5513 listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter
);
5516 #if GTEST_CAN_STREAM_RESULTS_
5517 // Configures listeners for streaming test results to the specified server.
5518 ConfigureStreamingOutput();
5519 #endif // GTEST_CAN_STREAM_RESULTS_
5522 if (GTEST_FLAG(install_failure_signal_handler
)) {
5523 absl::FailureSignalHandlerOptions options
;
5524 absl::InstallFailureSignalHandler(options
);
5526 #endif // GTEST_HAS_ABSL
5530 // A predicate that checks the name of a TestSuite against a known
5533 // This is used for implementation of the UnitTest class only. We put
5534 // it in the anonymous namespace to prevent polluting the outer
5537 // TestSuiteNameIs is copyable.
5538 class TestSuiteNameIs
{
5541 explicit TestSuiteNameIs(const std::string
& name
) : name_(name
) {}
5543 // Returns true if and only if the name of test_suite matches name_.
5544 bool operator()(const TestSuite
* test_suite
) const {
5545 return test_suite
!= nullptr &&
5546 strcmp(test_suite
->name(), name_
.c_str()) == 0;
5553 // Finds and returns a TestSuite with the given name. If one doesn't
5554 // exist, creates one and returns it. It's the CALLER'S
5555 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5556 // TESTS ARE NOT SHUFFLED.
5560 // test_suite_name: name of the test suite
5561 // type_param: the name of the test suite's type parameter, or NULL if
5562 // this is not a typed or a type-parameterized test suite.
5563 // set_up_tc: pointer to the function that sets up the test suite
5564 // tear_down_tc: pointer to the function that tears down the test suite
5565 TestSuite
* UnitTestImpl::GetTestSuite(
5566 const char* test_suite_name
, const char* type_param
,
5567 internal::SetUpTestSuiteFunc set_up_tc
,
5568 internal::TearDownTestSuiteFunc tear_down_tc
) {
5569 // Can we find a TestSuite with the given name?
5570 const auto test_suite
=
5571 std::find_if(test_suites_
.rbegin(), test_suites_
.rend(),
5572 TestSuiteNameIs(test_suite_name
));
5574 if (test_suite
!= test_suites_
.rend()) return *test_suite
;
5576 // No. Let's create one.
5577 auto* const new_test_suite
=
5578 new TestSuite(test_suite_name
, type_param
, set_up_tc
, tear_down_tc
);
5580 // Is this a death test suite?
5581 if (internal::UnitTestOptions::MatchesFilter(test_suite_name
,
5582 kDeathTestSuiteFilter
)) {
5583 // Yes. Inserts the test suite after the last death test suite
5584 // defined so far. This only works when the test suites haven't
5585 // been shuffled. Otherwise we may end up running a death test
5586 // after a non-death test.
5587 ++last_death_test_suite_
;
5588 test_suites_
.insert(test_suites_
.begin() + last_death_test_suite_
,
5591 // No. Appends to the end of the list.
5592 test_suites_
.push_back(new_test_suite
);
5595 test_suite_indices_
.push_back(static_cast<int>(test_suite_indices_
.size()));
5596 return new_test_suite
;
5599 // Helpers for setting up / tearing down the given environment. They
5600 // are for use in the ForEach() function.
5601 static void SetUpEnvironment(Environment
* env
) { env
->SetUp(); }
5602 static void TearDownEnvironment(Environment
* env
) { env
->TearDown(); }
5604 // Runs all tests in this UnitTest object, prints the result, and
5605 // returns true if all tests are successful. If any exception is
5606 // thrown during a test, the test is considered to be failed, but the
5607 // rest of the tests will still be run.
5609 // When parameterized tests are enabled, it expands and registers
5610 // parameterized tests first in RegisterParameterizedTests().
5611 // All other functions called from RunAllTests() may safely assume that
5612 // parameterized tests are ready to be counted and run.
5613 bool UnitTestImpl::RunAllTests() {
5614 // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
5616 const bool gtest_is_initialized_before_run_all_tests
= GTestIsInitialized();
5618 // Do not run any test if the --help flag was specified.
5622 // Repeats the call to the post-flag parsing initialization in case the
5623 // user didn't call InitGoogleTest.
5624 PostFlagParsingInit();
5626 // Even if sharding is not on, test runners may want to use the
5627 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5629 internal::WriteToShardStatusFileIfNeeded();
5631 // True if and only if we are in a subprocess for running a thread-safe-style
5633 bool in_subprocess_for_death_test
= false;
5635 #if GTEST_HAS_DEATH_TEST
5636 in_subprocess_for_death_test
=
5637 (internal_run_death_test_flag_
.get() != nullptr);
5638 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5639 if (in_subprocess_for_death_test
) {
5640 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5642 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5643 #endif // GTEST_HAS_DEATH_TEST
5645 const bool should_shard
= ShouldShard(kTestTotalShards
, kTestShardIndex
,
5646 in_subprocess_for_death_test
);
5648 // Compares the full test names with the filter to decide which
5650 const bool has_tests_to_run
= FilterTests(should_shard
5651 ? HONOR_SHARDING_PROTOCOL
5652 : IGNORE_SHARDING_PROTOCOL
) > 0;
5654 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5655 if (GTEST_FLAG(list_tests
)) {
5656 // This must be called *after* FilterTests() has been called.
5657 ListTestsMatchingFilter();
5661 random_seed_
= GTEST_FLAG(shuffle
) ?
5662 GetRandomSeedFromFlag(GTEST_FLAG(random_seed
)) : 0;
5664 // True if and only if at least one test has failed.
5665 bool failed
= false;
5667 TestEventListener
* repeater
= listeners()->repeater();
5669 start_timestamp_
= GetTimeInMillis();
5670 repeater
->OnTestProgramStart(*parent_
);
5672 // How many times to repeat the tests? We don't want to repeat them
5673 // when we are inside the subprocess of a death test.
5674 const int repeat
= in_subprocess_for_death_test
? 1 : GTEST_FLAG(repeat
);
5675 // Repeats forever if the repeat count is negative.
5676 const bool gtest_repeat_forever
= repeat
< 0;
5677 for (int i
= 0; gtest_repeat_forever
|| i
!= repeat
; i
++) {
5678 // We want to preserve failures generated by ad-hoc test
5679 // assertions executed before RUN_ALL_TESTS().
5680 ClearNonAdHocTestResult();
5682 const TimeInMillis start
= GetTimeInMillis();
5684 // Shuffles test suites and tests if requested.
5685 if (has_tests_to_run
&& GTEST_FLAG(shuffle
)) {
5686 random()->Reseed(static_cast<uint32_t>(random_seed_
));
5687 // This should be done before calling OnTestIterationStart(),
5688 // such that a test event listener can see the actual test order
5693 // Tells the unit test event listeners that the tests are about to start.
5694 repeater
->OnTestIterationStart(*parent_
, i
);
5696 // Runs each test suite if there is at least one test to run.
5697 if (has_tests_to_run
) {
5698 // Sets up all environments beforehand.
5699 repeater
->OnEnvironmentsSetUpStart(*parent_
);
5700 ForEach(environments_
, SetUpEnvironment
);
5701 repeater
->OnEnvironmentsSetUpEnd(*parent_
);
5703 // Runs the tests only if there was no fatal failure or skip triggered
5704 // during global set-up.
5705 if (Test::IsSkipped()) {
5706 // Emit diagnostics when global set-up calls skip, as it will not be
5707 // emitted by default.
5708 TestResult
& test_result
=
5709 *internal::GetUnitTestImpl()->current_test_result();
5710 for (int j
= 0; j
< test_result
.total_part_count(); ++j
) {
5711 const TestPartResult
& test_part_result
=
5712 test_result
.GetTestPartResult(j
);
5713 if (test_part_result
.type() == TestPartResult::kSkip
) {
5714 const std::string
& result
= test_part_result
.message();
5715 printf("%s\n", result
.c_str());
5719 } else if (!Test::HasFatalFailure()) {
5720 for (int test_index
= 0; test_index
< total_test_suite_count();
5722 GetMutableSuiteCase(test_index
)->Run();
5723 if (GTEST_FLAG(fail_fast
) &&
5724 GetMutableSuiteCase(test_index
)->Failed()) {
5725 for (int j
= test_index
+ 1; j
< total_test_suite_count(); j
++) {
5726 GetMutableSuiteCase(j
)->Skip();
5733 // Tears down all environments in reverse order afterwards.
5734 repeater
->OnEnvironmentsTearDownStart(*parent_
);
5735 std::for_each(environments_
.rbegin(), environments_
.rend(),
5736 TearDownEnvironment
);
5737 repeater
->OnEnvironmentsTearDownEnd(*parent_
);
5740 elapsed_time_
= GetTimeInMillis() - start
;
5742 // Tells the unit test event listener that the tests have just finished.
5743 repeater
->OnTestIterationEnd(*parent_
, i
);
5745 // Gets the result and clears it.
5750 // Restores the original test order after the iteration. This
5751 // allows the user to quickly repro a failure that happens in the
5752 // N-th iteration without repeating the first (N - 1) iterations.
5753 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5754 // case the user somehow changes the value of the flag somewhere
5755 // (it's always safe to unshuffle the tests).
5758 if (GTEST_FLAG(shuffle
)) {
5759 // Picks a new random seed for each iteration.
5760 random_seed_
= GetNextRandomSeed(random_seed_
);
5764 repeater
->OnTestProgramEnd(*parent_
);
5766 if (!gtest_is_initialized_before_run_all_tests
) {
5769 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5770 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5771 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5772 " will start to enforce the valid usage. "
5773 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
5774 #if GTEST_FOR_GOOGLE_
5775 ColoredPrintf(GTestColor::kRed
,
5776 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5777 #endif // GTEST_FOR_GOOGLE_
5783 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5784 // if the variable is present. If a file already exists at this location, this
5785 // function will write over it. If the variable is present, but the file cannot
5786 // be created, prints an error and exits.
5787 void WriteToShardStatusFileIfNeeded() {
5788 const char* const test_shard_file
= posix::GetEnv(kTestShardStatusFile
);
5789 if (test_shard_file
!= nullptr) {
5790 FILE* const file
= posix::FOpen(test_shard_file
, "w");
5791 if (file
== nullptr) {
5792 ColoredPrintf(GTestColor::kRed
,
5793 "Could not write to the test shard status file \"%s\" "
5794 "specified by the %s environment variable.\n",
5795 test_shard_file
, kTestShardStatusFile
);
5803 // Checks whether sharding is enabled by examining the relevant
5804 // environment variable values. If the variables are present,
5805 // but inconsistent (i.e., shard_index >= total_shards), prints
5806 // an error and exits. If in_subprocess_for_death_test, sharding is
5807 // disabled because it must only be applied to the original test
5808 // process. Otherwise, we could filter out death tests we intended to execute.
5809 bool ShouldShard(const char* total_shards_env
,
5810 const char* shard_index_env
,
5811 bool in_subprocess_for_death_test
) {
5812 if (in_subprocess_for_death_test
) {
5816 const int32_t total_shards
= Int32FromEnvOrDie(total_shards_env
, -1);
5817 const int32_t shard_index
= Int32FromEnvOrDie(shard_index_env
, -1);
5819 if (total_shards
== -1 && shard_index
== -1) {
5821 } else if (total_shards
== -1 && shard_index
!= -1) {
5822 const Message msg
= Message()
5823 << "Invalid environment variables: you have "
5824 << kTestShardIndex
<< " = " << shard_index
5825 << ", but have left " << kTestTotalShards
<< " unset.\n";
5826 ColoredPrintf(GTestColor::kRed
, "%s", msg
.GetString().c_str());
5829 } else if (total_shards
!= -1 && shard_index
== -1) {
5830 const Message msg
= Message()
5831 << "Invalid environment variables: you have "
5832 << kTestTotalShards
<< " = " << total_shards
5833 << ", but have left " << kTestShardIndex
<< " unset.\n";
5834 ColoredPrintf(GTestColor::kRed
, "%s", msg
.GetString().c_str());
5837 } else if (shard_index
< 0 || shard_index
>= total_shards
) {
5838 const Message msg
= Message()
5839 << "Invalid environment variables: we require 0 <= "
5840 << kTestShardIndex
<< " < " << kTestTotalShards
5841 << ", but you have " << kTestShardIndex
<< "=" << shard_index
5842 << ", " << kTestTotalShards
<< "=" << total_shards
<< ".\n";
5843 ColoredPrintf(GTestColor::kRed
, "%s", msg
.GetString().c_str());
5848 return total_shards
> 1;
5851 // Parses the environment variable var as an Int32. If it is unset,
5852 // returns default_val. If it is not an Int32, prints an error
5854 int32_t Int32FromEnvOrDie(const char* var
, int32_t default_val
) {
5855 const char* str_val
= posix::GetEnv(var
);
5856 if (str_val
== nullptr) {
5861 if (!ParseInt32(Message() << "The value of environment variable " << var
,
5862 str_val
, &result
)) {
5868 // Given the total number of shards, the shard index, and the test id,
5869 // returns true if and only if the test should be run on this shard. The test id
5870 // is some arbitrary but unique non-negative integer assigned to each test
5871 // method. Assumes that 0 <= shard_index < total_shards.
5872 bool ShouldRunTestOnShard(int total_shards
, int shard_index
, int test_id
) {
5873 return (test_id
% total_shards
) == shard_index
;
5876 // Compares the name of each test with the user-specified filter to
5877 // decide whether the test should be run, then records the result in
5878 // each TestSuite and TestInfo object.
5879 // If shard_tests == true, further filters tests based on sharding
5880 // variables in the environment - see
5881 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
5882 // . Returns the number of tests that should run.
5883 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests
) {
5884 const int32_t total_shards
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5885 Int32FromEnvOrDie(kTestTotalShards
, -1) : -1;
5886 const int32_t shard_index
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5887 Int32FromEnvOrDie(kTestShardIndex
, -1) : -1;
5889 // num_runnable_tests are the number of tests that will
5890 // run across all shards (i.e., match filter and are not disabled).
5891 // num_selected_tests are the number of tests to be run on
5893 int num_runnable_tests
= 0;
5894 int num_selected_tests
= 0;
5895 for (auto* test_suite
: test_suites_
) {
5896 const std::string
& test_suite_name
= test_suite
->name();
5897 test_suite
->set_should_run(false);
5899 for (size_t j
= 0; j
< test_suite
->test_info_list().size(); j
++) {
5900 TestInfo
* const test_info
= test_suite
->test_info_list()[j
];
5901 const std::string
test_name(test_info
->name());
5902 // A test is disabled if test suite name or test name matches
5903 // kDisableTestFilter.
5904 const bool is_disabled
= internal::UnitTestOptions::MatchesFilter(
5905 test_suite_name
, kDisableTestFilter
) ||
5906 internal::UnitTestOptions::MatchesFilter(
5907 test_name
, kDisableTestFilter
);
5908 test_info
->is_disabled_
= is_disabled
;
5910 const bool matches_filter
= internal::UnitTestOptions::FilterMatchesTest(
5911 test_suite_name
, test_name
);
5912 test_info
->matches_filter_
= matches_filter
;
5914 const bool is_runnable
=
5915 (GTEST_FLAG(also_run_disabled_tests
) || !is_disabled
) &&
5918 const bool is_in_another_shard
=
5919 shard_tests
!= IGNORE_SHARDING_PROTOCOL
&&
5920 !ShouldRunTestOnShard(total_shards
, shard_index
, num_runnable_tests
);
5921 test_info
->is_in_another_shard_
= is_in_another_shard
;
5922 const bool is_selected
= is_runnable
&& !is_in_another_shard
;
5924 num_runnable_tests
+= is_runnable
;
5925 num_selected_tests
+= is_selected
;
5927 test_info
->should_run_
= is_selected
;
5928 test_suite
->set_should_run(test_suite
->should_run() || is_selected
);
5931 return num_selected_tests
;
5934 // Prints the given C-string on a single line by replacing all '\n'
5935 // characters with string "\\n". If the output takes more than
5936 // max_length characters, only prints the first max_length characters
5938 static void PrintOnOneLine(const char* str
, int max_length
) {
5939 if (str
!= nullptr) {
5940 for (int i
= 0; *str
!= '\0'; ++str
) {
5941 if (i
>= max_length
) {
5956 // Prints the names of the tests matching the user-specified filter flag.
5957 void UnitTestImpl::ListTestsMatchingFilter() {
5958 // Print at most this many characters for each type/value parameter.
5959 const int kMaxParamLength
= 250;
5961 for (auto* test_suite
: test_suites_
) {
5962 bool printed_test_suite_name
= false;
5964 for (size_t j
= 0; j
< test_suite
->test_info_list().size(); j
++) {
5965 const TestInfo
* const test_info
= test_suite
->test_info_list()[j
];
5966 if (test_info
->matches_filter_
) {
5967 if (!printed_test_suite_name
) {
5968 printed_test_suite_name
= true;
5969 printf("%s.", test_suite
->name());
5970 if (test_suite
->type_param() != nullptr) {
5971 printf(" # %s = ", kTypeParamLabel
);
5972 // We print the type parameter on a single line to make
5973 // the output easy to parse by a program.
5974 PrintOnOneLine(test_suite
->type_param(), kMaxParamLength
);
5978 printf(" %s", test_info
->name());
5979 if (test_info
->value_param() != nullptr) {
5980 printf(" # %s = ", kValueParamLabel
);
5981 // We print the value parameter on a single line to make the
5982 // output easy to parse by a program.
5983 PrintOnOneLine(test_info
->value_param(), kMaxParamLength
);
5990 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5991 if (output_format
== "xml" || output_format
== "json") {
5992 FILE* fileout
= OpenFileForWriting(
5993 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
5994 std::stringstream stream
;
5995 if (output_format
== "xml") {
5996 XmlUnitTestResultPrinter(
5997 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5998 .PrintXmlTestsList(&stream
, test_suites_
);
5999 } else if (output_format
== "json") {
6000 JsonUnitTestResultPrinter(
6001 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6002 .PrintJsonTestList(&stream
, test_suites_
);
6004 fprintf(fileout
, "%s", StringStreamToString(&stream
).c_str());
6009 // Sets the OS stack trace getter.
6011 // Does nothing if the input and the current OS stack trace getter are
6012 // the same; otherwise, deletes the old getter and makes the input the
6014 void UnitTestImpl::set_os_stack_trace_getter(
6015 OsStackTraceGetterInterface
* getter
) {
6016 if (os_stack_trace_getter_
!= getter
) {
6017 delete os_stack_trace_getter_
;
6018 os_stack_trace_getter_
= getter
;
6022 // Returns the current OS stack trace getter if it is not NULL;
6023 // otherwise, creates an OsStackTraceGetter, makes it the current
6024 // getter, and returns it.
6025 OsStackTraceGetterInterface
* UnitTestImpl::os_stack_trace_getter() {
6026 if (os_stack_trace_getter_
== nullptr) {
6027 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6028 os_stack_trace_getter_
= new GTEST_OS_STACK_TRACE_GETTER_
;
6030 os_stack_trace_getter_
= new OsStackTraceGetter
;
6031 #endif // GTEST_OS_STACK_TRACE_GETTER_
6034 return os_stack_trace_getter_
;
6037 // Returns the most specific TestResult currently running.
6038 TestResult
* UnitTestImpl::current_test_result() {
6039 if (current_test_info_
!= nullptr) {
6040 return ¤t_test_info_
->result_
;
6042 if (current_test_suite_
!= nullptr) {
6043 return ¤t_test_suite_
->ad_hoc_test_result_
;
6045 return &ad_hoc_test_result_
;
6048 // Shuffles all test suites, and the tests within each test suite,
6049 // making sure that death tests are still run first.
6050 void UnitTestImpl::ShuffleTests() {
6051 // Shuffles the death test suites.
6052 ShuffleRange(random(), 0, last_death_test_suite_
+ 1, &test_suite_indices_
);
6054 // Shuffles the non-death test suites.
6055 ShuffleRange(random(), last_death_test_suite_
+ 1,
6056 static_cast<int>(test_suites_
.size()), &test_suite_indices_
);
6058 // Shuffles the tests inside each test suite.
6059 for (auto& test_suite
: test_suites_
) {
6060 test_suite
->ShuffleTests(random());
6064 // Restores the test suites and tests to their order before the first shuffle.
6065 void UnitTestImpl::UnshuffleTests() {
6066 for (size_t i
= 0; i
< test_suites_
.size(); i
++) {
6067 // Unshuffles the tests in each test suite.
6068 test_suites_
[i
]->UnshuffleTests();
6069 // Resets the index of each test suite.
6070 test_suite_indices_
[i
] = static_cast<int>(i
);
6074 // Returns the current OS stack trace as an std::string.
6076 // The maximum number of stack frames to be included is specified by
6077 // the gtest_stack_trace_depth flag. The skip_count parameter
6078 // specifies the number of top frames to be skipped, which doesn't
6079 // count against the number of frames to be included.
6081 // For example, if Foo() calls Bar(), which in turn calls
6082 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6083 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6084 std::string
GetCurrentOsStackTraceExceptTop(UnitTest
* /*unit_test*/,
6086 // We pass skip_count + 1 to skip this wrapper function in addition
6087 // to what the user really wants to skip.
6088 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count
+ 1);
6091 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6092 // suppress unreachable code warnings.
6094 class ClassUniqueToAlwaysTrue
{};
6097 bool IsTrue(bool condition
) { return condition
; }
6100 #if GTEST_HAS_EXCEPTIONS
6101 // This condition is always false so AlwaysTrue() never actually throws,
6102 // but it makes the compiler think that it may throw.
6104 throw ClassUniqueToAlwaysTrue();
6105 #endif // GTEST_HAS_EXCEPTIONS
6109 // If *pstr starts with the given prefix, modifies *pstr to be right
6110 // past the prefix and returns true; otherwise leaves *pstr unchanged
6111 // and returns false. None of pstr, *pstr, and prefix can be NULL.
6112 bool SkipPrefix(const char* prefix
, const char** pstr
) {
6113 const size_t prefix_len
= strlen(prefix
);
6114 if (strncmp(*pstr
, prefix
, prefix_len
) == 0) {
6115 *pstr
+= prefix_len
;
6121 // Parses a string as a command line flag. The string should have
6122 // the format "--flag=value". When def_optional is true, the "=value"
6123 // part can be omitted.
6125 // Returns the value of the flag, or NULL if the parsing failed.
6126 static const char* ParseFlagValue(const char* str
, const char* flag
,
6127 bool def_optional
) {
6128 // str and flag must not be NULL.
6129 if (str
== nullptr || flag
== nullptr) return nullptr;
6131 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6132 const std::string flag_str
= std::string("--") + GTEST_FLAG_PREFIX_
+ flag
;
6133 const size_t flag_len
= flag_str
.length();
6134 if (strncmp(str
, flag_str
.c_str(), flag_len
) != 0) return nullptr;
6136 // Skips the flag name.
6137 const char* flag_end
= str
+ flag_len
;
6139 // When def_optional is true, it's OK to not have a "=value" part.
6140 if (def_optional
&& (flag_end
[0] == '\0')) {
6144 // If def_optional is true and there are more characters after the
6145 // flag name, or if def_optional is false, there must be a '=' after
6147 if (flag_end
[0] != '=') return nullptr;
6149 // Returns the string after "=".
6150 return flag_end
+ 1;
6153 // Parses a string for a bool flag, in the form of either
6154 // "--flag=value" or "--flag".
6156 // In the former case, the value is taken as true as long as it does
6157 // not start with '0', 'f', or 'F'.
6159 // In the latter case, the value is taken as true.
6161 // On success, stores the value of the flag in *value, and returns
6162 // true. On failure, returns false without changing *value.
6163 static bool ParseBoolFlag(const char* str
, const char* flag
, bool* value
) {
6164 // Gets the value of the flag as a string.
6165 const char* const value_str
= ParseFlagValue(str
, flag
, true);
6167 // Aborts if the parsing failed.
6168 if (value_str
== nullptr) return false;
6170 // Converts the string value to a bool.
6171 *value
= !(*value_str
== '0' || *value_str
== 'f' || *value_str
== 'F');
6175 // Parses a string for an int32_t flag, in the form of "--flag=value".
6177 // On success, stores the value of the flag in *value, and returns
6178 // true. On failure, returns false without changing *value.
6179 bool ParseInt32Flag(const char* str
, const char* flag
, int32_t* value
) {
6180 // Gets the value of the flag as a string.
6181 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6183 // Aborts if the parsing failed.
6184 if (value_str
== nullptr) return false;
6186 // Sets *value to the value of the flag.
6187 return ParseInt32(Message() << "The value of flag --" << flag
,
6191 // Parses a string for a string flag, in the form of "--flag=value".
6193 // On success, stores the value of the flag in *value, and returns
6194 // true. On failure, returns false without changing *value.
6195 template <typename String
>
6196 static bool ParseStringFlag(const char* str
, const char* flag
, String
* value
) {
6197 // Gets the value of the flag as a string.
6198 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6200 // Aborts if the parsing failed.
6201 if (value_str
== nullptr) return false;
6203 // Sets *value to the value of the flag.
6208 // Determines whether a string has a prefix that Google Test uses for its
6209 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6210 // If Google Test detects that a command line flag has its prefix but is not
6211 // recognized, it will print its help message. Flags starting with
6212 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6213 // internal flags and do not trigger the help message.
6214 static bool HasGoogleTestFlagPrefix(const char* str
) {
6215 return (SkipPrefix("--", &str
) ||
6216 SkipPrefix("-", &str
) ||
6217 SkipPrefix("/", &str
)) &&
6218 !SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str
) &&
6219 (SkipPrefix(GTEST_FLAG_PREFIX_
, &str
) ||
6220 SkipPrefix(GTEST_FLAG_PREFIX_DASH_
, &str
));
6223 // Prints a string containing code-encoded text. The following escape
6224 // sequences can be used in the string to control the text color:
6226 // @@ prints a single '@' character.
6227 // @R changes the color to red.
6228 // @G changes the color to green.
6229 // @Y changes the color to yellow.
6230 // @D changes to the default terminal text color.
6232 static void PrintColorEncoded(const char* str
) {
6233 GTestColor color
= GTestColor::kDefault
; // The current color.
6235 // Conceptually, we split the string into segments divided by escape
6236 // sequences. Then we print one segment at a time. At the end of
6237 // each iteration, the str pointer advances to the beginning of the
6240 const char* p
= strchr(str
, '@');
6242 ColoredPrintf(color
, "%s", str
);
6246 ColoredPrintf(color
, "%s", std::string(str
, p
).c_str());
6248 const char ch
= p
[1];
6251 ColoredPrintf(color
, "@");
6252 } else if (ch
== 'D') {
6253 color
= GTestColor::kDefault
;
6254 } else if (ch
== 'R') {
6255 color
= GTestColor::kRed
;
6256 } else if (ch
== 'G') {
6257 color
= GTestColor::kGreen
;
6258 } else if (ch
== 'Y') {
6259 color
= GTestColor::kYellow
;
6266 static const char kColorEncodedHelpMessage
[] =
6267 "This program contains tests written using " GTEST_NAME_
6268 ". You can use the\n"
6269 "following command line flags to control its behavior:\n"
6272 " @G--" GTEST_FLAG_PREFIX_
6274 " List the names of all tests instead of running them. The name of\n"
6275 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6276 " @G--" GTEST_FLAG_PREFIX_
6277 "filter=@YPOSTIVE_PATTERNS"
6278 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6279 " Run only the tests whose name matches one of the positive patterns "
6281 " none of the negative patterns. '?' matches any single character; "
6283 " matches any substring; ':' separates two patterns.\n"
6284 " @G--" GTEST_FLAG_PREFIX_
6285 "also_run_disabled_tests@D\n"
6286 " Run all disabled tests too.\n"
6289 " @G--" GTEST_FLAG_PREFIX_
6290 "repeat=@Y[COUNT]@D\n"
6291 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6292 " @G--" GTEST_FLAG_PREFIX_
6294 " Randomize tests' orders on every iteration.\n"
6295 " @G--" GTEST_FLAG_PREFIX_
6296 "random_seed=@Y[NUMBER]@D\n"
6297 " Random number seed to use for shuffling test orders (between 1 and\n"
6298 " 99999, or 0 to use a seed based on the current time).\n"
6301 " @G--" GTEST_FLAG_PREFIX_
6302 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6303 " Enable/disable colored output. The default is @Gauto@D.\n"
6304 " @G--" GTEST_FLAG_PREFIX_
6306 " Only print test failures.\n"
6307 " @G--" GTEST_FLAG_PREFIX_
6309 " Don't print the elapsed time of each test.\n"
6310 " @G--" GTEST_FLAG_PREFIX_
6311 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6312 "@Y|@G:@YFILE_PATH]@D\n"
6313 " Generate a JSON or XML report in the given directory or with the "
6315 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6316 # if GTEST_CAN_STREAM_RESULTS_
6317 " @G--" GTEST_FLAG_PREFIX_
6318 "stream_result_to=@YHOST@G:@YPORT@D\n"
6319 " Stream test results to the given server.\n"
6320 # endif // GTEST_CAN_STREAM_RESULTS_
6322 "Assertion Behavior:\n"
6323 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6324 " @G--" GTEST_FLAG_PREFIX_
6325 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6326 " Set the default death test style.\n"
6327 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6328 " @G--" GTEST_FLAG_PREFIX_
6329 "break_on_failure@D\n"
6330 " Turn assertion failures into debugger break-points.\n"
6331 " @G--" GTEST_FLAG_PREFIX_
6332 "throw_on_failure@D\n"
6333 " Turn assertion failures into C++ exceptions for use by an external\n"
6334 " test framework.\n"
6335 " @G--" GTEST_FLAG_PREFIX_
6336 "catch_exceptions=0@D\n"
6337 " Do not report exceptions as test failures. Instead, allow them\n"
6338 " to crash the program or throw a pop-up (on Windows).\n"
6340 "Except for @G--" GTEST_FLAG_PREFIX_
6341 "list_tests@D, you can alternatively set "
6342 "the corresponding\n"
6343 "environment variable of a flag (all letters in upper-case). For example, "
6345 "disable colored text output, you can either specify "
6346 "@G--" GTEST_FLAG_PREFIX_
6347 "color=no@D or set\n"
6348 "the @G" GTEST_FLAG_PREFIX_UPPER_
6349 "COLOR@D environment variable to @Gno@D.\n"
6351 "For more information, please read the " GTEST_NAME_
6352 " documentation at\n"
6353 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
6355 "(not one in your own code or tests), please report it to\n"
6356 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
6358 static bool ParseGoogleTestFlag(const char* const arg
) {
6359 return ParseBoolFlag(arg
, kAlsoRunDisabledTestsFlag
,
6360 >EST_FLAG(also_run_disabled_tests
)) ||
6361 ParseBoolFlag(arg
, kBreakOnFailureFlag
,
6362 >EST_FLAG(break_on_failure
)) ||
6363 ParseBoolFlag(arg
, kCatchExceptionsFlag
,
6364 >EST_FLAG(catch_exceptions
)) ||
6365 ParseStringFlag(arg
, kColorFlag
, >EST_FLAG(color
)) ||
6366 ParseStringFlag(arg
, kDeathTestStyleFlag
,
6367 >EST_FLAG(death_test_style
)) ||
6368 ParseBoolFlag(arg
, kDeathTestUseFork
,
6369 >EST_FLAG(death_test_use_fork
)) ||
6370 ParseBoolFlag(arg
, kFailFast
, >EST_FLAG(fail_fast
)) ||
6371 ParseStringFlag(arg
, kFilterFlag
, >EST_FLAG(filter
)) ||
6372 ParseStringFlag(arg
, kInternalRunDeathTestFlag
,
6373 >EST_FLAG(internal_run_death_test
)) ||
6374 ParseBoolFlag(arg
, kListTestsFlag
, >EST_FLAG(list_tests
)) ||
6375 ParseStringFlag(arg
, kOutputFlag
, >EST_FLAG(output
)) ||
6376 ParseBoolFlag(arg
, kBriefFlag
, >EST_FLAG(brief
)) ||
6377 ParseBoolFlag(arg
, kPrintTimeFlag
, >EST_FLAG(print_time
)) ||
6378 ParseBoolFlag(arg
, kPrintUTF8Flag
, >EST_FLAG(print_utf8
)) ||
6379 ParseInt32Flag(arg
, kRandomSeedFlag
, >EST_FLAG(random_seed
)) ||
6380 ParseInt32Flag(arg
, kRepeatFlag
, >EST_FLAG(repeat
)) ||
6381 ParseBoolFlag(arg
, kShuffleFlag
, >EST_FLAG(shuffle
)) ||
6382 ParseInt32Flag(arg
, kStackTraceDepthFlag
,
6383 >EST_FLAG(stack_trace_depth
)) ||
6384 ParseStringFlag(arg
, kStreamResultToFlag
,
6385 >EST_FLAG(stream_result_to
)) ||
6386 ParseBoolFlag(arg
, kThrowOnFailureFlag
, >EST_FLAG(throw_on_failure
));
6389 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6390 static void LoadFlagsFromFile(const std::string
& path
) {
6391 FILE* flagfile
= posix::FOpen(path
.c_str(), "r");
6393 GTEST_LOG_(FATAL
) << "Unable to open file \"" << GTEST_FLAG(flagfile
)
6396 std::string
contents(ReadEntireFile(flagfile
));
6397 posix::FClose(flagfile
);
6398 std::vector
<std::string
> lines
;
6399 SplitString(contents
, '\n', &lines
);
6400 for (size_t i
= 0; i
< lines
.size(); ++i
) {
6401 if (lines
[i
].empty())
6403 if (!ParseGoogleTestFlag(lines
[i
].c_str()))
6407 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6409 // Parses the command line for Google Test flags, without initializing
6410 // other parts of Google Test. The type parameter CharType can be
6411 // instantiated to either char or wchar_t.
6412 template <typename CharType
>
6413 void ParseGoogleTestFlagsOnlyImpl(int* argc
, CharType
** argv
) {
6414 for (int i
= 1; i
< *argc
; i
++) {
6415 const std::string arg_string
= StreamableToString(argv
[i
]);
6416 const char* const arg
= arg_string
.c_str();
6418 using internal::ParseBoolFlag
;
6419 using internal::ParseInt32Flag
;
6420 using internal::ParseStringFlag
;
6422 bool remove_flag
= false;
6423 if (ParseGoogleTestFlag(arg
)) {
6425 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6426 } else if (ParseStringFlag(arg
, kFlagfileFlag
, >EST_FLAG(flagfile
))) {
6427 LoadFlagsFromFile(GTEST_FLAG(flagfile
));
6429 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6430 } else if (arg_string
== "--help" || arg_string
== "-h" ||
6431 arg_string
== "-?" || arg_string
== "/?" ||
6432 HasGoogleTestFlagPrefix(arg
)) {
6433 // Both help flag and unrecognized Google Test flags (excluding
6434 // internal ones) trigger help display.
6439 // Shift the remainder of the argv list left by one. Note
6440 // that argv has (*argc + 1) elements, the last one always being
6441 // NULL. The following loop moves the trailing NULL element as
6443 for (int j
= i
; j
!= *argc
; j
++) {
6444 argv
[j
] = argv
[j
+ 1];
6447 // Decrements the argument count.
6450 // We also need to decrement the iterator as we just removed
6457 // We print the help here instead of in RUN_ALL_TESTS(), as the
6458 // latter may not be called at all if the user is using Google
6459 // Test with another testing framework.
6460 PrintColorEncoded(kColorEncodedHelpMessage
);
6464 // Parses the command line for Google Test flags, without initializing
6465 // other parts of Google Test.
6466 void ParseGoogleTestFlagsOnly(int* argc
, char** argv
) {
6467 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6469 // Fix the value of *_NSGetArgc() on macOS, but if and only if
6470 // *_NSGetArgv() == argv
6471 // Only applicable to char** version of argv
6473 #ifndef GTEST_OS_IOS
6474 if (*_NSGetArgv() == argv
) {
6475 *_NSGetArgc() = *argc
;
6480 void ParseGoogleTestFlagsOnly(int* argc
, wchar_t** argv
) {
6481 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6484 // The internal implementation of InitGoogleTest().
6486 // The type parameter CharType can be instantiated to either char or
6488 template <typename CharType
>
6489 void InitGoogleTestImpl(int* argc
, CharType
** argv
) {
6490 // We don't want to run the initialization code twice.
6491 if (GTestIsInitialized()) return;
6493 if (*argc
<= 0) return;
6496 for (int i
= 0; i
!= *argc
; i
++) {
6497 g_argvs
.push_back(StreamableToString(argv
[i
]));
6501 absl::InitializeSymbolizer(g_argvs
[0].c_str());
6502 #endif // GTEST_HAS_ABSL
6504 ParseGoogleTestFlagsOnly(argc
, argv
);
6505 GetUnitTestImpl()->PostFlagParsingInit();
6508 } // namespace internal
6510 // Initializes Google Test. This must be called before calling
6511 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6512 // flags that Google Test recognizes. Whenever a Google Test flag is
6513 // seen, it is removed from argv, and *argc is decremented.
6515 // No value is returned. Instead, the Google Test flag variables are
6518 // Calling the function for the second time has no user-visible effect.
6519 void InitGoogleTest(int* argc
, char** argv
) {
6520 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6521 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc
, argv
);
6522 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6523 internal::InitGoogleTestImpl(argc
, argv
);
6524 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6527 // This overloaded version can be used in Windows programs compiled in
6529 void InitGoogleTest(int* argc
, wchar_t** argv
) {
6530 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6531 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc
, argv
);
6532 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6533 internal::InitGoogleTestImpl(argc
, argv
);
6534 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6537 // This overloaded version can be used on Arduino/embedded platforms where
6538 // there is no argc/argv.
6539 void InitGoogleTest() {
6540 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
6542 const auto arg0
= "dummy";
6543 char* argv0
= const_cast<char*>(arg0
);
6544 char** argv
= &argv0
;
6546 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6547 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc
, argv
);
6548 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6549 internal::InitGoogleTestImpl(&argc
, argv
);
6550 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6553 std::string
TempDir() {
6554 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6555 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6558 #if GTEST_OS_WINDOWS_MOBILE
6560 #elif GTEST_OS_WINDOWS
6561 const char* temp_dir
= internal::posix::GetEnv("TEMP");
6562 if (temp_dir
== nullptr || temp_dir
[0] == '\0')
6564 else if (temp_dir
[strlen(temp_dir
) - 1] == '\\')
6567 return std::string(temp_dir
) + "\\";
6568 #elif GTEST_OS_LINUX_ANDROID
6569 const char* temp_dir
= internal::posix::GetEnv("TEST_TMPDIR");
6570 if (temp_dir
== nullptr || temp_dir
[0] == '\0')
6571 return "/data/local/tmp/";
6576 #endif // GTEST_OS_WINDOWS_MOBILE
6579 // Class ScopedTrace
6581 // Pushes the given source file location and message onto a per-thread
6582 // trace stack maintained by Google Test.
6583 void ScopedTrace::PushTrace(const char* file
, int line
, std::string message
) {
6584 internal::TraceInfo trace
;
6587 trace
.message
.swap(message
);
6589 UnitTest::GetInstance()->PushGTestTrace(trace
);
6592 // Pops the info pushed by the c'tor.
6593 ScopedTrace::~ScopedTrace()
6594 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
6595 UnitTest::GetInstance()->PopGTestTrace();
6598 } // namespace testing