F´ Flight Software - C/C++ Documentation NASA-v1.6.0
A framework for building embedded system applications to NASA flight quality standards.
Loading...
Searching...
No Matches
gtest.cc
Go to the documentation of this file.
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30//
31// The Google C++ Testing and Mocking Framework (Google Test)
32
33#include "gtest/gtest.h"
34
35#include <ctype.h>
36#include <stdarg.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <time.h>
40#include <wchar.h>
41#include <wctype.h>
42
43#include <algorithm>
44#include <chrono> // NOLINT
45#include <cmath>
46#include <cstdint>
47#include <initializer_list>
48#include <iomanip>
49#include <iterator>
50#include <limits>
51#include <list>
52#include <map>
53#include <ostream> // NOLINT
54#include <sstream>
55#include <unordered_set>
56#include <vector>
57
58#include "gtest/gtest-assertion-result.h"
59#include "gtest/gtest-spi.h"
60#include "gtest/internal/custom/gtest.h"
61
62#if GTEST_OS_LINUX
63
64#include <fcntl.h> // NOLINT
65#include <limits.h> // NOLINT
66#include <sched.h> // NOLINT
67// Declares vsnprintf(). This header is not available on Windows.
68#include <strings.h> // NOLINT
69#include <sys/mman.h> // NOLINT
70#include <sys/time.h> // NOLINT
71#include <unistd.h> // NOLINT
72
73#include <string>
74
75#elif GTEST_OS_ZOS
76#include <sys/time.h> // NOLINT
77
78// On z/OS we additionally need strings.h for strcasecmp.
79#include <strings.h> // NOLINT
80
81#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
82
83#include <windows.h> // NOLINT
84#undef min
85
86#elif GTEST_OS_WINDOWS // We are on Windows proper.
87
88#include <windows.h> // NOLINT
89#undef min
90
91#ifdef _MSC_VER
92#include <crtdbg.h> // NOLINT
93#endif
94
95#include <io.h> // NOLINT
96#include <sys/stat.h> // NOLINT
97#include <sys/timeb.h> // NOLINT
98#include <sys/types.h> // NOLINT
99
100#if GTEST_OS_WINDOWS_MINGW
101#include <sys/time.h> // NOLINT
102#endif // GTEST_OS_WINDOWS_MINGW
103
104#else
105
106// cpplint thinks that the header is already included, so we want to
107// silence it.
108#include <sys/time.h> // NOLINT
109#include <unistd.h> // NOLINT
110
111#endif // GTEST_OS_LINUX
112
113#if GTEST_HAS_EXCEPTIONS
114#include <stdexcept>
115#endif
116
117#if GTEST_CAN_STREAM_RESULTS_
118#include <arpa/inet.h> // NOLINT
119#include <netdb.h> // NOLINT
120#include <sys/socket.h> // NOLINT
121#include <sys/types.h> // NOLINT
122#endif
123
125
126#if GTEST_OS_WINDOWS
127#define vsnprintf _vsnprintf
128#endif // GTEST_OS_WINDOWS
129
130#if GTEST_OS_MAC
131#ifndef GTEST_OS_IOS
132#include <crt_externs.h>
133#endif
134#endif
135
136#if GTEST_HAS_ABSL
137#include "absl/debugging/failure_signal_handler.h"
138#include "absl/debugging/stacktrace.h"
139#include "absl/debugging/symbolize.h"
140#include "absl/flags/parse.h"
141#include "absl/flags/usage.h"
142#include "absl/strings/str_cat.h"
143#include "absl/strings/str_replace.h"
144#endif // GTEST_HAS_ABSL
145
146namespace testing {
147
152
153// Constants.
154
155// A test whose test suite name or test name matches this filter is
156// disabled and not run.
157static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
158
159// A test suite whose name matches this filter is considered a death
160// test suite and will be run before test suites whose name doesn't
161// match this filter.
162static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
163
164// A test filter that matches everything.
165static const char kUniversalFilter[] = "*";
166
167// The default output format.
168static const char kDefaultOutputFormat[] = "xml";
169// The default output file.
170static const char kDefaultOutputFile[] = "test_detail";
171
172// The environment variable name for the test shard index.
173static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
174// The environment variable name for the total number of test shards.
175static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
176// The environment variable name for the test shard status file.
177static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
178
179namespace internal {
180
181// The text used in failure messages to indicate the start of the
182// stack trace.
183const char kStackTraceMarker[] = "\nStack trace:\n";
184
185// g_help_flag is true if and only if the --help flag or an equivalent form
186// is specified on the command line.
187bool g_help_flag = false;
188
189// Utility function to Open File for Writing
190static FILE* OpenFileForWriting(const std::string& output_file) {
191 FILE* fileout = nullptr;
192 FilePath output_file_path(output_file);
193 FilePath output_dir(output_file_path.RemoveFileName());
194
195 if (output_dir.CreateDirectoriesRecursively()) {
196 fileout = posix::FOpen(output_file.c_str(), "w");
197 }
198 if (fileout == nullptr) {
199 GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
200 }
201 return fileout;
202}
203
204} // namespace internal
205
206// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
207// environment variable.
208static const char* GetDefaultFilter() {
209 const char* const testbridge_test_only =
210 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
211 if (testbridge_test_only != nullptr) {
212 return testbridge_test_only;
213 }
214 return kUniversalFilter;
215}
216
217// Bazel passes in the argument to '--test_runner_fail_fast' via the
218// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
219static bool GetDefaultFailFast() {
220 const char* const testbridge_test_runner_fail_fast =
221 internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
222 if (testbridge_test_runner_fail_fast != nullptr) {
223 return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
224 }
225 return false;
226}
227
228} // namespace testing
229
231 fail_fast,
234 "True if and only if a test failure should stop further test execution.");
235
237 also_run_disabled_tests,
238 testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
239 "Run disabled tests too, in addition to the tests normally being run.");
240
242 break_on_failure,
243 testing::internal::BoolFromGTestEnv("break_on_failure", false),
244 "True if and only if a failed assertion should be a debugger "
245 "break-point.");
246
247GTEST_DEFINE_bool_(catch_exceptions,
248 testing::internal::BoolFromGTestEnv("catch_exceptions",
249 true),
250 "True if and only if " GTEST_NAME_
251 " should catch exceptions and treat them as test failures.");
252
254 color, testing::internal::StringFromGTestEnv("color", "auto"),
255 "Whether to use colors in the output. Valid values: yes, no, "
256 "and auto. 'auto' means to use colors if the output is "
257 "being sent to a terminal and the TERM environment variable "
258 "is set to a terminal type that supports colors.");
259
261 filter,
264 "A colon-separated list of glob (not regex) patterns "
265 "for filtering the tests to run, optionally followed by a "
266 "'-' and a : separated list of negative patterns (tests to "
267 "exclude). A test is run if it matches one of the positive "
268 "patterns and does not match any of the negative patterns.");
269
271 install_failure_signal_handler,
272 testing::internal::BoolFromGTestEnv("install_failure_signal_handler",
273 false),
274 "If true and supported on the current platform, " GTEST_NAME_
275 " should "
276 "install a signal handler that dumps debugging information when fatal "
277 "signals are raised.");
278
279GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
280
281// The net priority order after flag processing is thus:
282// --gtest_output command line flag
283// GTEST_OUTPUT environment variable
284// XML_OUTPUT_FILE environment variable
285// ''
287 output,
290 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
291 "optionally followed by a colon and an output file name or directory. "
292 "A directory is indicated by a trailing pathname separator. "
293 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
294 "If a directory is specified, output files will be created "
295 "within that directory, with file-names based on the test "
296 "executable's name and, if necessary, made unique by adding "
297 "digits.");
298
300 brief, testing::internal::BoolFromGTestEnv("brief", false),
301 "True if only test failures should be displayed in text output.");
302
304 testing::internal::BoolFromGTestEnv("print_time", true),
305 "True if and only if " GTEST_NAME_
306 " should display elapsed time in text output.");
307
309 testing::internal::BoolFromGTestEnv("print_utf8", true),
310 "True if and only if " GTEST_NAME_
311 " prints UTF8 characters as text.");
312
314 random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0),
315 "Random number seed to use when shuffling test orders. Must be in range "
316 "[1, 99999], or 0 to use a seed based on the current time.");
317
319 repeat, testing::internal::Int32FromGTestEnv("repeat", 1),
320 "How many times to repeat each test. Specify a negative number "
321 "for repeating forever. Useful for shaking out flaky tests.");
322
324 recreate_environments_when_repeating,
325 testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating",
326 false),
327 "Controls whether global test environments are recreated for each repeat "
328 "of the tests. If set to false the global test environments are only set "
329 "up once, for the first iteration, and only torn down once, for the last. "
330 "Useful for shaking out flaky tests with stable, expensive test "
331 "environments. If --gtest_repeat is set to a negative number, meaning "
332 "there is no last run, the environments will always be recreated to avoid "
333 "leaks.");
334
335GTEST_DEFINE_bool_(show_internal_stack_frames, false,
336 "True if and only if " GTEST_NAME_
337 " should include internal stack frames when "
338 "printing test failure stack traces.");
339
341 testing::internal::BoolFromGTestEnv("shuffle", false),
342 "True if and only if " GTEST_NAME_
343 " should randomize tests' order on every run.");
344
346 stack_trace_depth,
347 testing::internal::Int32FromGTestEnv("stack_trace_depth",
348 testing::kMaxStackTraceDepth),
349 "The maximum number of stack frames to print when an "
350 "assertion fails. The valid range is 0 through 100, inclusive.");
351
353 stream_result_to,
354 testing::internal::StringFromGTestEnv("stream_result_to", ""),
355 "This flag specifies the host name and the port number on which to stream "
356 "test results. Example: \"localhost:555\". The flag is effective only on "
357 "Linux.");
358
360 throw_on_failure,
361 testing::internal::BoolFromGTestEnv("throw_on_failure", false),
362 "When this flag is specified, a failed assertion will throw an exception "
363 "if exceptions are enabled or exit the program with a non-zero code "
364 "otherwise. For use with an external test framework.");
365
366#if GTEST_USE_OWN_FLAGFILE_FLAG_
368 flagfile, testing::internal::StringFromGTestEnv("flagfile", ""),
369 "This flag specifies the flagfile to read command-line flags from.");
370#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
371
372namespace testing {
373namespace internal {
374
375// Generates a random number from [0, range), using a Linear
376// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
377// than kMaxRange.
378uint32_t Random::Generate(uint32_t range) {
379 // These constants are the same as are used in glibc's rand(3).
380 // Use wider types than necessary to prevent unsigned overflow diagnostics.
381 state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
382
383 GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
384 GTEST_CHECK_(range <= kMaxRange)
385 << "Generation of a number in [0, " << range << ") was requested, "
386 << "but this can only generate numbers in [0, " << kMaxRange << ").";
387
388 // Converting via modulus introduces a bit of downward bias, but
389 // it's simple, and a linear congruential generator isn't too good
390 // to begin with.
391 return state_ % range;
392}
393
394// GTestIsInitialized() returns true if and only if the user has initialized
395// Google Test. Useful for catching the user mistake of not initializing
396// Google Test before calling RUN_ALL_TESTS().
397static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
398
399// Iterates over a vector of TestSuites, keeping a running sum of the
400// results of calling a given int-returning method on each.
401// Returns the sum.
402static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
403 int (TestSuite::*method)() const) {
404 int sum = 0;
405 for (size_t i = 0; i < case_list.size(); i++) {
406 sum += (case_list[i]->*method)();
407 }
408 return sum;
409}
410
411// Returns true if and only if the test suite passed.
412static bool TestSuitePassed(const TestSuite* test_suite) {
413 return test_suite->should_run() && test_suite->Passed();
414}
415
416// Returns true if and only if the test suite failed.
417static bool TestSuiteFailed(const TestSuite* test_suite) {
418 return test_suite->should_run() && test_suite->Failed();
419}
420
421// Returns true if and only if test_suite contains at least one test that
422// should run.
423static bool ShouldRunTestSuite(const TestSuite* test_suite) {
424 return test_suite->should_run();
425}
426
427// AssertHelper constructor.
428AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
429 int line, const char* message)
430 : data_(new AssertHelperData(type, file, line, message)) {}
431
432AssertHelper::~AssertHelper() { delete data_; }
433
434// Message assignment, for assertion streaming support.
435void AssertHelper::operator=(const Message& message) const {
436 UnitTest::GetInstance()->AddTestPartResult(
437 data_->type, data_->file, data_->line,
438 AppendUserMessage(data_->message, message),
439 UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
440 // Skips the stack frame for this function itself.
441 ); // NOLINT
442}
443
444namespace {
445
446// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
447// to creates test cases for it, a synthetic test case is
448// inserted to report ether an error or a log message.
449//
450// This configuration bit will likely be removed at some point.
451constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
452constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
453
454// A test that fails at a given file/line location with a given message.
455class FailureTest : public Test {
456 public:
457 explicit FailureTest(const CodeLocation& loc, std::string error_message,
458 bool as_error)
459 : loc_(loc),
460 error_message_(std::move(error_message)),
461 as_error_(as_error) {}
462
463 void TestBody() override {
464 if (as_error_) {
465 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
466 loc_.line, "") = Message() << error_message_;
467 } else {
468 std::cout << error_message_ << std::endl;
469 }
470 }
471
472 private:
473 const CodeLocation loc_;
474 const std::string error_message_;
475 const bool as_error_;
476};
477
478} // namespace
479
480std::set<std::string>* GetIgnoredParameterizedTestSuites() {
481 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
482}
483
484// Add a given test_suit to the list of them allow to go un-instantiated.
485MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
486 GetIgnoredParameterizedTestSuites()->insert(test_suite);
487}
488
489// If this parameterized test suite has no instantiations (and that
490// has not been marked as okay), emit a test case reporting that.
491void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
492 bool has_test_p) {
493 const auto& ignored = *GetIgnoredParameterizedTestSuites();
494 if (ignored.find(name) != ignored.end()) return;
495
496 const char kMissingInstantiation[] = //
497 " is defined via TEST_P, but never instantiated. None of the test cases "
498 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
499 "ones provided expand to nothing."
500 "\n\n"
501 "Ideally, TEST_P definitions should only ever be included as part of "
502 "binaries that intend to use them. (As opposed to, for example, being "
503 "placed in a library that may be linked in to get other utilities.)";
504
505 const char kMissingTestCase[] = //
506 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
507 "defined via TEST_P . No test cases will run."
508 "\n\n"
509 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
510 "code that always depend on code that provides TEST_P. Failing to do "
511 "so is often an indication of dead code, e.g. the last TEST_P was "
512 "removed but the rest got left behind.";
513
514 std::string message =
515 "Parameterized test suite " + name +
516 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
517 "\n\n"
518 "To suppress this error for this test suite, insert the following line "
519 "(in a non-header) in the namespace it is defined in:"
520 "\n\n"
521 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
522 name + ");";
523
524 std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
525 RegisterTest( //
526 "GoogleTestVerification", full_name.c_str(),
527 nullptr, // No type parameter.
528 nullptr, // No value parameter.
529 location.file.c_str(), location.line, [message, location] {
530 return new FailureTest(location, message,
531 kErrorOnUninstantiatedParameterizedTest);
532 });
533}
534
535void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
536 CodeLocation code_location) {
537 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
538 test_suite_name, code_location);
539}
540
542 GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
543 case_name);
544}
545
546void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
547 const char* test_suite_name, CodeLocation code_location) {
548 suites_.emplace(std::string(test_suite_name),
549 TypeParameterizedTestSuiteInfo(code_location));
550}
551
552void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
553 const char* test_suite_name) {
554 auto it = suites_.find(std::string(test_suite_name));
555 if (it != suites_.end()) {
556 it->second.instantiated = true;
557 } else {
558 GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
559 << test_suite_name << "'";
560 }
561}
562
563void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
564 const auto& ignored = *GetIgnoredParameterizedTestSuites();
565 for (const auto& testcase : suites_) {
566 if (testcase.second.instantiated) continue;
567 if (ignored.find(testcase.first) != ignored.end()) continue;
568
569 std::string message =
570 "Type parameterized test suite " + testcase.first +
571 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
572 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
573 "\n\n"
574 "Ideally, TYPED_TEST_P definitions should only ever be included as "
575 "part of binaries that intend to use them. (As opposed to, for "
576 "example, being placed in a library that may be linked in to get other "
577 "utilities.)"
578 "\n\n"
579 "To suppress this error for this test suite, insert the following line "
580 "(in a non-header) in the namespace it is defined in:"
581 "\n\n"
582 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
583 testcase.first + ");";
584
585 std::string full_name =
586 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
587 RegisterTest( //
588 "GoogleTestVerification", full_name.c_str(),
589 nullptr, // No type parameter.
590 nullptr, // No value parameter.
591 testcase.second.code_location.file.c_str(),
592 testcase.second.code_location.line, [message, testcase] {
593 return new FailureTest(testcase.second.code_location, message,
594 kErrorOnUninstantiatedTypeParameterizedTest);
595 });
596 }
597}
598
599// A copy of all command line arguments. Set by InitGoogleTest().
600static ::std::vector<std::string> g_argvs;
601
602::std::vector<std::string> GetArgvs() {
603#if defined(GTEST_CUSTOM_GET_ARGVS_)
604 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
605 // ::string. This code converts it to the appropriate type.
606 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
607 return ::std::vector<std::string>(custom.begin(), custom.end());
608#else // defined(GTEST_CUSTOM_GET_ARGVS_)
609 return g_argvs;
610#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
611}
612
613// Returns the current application's name, removing directory path if that
614// is present.
616 FilePath result;
617
618#if GTEST_OS_WINDOWS || GTEST_OS_OS2
619 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
620#else
621 result.Set(FilePath(GetArgvs()[0]));
622#endif // GTEST_OS_WINDOWS
623
624 return result.RemoveDirectoryName();
625}
626
627// Functions for processing the gtest_output flag.
628
629// Returns the output format, or "" for normal printed output.
630std::string UnitTestOptions::GetOutputFormat() {
631 std::string s = GTEST_FLAG_GET(output);
632 const char* const gtest_output_flag = s.c_str();
633 const char* const colon = strchr(gtest_output_flag, ':');
634 return (colon == nullptr)
635 ? std::string(gtest_output_flag)
636 : std::string(gtest_output_flag,
637 static_cast<size_t>(colon - gtest_output_flag));
638}
639
640// Returns the name of the requested output file, or the default if none
641// was explicitly specified.
642std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
643 std::string s = GTEST_FLAG_GET(output);
644 const char* const gtest_output_flag = s.c_str();
645
646 std::string format = GetOutputFormat();
647 if (format.empty()) format = std::string(kDefaultOutputFormat);
648
649 const char* const colon = strchr(gtest_output_flag, ':');
650 if (colon == nullptr)
651 return internal::FilePath::MakeFileName(
652 internal::FilePath(
653 UnitTest::GetInstance()->original_working_dir()),
654 internal::FilePath(kDefaultOutputFile), 0, format.c_str())
655 .string();
656
657 internal::FilePath output_name(colon + 1);
658 if (!output_name.IsAbsolutePath())
659 output_name = internal::FilePath::ConcatPaths(
660 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
661 internal::FilePath(colon + 1));
662
663 if (!output_name.IsDirectory()) return output_name.string();
664
665 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
667 GetOutputFormat().c_str()));
668 return result.string();
669}
670
671// Returns true if and only if the wildcard pattern matches the string. Each
672// pattern consists of regular characters, single-character wildcards (?), and
673// multi-character wildcards (*).
674//
675// This function implements a linear-time string globbing algorithm based on
676// https://research.swtch.com/glob.
677static bool PatternMatchesString(const std::string& name_str,
678 const char* pattern, const char* pattern_end) {
679 const char* name = name_str.c_str();
680 const char* const name_begin = name;
681 const char* const name_end = name + name_str.size();
682
683 const char* pattern_next = pattern;
684 const char* name_next = name;
685
686 while (pattern < pattern_end || name < name_end) {
687 if (pattern < pattern_end) {
688 switch (*pattern) {
689 default: // Match an ordinary character.
690 if (name < name_end && *name == *pattern) {
691 ++pattern;
692 ++name;
693 continue;
694 }
695 break;
696 case '?': // Match any single character.
697 if (name < name_end) {
698 ++pattern;
699 ++name;
700 continue;
701 }
702 break;
703 case '*':
704 // Match zero or more characters. Start by skipping over the wildcard
705 // and matching zero characters from name. If that fails, restart and
706 // match one more character than the last attempt.
707 pattern_next = pattern;
708 name_next = name + 1;
709 ++pattern;
710 continue;
711 }
712 }
713 // Failed to match a character. Restart if possible.
714 if (name_begin < name_next && name_next <= name_end) {
715 pattern = pattern_next;
716 name = name_next;
717 continue;
718 }
719 return false;
720 }
721 return true;
722}
723
724namespace {
725
726bool IsGlobPattern(const std::string& pattern) {
727 return std::any_of(pattern.begin(), pattern.end(),
728 [](const char c) { return c == '?' || c == '*'; });
729}
730
731class UnitTestFilter {
732 public:
733 UnitTestFilter() = default;
734
735 // Constructs a filter from a string of patterns separated by `:`.
736 explicit UnitTestFilter(const std::string& filter) {
737 // By design "" filter matches "" string.
738 std::vector<std::string> all_patterns;
739 SplitString(filter, ':', &all_patterns);
740 const auto exact_match_patterns_begin = std::partition(
741 all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
742
743 glob_patterns_.reserve(static_cast<size_t>(
744 std::distance(all_patterns.begin(), exact_match_patterns_begin)));
745 std::move(all_patterns.begin(), exact_match_patterns_begin,
746 std::inserter(glob_patterns_, glob_patterns_.begin()));
747 std::move(
748 exact_match_patterns_begin, all_patterns.end(),
749 std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
750 }
751
752 // Returns true if and only if name matches at least one of the patterns in
753 // the filter.
754 bool MatchesName(const std::string& name) const {
755 return exact_match_patterns_.count(name) > 0 ||
756 std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
757 [&name](const std::string& pattern) {
758 return PatternMatchesString(
759 name, pattern.c_str(),
760 pattern.c_str() + pattern.size());
761 });
762 }
763
764 private:
765 std::vector<std::string> glob_patterns_;
766 std::unordered_set<std::string> exact_match_patterns_;
767};
768
769class PositiveAndNegativeUnitTestFilter {
770 public:
771 // Constructs a positive and a negative filter from a string. The string
772 // contains a positive filter optionally followed by a '-' character and a
773 // negative filter. In case only a negative filter is provided the positive
774 // filter will be assumed "*".
775 // A filter is a list of patterns separated by ':'.
776 explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {
777 std::vector<std::string> positive_and_negative_filters;
778
779 // NOTE: `SplitString` always returns a non-empty container.
780 SplitString(filter, '-', &positive_and_negative_filters);
781 const auto& positive_filter = positive_and_negative_filters.front();
782
783 if (positive_and_negative_filters.size() > 1) {
784 positive_filter_ = UnitTestFilter(
785 positive_filter.empty() ? kUniversalFilter : positive_filter);
786
787 // TODO(b/214626361): Fail on multiple '-' characters
788 // For the moment to preserve old behavior we concatenate the rest of the
789 // string parts with `-` as separator to generate the negative filter.
790 auto negative_filter_string = positive_and_negative_filters[1];
791 for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
792 negative_filter_string =
793 negative_filter_string + '-' + positive_and_negative_filters[i];
794 negative_filter_ = UnitTestFilter(negative_filter_string);
795 } else {
796 // In case we don't have a negative filter and positive filter is ""
797 // we do not use kUniversalFilter by design as opposed to when we have a
798 // negative filter.
799 positive_filter_ = UnitTestFilter(positive_filter);
800 }
801 }
802
803 // Returns true if and only if test name (this is generated by appending test
804 // suit name and test name via a '.' character) matches the positive filter
805 // and does not match the negative filter.
806 bool MatchesTest(const std::string& test_suite_name,
807 const std::string& test_name) const {
808 return MatchesName(test_suite_name + "." + test_name);
809 }
810
811 // Returns true if and only if name matches the positive filter and does not
812 // match the negative filter.
813 bool MatchesName(const std::string& name) const {
814 return positive_filter_.MatchesName(name) &&
815 !negative_filter_.MatchesName(name);
816 }
817
818 private:
819 UnitTestFilter positive_filter_;
820 UnitTestFilter negative_filter_;
821};
822} // namespace
823
824bool UnitTestOptions::MatchesFilter(const std::string& name_str,
825 const char* filter) {
826 return UnitTestFilter(filter).MatchesName(name_str);
827}
828
829// Returns true if and only if the user-specified filter matches the test
830// suite name and the test name.
831bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
832 const std::string& test_name) {
833 // Split --gtest_filter at '-', if there is one, to separate into
834 // positive filter and negative filter portions
835 return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
836 .MatchesTest(test_suite_name, test_name);
837}
838
839#if GTEST_HAS_SEH
840// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
841// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
842// This function is useful as an __except condition.
843int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
844 // Google Test should handle a SEH exception if:
845 // 1. the user wants it to, AND
846 // 2. this is not a breakpoint exception, AND
847 // 3. this is not a C++ exception (VC++ implements them via SEH,
848 // apparently).
849 //
850 // SEH exception code for C++ exceptions.
851 // (see http://support.microsoft.com/kb/185294 for more information).
852 const DWORD kCxxExceptionCode = 0xe06d7363;
853
854 bool should_handle = true;
855
856 if (!GTEST_FLAG_GET(catch_exceptions))
857 should_handle = false;
858 else if (exception_code == EXCEPTION_BREAKPOINT)
859 should_handle = false;
860 else if (exception_code == kCxxExceptionCode)
861 should_handle = false;
862
863 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
864}
865#endif // GTEST_HAS_SEH
866
867} // namespace internal
868
869// The c'tor sets this object as the test part result reporter used by
870// Google Test. The 'result' parameter specifies where to report the
871// results. Intercepts only failures from the current thread.
872ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
873 TestPartResultArray* result)
874 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
875 Init();
876}
877
878// The c'tor sets this object as the test part result reporter used by
879// Google Test. The 'result' parameter specifies where to report the
880// results.
881ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
882 InterceptMode intercept_mode, TestPartResultArray* result)
883 : intercept_mode_(intercept_mode), result_(result) {
884 Init();
885}
886
887void ScopedFakeTestPartResultReporter::Init() {
888 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
889 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
890 old_reporter_ = impl->GetGlobalTestPartResultReporter();
891 impl->SetGlobalTestPartResultReporter(this);
892 } else {
893 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
894 impl->SetTestPartResultReporterForCurrentThread(this);
895 }
896}
897
898// The d'tor restores the test part result reporter used by Google Test
899// before.
900ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
901 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
902 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
903 impl->SetGlobalTestPartResultReporter(old_reporter_);
904 } else {
905 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
906 }
907}
908
909// Increments the test part result count and remembers the result.
910// This method is from the TestPartResultReporterInterface interface.
911void ScopedFakeTestPartResultReporter::ReportTestPartResult(
912 const TestPartResult& result) {
913 result_->Append(result);
914}
915
916namespace internal {
917
918// Returns the type ID of ::testing::Test. We should always call this
919// instead of GetTypeId< ::testing::Test>() to get the type ID of
920// testing::Test. This is to work around a suspected linker bug when
921// using Google Test as a framework on Mac OS X. The bug causes
922// GetTypeId< ::testing::Test>() to return different values depending
923// on whether the call is from the Google Test framework itself or
924// from user test code. GetTestTypeId() is guaranteed to always
925// return the same value, as it always calls GetTypeId<>() from the
926// gtest.cc, which is within the Google Test framework.
927TypeId GetTestTypeId() { return GetTypeId<Test>(); }
928
929// The value of GetTestTypeId() as seen from within the Google Test
930// library. This is solely for testing GetTestTypeId().
932
933// This predicate-formatter checks that 'results' contains a test part
934// failure of the given type and that the failure message contains the
935// given substring.
936static AssertionResult HasOneFailure(const char* /* results_expr */,
937 const char* /* type_expr */,
938 const char* /* substr_expr */,
939 const TestPartResultArray& results,
940 TestPartResult::Type type,
941 const std::string& substr) {
942 const std::string expected(type == TestPartResult::kFatalFailure
943 ? "1 fatal failure"
944 : "1 non-fatal failure");
945 Message msg;
946 if (results.size() != 1) {
947 msg << "Expected: " << expected << "\n"
948 << " Actual: " << results.size() << " failures";
949 for (int i = 0; i < results.size(); i++) {
950 msg << "\n" << results.GetTestPartResult(i);
951 }
952 return AssertionFailure() << msg;
953 }
954
955 const TestPartResult& r = results.GetTestPartResult(0);
956 if (r.type() != type) {
957 return AssertionFailure() << "Expected: " << expected << "\n"
958 << " Actual:\n"
959 << r;
960 }
961
962 if (strstr(r.message(), substr.c_str()) == nullptr) {
963 return AssertionFailure()
964 << "Expected: " << expected << " containing \"" << substr << "\"\n"
965 << " Actual:\n"
966 << r;
967 }
968
969 return AssertionSuccess();
970}
971
972// The constructor of SingleFailureChecker remembers where to look up
973// test part results, what type of failure we expect, and what
974// substring the failure message should contain.
975SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
976 TestPartResult::Type type,
977 const std::string& substr)
978 : results_(results), type_(type), substr_(substr) {}
979
980// The destructor of SingleFailureChecker verifies that the given
981// TestPartResultArray contains exactly one failure that has the given
982// type and contains the given substring. If that's not the case, a
983// non-fatal failure will be generated.
984SingleFailureChecker::~SingleFailureChecker() {
985 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
986}
987
988DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
989 UnitTestImpl* unit_test)
990 : unit_test_(unit_test) {}
991
993 const TestPartResult& result) {
994 unit_test_->current_test_result()->AddTestPartResult(result);
995 unit_test_->listeners()->repeater()->OnTestPartResult(result);
996}
997
1001
1003 const TestPartResult& result) {
1004 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1005}
1006
1007// Returns the global test part result reporter.
1008TestPartResultReporterInterface*
1010 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1011 return global_test_part_result_repoter_;
1012}
1013
1014// Sets the global test part result reporter.
1016 TestPartResultReporterInterface* reporter) {
1017 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1018 global_test_part_result_repoter_ = reporter;
1019}
1020
1021// Returns the test part result reporter for the current thread.
1022TestPartResultReporterInterface*
1024 return per_thread_test_part_result_reporter_.get();
1025}
1026
1027// Sets the test part result reporter for the current thread.
1029 TestPartResultReporterInterface* reporter) {
1030 per_thread_test_part_result_reporter_.set(reporter);
1031}
1032
1033// Gets the number of successful test suites.
1035 return CountIf(test_suites_, TestSuitePassed);
1036}
1037
1038// Gets the number of failed test suites.
1040 return CountIf(test_suites_, TestSuiteFailed);
1041}
1042
1043// Gets the number of all test suites.
1045 return static_cast<int>(test_suites_.size());
1046}
1047
1048// Gets the number of all test suites that contain at least one test
1049// that should run.
1051 return CountIf(test_suites_, ShouldRunTestSuite);
1052}
1053
1054// Gets the number of successful tests.
1056 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
1057}
1058
1059// Gets the number of skipped tests.
1061 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
1062}
1063
1064// Gets the number of failed tests.
1066 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
1067}
1068
1069// Gets the number of disabled tests that will be reported in the XML report.
1071 return SumOverTestSuiteList(test_suites_,
1072 &TestSuite::reportable_disabled_test_count);
1073}
1074
1075// Gets the number of disabled tests.
1077 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
1078}
1079
1080// Gets the number of tests to be printed in the XML report.
1082 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
1083}
1084
1085// Gets the number of all tests.
1087 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
1088}
1089
1090// Gets the number of tests that should run.
1092 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
1093}
1094
1095// Returns the current OS stack trace as an std::string.
1096//
1097// The maximum number of stack frames to be included is specified by
1098// the gtest_stack_trace_depth flag. The skip_count parameter
1099// specifies the number of top frames to be skipped, which doesn't
1100// count against the number of frames to be included.
1101//
1102// For example, if Foo() calls Bar(), which in turn calls
1103// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1104// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1107 static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1108 // Skips the user-specified number of frames plus this function
1109 // itself.
1110 ); // NOLINT
1111}
1112
1113// A helper class for measuring elapsed times.
1114class Timer {
1115 public:
1116 Timer() : start_(std::chrono::steady_clock::now()) {}
1117
1118 // Return time elapsed in milliseconds since the timer was created.
1119 TimeInMillis Elapsed() {
1120 return std::chrono::duration_cast<std::chrono::milliseconds>(
1121 std::chrono::steady_clock::now() - start_)
1122 .count();
1123 }
1124
1125 private:
1126 std::chrono::steady_clock::time_point start_;
1127};
1128
1129// Returns a timestamp as milliseconds since the epoch. Note this time may jump
1130// around subject to adjustments by the system, to measure elapsed time use
1131// Timer instead.
1132TimeInMillis GetTimeInMillis() {
1133 return std::chrono::duration_cast<std::chrono::milliseconds>(
1134 std::chrono::system_clock::now() -
1135 std::chrono::system_clock::from_time_t(0))
1136 .count();
1137}
1138
1139// Utilities
1140
1141// class String.
1142
1143#if GTEST_OS_WINDOWS_MOBILE
1144// Creates a UTF-16 wide string from the given ANSI string, allocating
1145// memory using new. The caller is responsible for deleting the return
1146// value using delete[]. Returns the wide string, or NULL if the
1147// input is NULL.
1148LPCWSTR String::AnsiToUtf16(const char* ansi) {
1149 if (!ansi) return nullptr;
1150 const int length = strlen(ansi);
1151 const int unicode_length =
1152 MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
1153 WCHAR* unicode = new WCHAR[unicode_length + 1];
1154 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1155 unicode[unicode_length] = 0;
1156 return unicode;
1157}
1158
1159// Creates an ANSI string from the given wide string, allocating
1160// memory using new. The caller is responsible for deleting the return
1161// value using delete[]. Returns the ANSI string, or NULL if the
1162// input is NULL.
1163const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1164 if (!utf16_str) return nullptr;
1165 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
1166 0, nullptr, nullptr);
1167 char* ansi = new char[ansi_length + 1];
1168 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
1169 nullptr);
1170 ansi[ansi_length] = 0;
1171 return ansi;
1172}
1173
1174#endif // GTEST_OS_WINDOWS_MOBILE
1175
1176// Compares two C strings. Returns true if and only if they have the same
1177// content.
1178//
1179// Unlike strcmp(), this function can handle NULL argument(s). A NULL
1180// C string is considered different to any non-NULL C string,
1181// including the empty string.
1182bool String::CStringEquals(const char* lhs, const char* rhs) {
1183 if (lhs == nullptr) return rhs == nullptr;
1184
1185 if (rhs == nullptr) return false;
1186
1187 return strcmp(lhs, rhs) == 0;
1188}
1189
1190#if GTEST_HAS_STD_WSTRING
1191
1192// Converts an array of wide chars to a narrow string using the UTF-8
1193// encoding, and streams the result to the given Message object.
1194static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
1195 Message* msg) {
1196 for (size_t i = 0; i != length;) { // NOLINT
1197 if (wstr[i] != L'\0') {
1198 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
1199 while (i != length && wstr[i] != L'\0') i++;
1200 } else {
1201 *msg << '\0';
1202 i++;
1203 }
1204 }
1205}
1206
1207#endif // GTEST_HAS_STD_WSTRING
1208
1209void SplitString(const ::std::string& str, char delimiter,
1210 ::std::vector< ::std::string>* dest) {
1211 ::std::vector< ::std::string> parsed;
1212 ::std::string::size_type pos = 0;
1214 const ::std::string::size_type colon = str.find(delimiter, pos);
1215 if (colon == ::std::string::npos) {
1216 parsed.push_back(str.substr(pos));
1217 break;
1218 } else {
1219 parsed.push_back(str.substr(pos, colon - pos));
1220 pos = colon + 1;
1221 }
1222 }
1223 dest->swap(parsed);
1224}
1225
1226} // namespace internal
1227
1228// Constructs an empty Message.
1229// We allocate the stringstream separately because otherwise each use of
1230// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
1231// stack frame leading to huge stack frames in some cases; gcc does not reuse
1232// the stack space.
1233Message::Message() : ss_(new ::std::stringstream) {
1234 // By default, we want there to be enough precision when printing
1235 // a double to a Message.
1236 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1237}
1238
1239// These two overloads allow streaming a wide C string to a Message
1240// using the UTF-8 encoding.
1241Message& Message::operator<<(const wchar_t* wide_c_str) {
1242 return *this << internal::String::ShowWideCString(wide_c_str);
1243}
1244Message& Message::operator<<(wchar_t* wide_c_str) {
1245 return *this << internal::String::ShowWideCString(wide_c_str);
1246}
1247
1248#if GTEST_HAS_STD_WSTRING
1249// Converts the given wide string to a narrow string using the UTF-8
1250// encoding, and streams the result to this Message object.
1251Message& Message::operator<<(const ::std::wstring& wstr) {
1252 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
1253 return *this;
1254}
1255#endif // GTEST_HAS_STD_WSTRING
1256
1257// Gets the text streamed to this object so far as an std::string.
1258// Each '\0' character in the buffer is replaced with "\\0".
1259std::string Message::GetString() const {
1260 return internal::StringStreamToString(ss_.get());
1261}
1262
1263namespace internal {
1264
1265namespace edit_distance {
1266std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1267 const std::vector<size_t>& right) {
1268 std::vector<std::vector<double> > costs(
1269 left.size() + 1, std::vector<double>(right.size() + 1));
1270 std::vector<std::vector<EditType> > best_move(
1271 left.size() + 1, std::vector<EditType>(right.size() + 1));
1272
1273 // Populate for empty right.
1274 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1275 costs[l_i][0] = static_cast<double>(l_i);
1276 best_move[l_i][0] = kRemove;
1277 }
1278 // Populate for empty left.
1279 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1280 costs[0][r_i] = static_cast<double>(r_i);
1281 best_move[0][r_i] = kAdd;
1282 }
1283
1284 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1285 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1286 if (left[l_i] == right[r_i]) {
1287 // Found a match. Consume it.
1288 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1289 best_move[l_i + 1][r_i + 1] = kMatch;
1290 continue;
1291 }
1292
1293 const double add = costs[l_i + 1][r_i];
1294 const double remove = costs[l_i][r_i + 1];
1295 const double replace = costs[l_i][r_i];
1296 if (add < remove && add < replace) {
1297 costs[l_i + 1][r_i + 1] = add + 1;
1298 best_move[l_i + 1][r_i + 1] = kAdd;
1299 } else if (remove < add && remove < replace) {
1300 costs[l_i + 1][r_i + 1] = remove + 1;
1301 best_move[l_i + 1][r_i + 1] = kRemove;
1302 } else {
1303 // We make replace a little more expensive than add/remove to lower
1304 // their priority.
1305 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1306 best_move[l_i + 1][r_i + 1] = kReplace;
1307 }
1308 }
1309 }
1310
1311 // Reconstruct the best path. We do it in reverse order.
1312 std::vector<EditType> best_path;
1313 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1314 EditType move = best_move[l_i][r_i];
1315 best_path.push_back(move);
1316 l_i -= move != kAdd;
1317 r_i -= move != kRemove;
1318 }
1319 std::reverse(best_path.begin(), best_path.end());
1320 return best_path;
1321}
1322
1323namespace {
1324
1325// Helper class to convert string into ids with deduplication.
1326class InternalStrings {
1327 public:
1328 size_t GetId(const std::string& str) {
1329 IdMap::iterator it = ids_.find(str);
1330 if (it != ids_.end()) return it->second;
1331 size_t id = ids_.size();
1332 return ids_[str] = id;
1333 }
1334
1335 private:
1336 typedef std::map<std::string, size_t> IdMap;
1337 IdMap ids_;
1338};
1339
1340} // namespace
1341
1342std::vector<EditType> CalculateOptimalEdits(
1343 const std::vector<std::string>& left,
1344 const std::vector<std::string>& right) {
1345 std::vector<size_t> left_ids, right_ids;
1346 {
1347 InternalStrings intern_table;
1348 for (size_t i = 0; i < left.size(); ++i) {
1349 left_ids.push_back(intern_table.GetId(left[i]));
1350 }
1351 for (size_t i = 0; i < right.size(); ++i) {
1352 right_ids.push_back(intern_table.GetId(right[i]));
1353 }
1354 }
1355 return CalculateOptimalEdits(left_ids, right_ids);
1356}
1357
1358namespace {
1359
1360// Helper class that holds the state for one hunk and prints it out to the
1361// stream.
1362// It reorders adds/removes when possible to group all removes before all
1363// adds. It also adds the hunk header before printint into the stream.
1364class Hunk {
1365 public:
1366 Hunk(size_t left_start, size_t right_start)
1367 : left_start_(left_start),
1368 right_start_(right_start),
1369 adds_(),
1370 removes_(),
1371 common_() {}
1372
1373 void PushLine(char edit, const char* line) {
1374 switch (edit) {
1375 case ' ':
1376 ++common_;
1377 FlushEdits();
1378 hunk_.push_back(std::make_pair(' ', line));
1379 break;
1380 case '-':
1381 ++removes_;
1382 hunk_removes_.push_back(std::make_pair('-', line));
1383 break;
1384 case '+':
1385 ++adds_;
1386 hunk_adds_.push_back(std::make_pair('+', line));
1387 break;
1388 }
1389 }
1390
1391 void PrintTo(std::ostream* os) {
1392 PrintHeader(os);
1393 FlushEdits();
1394 for (std::list<std::pair<char, const char*> >::const_iterator it =
1395 hunk_.begin();
1396 it != hunk_.end(); ++it) {
1397 *os << it->first << it->second << "\n";
1398 }
1399 }
1400
1401 bool has_edits() const { return adds_ || removes_; }
1402
1403 private:
1404 void FlushEdits() {
1405 hunk_.splice(hunk_.end(), hunk_removes_);
1406 hunk_.splice(hunk_.end(), hunk_adds_);
1407 }
1408
1409 // Print a unified diff header for one hunk.
1410 // The format is
1411 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1412 // where the left/right parts are omitted if unnecessary.
1413 void PrintHeader(std::ostream* ss) const {
1414 *ss << "@@ ";
1415 if (removes_) {
1416 *ss << "-" << left_start_ << "," << (removes_ + common_);
1417 }
1418 if (removes_ && adds_) {
1419 *ss << " ";
1420 }
1421 if (adds_) {
1422 *ss << "+" << right_start_ << "," << (adds_ + common_);
1423 }
1424 *ss << " @@\n";
1425 }
1426
1427 size_t left_start_, right_start_;
1428 size_t adds_, removes_, common_;
1429 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1430};
1431
1432} // namespace
1433
1434// Create a list of diff hunks in Unified diff format.
1435// Each hunk has a header generated by PrintHeader above plus a body with
1436// lines prefixed with ' ' for no change, '-' for deletion and '+' for
1437// addition.
1438// 'context' represents the desired unchanged prefix/suffix around the diff.
1439// If two hunks are close enough that their contexts overlap, then they are
1440// joined into one hunk.
1441std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1442 const std::vector<std::string>& right,
1443 size_t context) {
1444 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1445
1446 size_t l_i = 0, r_i = 0, edit_i = 0;
1447 std::stringstream ss;
1448 while (edit_i < edits.size()) {
1449 // Find first edit.
1450 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1451 ++l_i;
1452 ++r_i;
1453 ++edit_i;
1454 }
1455
1456 // Find the first line to include in the hunk.
1457 const size_t prefix_context = std::min(l_i, context);
1458 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1459 for (size_t i = prefix_context; i > 0; --i) {
1460 hunk.PushLine(' ', left[l_i - i].c_str());
1461 }
1462
1463 // Iterate the edits until we found enough suffix for the hunk or the input
1464 // is over.
1465 size_t n_suffix = 0;
1466 for (; edit_i < edits.size(); ++edit_i) {
1467 if (n_suffix >= context) {
1468 // Continue only if the next hunk is very close.
1469 auto it = edits.begin() + static_cast<int>(edit_i);
1470 while (it != edits.end() && *it == kMatch) ++it;
1471 if (it == edits.end() ||
1472 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1473 // There is no next edit or it is too far away.
1474 break;
1475 }
1476 }
1477
1478 EditType edit = edits[edit_i];
1479 // Reset count when a non match is found.
1480 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1481
1482 if (edit == kMatch || edit == kRemove || edit == kReplace) {
1483 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1484 }
1485 if (edit == kAdd || edit == kReplace) {
1486 hunk.PushLine('+', right[r_i].c_str());
1487 }
1488
1489 // Advance indices, depending on edit type.
1490 l_i += edit != kAdd;
1491 r_i += edit != kRemove;
1492 }
1493
1494 if (!hunk.has_edits()) {
1495 // We are done. We don't want this hunk.
1496 break;
1497 }
1498
1499 hunk.PrintTo(&ss);
1500 }
1501 return ss.str();
1502}
1503
1504} // namespace edit_distance
1505
1506namespace {
1507
1508// The string representation of the values received in EqFailure() are already
1509// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1510// characters the same.
1511std::vector<std::string> SplitEscapedString(const std::string& str) {
1512 std::vector<std::string> lines;
1513 size_t start = 0, end = str.size();
1514 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1515 ++start;
1516 --end;
1517 }
1518 bool escaped = false;
1519 for (size_t i = start; i + 1 < end; ++i) {
1520 if (escaped) {
1521 escaped = false;
1522 if (str[i] == 'n') {
1523 lines.push_back(str.substr(start, i - start - 1));
1524 start = i + 1;
1525 }
1526 } else {
1527 escaped = str[i] == '\\';
1528 }
1529 }
1530 lines.push_back(str.substr(start, end - start));
1531 return lines;
1532}
1533
1534} // namespace
1535
1536// Constructs and returns the message for an equality assertion
1537// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1538//
1539// The first four parameters are the expressions used in the assertion
1540// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1541// where foo is 5 and bar is 6, we have:
1542//
1543// lhs_expression: "foo"
1544// rhs_expression: "bar"
1545// lhs_value: "5"
1546// rhs_value: "6"
1547//
1548// The ignoring_case parameter is true if and only if the assertion is a
1549// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
1550// be inserted into the message.
1551AssertionResult EqFailure(const char* lhs_expression,
1552 const char* rhs_expression,
1553 const std::string& lhs_value,
1554 const std::string& rhs_value, bool ignoring_case) {
1555 Message msg;
1556 msg << "Expected equality of these values:";
1557 msg << "\n " << lhs_expression;
1558 if (lhs_value != lhs_expression) {
1559 msg << "\n Which is: " << lhs_value;
1560 }
1561 msg << "\n " << rhs_expression;
1562 if (rhs_value != rhs_expression) {
1563 msg << "\n Which is: " << rhs_value;
1564 }
1565
1566 if (ignoring_case) {
1567 msg << "\nIgnoring case";
1568 }
1569
1570 if (!lhs_value.empty() && !rhs_value.empty()) {
1571 const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1572 const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1573 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1574 msg << "\nWith diff:\n"
1575 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
1576 }
1577 }
1578
1579 return AssertionFailure() << msg;
1580}
1581
1582// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1584 const AssertionResult& assertion_result, const char* expression_text,
1585 const char* actual_predicate_value, const char* expected_predicate_value) {
1586 const char* actual_message = assertion_result.message();
1587 Message msg;
1588 msg << "Value of: " << expression_text
1589 << "\n Actual: " << actual_predicate_value;
1590 if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
1591 msg << "\nExpected: " << expected_predicate_value;
1592 return msg.GetString();
1593}
1594
1595// Helper function for implementing ASSERT_NEAR.
1596AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
1597 const char* abs_error_expr, double val1,
1598 double val2, double abs_error) {
1599 const double diff = fabs(val1 - val2);
1600 if (diff <= abs_error) return AssertionSuccess();
1601
1602 // Find the value which is closest to zero.
1603 const double min_abs = std::min(fabs(val1), fabs(val2));
1604 // Find the distance to the next double from that value.
1605 const double epsilon =
1606 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1607 // Detect the case where abs_error is so small that EXPECT_NEAR is
1608 // effectively the same as EXPECT_EQUAL, and give an informative error
1609 // message so that the situation can be more easily understood without
1610 // requiring exotic floating-point knowledge.
1611 // Don't do an epsilon check if abs_error is zero because that implies
1612 // that an equality check was actually intended.
1613 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1614 abs_error < epsilon) {
1615 return AssertionFailure()
1616 << "The difference between " << expr1 << " and " << expr2 << " is "
1617 << diff << ", where\n"
1618 << expr1 << " evaluates to " << val1 << ",\n"
1619 << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
1620 << abs_error_expr << " evaluates to " << abs_error
1621 << " which is smaller than the minimum distance between doubles for "
1622 "numbers of this magnitude which is "
1623 << epsilon
1624 << ", thus making this EXPECT_NEAR check equivalent to "
1625 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1626 }
1627 return AssertionFailure()
1628 << "The difference between " << expr1 << " and " << expr2 << " is "
1629 << diff << ", which exceeds " << abs_error_expr << ", where\n"
1630 << expr1 << " evaluates to " << val1 << ",\n"
1631 << expr2 << " evaluates to " << val2 << ", and\n"
1632 << abs_error_expr << " evaluates to " << abs_error << ".";
1633}
1634
1635// Helper template for implementing FloatLE() and DoubleLE().
1636template <typename RawType>
1637AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
1638 RawType val1, RawType val2) {
1639 // Returns success if val1 is less than val2,
1640 if (val1 < val2) {
1641 return AssertionSuccess();
1642 }
1643
1644 // or if val1 is almost equal to val2.
1645 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1646 if (lhs.AlmostEquals(rhs)) {
1647 return AssertionSuccess();
1648 }
1649
1650 // Note that the above two checks will both fail if either val1 or
1651 // val2 is NaN, as the IEEE floating-point standard requires that
1652 // any predicate involving a NaN must return false.
1653
1654 ::std::stringstream val1_ss;
1655 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1656 << val1;
1657
1658 ::std::stringstream val2_ss;
1659 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1660 << val2;
1661
1662 return AssertionFailure()
1663 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1664 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
1665 << StringStreamToString(&val2_ss);
1666}
1667
1668} // namespace internal
1669
1670// Asserts that val1 is less than, or almost equal to, val2. Fails
1671// otherwise. In particular, it fails if either val1 or val2 is NaN.
1672AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
1673 float val2) {
1674 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1675}
1676
1677// Asserts that val1 is less than, or almost equal to, val2. Fails
1678// otherwise. In particular, it fails if either val1 or val2 is NaN.
1679AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
1680 double val2) {
1681 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1682}
1683
1684namespace internal {
1685
1686// The helper function for {ASSERT|EXPECT}_STREQ.
1687AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1688 const char* rhs_expression, const char* lhs,
1689 const char* rhs) {
1690 if (String::CStringEquals(lhs, rhs)) {
1691 return AssertionSuccess();
1692 }
1693
1694 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1695 PrintToString(rhs), false);
1696}
1697
1698// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1699AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
1700 const char* rhs_expression, const char* lhs,
1701 const char* rhs) {
1702 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
1703 return AssertionSuccess();
1704 }
1705
1706 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1707 PrintToString(rhs), true);
1708}
1709
1710// The helper function for {ASSERT|EXPECT}_STRNE.
1711AssertionResult CmpHelperSTRNE(const char* s1_expression,
1712 const char* s2_expression, const char* s1,
1713 const char* s2) {
1714 if (!String::CStringEquals(s1, s2)) {
1715 return AssertionSuccess();
1716 } else {
1717 return AssertionFailure()
1718 << "Expected: (" << s1_expression << ") != (" << s2_expression
1719 << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
1720 }
1721}
1722
1723// The helper function for {ASSERT|EXPECT}_STRCASENE.
1724AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1725 const char* s2_expression, const char* s1,
1726 const char* s2) {
1727 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1728 return AssertionSuccess();
1729 } else {
1730 return AssertionFailure()
1731 << "Expected: (" << s1_expression << ") != (" << s2_expression
1732 << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
1733 }
1734}
1735
1736} // namespace internal
1737
1738namespace {
1739
1740// Helper functions for implementing IsSubString() and IsNotSubstring().
1741
1742// This group of overloaded functions return true if and only if needle
1743// is a substring of haystack. NULL is considered a substring of
1744// itself only.
1745
1746bool IsSubstringPred(const char* needle, const char* haystack) {
1747 if (needle == nullptr || haystack == nullptr) return needle == haystack;
1748
1749 return strstr(haystack, needle) != nullptr;
1750}
1751
1752bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1753 if (needle == nullptr || haystack == nullptr) return needle == haystack;
1754
1755 return wcsstr(haystack, needle) != nullptr;
1756}
1757
1758// StringType here can be either ::std::string or ::std::wstring.
1759template <typename StringType>
1760bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
1761 return haystack.find(needle) != StringType::npos;
1762}
1763
1764// This function implements either IsSubstring() or IsNotSubstring(),
1765// depending on the value of the expected_to_be_substring parameter.
1766// StringType here can be const char*, const wchar_t*, ::std::string,
1767// or ::std::wstring.
1768template <typename StringType>
1769AssertionResult IsSubstringImpl(bool expected_to_be_substring,
1770 const char* needle_expr,
1771 const char* haystack_expr,
1772 const StringType& needle,
1773 const StringType& haystack) {
1774 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1775 return AssertionSuccess();
1776
1777 const bool is_wide_string = sizeof(needle[0]) > 1;
1778 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1779 return AssertionFailure()
1780 << "Value of: " << needle_expr << "\n"
1781 << " Actual: " << begin_string_quote << needle << "\"\n"
1782 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1783 << "a substring of " << haystack_expr << "\n"
1784 << "Which is: " << begin_string_quote << haystack << "\"";
1785}
1786
1787} // namespace
1788
1789// IsSubstring() and IsNotSubstring() check whether needle is a
1790// substring of haystack (NULL is considered a substring of itself
1791// only), and return an appropriate error message when they fail.
1792
1793AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1794 const char* needle, const char* haystack) {
1795 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1796}
1797
1798AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1799 const wchar_t* needle, const wchar_t* haystack) {
1800 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1801}
1802
1803AssertionResult IsNotSubstring(const char* needle_expr,
1804 const char* haystack_expr, const char* needle,
1805 const char* haystack) {
1806 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1807}
1808
1809AssertionResult IsNotSubstring(const char* needle_expr,
1810 const char* haystack_expr, const wchar_t* needle,
1811 const wchar_t* haystack) {
1812 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1813}
1814
1815AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1816 const ::std::string& needle,
1817 const ::std::string& haystack) {
1818 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1819}
1820
1821AssertionResult IsNotSubstring(const char* needle_expr,
1822 const char* haystack_expr,
1823 const ::std::string& needle,
1824 const ::std::string& haystack) {
1825 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1826}
1827
1828#if GTEST_HAS_STD_WSTRING
1829AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1830 const ::std::wstring& needle,
1831 const ::std::wstring& haystack) {
1832 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1833}
1834
1835AssertionResult IsNotSubstring(const char* needle_expr,
1836 const char* haystack_expr,
1837 const ::std::wstring& needle,
1838 const ::std::wstring& haystack) {
1839 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1840}
1841#endif // GTEST_HAS_STD_WSTRING
1842
1843namespace internal {
1844
1845#if GTEST_OS_WINDOWS
1846
1847namespace {
1848
1849// Helper function for IsHRESULT{SuccessFailure} predicates
1850AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
1851 long hr) { // NOLINT
1852#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1853
1854 // Windows CE doesn't support FormatMessage.
1855 const char error_text[] = "";
1856
1857#else
1858
1859 // Looks up the human-readable system message for the HRESULT code
1860 // and since we're not passing any params to FormatMessage, we don't
1861 // want inserts expanded.
1862 const DWORD kFlags =
1863 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1864 const DWORD kBufSize = 4096;
1865 // Gets the system's human readable message string for this HRESULT.
1866 char error_text[kBufSize] = {'\0'};
1867 DWORD message_length = ::FormatMessageA(kFlags,
1868 0, // no source, we're asking system
1869 static_cast<DWORD>(hr), // the error
1870 0, // no line width restrictions
1871 error_text, // output buffer
1872 kBufSize, // buf size
1873 nullptr); // no arguments for inserts
1874 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1875 for (; message_length && IsSpace(error_text[message_length - 1]);
1876 --message_length) {
1877 error_text[message_length - 1] = '\0';
1878 }
1879
1880#endif // GTEST_OS_WINDOWS_MOBILE
1881
1882 const std::string error_hex("0x" + String::FormatHexInt(hr));
1883 return ::testing::AssertionFailure()
1884 << "Expected: " << expr << " " << expected << ".\n"
1885 << " Actual: " << error_hex << " " << error_text << "\n";
1886}
1887
1888} // namespace
1889
1890AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1891 if (SUCCEEDED(hr)) {
1892 return AssertionSuccess();
1893 }
1894 return HRESULTFailureHelper(expr, "succeeds", hr);
1895}
1896
1897AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1898 if (FAILED(hr)) {
1899 return AssertionSuccess();
1900 }
1901 return HRESULTFailureHelper(expr, "fails", hr);
1902}
1903
1904#endif // GTEST_OS_WINDOWS
1905
1906// Utility functions for encoding Unicode text (wide strings) in
1907// UTF-8.
1908
1909// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1910// like this:
1911//
1912// Code-point length Encoding
1913// 0 - 7 bits 0xxxxxxx
1914// 8 - 11 bits 110xxxxx 10xxxxxx
1915// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1916// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1917
1918// The maximum code-point a one-byte UTF-8 sequence can represent.
1919constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
1920
1921// The maximum code-point a two-byte UTF-8 sequence can represent.
1922constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
1923
1924// The maximum code-point a three-byte UTF-8 sequence can represent.
1925constexpr uint32_t kMaxCodePoint3 =
1926 (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
1927
1928// The maximum code-point a four-byte UTF-8 sequence can represent.
1929constexpr uint32_t kMaxCodePoint4 =
1930 (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
1931
1932// Chops off the n lowest bits from a bit pattern. Returns the n
1933// lowest bits. As a side effect, the original bit pattern will be
1934// shifted to the right by n bits.
1935inline uint32_t ChopLowBits(uint32_t* bits, int n) {
1936 const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
1937 *bits >>= n;
1938 return low_bits;
1939}
1940
1941// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1942// code_point parameter is of type uint32_t because wchar_t may not be
1943// wide enough to contain a code point.
1944// If the code_point is not a valid Unicode code point
1945// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1946// to "(Invalid Unicode 0xXXXXXXXX)".
1947std::string CodePointToUtf8(uint32_t code_point) {
1948 if (code_point > kMaxCodePoint4) {
1949 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
1950 }
1951
1952 char str[5]; // Big enough for the largest valid code point.
1953 if (code_point <= kMaxCodePoint1) {
1954 str[1] = '\0';
1955 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1956 } else if (code_point <= kMaxCodePoint2) {
1957 str[2] = '\0';
1958 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1959 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1960 } else if (code_point <= kMaxCodePoint3) {
1961 str[3] = '\0';
1962 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1963 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1964 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1965 } else { // code_point <= kMaxCodePoint4
1966 str[4] = '\0';
1967 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1968 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1969 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1970 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1971 }
1972 return str;
1973}
1974
1975// The following two functions only make sense if the system
1976// uses UTF-16 for wide string encoding. All supported systems
1977// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
1978
1979// Determines if the arguments constitute UTF-16 surrogate pair
1980// and thus should be combined into a single Unicode code point
1981// using CreateCodePointFromUtf16SurrogatePair.
1982inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1983 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
1984 (second & 0xFC00) == 0xDC00;
1985}
1986
1987// Creates a Unicode code point from UTF16 surrogate pair.
1988inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1989 wchar_t second) {
1990 const auto first_u = static_cast<uint32_t>(first);
1991 const auto second_u = static_cast<uint32_t>(second);
1992 const uint32_t mask = (1 << 10) - 1;
1993 return (sizeof(wchar_t) == 2)
1994 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
1995 :
1996 // This function should not be called when the condition is
1997 // false, but we provide a sensible default in case it is.
1998 first_u;
1999}
2000
2001// Converts a wide string to a narrow string in UTF-8 encoding.
2002// The wide string is assumed to have the following encoding:
2003// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
2004// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2005// Parameter str points to a null-terminated wide string.
2006// Parameter num_chars may additionally limit the number
2007// of wchar_t characters processed. -1 is used when the entire string
2008// should be processed.
2009// If the string contains code points that are not valid Unicode code points
2010// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2011// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2012// and contains invalid UTF-16 surrogate pairs, values in those pairs
2013// will be encoded as individual Unicode characters from Basic Normal Plane.
2014std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2015 if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
2016
2017 ::std::stringstream stream;
2018 for (int i = 0; i < num_chars; ++i) {
2019 uint32_t unicode_code_point;
2020
2021 if (str[i] == L'\0') {
2022 break;
2023 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2024 unicode_code_point =
2025 CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
2026 i++;
2027 } else {
2028 unicode_code_point = static_cast<uint32_t>(str[i]);
2029 }
2030
2031 stream << CodePointToUtf8(unicode_code_point);
2032 }
2033 return StringStreamToString(&stream);
2034}
2035
2036// Converts a wide C string to an std::string using the UTF-8 encoding.
2037// NULL will be converted to "(null)".
2038std::string String::ShowWideCString(const wchar_t* wide_c_str) {
2039 if (wide_c_str == nullptr) return "(null)";
2040
2041 return internal::WideStringToUtf8(wide_c_str, -1);
2042}
2043
2044// Compares two wide C strings. Returns true if and only if they have the
2045// same content.
2046//
2047// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2048// C string is considered different to any non-NULL C string,
2049// including the empty string.
2050bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
2051 if (lhs == nullptr) return rhs == nullptr;
2052
2053 if (rhs == nullptr) return false;
2054
2055 return wcscmp(lhs, rhs) == 0;
2056}
2057
2058// Helper function for *_STREQ on wide strings.
2059AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2060 const char* rhs_expression, const wchar_t* lhs,
2061 const wchar_t* rhs) {
2062 if (String::WideCStringEquals(lhs, rhs)) {
2063 return AssertionSuccess();
2064 }
2065
2066 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
2067 PrintToString(rhs), false);
2068}
2069
2070// Helper function for *_STRNE on wide strings.
2071AssertionResult CmpHelperSTRNE(const char* s1_expression,
2072 const char* s2_expression, const wchar_t* s1,
2073 const wchar_t* s2) {
2074 if (!String::WideCStringEquals(s1, s2)) {
2075 return AssertionSuccess();
2076 }
2077
2078 return AssertionFailure()
2079 << "Expected: (" << s1_expression << ") != (" << s2_expression
2080 << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
2081}
2082
2083// Compares two C strings, ignoring case. Returns true if and only if they have
2084// the same content.
2085//
2086// Unlike strcasecmp(), this function can handle NULL argument(s). A
2087// NULL C string is considered different to any non-NULL C string,
2088// including the empty string.
2089bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
2090 if (lhs == nullptr) return rhs == nullptr;
2091 if (rhs == nullptr) return false;
2092 return posix::StrCaseCmp(lhs, rhs) == 0;
2093}
2094
2095// Compares two wide C strings, ignoring case. Returns true if and only if they
2096// have the same content.
2097//
2098// Unlike wcscasecmp(), this function can handle NULL argument(s).
2099// A NULL C string is considered different to any non-NULL wide C string,
2100// including the empty string.
2101// NB: The implementations on different platforms slightly differ.
2102// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2103// environment variable. On GNU platform this method uses wcscasecmp
2104// which compares according to LC_CTYPE category of the current locale.
2105// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2106// current locale.
2107bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2108 const wchar_t* rhs) {
2109 if (lhs == nullptr) return rhs == nullptr;
2110
2111 if (rhs == nullptr) return false;
2112
2113#if GTEST_OS_WINDOWS
2114 return _wcsicmp(lhs, rhs) == 0;
2115#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2116 return wcscasecmp(lhs, rhs) == 0;
2117#else
2118 // Android, Mac OS X and Cygwin don't define wcscasecmp.
2119 // Other unknown OSes may not define it either.
2120 wint_t left, right;
2121 do {
2122 left = towlower(static_cast<wint_t>(*lhs++));
2123 right = towlower(static_cast<wint_t>(*rhs++));
2124 } while (left && left == right);
2125 return left == right;
2126#endif // OS selector
2127}
2128
2129// Returns true if and only if str ends with the given suffix, ignoring case.
2130// Any string is considered to end with an empty suffix.
2131bool String::EndsWithCaseInsensitive(const std::string& str,
2132 const std::string& suffix) {
2133 const size_t str_len = str.length();
2134 const size_t suffix_len = suffix.length();
2135 return (str_len >= suffix_len) &&
2136 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
2137 suffix.c_str());
2138}
2139
2140// Formats an int value as "%02d".
2141std::string String::FormatIntWidth2(int value) {
2142 return FormatIntWidthN(value, 2);
2143}
2144
2145// Formats an int value to given width with leading zeros.
2146std::string String::FormatIntWidthN(int value, int width) {
2147 std::stringstream ss;
2148 ss << std::setfill('0') << std::setw(width) << value;
2149 return ss.str();
2150}
2151
2152// Formats an int value as "%X".
2153std::string String::FormatHexUInt32(uint32_t value) {
2154 std::stringstream ss;
2155 ss << std::hex << std::uppercase << value;
2156 return ss.str();
2157}
2158
2159// Formats an int value as "%X".
2160std::string String::FormatHexInt(int value) {
2161 return FormatHexUInt32(static_cast<uint32_t>(value));
2162}
2163
2164// Formats a byte as "%02X".
2165std::string String::FormatByte(unsigned char value) {
2166 std::stringstream ss;
2167 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
2168 << static_cast<unsigned int>(value);
2169 return ss.str();
2170}
2171
2172// Converts the buffer in a stringstream to an std::string, converting NUL
2173// bytes to "\\0" along the way.
2174std::string StringStreamToString(::std::stringstream* ss) {
2175 const ::std::string& str = ss->str();
2176 const char* const start = str.c_str();
2177 const char* const end = start + str.length();
2178
2179 std::string result;
2180 result.reserve(static_cast<size_t>(2 * (end - start)));
2181 for (const char* ch = start; ch != end; ++ch) {
2182 if (*ch == '\0') {
2183 result += "\\0"; // Replaces NUL with "\\0";
2184 } else {
2185 result += *ch;
2186 }
2187 }
2188
2189 return result;
2190}
2191
2192// Appends the user-supplied message to the Google-Test-generated message.
2193std::string AppendUserMessage(const std::string& gtest_msg,
2194 const Message& user_msg) {
2195 // Appends the user message if it's non-empty.
2196 const std::string user_msg_string = user_msg.GetString();
2197 if (user_msg_string.empty()) {
2198 return gtest_msg;
2199 }
2200 if (gtest_msg.empty()) {
2201 return user_msg_string;
2202 }
2203 return gtest_msg + "\n" + user_msg_string;
2204}
2205
2206} // namespace internal
2207
2208// class TestResult
2209
2210// Creates an empty TestResult.
2211TestResult::TestResult()
2212 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2213
2214// D'tor.
2215TestResult::~TestResult() {}
2216
2217// Returns the i-th test part result among all the results. i can
2218// range from 0 to total_part_count() - 1. If i is not in that range,
2219// aborts the program.
2220const TestPartResult& TestResult::GetTestPartResult(int i) const {
2221 if (i < 0 || i >= total_part_count()) internal::posix::Abort();
2222 return test_part_results_.at(static_cast<size_t>(i));
2223}
2224
2225// Returns the i-th test property. i can range from 0 to
2226// test_property_count() - 1. If i is not in that range, aborts the
2227// program.
2228const TestProperty& TestResult::GetTestProperty(int i) const {
2229 if (i < 0 || i >= test_property_count()) internal::posix::Abort();
2230 return test_properties_.at(static_cast<size_t>(i));
2231}
2232
2233// Clears the test part results.
2234void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
2235
2236// Adds a test part result to the list.
2237void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2238 test_part_results_.push_back(test_part_result);
2239}
2240
2241// Adds a test property to the list. If a property with the same key as the
2242// supplied property is already represented, the value of this test_property
2243// replaces the old value for that key.
2244void TestResult::RecordProperty(const std::string& xml_element,
2245 const TestProperty& test_property) {
2246 if (!ValidateTestProperty(xml_element, test_property)) {
2247 return;
2248 }
2249 internal::MutexLock lock(&test_properties_mutex_);
2250 const std::vector<TestProperty>::iterator property_with_matching_key =
2251 std::find_if(test_properties_.begin(), test_properties_.end(),
2252 internal::TestPropertyKeyIs(test_property.key()));
2253 if (property_with_matching_key == test_properties_.end()) {
2254 test_properties_.push_back(test_property);
2255 return;
2256 }
2257 property_with_matching_key->SetValue(test_property.value());
2258}
2259
2260// The list of reserved attributes used in the <testsuites> element of XML
2261// output.
2262static const char* const kReservedTestSuitesAttributes[] = {
2263 "disabled", "errors", "failures", "name",
2264 "random_seed", "tests", "time", "timestamp"};
2265
2266// The list of reserved attributes used in the <testsuite> element of XML
2267// output.
2268static const char* const kReservedTestSuiteAttributes[] = {
2269 "disabled", "errors", "failures", "name",
2270 "tests", "time", "timestamp", "skipped"};
2271
2272// The list of reserved attributes used in the <testcase> element of XML output.
2273static const char* const kReservedTestCaseAttributes[] = {
2274 "classname", "name", "status", "time",
2275 "type_param", "value_param", "file", "line"};
2276
2277// Use a slightly different set for allowed output to ensure existing tests can
2278// still RecordProperty("result") or "RecordProperty(timestamp")
2279static const char* const kReservedOutputTestCaseAttributes[] = {
2280 "classname", "name", "status", "time", "type_param",
2281 "value_param", "file", "line", "result", "timestamp"};
2282
2283template <size_t kSize>
2284std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2285 return std::vector<std::string>(array, array + kSize);
2286}
2287
2288static std::vector<std::string> GetReservedAttributesForElement(
2289 const std::string& xml_element) {
2290 if (xml_element == "testsuites") {
2292 } else if (xml_element == "testsuite") {
2294 } else if (xml_element == "testcase") {
2296 } else {
2297 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2298 }
2299 // This code is unreachable but some compilers may not realizes that.
2300 return std::vector<std::string>();
2301}
2302
2303// TODO(jdesprez): Merge the two getReserved attributes once skip is improved
2304static std::vector<std::string> GetReservedOutputAttributesForElement(
2305 const std::string& xml_element) {
2306 if (xml_element == "testsuites") {
2308 } else if (xml_element == "testsuite") {
2310 } else if (xml_element == "testcase") {
2312 } else {
2313 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2314 }
2315 // This code is unreachable but some compilers may not realizes that.
2316 return std::vector<std::string>();
2317}
2318
2319static std::string FormatWordList(const std::vector<std::string>& words) {
2320 Message word_list;
2321 for (size_t i = 0; i < words.size(); ++i) {
2322 if (i > 0 && words.size() > 2) {
2323 word_list << ", ";
2324 }
2325 if (i == words.size() - 1) {
2326 word_list << "and ";
2327 }
2328 word_list << "'" << words[i] << "'";
2329 }
2330 return word_list.GetString();
2331}
2332
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_ << ")";
2341 return false;
2342 }
2343 return true;
2344}
2345
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.
2348bool TestResult::ValidateTestProperty(const std::string& xml_element,
2349 const TestProperty& test_property) {
2350 return ValidateTestPropertyName(test_property.key(),
2351 GetReservedAttributesForElement(xml_element));
2352}
2353
2354// Clears the object.
2355void TestResult::Clear() {
2356 test_part_results_.clear();
2357 test_properties_.clear();
2358 death_test_count_ = 0;
2359 elapsed_time_ = 0;
2360}
2361
2362// Returns true off the test part was skipped.
2363static bool TestPartSkipped(const TestPartResult& result) {
2364 return result.skipped();
2365}
2366
2367// Returns true if and only if the test was skipped.
2368bool TestResult::Skipped() const {
2369 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
2370}
2371
2372// Returns true if and only if the test failed.
2373bool TestResult::Failed() const {
2374 for (int i = 0; i < total_part_count(); ++i) {
2375 if (GetTestPartResult(i).failed()) return true;
2376 }
2377 return false;
2378}
2379
2380// Returns true if and only if the test part fatally failed.
2381static bool TestPartFatallyFailed(const TestPartResult& result) {
2382 return result.fatally_failed();
2383}
2384
2385// Returns true if and only if the test fatally failed.
2386bool TestResult::HasFatalFailure() const {
2387 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2388}
2389
2390// Returns true if and only if the test part non-fatally failed.
2391static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2392 return result.nonfatally_failed();
2393}
2394
2395// Returns true if and only if the test has a non-fatal failure.
2396bool TestResult::HasNonfatalFailure() const {
2397 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2398}
2399
2400// Gets the number of all test parts. This is the sum of the number
2401// of successful test parts and the number of failed test parts.
2402int TestResult::total_part_count() const {
2403 return static_cast<int>(test_part_results_.size());
2404}
2405
2406// Returns the number of the test properties.
2407int TestResult::test_property_count() const {
2408 return static_cast<int>(test_properties_.size());
2409}
2410
2411// class Test
2412
2413// Creates a Test object.
2414
2415// The c'tor saves the states of all flags.
2416Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
2417
2418// The d'tor restores the states of all flags. The actual work is
2419// done by the d'tor of the gtest_flag_saver_ field, and thus not
2420// visible here.
2421Test::~Test() {}
2422
2423// Sets up the test fixture.
2424//
2425// A sub-class may override this.
2426void Test::SetUp() {}
2427
2428// Tears down the test fixture.
2429//
2430// A sub-class may override this.
2431void Test::TearDown() {}
2432
2433// Allows user supplied key value pairs to be recorded for later output.
2434void Test::RecordProperty(const std::string& key, const std::string& value) {
2435 UnitTest::GetInstance()->RecordProperty(key, value);
2436}
2437
2438// Allows user supplied key value pairs to be recorded for later output.
2439void Test::RecordProperty(const std::string& key, int value) {
2440 Message value_message;
2441 value_message << value;
2442 RecordProperty(key, value_message.GetString().c_str());
2443}
2444
2445namespace internal {
2446
2447void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2448 const std::string& message) {
2449 // This function is a friend of UnitTest and as such has access to
2450 // AddTestPartResult.
2451 UnitTest::GetInstance()->AddTestPartResult(
2452 result_type,
2453 nullptr, // No info about the source file where the exception occurred.
2454 -1, // We have no info on which line caused the exception.
2455 message,
2456 ""); // No stack trace, either.
2457}
2458
2459} // namespace internal
2460
2461// Google Test requires all tests in the same test suite to use the same test
2462// fixture class. This function checks if the current test has the
2463// same fixture class as the first test in the current test suite. If
2464// yes, it returns true; otherwise it generates a Google Test failure and
2465// returns false.
2466bool Test::HasSameFixtureClass() {
2467 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2468 const TestSuite* const test_suite = impl->current_test_suite();
2469
2470 // Info about the first test in the current test suite.
2471 const TestInfo* const first_test_info = test_suite->test_info_list()[0];
2472 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2473 const char* const first_test_name = first_test_info->name();
2474
2475 // Info about the current test.
2476 const TestInfo* const this_test_info = impl->current_test_info();
2477 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2478 const char* const this_test_name = this_test_info->name();
2479
2480 if (this_fixture_id != first_fixture_id) {
2481 // Is the first test defined using TEST?
2482 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2483 // Is this test defined using TEST?
2484 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2485
2486 if (first_is_TEST || this_is_TEST) {
2487 // Both TEST and TEST_F appear in same test suite, which is incorrect.
2488 // Tell the user how to fix this.
2489
2490 // Gets the name of the TEST and the name of the TEST_F. Note
2491 // that first_is_TEST and this_is_TEST cannot both be true, as
2492 // the fixture IDs are different for the two tests.
2493 const char* const TEST_name =
2494 first_is_TEST ? first_test_name : this_test_name;
2495 const char* const TEST_F_name =
2496 first_is_TEST ? this_test_name : first_test_name;
2497
2498 ADD_FAILURE()
2499 << "All tests in the same test suite must use the same test fixture\n"
2500 << "class, so mixing TEST_F and TEST in the same test suite is\n"
2501 << "illegal. In test suite " << this_test_info->test_suite_name()
2502 << ",\n"
2503 << "test " << TEST_F_name << " is defined using TEST_F but\n"
2504 << "test " << TEST_name << " is defined using TEST. You probably\n"
2505 << "want to change the TEST to TEST_F or move it to another test\n"
2506 << "case.";
2507 } else {
2508 // Two fixture classes with the same name appear in two different
2509 // namespaces, which is not allowed. Tell the user how to fix this.
2510 ADD_FAILURE()
2511 << "All tests in the same test suite must use the same test fixture\n"
2512 << "class. However, in test suite "
2513 << this_test_info->test_suite_name() << ",\n"
2514 << "you defined test " << first_test_name << " and test "
2515 << this_test_name << "\n"
2516 << "using two different test fixture classes. This can happen if\n"
2517 << "the two classes are from different namespaces or translation\n"
2518 << "units and have the same name. You should probably rename one\n"
2519 << "of the classes to put the tests into different test suites.";
2520 }
2521 return false;
2522 }
2523
2524 return true;
2525}
2526
2527#if GTEST_HAS_SEH
2528
2529// Adds an "exception thrown" fatal failure to the current test. This
2530// function returns its result via an output parameter pointer because VC++
2531// prohibits creation of objects with destructors on stack in functions
2532// using __try (see error C2712).
2533static std::string* FormatSehExceptionMessage(DWORD exception_code,
2534 const char* location) {
2535 Message message;
2536 message << "SEH exception with code 0x" << std::setbase(16) << exception_code
2537 << std::setbase(10) << " thrown in " << location << ".";
2538
2539 return new std::string(message.GetString());
2540}
2541
2542#endif // GTEST_HAS_SEH
2543
2544namespace internal {
2545
2546#if GTEST_HAS_EXCEPTIONS
2547
2548// Adds an "exception thrown" fatal failure to the current test.
2549static std::string FormatCxxExceptionMessage(const char* description,
2550 const char* location) {
2551 Message message;
2552 if (description != nullptr) {
2553 message << "C++ exception with description \"" << description << "\"";
2554 } else {
2555 message << "Unknown C++ exception";
2556 }
2557 message << " thrown in " << location << ".";
2558
2559 return message.GetString();
2560}
2561
2562static std::string PrintTestPartResultToString(
2563 const TestPartResult& test_part_result);
2564
2565GoogleTestFailureException::GoogleTestFailureException(
2566 const TestPartResult& failure)
2567 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2568
2569#endif // GTEST_HAS_EXCEPTIONS
2570
2571// We put these helper functions in the internal namespace as IBM's xlC
2572// compiler rejects the code if they were declared static.
2573
2574// Runs the given method and handles SEH exceptions it throws, when
2575// SEH is supported; returns the 0-value for type Result in case of an
2576// SEH exception. (Microsoft compilers cannot handle SEH and C++
2577// exceptions in the same function. Therefore, we provide a separate
2578// wrapper function for handling SEH exceptions.)
2579template <class T, typename Result>
2580Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
2581 const char* location) {
2582#if GTEST_HAS_SEH
2583 __try {
2584 return (object->*method)();
2585 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
2586 GetExceptionCode())) {
2587 // We create the exception message on the heap because VC++ prohibits
2588 // creation of objects with destructors on stack in functions using __try
2589 // (see error C2712).
2590 std::string* exception_message =
2591 FormatSehExceptionMessage(GetExceptionCode(), location);
2592 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2593 *exception_message);
2594 delete exception_message;
2595 return static_cast<Result>(0);
2596 }
2597#else
2598 (void)location;
2599 return (object->*method)();
2600#endif // GTEST_HAS_SEH
2601}
2602
2603// Runs the given method and catches and reports C++ and/or SEH-style
2604// exceptions, if they are supported; returns the 0-value for type
2605// Result in case of an SEH exception.
2606template <class T, typename Result>
2607Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
2608 const char* location) {
2609 // NOTE: The user code can affect the way in which Google Test handles
2610 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2611 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2612 // after the exception is caught and either report or re-throw the
2613 // exception based on the flag's value:
2614 //
2615 // try {
2616 // // Perform the test method.
2617 // } catch (...) {
2618 // if (GTEST_FLAG_GET(catch_exceptions))
2619 // // Report the exception as failure.
2620 // else
2621 // throw; // Re-throws the original exception.
2622 // }
2623 //
2624 // However, the purpose of this flag is to allow the program to drop into
2625 // the debugger when the exception is thrown. On most platforms, once the
2626 // control enters the catch block, the exception origin information is
2627 // lost and the debugger will stop the program at the point of the
2628 // re-throw in this function -- instead of at the point of the original
2629 // throw statement in the code under test. For this reason, we perform
2630 // the check early, sacrificing the ability to affect Google Test's
2631 // exception handling in the method where the exception is thrown.
2632 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2633#if GTEST_HAS_EXCEPTIONS
2634 try {
2635 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2636 } catch (const AssertionException&) { // NOLINT
2637 // This failure was reported already.
2638 } catch (const internal::GoogleTestFailureException&) { // NOLINT
2639 // This exception type can only be thrown by a failed Google
2640 // Test assertion with the intention of letting another testing
2641 // framework catch it. Therefore we just re-throw it.
2642 throw;
2643 } catch (const std::exception& e) { // NOLINT
2645 TestPartResult::kFatalFailure,
2646 FormatCxxExceptionMessage(e.what(), location));
2647 } catch (...) { // NOLINT
2649 TestPartResult::kFatalFailure,
2650 FormatCxxExceptionMessage(nullptr, location));
2651 }
2652 return static_cast<Result>(0);
2653#else
2654 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2655#endif // GTEST_HAS_EXCEPTIONS
2656 } else {
2657 return (object->*method)();
2658 }
2659}
2660
2661} // namespace internal
2662
2663// Runs the test and updates the test result.
2664void Test::Run() {
2665 if (!HasSameFixtureClass()) return;
2666
2667 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2668 impl->os_stack_trace_getter()->UponLeavingGTest();
2669 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2670 // We will run the test only if SetUp() was successful and didn't call
2671 // GTEST_SKIP().
2672 if (!HasFatalFailure() && !IsSkipped()) {
2673 impl->os_stack_trace_getter()->UponLeavingGTest();
2674 internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
2675 "the test body");
2676 }
2677
2678 // However, we want to clean up as much as possible. Hence we will
2679 // always call TearDown(), even if SetUp() or the test body has
2680 // failed.
2681 impl->os_stack_trace_getter()->UponLeavingGTest();
2682 internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
2683 "TearDown()");
2684}
2685
2686// Returns true if and only if the current test has a fatal failure.
2687bool Test::HasFatalFailure() {
2688 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2689}
2690
2691// Returns true if and only if the current test has a non-fatal failure.
2692bool Test::HasNonfatalFailure() {
2693 return internal::GetUnitTestImpl()
2694 ->current_test_result()
2695 ->HasNonfatalFailure();
2696}
2697
2698// Returns true if and only if the current test was skipped.
2699bool Test::IsSkipped() {
2700 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2701}
2702
2703// class TestInfo
2704
2705// Constructs a TestInfo object. It assumes ownership of the test factory
2706// object.
2707TestInfo::TestInfo(const std::string& a_test_suite_name,
2708 const std::string& a_name, const char* a_type_param,
2709 const char* a_value_param,
2710 internal::CodeLocation a_code_location,
2711 internal::TypeId fixture_class_id,
2712 internal::TestFactoryBase* factory)
2713 : test_suite_name_(a_test_suite_name),
2714 name_(a_name),
2715 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2716 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
2717 location_(a_code_location),
2718 fixture_class_id_(fixture_class_id),
2719 should_run_(false),
2720 is_disabled_(false),
2721 matches_filter_(false),
2722 is_in_another_shard_(false),
2723 factory_(factory),
2724 result_() {}
2725
2726// Destructs a TestInfo object.
2727TestInfo::~TestInfo() { delete factory_; }
2728
2729namespace internal {
2730
2731// Creates a new TestInfo object and registers it with Google Test;
2732// returns the created object.
2733//
2734// Arguments:
2735//
2736// test_suite_name: name of the test suite
2737// name: name of the test
2738// type_param: the name of the test's type parameter, or NULL if
2739// this is not a typed or a type-parameterized test.
2740// value_param: text representation of the test's value parameter,
2741// or NULL if this is not a value-parameterized test.
2742// code_location: code location where the test is defined
2743// fixture_class_id: ID of the test fixture class
2744// set_up_tc: pointer to the function that sets up the test suite
2745// tear_down_tc: pointer to the function that tears down the test suite
2746// factory: pointer to the factory that creates a test object.
2747// The newly created TestInfo instance will assume
2748// ownership of the factory object.
2750 const char* test_suite_name, const char* name, const char* type_param,
2751 const char* value_param, CodeLocation code_location,
2752 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
2753 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
2754 TestInfo* const test_info =
2755 new TestInfo(test_suite_name, name, type_param, value_param,
2756 code_location, fixture_class_id, factory);
2757 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2758 return test_info;
2759}
2760
2761void ReportInvalidTestSuiteType(const char* test_suite_name,
2762 CodeLocation code_location) {
2763 Message errors;
2764 errors
2765 << "Attempted redefinition of test suite " << test_suite_name << ".\n"
2766 << "All tests in the same test suite must use the same test fixture\n"
2767 << "class. However, in test suite " << test_suite_name << ", you tried\n"
2768 << "to define a test using a fixture class different from the one\n"
2769 << "used earlier. This can happen if the two fixture classes are\n"
2770 << "from different namespaces and have the same name. You should\n"
2771 << "probably rename one of the classes to put the tests into different\n"
2772 << "test suites.";
2773
2774 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2775 code_location.line)
2776 << " " << errors.GetString();
2777}
2778} // namespace internal
2779
2780namespace {
2781
2782// A predicate that checks the test name of a TestInfo against a known
2783// value.
2784//
2785// This is used for implementation of the TestSuite class only. We put
2786// it in the anonymous namespace to prevent polluting the outer
2787// namespace.
2788//
2789// TestNameIs is copyable.
2790class TestNameIs {
2791 public:
2792 // Constructor.
2793 //
2794 // TestNameIs has NO default constructor.
2795 explicit TestNameIs(const char* name) : name_(name) {}
2796
2797 // Returns true if and only if the test name of test_info matches name_.
2798 bool operator()(const TestInfo* test_info) const {
2799 return test_info && test_info->name() == name_;
2800 }
2801
2802 private:
2803 std::string name_;
2804};
2805
2806} // namespace
2807
2808namespace internal {
2809
2810// This method expands all parameterized tests registered with macros TEST_P
2811// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
2812// This will be done just once during the program runtime.
2814 if (!parameterized_tests_registered_) {
2815 parameterized_test_registry_.RegisterTests();
2816 type_parameterized_test_registry_.CheckForInstantiations();
2817 parameterized_tests_registered_ = true;
2818 }
2819}
2820
2821} // namespace internal
2822
2823// Creates the test object, runs it, records its result, and then
2824// deletes it.
2825void TestInfo::Run() {
2826 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2827 if (!should_run_) {
2828 if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this);
2829 return;
2830 }
2831
2832 // Tells UnitTest where to store test result.
2833 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2834 impl->set_current_test_info(this);
2835
2836 // Notifies the unit test event listeners that a test is about to start.
2837 repeater->OnTestStart(*this);
2838 result_.set_start_timestamp(internal::GetTimeInMillis());
2839 internal::Timer timer;
2840 impl->os_stack_trace_getter()->UponLeavingGTest();
2841
2842 // Creates the test object.
2844 factory_, &internal::TestFactoryBase::CreateTest,
2845 "the test fixture's constructor");
2846
2847 // Runs the test if the constructor didn't generate a fatal failure or invoke
2848 // GTEST_SKIP().
2849 // Note that the object will not be null
2850 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2851 // This doesn't throw as all user code that can throw are wrapped into
2852 // exception handling code.
2853 test->Run();
2854 }
2855
2856 if (test != nullptr) {
2857 // Deletes the test object.
2858 impl->os_stack_trace_getter()->UponLeavingGTest();
2860 test, &Test::DeleteSelf_, "the test fixture's destructor");
2861 }
2862
2863 result_.set_elapsed_time(timer.Elapsed());
2864
2865 // Notifies the unit test event listener that a test has just finished.
2866 repeater->OnTestEnd(*this);
2867
2868 // Tells UnitTest to stop associating assertion results to this
2869 // test.
2870 impl->set_current_test_info(nullptr);
2871}
2872
2873// Skip and records a skipped test result for this object.
2874void TestInfo::Skip() {
2875 if (!should_run_) return;
2876
2877 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2878 impl->set_current_test_info(this);
2879
2880 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2881
2882 // Notifies the unit test event listeners that a test is about to start.
2883 repeater->OnTestStart(*this);
2884
2885 const TestPartResult test_part_result =
2886 TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
2887 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
2888 test_part_result);
2889
2890 // Notifies the unit test event listener that a test has just finished.
2891 repeater->OnTestEnd(*this);
2892 impl->set_current_test_info(nullptr);
2893}
2894
2895// class TestSuite
2896
2897// Gets the number of successful tests in this test suite.
2898int TestSuite::successful_test_count() const {
2899 return CountIf(test_info_list_, TestPassed);
2900}
2901
2902// Gets the number of successful tests in this test suite.
2903int TestSuite::skipped_test_count() const {
2904 return CountIf(test_info_list_, TestSkipped);
2905}
2906
2907// Gets the number of failed tests in this test suite.
2908int TestSuite::failed_test_count() const {
2909 return CountIf(test_info_list_, TestFailed);
2910}
2911
2912// Gets the number of disabled tests that will be reported in the XML report.
2913int TestSuite::reportable_disabled_test_count() const {
2914 return CountIf(test_info_list_, TestReportableDisabled);
2915}
2916
2917// Gets the number of disabled tests in this test suite.
2918int TestSuite::disabled_test_count() const {
2919 return CountIf(test_info_list_, TestDisabled);
2920}
2921
2922// Gets the number of tests to be printed in the XML report.
2923int TestSuite::reportable_test_count() const {
2924 return CountIf(test_info_list_, TestReportable);
2925}
2926
2927// Get the number of tests in this test suite that should run.
2928int TestSuite::test_to_run_count() const {
2929 return CountIf(test_info_list_, ShouldRunTest);
2930}
2931
2932// Gets the number of all tests.
2933int TestSuite::total_test_count() const {
2934 return static_cast<int>(test_info_list_.size());
2935}
2936
2937// Creates a TestSuite with the given name.
2938//
2939// Arguments:
2940//
2941// a_name: name of the test suite
2942// a_type_param: the name of the test suite's type parameter, or NULL if
2943// this is not a typed or a type-parameterized test suite.
2944// set_up_tc: pointer to the function that sets up the test suite
2945// tear_down_tc: pointer to the function that tears down the test suite
2946TestSuite::TestSuite(const char* a_name, const char* a_type_param,
2947 internal::SetUpTestSuiteFunc set_up_tc,
2948 internal::TearDownTestSuiteFunc tear_down_tc)
2949 : name_(a_name),
2950 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2951 set_up_tc_(set_up_tc),
2952 tear_down_tc_(tear_down_tc),
2953 should_run_(false),
2954 start_timestamp_(0),
2955 elapsed_time_(0) {}
2956
2957// Destructor of TestSuite.
2958TestSuite::~TestSuite() {
2959 // Deletes every Test in the collection.
2960 ForEach(test_info_list_, internal::Delete<TestInfo>);
2961}
2962
2963// Returns the i-th test among all the tests. i can range from 0 to
2964// total_test_count() - 1. If i is not in that range, returns NULL.
2965const TestInfo* TestSuite::GetTestInfo(int i) const {
2966 const int index = GetElementOr(test_indices_, i, -1);
2967 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2968}
2969
2970// Returns the i-th test among all the tests. i can range from 0 to
2971// total_test_count() - 1. If i is not in that range, returns NULL.
2972TestInfo* TestSuite::GetMutableTestInfo(int i) {
2973 const int index = GetElementOr(test_indices_, i, -1);
2974 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2975}
2976
2977// Adds a test to this test suite. Will delete the test upon
2978// destruction of the TestSuite object.
2979void TestSuite::AddTestInfo(TestInfo* test_info) {
2980 test_info_list_.push_back(test_info);
2981 test_indices_.push_back(static_cast<int>(test_indices_.size()));
2982}
2983
2984// Runs every test in this TestSuite.
2985void TestSuite::Run() {
2986 if (!should_run_) return;
2987
2988 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2989 impl->set_current_test_suite(this);
2990
2991 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2992
2993 // Call both legacy and the new API
2994 repeater->OnTestSuiteStart(*this);
2995// Legacy API is deprecated but still available
2996#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2997 repeater->OnTestCaseStart(*this);
2998#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2999
3000 impl->os_stack_trace_getter()->UponLeavingGTest();
3002 this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
3003
3004 const bool skip_all = ad_hoc_test_result().Failed();
3005
3006 start_timestamp_ = internal::GetTimeInMillis();
3007 internal::Timer timer;
3008 for (int i = 0; i < total_test_count(); i++) {
3009 if (skip_all) {
3010 GetMutableTestInfo(i)->Skip();
3011 } else {
3012 GetMutableTestInfo(i)->Run();
3013 }
3014 if (GTEST_FLAG_GET(fail_fast) &&
3015 GetMutableTestInfo(i)->result()->Failed()) {
3016 for (int j = i + 1; j < total_test_count(); j++) {
3017 GetMutableTestInfo(j)->Skip();
3018 }
3019 break;
3020 }
3021 }
3022 elapsed_time_ = timer.Elapsed();
3023
3024 impl->os_stack_trace_getter()->UponLeavingGTest();
3026 this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
3027
3028 // Call both legacy and the new API
3029 repeater->OnTestSuiteEnd(*this);
3030// Legacy API is deprecated but still available
3031#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3032 repeater->OnTestCaseEnd(*this);
3033#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3034
3035 impl->set_current_test_suite(nullptr);
3036}
3037
3038// Skips all tests under this TestSuite.
3039void TestSuite::Skip() {
3040 if (!should_run_) return;
3041
3042 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3043 impl->set_current_test_suite(this);
3044
3045 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3046
3047 // Call both legacy and the new API
3048 repeater->OnTestSuiteStart(*this);
3049// Legacy API is deprecated but still available
3050#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3051 repeater->OnTestCaseStart(*this);
3052#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3053
3054 for (int i = 0; i < total_test_count(); i++) {
3055 GetMutableTestInfo(i)->Skip();
3056 }
3057
3058 // Call both legacy and the new API
3059 repeater->OnTestSuiteEnd(*this);
3060 // Legacy API is deprecated but still available
3061#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3062 repeater->OnTestCaseEnd(*this);
3063#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3064
3065 impl->set_current_test_suite(nullptr);
3066}
3067
3068// Clears the results of all tests in this test suite.
3069void TestSuite::ClearResult() {
3070 ad_hoc_test_result_.Clear();
3071 ForEach(test_info_list_, TestInfo::ClearTestResult);
3072}
3073
3074// Shuffles the tests in this test suite.
3075void TestSuite::ShuffleTests(internal::Random* random) {
3076 Shuffle(random, &test_indices_);
3077}
3078
3079// Restores the test order to before the first shuffle.
3080void TestSuite::UnshuffleTests() {
3081 for (size_t i = 0; i < test_indices_.size(); i++) {
3082 test_indices_[i] = static_cast<int>(i);
3083 }
3084}
3085
3086// Formats a countable noun. Depending on its quantity, either the
3087// singular form or the plural form is used. e.g.
3088//
3089// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3090// FormatCountableNoun(5, "book", "books") returns "5 books".
3091static std::string FormatCountableNoun(int count, const char* singular_form,
3092 const char* plural_form) {
3093 return internal::StreamableToString(count) + " " +
3094 (count == 1 ? singular_form : plural_form);
3095}
3096
3097// Formats the count of tests.
3098static std::string FormatTestCount(int test_count) {
3099 return FormatCountableNoun(test_count, "test", "tests");
3100}
3101
3102// Formats the count of test suites.
3103static std::string FormatTestSuiteCount(int test_suite_count) {
3104 return FormatCountableNoun(test_suite_count, "test suite", "test suites");
3105}
3106
3107// Converts a TestPartResult::Type enum to human-friendly string
3108// representation. Both kNonFatalFailure and kFatalFailure are translated
3109// to "Failure", as the user usually doesn't care about the difference
3110// between the two when viewing the test result.
3111static const char* TestPartResultTypeToString(TestPartResult::Type type) {
3112 switch (type) {
3113 case TestPartResult::kSkip:
3114 return "Skipped\n";
3115 case TestPartResult::kSuccess:
3116 return "Success";
3117
3118 case TestPartResult::kNonFatalFailure:
3119 case TestPartResult::kFatalFailure:
3120#ifdef _MSC_VER
3121 return "error: ";
3122#else
3123 return "Failure\n";
3124#endif
3125 default:
3126 return "Unknown result type";
3127 }
3128}
3129
3130namespace internal {
3131namespace {
3132enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3133} // namespace
3134
3135// Prints a TestPartResult to an std::string.
3137 const TestPartResult& test_part_result) {
3138 return (Message() << internal::FormatFileLocation(
3139 test_part_result.file_name(),
3140 test_part_result.line_number())
3141 << " "
3142 << TestPartResultTypeToString(test_part_result.type())
3143 << test_part_result.message())
3144 .GetString();
3145}
3146
3147// Prints a TestPartResult.
3148static void PrintTestPartResult(const TestPartResult& test_part_result) {
3149 const std::string& result = PrintTestPartResultToString(test_part_result);
3150 printf("%s\n", result.c_str());
3151 fflush(stdout);
3152 // If the test program runs in Visual Studio or a debugger, the
3153 // following statements add the test part result message to the Output
3154 // window such that the user can double-click on it to jump to the
3155 // corresponding source code location; otherwise they do nothing.
3156#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3157 // We don't call OutputDebugString*() on Windows Mobile, as printing
3158 // to stdout is done by OutputDebugString() there already - we don't
3159 // want the same message printed twice.
3160 ::OutputDebugStringA(result.c_str());
3161 ::OutputDebugStringA("\n");
3162#endif
3163}
3164
3165// class PrettyUnitTestResultPrinter
3166#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3167 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3168
3169// Returns the character attribute for the given color.
3170static WORD GetColorAttribute(GTestColor color) {
3171 switch (color) {
3172 case GTestColor::kRed:
3173 return FOREGROUND_RED;
3174 case GTestColor::kGreen:
3175 return FOREGROUND_GREEN;
3176 case GTestColor::kYellow:
3177 return FOREGROUND_RED | FOREGROUND_GREEN;
3178 default:
3179 return 0;
3180 }
3181}
3182
3183static int GetBitOffset(WORD color_mask) {
3184 if (color_mask == 0) return 0;
3185
3186 int bitOffset = 0;
3187 while ((color_mask & 1) == 0) {
3188 color_mask >>= 1;
3189 ++bitOffset;
3190 }
3191 return bitOffset;
3192}
3193
3194static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3195 // Let's reuse the BG
3196 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3197 BACKGROUND_RED | BACKGROUND_INTENSITY;
3198 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3199 FOREGROUND_RED | FOREGROUND_INTENSITY;
3200 const WORD existing_bg = old_color_attrs & background_mask;
3201
3202 WORD new_color =
3203 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3204 static const int bg_bitOffset = GetBitOffset(background_mask);
3205 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3206
3207 if (((new_color & background_mask) >> bg_bitOffset) ==
3208 ((new_color & foreground_mask) >> fg_bitOffset)) {
3209 new_color ^= FOREGROUND_INTENSITY; // invert intensity
3210 }
3211 return new_color;
3212}
3213
3214#else
3215
3216// Returns the ANSI color code for the given color. GTestColor::kDefault is
3217// an invalid input.
3218static const char* GetAnsiColorCode(GTestColor color) {
3219 switch (color) {
3220 case GTestColor::kRed:
3221 return "1";
3222 case GTestColor::kGreen:
3223 return "2";
3224 case GTestColor::kYellow:
3225 return "3";
3226 default:
3227 return nullptr;
3228 }
3229}
3230
3231#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3232
3233// Returns true if and only if Google Test should use colors in the output.
3234bool ShouldUseColor(bool stdout_is_tty) {
3235 std::string c = GTEST_FLAG_GET(color);
3236 const char* const gtest_color = c.c_str();
3237
3238 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3239#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
3240 // On Windows the TERM variable is usually not set, but the
3241 // console there does support colors.
3242 return stdout_is_tty;
3243#else
3244 // On non-Windows platforms, we rely on the TERM variable.
3245 const char* const term = posix::GetEnv("TERM");
3246 const bool term_supports_color =
3247 String::CStringEquals(term, "xterm") ||
3248 String::CStringEquals(term, "xterm-color") ||
3249 String::CStringEquals(term, "xterm-256color") ||
3250 String::CStringEquals(term, "screen") ||
3251 String::CStringEquals(term, "screen-256color") ||
3252 String::CStringEquals(term, "tmux") ||
3253 String::CStringEquals(term, "tmux-256color") ||
3254 String::CStringEquals(term, "rxvt-unicode") ||
3255 String::CStringEquals(term, "rxvt-unicode-256color") ||
3256 String::CStringEquals(term, "linux") ||
3257 String::CStringEquals(term, "cygwin");
3258 return stdout_is_tty && term_supports_color;
3259#endif // GTEST_OS_WINDOWS
3260 }
3261
3262 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3263 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3264 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3265 String::CStringEquals(gtest_color, "1");
3266 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3267 // value is neither one of these nor "auto", we treat it as "no" to
3268 // be conservative.
3269}
3270
3271// Helpers for printing colored strings to stdout. Note that on Windows, we
3272// cannot simply emit special characters and have the terminal change colors.
3273// This routine must actually emit the characters rather than return a string
3274// that would be colored when printed, as can be done on Linux.
3275
3276GTEST_ATTRIBUTE_PRINTF_(2, 3)
3277static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3278 va_list args;
3279 va_start(args, fmt);
3280
3281 static const bool in_color_mode =
3282 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3283 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3284
3285 if (!use_color) {
3286 vprintf(fmt, args);
3287 va_end(args);
3288 return;
3289 }
3290
3291#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3292 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3293 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3294
3295 // Gets the current text color.
3296 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3297 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3298 const WORD old_color_attrs = buffer_info.wAttributes;
3299 const WORD new_color = GetNewColor(color, old_color_attrs);
3300
3301 // We need to flush the stream buffers into the console before each
3302 // SetConsoleTextAttribute call lest it affect the text that is already
3303 // printed but has not yet reached the console.
3304 fflush(stdout);
3305 SetConsoleTextAttribute(stdout_handle, new_color);
3306
3307 vprintf(fmt, args);
3308
3309 fflush(stdout);
3310 // Restores the text color.
3311 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3312#else
3313 printf("\033[0;3%sm", GetAnsiColorCode(color));
3314 vprintf(fmt, args);
3315 printf("\033[m"); // Resets the terminal to default.
3316#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3317 va_end(args);
3318}
3319
3320// Text printed in Google Test's text output and --gtest_list_tests
3321// output to label the type parameter and value parameter for a test.
3322static const char kTypeParamLabel[] = "TypeParam";
3323static const char kValueParamLabel[] = "GetParam()";
3324
3325static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3326 const char* const type_param = test_info.type_param();
3327 const char* const value_param = test_info.value_param();
3328
3329 if (type_param != nullptr || value_param != nullptr) {
3330 printf(", where ");
3331 if (type_param != nullptr) {
3332 printf("%s = %s", kTypeParamLabel, type_param);
3333 if (value_param != nullptr) printf(" and ");
3334 }
3335 if (value_param != nullptr) {
3336 printf("%s = %s", kValueParamLabel, value_param);
3337 }
3338 }
3339}
3340
3341// This class implements the TestEventListener interface.
3342//
3343// Class PrettyUnitTestResultPrinter is copyable.
3344class PrettyUnitTestResultPrinter : public TestEventListener {
3345 public:
3347 static void PrintTestName(const char* test_suite, const char* test) {
3348 printf("%s.%s", test_suite, test);
3349 }
3350
3351 // The following methods override what's in the TestEventListener class.
3352 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
3353 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3354 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
3355 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
3356#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3357 void OnTestCaseStart(const TestCase& test_case) override;
3358#else
3359 void OnTestSuiteStart(const TestSuite& test_suite) override;
3360#endif // OnTestCaseStart
3361
3362 void OnTestStart(const TestInfo& test_info) override;
3363 void OnTestDisabled(const TestInfo& test_info) override;
3364
3365 void OnTestPartResult(const TestPartResult& result) override;
3366 void OnTestEnd(const TestInfo& test_info) override;
3367#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3368 void OnTestCaseEnd(const TestCase& test_case) override;
3369#else
3370 void OnTestSuiteEnd(const TestSuite& test_suite) override;
3371#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3372
3373 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
3374 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
3375 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3376 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
3377
3378 private:
3379 static void PrintFailedTests(const UnitTest& unit_test);
3380 static void PrintFailedTestSuites(const UnitTest& unit_test);
3381 static void PrintSkippedTests(const UnitTest& unit_test);
3382};
3383
3384// Fired before each iteration of tests starts.
3385void PrettyUnitTestResultPrinter::OnTestIterationStart(
3386 const UnitTest& unit_test, int iteration) {
3387 if (GTEST_FLAG_GET(repeat) != 1)
3388 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3389
3390 std::string f = GTEST_FLAG_GET(filter);
3391 const char* const filter = f.c_str();
3392
3393 // Prints the filter if it's not *. This reminds the user that some
3394 // tests may be skipped.
3395 if (!String::CStringEquals(filter, kUniversalFilter)) {
3396 ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
3397 filter);
3398 }
3399
3400 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3401 const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3402 ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
3403 static_cast<int>(shard_index) + 1,
3404 internal::posix::GetEnv(kTestTotalShards));
3405 }
3406
3407 if (GTEST_FLAG_GET(shuffle)) {
3408 ColoredPrintf(GTestColor::kYellow,
3409 "Note: Randomizing tests' orders with a seed of %d .\n",
3410 unit_test.random_seed());
3411 }
3412
3413 ColoredPrintf(GTestColor::kGreen, "[==========] ");
3414 printf("Running %s from %s.\n",
3415 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3416 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3417 fflush(stdout);
3418}
3419
3420void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3421 const UnitTest& /*unit_test*/) {
3422 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3423 printf("Global test environment set-up.\n");
3424 fflush(stdout);
3425}
3426
3427#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3428void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
3429 const std::string counts =
3430 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3431 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3432 printf("%s from %s", counts.c_str(), test_case.name());
3433 if (test_case.type_param() == nullptr) {
3434 printf("\n");
3435 } else {
3436 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3437 }
3438 fflush(stdout);
3439}
3440#else
3441void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3442 const TestSuite& test_suite) {
3443 const std::string counts =
3444 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3445 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3446 printf("%s from %s", counts.c_str(), test_suite.name());
3447 if (test_suite.type_param() == nullptr) {
3448 printf("\n");
3449 } else {
3450 printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
3451 }
3452 fflush(stdout);
3453}
3454#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3455
3456void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
3457 ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
3458 PrintTestName(test_info.test_suite_name(), test_info.name());
3459 printf("\n");
3460 fflush(stdout);
3461}
3462
3463void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) {
3464 ColoredPrintf(GTestColor::kYellow, "[ DISABLED ] ");
3465 PrintTestName(test_info.test_suite_name(), test_info.name());
3466 printf("\n");
3467 fflush(stdout);
3468}
3469
3470// Called after an assertion failure.
3471void PrettyUnitTestResultPrinter::OnTestPartResult(
3472 const TestPartResult& result) {
3473 switch (result.type()) {
3474 // If the test part succeeded, we don't need to do anything.
3475 case TestPartResult::kSuccess:
3476 return;
3477 default:
3478 // Print failure message from the assertion
3479 // (e.g. expected this and got that).
3480 PrintTestPartResult(result);
3481 fflush(stdout);
3482 }
3483}
3484
3485void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3486 if (test_info.result()->Passed()) {
3487 ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
3488 } else if (test_info.result()->Skipped()) {
3489 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3490 } else {
3491 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3492 }
3493 PrintTestName(test_info.test_suite_name(), test_info.name());
3494 if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
3495
3496 if (GTEST_FLAG_GET(print_time)) {
3497 printf(" (%s ms)\n",
3498 internal::StreamableToString(test_info.result()->elapsed_time())
3499 .c_str());
3500 } else {
3501 printf("\n");
3502 }
3503 fflush(stdout);
3504}
3505
3506#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3507void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
3508 if (!GTEST_FLAG_GET(print_time)) return;
3509
3510 const std::string counts =
3511 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3512 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3513 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
3514 internal::StreamableToString(test_case.elapsed_time()).c_str());
3515 fflush(stdout);
3516}
3517#else
3518void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
3519 if (!GTEST_FLAG_GET(print_time)) return;
3520
3521 const std::string counts =
3522 FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3523 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3524 printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
3525 internal::StreamableToString(test_suite.elapsed_time()).c_str());
3526 fflush(stdout);
3527}
3528#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3529
3530void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3531 const UnitTest& /*unit_test*/) {
3532 ColoredPrintf(GTestColor::kGreen, "[----------] ");
3533 printf("Global test environment tear-down\n");
3534 fflush(stdout);
3535}
3536
3537// Internal helper for printing the list of failed tests.
3538void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3539 const int failed_test_count = unit_test.failed_test_count();
3540 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3541 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3542
3543 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3544 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3545 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
3546 continue;
3547 }
3548 for (int j = 0; j < test_suite.total_test_count(); ++j) {
3549 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3550 if (!test_info.should_run() || !test_info.result()->Failed()) {
3551 continue;
3552 }
3553 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3554 printf("%s.%s", test_suite.name(), test_info.name());
3555 PrintFullTestCommentIfPresent(test_info);
3556 printf("\n");
3557 }
3558 }
3559 printf("\n%2d FAILED %s\n", failed_test_count,
3560 failed_test_count == 1 ? "TEST" : "TESTS");
3561}
3562
3563// Internal helper for printing the list of test suite failures not covered by
3564// PrintFailedTests.
3565void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3566 const UnitTest& unit_test) {
3567 int suite_failure_count = 0;
3568 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3569 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3570 if (!test_suite.should_run()) {
3571 continue;
3572 }
3573 if (test_suite.ad_hoc_test_result().Failed()) {
3574 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3575 printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
3576 ++suite_failure_count;
3577 }
3578 }
3579 if (suite_failure_count > 0) {
3580 printf("\n%2d FAILED TEST %s\n", suite_failure_count,
3581 suite_failure_count == 1 ? "SUITE" : "SUITES");
3582 }
3583}
3584
3585// Internal helper for printing the list of skipped tests.
3586void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
3587 const int skipped_test_count = unit_test.skipped_test_count();
3588 if (skipped_test_count == 0) {
3589 return;
3590 }
3591
3592 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3593 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3594 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3595 continue;
3596 }
3597 for (int j = 0; j < test_suite.total_test_count(); ++j) {
3598 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3599 if (!test_info.should_run() || !test_info.result()->Skipped()) {
3600 continue;
3601 }
3602 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3603 printf("%s.%s", test_suite.name(), test_info.name());
3604 printf("\n");
3605 }
3606 }
3607}
3608
3609void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3610 int /*iteration*/) {
3611 ColoredPrintf(GTestColor::kGreen, "[==========] ");
3612 printf("%s from %s ran.",
3613 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3614 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3615 if (GTEST_FLAG_GET(print_time)) {
3616 printf(" (%s ms total)",
3617 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3618 }
3619 printf("\n");
3620 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
3621 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3622
3623 const int skipped_test_count = unit_test.skipped_test_count();
3624 if (skipped_test_count > 0) {
3625 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3626 printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
3627 PrintSkippedTests(unit_test);
3628 }
3629
3630 if (!unit_test.Passed()) {
3631 PrintFailedTests(unit_test);
3632 PrintFailedTestSuites(unit_test);
3633 }
3634
3635 int num_disabled = unit_test.reportable_disabled_test_count();
3636 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3637 if (unit_test.Passed()) {
3638 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3639 }
3640 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
3641 num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
3642 }
3643 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3644 fflush(stdout);
3645}
3646
3647// End PrettyUnitTestResultPrinter
3648
3649// This class implements the TestEventListener interface.
3650//
3651// Class BriefUnitTestResultPrinter is copyable.
3652class BriefUnitTestResultPrinter : public TestEventListener {
3653 public:
3655 static void PrintTestName(const char* test_suite, const char* test) {
3656 printf("%s.%s", test_suite, test);
3657 }
3658
3659 // The following methods override what's in the TestEventListener class.
3660 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
3661 void OnTestIterationStart(const UnitTest& /*unit_test*/,
3662 int /*iteration*/) override {}
3663 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
3664 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
3665#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3666 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
3667#else
3668 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
3669#endif // OnTestCaseStart
3670
3671 void OnTestStart(const TestInfo& /*test_info*/) override {}
3672 void OnTestDisabled(const TestInfo& /*test_info*/) override {}
3673
3674 void OnTestPartResult(const TestPartResult& result) override;
3675 void OnTestEnd(const TestInfo& test_info) override;
3676#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3677 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
3678#else
3679 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
3680#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3681
3682 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
3683 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
3684 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3685 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
3686};
3687
3688// Called after an assertion failure.
3689void BriefUnitTestResultPrinter::OnTestPartResult(
3690 const TestPartResult& result) {
3691 switch (result.type()) {
3692 // If the test part succeeded, we don't need to do anything.
3693 case TestPartResult::kSuccess:
3694 return;
3695 default:
3696 // Print failure message from the assertion
3697 // (e.g. expected this and got that).
3698 PrintTestPartResult(result);
3699 fflush(stdout);
3700 }
3701}
3702
3703void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3704 if (test_info.result()->Failed()) {
3705 ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3706 PrintTestName(test_info.test_suite_name(), test_info.name());
3708
3709 if (GTEST_FLAG_GET(print_time)) {
3710 printf(" (%s ms)\n",
3711 internal::StreamableToString(test_info.result()->elapsed_time())
3712 .c_str());
3713 } else {
3714 printf("\n");
3715 }
3716 fflush(stdout);
3717 }
3718}
3719
3720void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3721 int /*iteration*/) {
3722 ColoredPrintf(GTestColor::kGreen, "[==========] ");
3723 printf("%s from %s ran.",
3724 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3725 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3726 if (GTEST_FLAG_GET(print_time)) {
3727 printf(" (%s ms total)",
3728 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3729 }
3730 printf("\n");
3731 ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
3732 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3733
3734 const int skipped_test_count = unit_test.skipped_test_count();
3735 if (skipped_test_count > 0) {
3736 ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3737 printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
3738 }
3739
3740 int num_disabled = unit_test.reportable_disabled_test_count();
3741 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3742 if (unit_test.Passed()) {
3743 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3744 }
3745 ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
3746 num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
3747 }
3748 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3749 fflush(stdout);
3750}
3751
3752// End BriefUnitTestResultPrinter
3753
3754// class TestEventRepeater
3755//
3756// This class forwards events to other event listeners.
3757class TestEventRepeater : public TestEventListener {
3758 public:
3759 TestEventRepeater() : forwarding_enabled_(true) {}
3760 ~TestEventRepeater() override;
3761 void Append(TestEventListener* listener);
3762 TestEventListener* Release(TestEventListener* listener);
3763
3764 // Controls whether events will be forwarded to listeners_. Set to false
3765 // in death test child processes.
3766 bool forwarding_enabled() const { return forwarding_enabled_; }
3767 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3768
3769 void OnTestProgramStart(const UnitTest& unit_test) override;
3770 void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3771 void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
3772 void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
3773// Legacy API is deprecated but still available
3774#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3775 void OnTestCaseStart(const TestSuite& parameter) override;
3776#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3777 void OnTestSuiteStart(const TestSuite& parameter) override;
3778 void OnTestStart(const TestInfo& test_info) override;
3779 void OnTestDisabled(const TestInfo& test_info) override;
3780 void OnTestPartResult(const TestPartResult& result) override;
3781 void OnTestEnd(const TestInfo& test_info) override;
3782// Legacy API is deprecated but still available
3783#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3784 void OnTestCaseEnd(const TestCase& parameter) override;
3785#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3786 void OnTestSuiteEnd(const TestSuite& parameter) override;
3787 void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
3788 void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
3789 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3790 void OnTestProgramEnd(const UnitTest& unit_test) override;
3791
3792 private:
3793 // Controls whether events will be forwarded to listeners_. Set to false
3794 // in death test child processes.
3795 bool forwarding_enabled_;
3796 // The list of listeners that receive events.
3797 std::vector<TestEventListener*> listeners_;
3798
3799 TestEventRepeater(const TestEventRepeater&) = delete;
3800 TestEventRepeater& operator=(const TestEventRepeater&) = delete;
3801};
3802
3803TestEventRepeater::~TestEventRepeater() {
3804 ForEach(listeners_, Delete<TestEventListener>);
3805}
3806
3807void TestEventRepeater::Append(TestEventListener* listener) {
3808 listeners_.push_back(listener);
3809}
3810
3811TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
3812 for (size_t i = 0; i < listeners_.size(); ++i) {
3813 if (listeners_[i] == listener) {
3814 listeners_.erase(listeners_.begin() + static_cast<int>(i));
3815 return listener;
3816 }
3817 }
3818
3819 return nullptr;
3820}
3821
3822// Since most methods are very similar, use macros to reduce boilerplate.
3823// This defines a member that forwards the call to all listeners.
3824#define GTEST_REPEATER_METHOD_(Name, Type) \
3825 void TestEventRepeater::Name(const Type& parameter) { \
3826 if (forwarding_enabled_) { \
3827 for (size_t i = 0; i < listeners_.size(); i++) { \
3828 listeners_[i]->Name(parameter); \
3829 } \
3830 } \
3831 }
3832// This defines a member that forwards the call to all listeners in reverse
3833// order.
3834#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3835 void TestEventRepeater::Name(const Type& parameter) { \
3836 if (forwarding_enabled_) { \
3837 for (size_t i = listeners_.size(); i != 0; i--) { \
3838 listeners_[i - 1]->Name(parameter); \
3839 } \
3840 } \
3841 }
3842
3843GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3844GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3845// Legacy API is deprecated but still available
3846#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3847GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
3848#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3849GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
3850GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3851GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)
3852GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3853GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3854GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3855GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3856GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3857// Legacy API is deprecated but still available
3858#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3859GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
3860#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3861GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
3862GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3863
3864#undef GTEST_REPEATER_METHOD_
3865#undef GTEST_REVERSE_REPEATER_METHOD_
3866
3867void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
3868 int iteration) {
3869 if (forwarding_enabled_) {
3870 for (size_t i = 0; i < listeners_.size(); i++) {
3871 listeners_[i]->OnTestIterationStart(unit_test, iteration);
3872 }
3873 }
3874}
3875
3876void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
3877 int iteration) {
3878 if (forwarding_enabled_) {
3879 for (size_t i = listeners_.size(); i > 0; i--) {
3880 listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
3881 }
3882 }
3883}
3884
3885// End TestEventRepeater
3886
3887// This class generates an XML output file.
3888class XmlUnitTestResultPrinter : public EmptyTestEventListener {
3889 public:
3890 explicit XmlUnitTestResultPrinter(const char* output_file);
3891
3892 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3893 void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
3894
3895 // Prints an XML summary of all unit tests.
3896 static void PrintXmlTestsList(std::ostream* stream,
3897 const std::vector<TestSuite*>& test_suites);
3898
3899 private:
3900 // Is c a whitespace character that is normalized to a space character
3901 // when it appears in an XML attribute value?
3902 static bool IsNormalizableWhitespace(unsigned char c) {
3903 return c == '\t' || c == '\n' || c == '\r';
3904 }
3905
3906 // May c appear in a well-formed XML document?
3907 // https://www.w3.org/TR/REC-xml/#charsets
3908 static bool IsValidXmlCharacter(unsigned char c) {
3909 return IsNormalizableWhitespace(c) || c >= 0x20;
3910 }
3911
3912 // Returns an XML-escaped copy of the input string str. If
3913 // is_attribute is true, the text is meant to appear as an attribute
3914 // value, and normalizable whitespace is preserved by replacing it
3915 // with character references.
3916 static std::string EscapeXml(const std::string& str, bool is_attribute);
3917
3918 // Returns the given string with all characters invalid in XML removed.
3919 static std::string RemoveInvalidXmlCharacters(const std::string& str);
3920
3921 // Convenience wrapper around EscapeXml when str is an attribute value.
3922 static std::string EscapeXmlAttribute(const std::string& str) {
3923 return EscapeXml(str, true);
3924 }
3925
3926 // Convenience wrapper around EscapeXml when str is not an attribute value.
3927 static std::string EscapeXmlText(const char* str) {
3928 return EscapeXml(str, false);
3929 }
3930
3931 // Verifies that the given attribute belongs to the given element and
3932 // streams the attribute as XML.
3933 static void OutputXmlAttribute(std::ostream* stream,
3934 const std::string& element_name,
3935 const std::string& name,
3936 const std::string& value);
3937
3938 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3939 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3940
3941 // Streams a test suite XML stanza containing the given test result.
3942 //
3943 // Requires: result.Failed()
3944 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
3945 const TestResult& result);
3946
3947 // Streams an XML representation of a TestResult object.
3948 static void OutputXmlTestResult(::std::ostream* stream,
3949 const TestResult& result);
3950
3951 // Streams an XML representation of a TestInfo object.
3952 static void OutputXmlTestInfo(::std::ostream* stream,
3953 const char* test_suite_name,
3954 const TestInfo& test_info);
3955
3956 // Prints an XML representation of a TestSuite object
3957 static void PrintXmlTestSuite(::std::ostream* stream,
3958 const TestSuite& test_suite);
3959
3960 // Prints an XML summary of unit_test to output stream out.
3961 static void PrintXmlUnitTest(::std::ostream* stream,
3962 const UnitTest& unit_test);
3963
3964 // Produces a string representing the test properties in a result as space
3965 // delimited XML attributes based on the property key="value" pairs.
3966 // When the std::string is not empty, it includes a space at the beginning,
3967 // to delimit this attribute from prior attributes.
3968 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3969
3970 // Streams an XML representation of the test properties of a TestResult
3971 // object.
3972 static void OutputXmlTestProperties(std::ostream* stream,
3973 const TestResult& result);
3974
3975 // The output file.
3976 const std::string output_file_;
3977
3979 XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete;
3980};
3981
3982// Creates a new XmlUnitTestResultPrinter.
3983XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3984 : output_file_(output_file) {
3985 if (output_file_.empty()) {
3986 GTEST_LOG_(FATAL) << "XML output file may not be null";
3987 }
3988}
3989
3990// Called after the unit test ends.
3992 int /*iteration*/) {
3993 FILE* xmlout = OpenFileForWriting(output_file_);
3994 std::stringstream stream;
3995 PrintXmlUnitTest(&stream, unit_test);
3996 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3997 fclose(xmlout);
3998}
3999
4001 const std::vector<TestSuite*>& test_suites) {
4002 FILE* xmlout = OpenFileForWriting(output_file_);
4003 std::stringstream stream;
4004 PrintXmlTestsList(&stream, test_suites);
4005 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4006 fclose(xmlout);
4007}
4008
4009// Returns an XML-escaped copy of the input string str. If is_attribute
4010// is true, the text is meant to appear as an attribute value, and
4011// normalizable whitespace is preserved by replacing it with character
4012// references.
4013//
4014// Invalid XML characters in str, if any, are stripped from the output.
4015// It is expected that most, if not all, of the text processed by this
4016// module will consist of ordinary English text.
4017// If this module is ever modified to produce version 1.1 XML output,
4018// most invalid characters can be retained using character references.
4019std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
4020 bool is_attribute) {
4021 Message m;
4022
4023 for (size_t i = 0; i < str.size(); ++i) {
4024 const char ch = str[i];
4025 switch (ch) {
4026 case '<':
4027 m << "&lt;";
4028 break;
4029 case '>':
4030 m << "&gt;";
4031 break;
4032 case '&':
4033 m << "&amp;";
4034 break;
4035 case '\'':
4036 if (is_attribute)
4037 m << "&apos;";
4038 else
4039 m << '\'';
4040 break;
4041 case '"':
4042 if (is_attribute)
4043 m << "&quot;";
4044 else
4045 m << '"';
4046 break;
4047 default:
4048 if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {
4049 if (is_attribute &&
4050 IsNormalizableWhitespace(static_cast<unsigned char>(ch)))
4051 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4052 << ";";
4053 else
4054 m << ch;
4055 }
4056 break;
4057 }
4058 }
4059
4060 return m.GetString();
4061}
4062
4063// Returns the given string with all characters invalid in XML removed.
4064// Currently invalid characters are dropped from the string. An
4065// alternative is to replace them with certain characters such as . or ?.
4066std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4067 const std::string& str) {
4068 std::string output;
4069 output.reserve(str.size());
4070 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4071 if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))
4072 output.push_back(*it);
4073
4074 return output;
4075}
4076
4077// The following routines generate an XML representation of a UnitTest
4078// object.
4079//
4080// This is how Google Test concepts map to the DTD:
4081//
4082// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4083// <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
4084// <testcase name="test-name"> <-- corresponds to a TestInfo object
4085// <failure message="...">...</failure>
4086// <failure message="...">...</failure>
4087// <failure message="...">...</failure>
4088// <-- individual assertion failures
4089// </testcase>
4090// </testsuite>
4091// </testsuites>
4092
4093// Formats the given time in milliseconds as seconds.
4094std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4095 ::std::stringstream ss;
4096 ss << (static_cast<double>(ms) * 1e-3);
4097 return ss.str();
4098}
4099
4100static bool PortableLocaltime(time_t seconds, struct tm* out) {
4101#if defined(_MSC_VER)
4102 return localtime_s(out, &seconds) == 0;
4103#elif defined(__MINGW32__) || defined(__MINGW64__)
4104 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
4105 // Windows' localtime(), which has a thread-local tm buffer.
4106 struct tm* tm_ptr = localtime(&seconds); // NOLINT
4107 if (tm_ptr == nullptr) return false;
4108 *out = *tm_ptr;
4109 return true;
4110#elif defined(__STDC_LIB_EXT1__)
4111 // Uses localtime_s when available as localtime_r is only available from
4112 // C23 standard.
4113 return localtime_s(&seconds, out) != nullptr;
4114#else
4115 return localtime_r(&seconds, out) != nullptr;
4116#endif
4117}
4118
4119// Converts the given epoch time in milliseconds to a date string in the ISO
4120// 8601 format, without the timezone information.
4121std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4122 struct tm time_struct;
4123 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4124 return "";
4125 // YYYY-MM-DDThh:mm:ss.sss
4126 return StreamableToString(time_struct.tm_year + 1900) + "-" +
4127 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4128 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4129 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4130 String::FormatIntWidth2(time_struct.tm_min) + ":" +
4131 String::FormatIntWidth2(time_struct.tm_sec) + "." +
4132 String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
4133}
4134
4135// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4136void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4137 const char* data) {
4138 const char* segment = data;
4139 *stream << "<![CDATA[";
4140 for (;;) {
4141 const char* const next_segment = strstr(segment, "]]>");
4142 if (next_segment != nullptr) {
4143 stream->write(segment,
4144 static_cast<std::streamsize>(next_segment - segment));
4145 *stream << "]]>]]&gt;<![CDATA[";
4146 segment = next_segment + strlen("]]>");
4147 } else {
4148 *stream << segment;
4149 break;
4150 }
4151 }
4152 *stream << "]]>";
4153}
4154
4155void XmlUnitTestResultPrinter::OutputXmlAttribute(
4156 std::ostream* stream, const std::string& element_name,
4157 const std::string& name, const std::string& value) {
4158 const std::vector<std::string>& allowed_names =
4160
4161 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4162 allowed_names.end())
4163 << "Attribute " << name << " is not allowed for element <" << element_name
4164 << ">.";
4165
4166 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4167}
4168
4169// Streams a test suite XML stanza containing the given test result.
4170void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4171 ::std::ostream* stream, const TestResult& result) {
4172 // Output the boilerplate for a minimal test suite with one test.
4173 *stream << " <testsuite";
4174 OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
4175 OutputXmlAttribute(stream, "testsuite", "tests", "1");
4176 OutputXmlAttribute(stream, "testsuite", "failures", "1");
4177 OutputXmlAttribute(stream, "testsuite", "disabled", "0");
4178 OutputXmlAttribute(stream, "testsuite", "skipped", "0");
4179 OutputXmlAttribute(stream, "testsuite", "errors", "0");
4180 OutputXmlAttribute(stream, "testsuite", "time",
4181 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4182 OutputXmlAttribute(
4183 stream, "testsuite", "timestamp",
4184 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4185 *stream << ">";
4186
4187 // Output the boilerplate for a minimal test case with a single test.
4188 *stream << " <testcase";
4189 OutputXmlAttribute(stream, "testcase", "name", "");
4190 OutputXmlAttribute(stream, "testcase", "status", "run");
4191 OutputXmlAttribute(stream, "testcase", "result", "completed");
4192 OutputXmlAttribute(stream, "testcase", "classname", "");
4193 OutputXmlAttribute(stream, "testcase", "time",
4194 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4195 OutputXmlAttribute(
4196 stream, "testcase", "timestamp",
4197 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4198
4199 // Output the actual test result.
4200 OutputXmlTestResult(stream, result);
4201
4202 // Complete the test suite.
4203 *stream << " </testsuite>\n";
4204}
4205
4206// Prints an XML representation of a TestInfo object.
4207void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4208 const char* test_suite_name,
4209 const TestInfo& test_info) {
4210 const TestResult& result = *test_info.result();
4211 const std::string kTestsuite = "testcase";
4212
4213 if (test_info.is_in_another_shard()) {
4214 return;
4215 }
4216
4217 *stream << " <testcase";
4218 OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
4219
4220 if (test_info.value_param() != nullptr) {
4221 OutputXmlAttribute(stream, kTestsuite, "value_param",
4222 test_info.value_param());
4223 }
4224 if (test_info.type_param() != nullptr) {
4225 OutputXmlAttribute(stream, kTestsuite, "type_param",
4226 test_info.type_param());
4227 }
4228
4229 OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
4230 OutputXmlAttribute(stream, kTestsuite, "line",
4231 StreamableToString(test_info.line()));
4232 if (GTEST_FLAG_GET(list_tests)) {
4233 *stream << " />\n";
4234 return;
4235 }
4236
4237 OutputXmlAttribute(stream, kTestsuite, "status",
4238 test_info.should_run() ? "run" : "notrun");
4239 OutputXmlAttribute(stream, kTestsuite, "result",
4240 test_info.should_run()
4241 ? (result.Skipped() ? "skipped" : "completed")
4242 : "suppressed");
4243 OutputXmlAttribute(stream, kTestsuite, "time",
4244 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4245 OutputXmlAttribute(
4246 stream, kTestsuite, "timestamp",
4247 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4248 OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
4249
4250 OutputXmlTestResult(stream, result);
4251}
4252
4253void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4254 const TestResult& result) {
4255 int failures = 0;
4256 int skips = 0;
4257 for (int i = 0; i < result.total_part_count(); ++i) {
4258 const TestPartResult& part = result.GetTestPartResult(i);
4259 if (part.failed()) {
4260 if (++failures == 1 && skips == 0) {
4261 *stream << ">\n";
4262 }
4263 const std::string location =
4265 part.line_number());
4266 const std::string summary = location + "\n" + part.summary();
4267 *stream << " <failure message=\"" << EscapeXmlAttribute(summary)
4268 << "\" type=\"\">";
4269 const std::string detail = location + "\n" + part.message();
4270 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4271 *stream << "</failure>\n";
4272 } else if (part.skipped()) {
4273 if (++skips == 1 && failures == 0) {
4274 *stream << ">\n";
4275 }
4276 const std::string location =
4278 part.line_number());
4279 const std::string summary = location + "\n" + part.summary();
4280 *stream << " <skipped message=\""
4281 << EscapeXmlAttribute(summary.c_str()) << "\">";
4282 const std::string detail = location + "\n" + part.message();
4283 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4284 *stream << "</skipped>\n";
4285 }
4286 }
4287
4288 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4289 *stream << " />\n";
4290 } else {
4291 if (failures == 0 && skips == 0) {
4292 *stream << ">\n";
4293 }
4294 OutputXmlTestProperties(stream, result);
4295 *stream << " </testcase>\n";
4296 }
4297}
4298
4299// Prints an XML representation of a TestSuite object
4300void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4301 const TestSuite& test_suite) {
4302 const std::string kTestsuite = "testsuite";
4303 *stream << " <" << kTestsuite;
4304 OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
4305 OutputXmlAttribute(stream, kTestsuite, "tests",
4306 StreamableToString(test_suite.reportable_test_count()));
4307 if (!GTEST_FLAG_GET(list_tests)) {
4308 OutputXmlAttribute(stream, kTestsuite, "failures",
4309 StreamableToString(test_suite.failed_test_count()));
4310 OutputXmlAttribute(
4311 stream, kTestsuite, "disabled",
4312 StreamableToString(test_suite.reportable_disabled_test_count()));
4313 OutputXmlAttribute(stream, kTestsuite, "skipped",
4314 StreamableToString(test_suite.skipped_test_count()));
4315
4316 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4317
4318 OutputXmlAttribute(stream, kTestsuite, "time",
4319 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
4320 OutputXmlAttribute(
4321 stream, kTestsuite, "timestamp",
4322 FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
4323 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
4324 }
4325 *stream << ">\n";
4326 for (int i = 0; i < test_suite.total_test_count(); ++i) {
4327 if (test_suite.GetTestInfo(i)->is_reportable())
4328 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4329 }
4330 *stream << " </" << kTestsuite << ">\n";
4331}
4332
4333// Prints an XML summary of unit_test to output stream out.
4334void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4335 const UnitTest& unit_test) {
4336 const std::string kTestsuites = "testsuites";
4337
4338 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4339 *stream << "<" << kTestsuites;
4340
4341 OutputXmlAttribute(stream, kTestsuites, "tests",
4342 StreamableToString(unit_test.reportable_test_count()));
4343 OutputXmlAttribute(stream, kTestsuites, "failures",
4344 StreamableToString(unit_test.failed_test_count()));
4345 OutputXmlAttribute(
4346 stream, kTestsuites, "disabled",
4347 StreamableToString(unit_test.reportable_disabled_test_count()));
4348 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4349 OutputXmlAttribute(stream, kTestsuites, "time",
4350 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4351 OutputXmlAttribute(
4352 stream, kTestsuites, "timestamp",
4353 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4354
4355 if (GTEST_FLAG_GET(shuffle)) {
4356 OutputXmlAttribute(stream, kTestsuites, "random_seed",
4357 StreamableToString(unit_test.random_seed()));
4358 }
4359 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4360
4361 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4362 *stream << ">\n";
4363
4364 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4365 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
4366 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
4367 }
4368
4369 // If there was a test failure outside of one of the test suites (like in a
4370 // test environment) include that in the output.
4371 if (unit_test.ad_hoc_test_result().Failed()) {
4372 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4373 }
4374
4375 *stream << "</" << kTestsuites << ">\n";
4376}
4377
4379 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
4380 const std::string kTestsuites = "testsuites";
4381
4382 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4383 *stream << "<" << kTestsuites;
4384
4385 int total_tests = 0;
4386 for (auto test_suite : test_suites) {
4387 total_tests += test_suite->total_test_count();
4388 }
4389 OutputXmlAttribute(stream, kTestsuites, "tests",
4390 StreamableToString(total_tests));
4391 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4392 *stream << ">\n";
4393
4394 for (auto test_suite : test_suites) {
4395 PrintXmlTestSuite(stream, *test_suite);
4396 }
4397 *stream << "</" << kTestsuites << ">\n";
4398}
4399
4400// Produces a string representing the test properties in a result as space
4401// delimited XML attributes based on the property key="value" pairs.
4402std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4403 const TestResult& result) {
4404 Message attributes;
4405 for (int i = 0; i < result.test_property_count(); ++i) {
4406 const TestProperty& property = result.GetTestProperty(i);
4407 attributes << " " << property.key() << "="
4408 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4409 }
4410 return attributes.GetString();
4411}
4412
4413void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4414 std::ostream* stream, const TestResult& result) {
4415 const std::string kProperties = "properties";
4416 const std::string kProperty = "property";
4417
4418 if (result.test_property_count() <= 0) {
4419 return;
4420 }
4421
4422 *stream << " <" << kProperties << ">\n";
4423 for (int i = 0; i < result.test_property_count(); ++i) {
4424 const TestProperty& property = result.GetTestProperty(i);
4425 *stream << " <" << kProperty;
4426 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
4427 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
4428 *stream << "/>\n";
4429 }
4430 *stream << " </" << kProperties << ">\n";
4431}
4432
4433// End XmlUnitTestResultPrinter
4434
4435// This class generates an JSON output file.
4436class JsonUnitTestResultPrinter : public EmptyTestEventListener {
4437 public:
4438 explicit JsonUnitTestResultPrinter(const char* output_file);
4439
4440 void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4441
4442 // Prints an JSON summary of all unit tests.
4443 static void PrintJsonTestList(::std::ostream* stream,
4444 const std::vector<TestSuite*>& test_suites);
4445
4446 private:
4447 // Returns an JSON-escaped copy of the input string str.
4448 static std::string EscapeJson(const std::string& str);
4449
4452 static void OutputJsonKey(std::ostream* stream,
4453 const std::string& element_name,
4454 const std::string& name, const std::string& value,
4455 const std::string& indent, bool comma = true);
4456 static void OutputJsonKey(std::ostream* stream,
4457 const std::string& element_name,
4458 const std::string& name, int value,
4459 const std::string& indent, bool comma = true);
4460
4461 // Streams a test suite JSON stanza containing the given test result.
4462 //
4463 // Requires: result.Failed()
4464 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4465 const TestResult& result);
4466
4467 // Streams a JSON representation of a TestResult object.
4468 static void OutputJsonTestResult(::std::ostream* stream,
4469 const TestResult& result);
4470
4471 // Streams a JSON representation of a TestInfo object.
4472 static void OutputJsonTestInfo(::std::ostream* stream,
4473 const char* test_suite_name,
4474 const TestInfo& test_info);
4475
4476 // Prints a JSON representation of a TestSuite object
4477 static void PrintJsonTestSuite(::std::ostream* stream,
4478 const TestSuite& test_suite);
4479
4480 // Prints a JSON summary of unit_test to output stream out.
4481 static void PrintJsonUnitTest(::std::ostream* stream,
4482 const UnitTest& unit_test);
4483
4484 // Produces a string representing the test properties in a result as
4485 // a JSON dictionary.
4486 static std::string TestPropertiesAsJson(const TestResult& result,
4487 const std::string& indent);
4488
4489 // The output file.
4490 const std::string output_file_;
4491
4494 delete;
4495};
4496
4497// Creates a new JsonUnitTestResultPrinter.
4499 : output_file_(output_file) {
4500 if (output_file_.empty()) {
4501 GTEST_LOG_(FATAL) << "JSON output file may not be null";
4502 }
4503}
4504
4506 int /*iteration*/) {
4507 FILE* jsonout = OpenFileForWriting(output_file_);
4508 std::stringstream stream;
4509 PrintJsonUnitTest(&stream, unit_test);
4510 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
4511 fclose(jsonout);
4512}
4513
4514// Returns an JSON-escaped copy of the input string str.
4515std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
4516 Message m;
4517
4518 for (size_t i = 0; i < str.size(); ++i) {
4519 const char ch = str[i];
4520 switch (ch) {
4521 case '\\':
4522 case '"':
4523 case '/':
4524 m << '\\' << ch;
4525 break;
4526 case '\b':
4527 m << "\\b";
4528 break;
4529 case '\t':
4530 m << "\\t";
4531 break;
4532 case '\n':
4533 m << "\\n";
4534 break;
4535 case '\f':
4536 m << "\\f";
4537 break;
4538 case '\r':
4539 m << "\\r";
4540 break;
4541 default:
4542 if (ch < ' ') {
4543 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
4544 } else {
4545 m << ch;
4546 }
4547 break;
4548 }
4549 }
4550
4551 return m.GetString();
4552}
4553
4554// The following routines generate an JSON representation of a UnitTest
4555// object.
4556
4557// Formats the given time in milliseconds as seconds.
4558static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
4559 ::std::stringstream ss;
4560 ss << (static_cast<double>(ms) * 1e-3) << "s";
4561 return ss.str();
4562}
4563
4564// Converts the given epoch time in milliseconds to a date string in the
4565// RFC3339 format, without the timezone information.
4566static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4567 struct tm time_struct;
4568 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4569 return "";
4570 // YYYY-MM-DDThh:mm:ss
4571 return StreamableToString(time_struct.tm_year + 1900) + "-" +
4572 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4573 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4574 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4575 String::FormatIntWidth2(time_struct.tm_min) + ":" +
4576 String::FormatIntWidth2(time_struct.tm_sec) + "Z";
4577}
4578
4579static inline std::string Indent(size_t width) {
4580 return std::string(width, ' ');
4581}
4582
4583void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4584 const std::string& element_name,
4585 const std::string& name,
4586 const std::string& value,
4587 const std::string& indent,
4588 bool comma) {
4589 const std::vector<std::string>& allowed_names =
4591
4592 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4593 allowed_names.end())
4594 << "Key \"" << name << "\" is not allowed for value \"" << element_name
4595 << "\".";
4596
4597 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
4598 if (comma) *stream << ",\n";
4599}
4600
4601void JsonUnitTestResultPrinter::OutputJsonKey(
4602 std::ostream* stream, const std::string& element_name,
4603 const std::string& name, int value, const std::string& indent, bool comma) {
4604 const std::vector<std::string>& allowed_names =
4606
4607 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4608 allowed_names.end())
4609 << "Key \"" << name << "\" is not allowed for value \"" << element_name
4610 << "\".";
4611
4612 *stream << indent << "\"" << name << "\": " << StreamableToString(value);
4613 if (comma) *stream << ",\n";
4614}
4615
4616// Streams a test suite JSON stanza containing the given test result.
4617void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4618 ::std::ostream* stream, const TestResult& result) {
4619 // Output the boilerplate for a new test suite.
4620 *stream << Indent(4) << "{\n";
4621 OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
4622 OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
4623 if (!GTEST_FLAG_GET(list_tests)) {
4624 OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
4625 OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
4626 OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
4627 OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
4628 OutputJsonKey(stream, "testsuite", "time",
4629 FormatTimeInMillisAsDuration(result.elapsed_time()),
4630 Indent(6));
4631 OutputJsonKey(stream, "testsuite", "timestamp",
4632 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4633 Indent(6));
4634 }
4635 *stream << Indent(6) << "\"testsuite\": [\n";
4636
4637 // Output the boilerplate for a new test case.
4638 *stream << Indent(8) << "{\n";
4639 OutputJsonKey(stream, "testcase", "name", "", Indent(10));
4640 OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
4641 OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
4642 OutputJsonKey(stream, "testcase", "timestamp",
4643 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4644 Indent(10));
4645 OutputJsonKey(stream, "testcase", "time",
4646 FormatTimeInMillisAsDuration(result.elapsed_time()),
4647 Indent(10));
4648 OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
4649 *stream << TestPropertiesAsJson(result, Indent(10));
4650
4651 // Output the actual test result.
4652 OutputJsonTestResult(stream, result);
4653
4654 // Finish the test suite.
4655 *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
4656}
4657
4658// Prints a JSON representation of a TestInfo object.
4659void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4660 const char* test_suite_name,
4661 const TestInfo& test_info) {
4662 const TestResult& result = *test_info.result();
4663 const std::string kTestsuite = "testcase";
4664 const std::string kIndent = Indent(10);
4665
4666 *stream << Indent(8) << "{\n";
4667 OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
4668
4669 if (test_info.value_param() != nullptr) {
4670 OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
4671 kIndent);
4672 }
4673 if (test_info.type_param() != nullptr) {
4674 OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
4675 kIndent);
4676 }
4677
4678 OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
4679 OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
4680 if (GTEST_FLAG_GET(list_tests)) {
4681 *stream << "\n" << Indent(8) << "}";
4682 return;
4683 } else {
4684 *stream << ",\n";
4685 }
4686
4687 OutputJsonKey(stream, kTestsuite, "status",
4688 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
4689 OutputJsonKey(stream, kTestsuite, "result",
4690 test_info.should_run()
4691 ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
4692 : "SUPPRESSED",
4693 kIndent);
4694 OutputJsonKey(stream, kTestsuite, "timestamp",
4695 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4696 kIndent);
4697 OutputJsonKey(stream, kTestsuite, "time",
4698 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4699 OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
4700 false);
4701 *stream << TestPropertiesAsJson(result, kIndent);
4702
4703 OutputJsonTestResult(stream, result);
4704}
4705
4706void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4707 const TestResult& result) {
4708 const std::string kIndent = Indent(10);
4709
4710 int failures = 0;
4711 for (int i = 0; i < result.total_part_count(); ++i) {
4712 const TestPartResult& part = result.GetTestPartResult(i);
4713 if (part.failed()) {
4714 *stream << ",\n";
4715 if (++failures == 1) {
4716 *stream << kIndent << "\""
4717 << "failures"
4718 << "\": [\n";
4719 }
4720 const std::string location =
4722 part.line_number());
4723 const std::string message = EscapeJson(location + "\n" + part.message());
4724 *stream << kIndent << " {\n"
4725 << kIndent << " \"failure\": \"" << message << "\",\n"
4726 << kIndent << " \"type\": \"\"\n"
4727 << kIndent << " }";
4728 }
4729 }
4730
4731 if (failures > 0) *stream << "\n" << kIndent << "]";
4732 *stream << "\n" << Indent(8) << "}";
4733}
4734
4735// Prints an JSON representation of a TestSuite object
4736void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4737 std::ostream* stream, const TestSuite& test_suite) {
4738 const std::string kTestsuite = "testsuite";
4739 const std::string kIndent = Indent(6);
4740
4741 *stream << Indent(4) << "{\n";
4742 OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
4743 OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
4744 kIndent);
4745 if (!GTEST_FLAG_GET(list_tests)) {
4746 OutputJsonKey(stream, kTestsuite, "failures",
4747 test_suite.failed_test_count(), kIndent);
4748 OutputJsonKey(stream, kTestsuite, "disabled",
4749 test_suite.reportable_disabled_test_count(), kIndent);
4750 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
4751 OutputJsonKey(
4752 stream, kTestsuite, "timestamp",
4753 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4754 kIndent);
4755 OutputJsonKey(stream, kTestsuite, "time",
4756 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4757 kIndent, false);
4758 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4759 << ",\n";
4760 }
4761
4762 *stream << kIndent << "\"" << kTestsuite << "\": [\n";
4763
4764 bool comma = false;
4765 for (int i = 0; i < test_suite.total_test_count(); ++i) {
4766 if (test_suite.GetTestInfo(i)->is_reportable()) {
4767 if (comma) {
4768 *stream << ",\n";
4769 } else {
4770 comma = true;
4771 }
4772 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4773 }
4774 }
4775 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
4776}
4777
4778// Prints a JSON summary of unit_test to output stream out.
4779void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4780 const UnitTest& unit_test) {
4781 const std::string kTestsuites = "testsuites";
4782 const std::string kIndent = Indent(2);
4783 *stream << "{\n";
4784
4785 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
4786 kIndent);
4787 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
4788 kIndent);
4789 OutputJsonKey(stream, kTestsuites, "disabled",
4790 unit_test.reportable_disabled_test_count(), kIndent);
4791 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
4792 if (GTEST_FLAG_GET(shuffle)) {
4793 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
4794 kIndent);
4795 }
4796 OutputJsonKey(stream, kTestsuites, "timestamp",
4797 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4798 kIndent);
4799 OutputJsonKey(stream, kTestsuites, "time",
4800 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4801 false);
4802
4803 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4804 << ",\n";
4805
4806 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4807 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4808
4809 bool comma = false;
4810 for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4811 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
4812 if (comma) {
4813 *stream << ",\n";
4814 } else {
4815 comma = true;
4816 }
4817 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
4818 }
4819 }
4820
4821 // If there was a test failure outside of one of the test suites (like in a
4822 // test environment) include that in the output.
4823 if (unit_test.ad_hoc_test_result().Failed()) {
4824 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4825 }
4826
4827 *stream << "\n"
4828 << kIndent << "]\n"
4829 << "}\n";
4830}
4831
4833 std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
4834 const std::string kTestsuites = "testsuites";
4835 const std::string kIndent = Indent(2);
4836 *stream << "{\n";
4837 int total_tests = 0;
4838 for (auto test_suite : test_suites) {
4839 total_tests += test_suite->total_test_count();
4840 }
4841 OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
4842
4843 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4844 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4845
4846 for (size_t i = 0; i < test_suites.size(); ++i) {
4847 if (i != 0) {
4848 *stream << ",\n";
4849 }
4850 PrintJsonTestSuite(stream, *test_suites[i]);
4851 }
4852
4853 *stream << "\n"
4854 << kIndent << "]\n"
4855 << "}\n";
4856}
4857// Produces a string representing the test properties in a result as
4858// a JSON dictionary.
4859std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4860 const TestResult& result, const std::string& indent) {
4861 Message attributes;
4862 for (int i = 0; i < result.test_property_count(); ++i) {
4863 const TestProperty& property = result.GetTestProperty(i);
4864 attributes << ",\n"
4865 << indent << "\"" << property.key() << "\": "
4866 << "\"" << EscapeJson(property.value()) << "\"";
4867 }
4868 return attributes.GetString();
4869}
4870
4871// End JsonUnitTestResultPrinter
4872
4873#if GTEST_CAN_STREAM_RESULTS_
4874
4875// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4876// replaces them by "%xx" where xx is their hexadecimal value. For
4877// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4878// in both time and space -- important as the input str may contain an
4879// arbitrarily long test failure message and stack trace.
4880std::string StreamingListener::UrlEncode(const char* str) {
4881 std::string result;
4882 result.reserve(strlen(str) + 1);
4883 for (char ch = *str; ch != '\0'; ch = *++str) {
4884 switch (ch) {
4885 case '%':
4886 case '=':
4887 case '&':
4888 case '\n':
4889 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4890 break;
4891 default:
4892 result.push_back(ch);
4893 break;
4894 }
4895 }
4896 return result;
4897}
4898
4899void StreamingListener::SocketWriter::MakeConnection() {
4900 GTEST_CHECK_(sockfd_ == -1)
4901 << "MakeConnection() can't be called when there is already a connection.";
4902
4903 addrinfo hints;
4904 memset(&hints, 0, sizeof(hints));
4905 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4906 hints.ai_socktype = SOCK_STREAM;
4907 addrinfo* servinfo = nullptr;
4908
4909 // Use the getaddrinfo() to get a linked list of IP addresses for
4910 // the given host name.
4911 const int error_num =
4912 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4913 if (error_num != 0) {
4914 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4915 << gai_strerror(error_num);
4916 }
4917
4918 // Loop through all the results and connect to the first we can.
4919 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
4920 cur_addr = cur_addr->ai_next) {
4921 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4922 cur_addr->ai_protocol);
4923 if (sockfd_ != -1) {
4924 // Connect the client socket to the server socket.
4925 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4926 close(sockfd_);
4927 sockfd_ = -1;
4928 }
4929 }
4930 }
4931
4932 freeaddrinfo(servinfo); // all done with this structure
4933
4934 if (sockfd_ == -1) {
4935 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4936 << host_name_ << ":" << port_num_;
4937 }
4938}
4939
4940// End of class Streaming Listener
4941#endif // GTEST_CAN_STREAM_RESULTS__
4942
4943// class OsStackTraceGetter
4944
4946 "... " GTEST_NAME_ " internal frames ...";
4947
4948std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
4949 GTEST_LOCK_EXCLUDED_(mutex_) {
4950#if GTEST_HAS_ABSL
4951 std::string result;
4952
4953 if (max_depth <= 0) {
4954 return result;
4955 }
4956
4957 max_depth = std::min(max_depth, kMaxStackTraceDepth);
4958
4959 std::vector<void*> raw_stack(max_depth);
4960 // Skips the frames requested by the caller, plus this function.
4961 const int raw_stack_size =
4962 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4963
4964 void* caller_frame = nullptr;
4965 {
4966 MutexLock lock(&mutex_);
4967 caller_frame = caller_frame_;
4968 }
4969
4970 for (int i = 0; i < raw_stack_size; ++i) {
4971 if (raw_stack[i] == caller_frame &&
4972 !GTEST_FLAG_GET(show_internal_stack_frames)) {
4973 // Add a marker to the trace and stop adding frames.
4974 absl::StrAppend(&result, kElidedFramesMarker, "\n");
4975 break;
4976 }
4977
4978 char tmp[1024];
4979 const char* symbol = "(unknown)";
4980 if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
4981 symbol = tmp;
4982 }
4983
4984 char line[1024];
4985 snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
4986 result += line;
4987 }
4988
4989 return result;
4990
4991#else // !GTEST_HAS_ABSL
4992 static_cast<void>(max_depth);
4993 static_cast<void>(skip_count);
4994 return "";
4995#endif // GTEST_HAS_ABSL
4996}
4997
4998void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
4999#if GTEST_HAS_ABSL
5000 void* caller_frame = nullptr;
5001 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5002 caller_frame = nullptr;
5003 }
5004
5005 MutexLock lock(&mutex_);
5006 caller_frame_ = caller_frame;
5007#endif // GTEST_HAS_ABSL
5008}
5009
5010// A helper class that creates the premature-exit file in its
5011// constructor and deletes the file in its destructor.
5013 public:
5014 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5015 : premature_exit_filepath_(
5016 premature_exit_filepath ? premature_exit_filepath : "") {
5017 // If a path to the premature-exit file is specified...
5018 if (!premature_exit_filepath_.empty()) {
5019 // create the file with a single "0" character in it. I/O
5020 // errors are ignored as there's nothing better we can do and we
5021 // don't want to fail the test because of this.
5022 FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
5023 fwrite("0", 1, 1, pfile);
5024 fclose(pfile);
5025 }
5026 }
5027
5029#if !defined GTEST_OS_ESP8266
5030 if (!premature_exit_filepath_.empty()) {
5031 int retval = remove(premature_exit_filepath_.c_str());
5032 if (retval) {
5033 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5034 << premature_exit_filepath_ << "\" with error "
5035 << retval;
5036 }
5037 }
5038#endif
5039 }
5040
5041 private:
5042 const std::string premature_exit_filepath_;
5043
5045 ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
5046};
5047
5048} // namespace internal
5049
5050// class TestEventListeners
5051
5052TestEventListeners::TestEventListeners()
5053 : repeater_(new internal::TestEventRepeater()),
5054 default_result_printer_(nullptr),
5055 default_xml_generator_(nullptr) {}
5056
5057TestEventListeners::~TestEventListeners() { delete repeater_; }
5058
5059// Returns the standard listener responsible for the default console
5060// output. Can be removed from the listeners list to shut down default
5061// console output. Note that removing this object from the listener list
5062// with Release transfers its ownership to the user.
5063void TestEventListeners::Append(TestEventListener* listener) {
5064 repeater_->Append(listener);
5065}
5066
5067// Removes the given event listener from the list and returns it. It then
5068// becomes the caller's responsibility to delete the listener. Returns
5069// NULL if the listener is not found in the list.
5070TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5071 if (listener == default_result_printer_)
5072 default_result_printer_ = nullptr;
5073 else if (listener == default_xml_generator_)
5074 default_xml_generator_ = nullptr;
5075 return repeater_->Release(listener);
5076}
5077
5078// Returns repeater that broadcasts the TestEventListener events to all
5079// subscribers.
5080TestEventListener* TestEventListeners::repeater() { return repeater_; }
5081
5082// Sets the default_result_printer attribute to the provided listener.
5083// The listener is also added to the listener list and previous
5084// default_result_printer is removed from it and deleted. The listener can
5085// also be NULL in which case it will not be added to the list. Does
5086// nothing if the previous and the current listener objects are the same.
5087void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5088 if (default_result_printer_ != listener) {
5089 // It is an error to pass this method a listener that is already in the
5090 // list.
5091 delete Release(default_result_printer_);
5092 default_result_printer_ = listener;
5093 if (listener != nullptr) Append(listener);
5094 }
5095}
5096
5097// Sets the default_xml_generator attribute to the provided listener. The
5098// listener is also added to the listener list and previous
5099// default_xml_generator is removed from it and deleted. The listener can
5100// also be NULL in which case it will not be added to the list. Does
5101// nothing if the previous and the current listener objects are the same.
5102void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5103 if (default_xml_generator_ != listener) {
5104 // It is an error to pass this method a listener that is already in the
5105 // list.
5106 delete Release(default_xml_generator_);
5107 default_xml_generator_ = listener;
5108 if (listener != nullptr) Append(listener);
5109 }
5110}
5111
5112// Controls whether events will be forwarded by the repeater to the
5113// listeners in the list.
5114bool TestEventListeners::EventForwardingEnabled() const {
5115 return repeater_->forwarding_enabled();
5116}
5117
5118void TestEventListeners::SuppressEventForwarding() {
5119 repeater_->set_forwarding_enabled(false);
5120}
5121
5122// class UnitTest
5123
5124// Gets the singleton UnitTest object. The first time this method is
5125// called, a UnitTest object is constructed and returned. Consecutive
5126// calls will return the same object.
5127//
5128// We don't protect this under mutex_ as a user is not supposed to
5129// call this before main() starts, from which point on the return
5130// value will never change.
5131UnitTest* UnitTest::GetInstance() {
5132 // CodeGear C++Builder insists on a public destructor for the
5133 // default implementation. Use this implementation to keep good OO
5134 // design with private destructor.
5135
5136#if defined(__BORLANDC__)
5137 static UnitTest* const instance = new UnitTest;
5138 return instance;
5139#else
5140 static UnitTest instance;
5141 return &instance;
5142#endif // defined(__BORLANDC__)
5143}
5144
5145// Gets the number of successful test suites.
5146int UnitTest::successful_test_suite_count() const {
5147 return impl()->successful_test_suite_count();
5148}
5149
5150// Gets the number of failed test suites.
5151int UnitTest::failed_test_suite_count() const {
5152 return impl()->failed_test_suite_count();
5153}
5154
5155// Gets the number of all test suites.
5156int UnitTest::total_test_suite_count() const {
5157 return impl()->total_test_suite_count();
5158}
5159
5160// Gets the number of all test suites that contain at least one test
5161// that should run.
5162int UnitTest::test_suite_to_run_count() const {
5163 return impl()->test_suite_to_run_count();
5164}
5165
5166// Legacy API is deprecated but still available
5167#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5168int UnitTest::successful_test_case_count() const {
5169 return impl()->successful_test_suite_count();
5170}
5171int UnitTest::failed_test_case_count() const {
5172 return impl()->failed_test_suite_count();
5173}
5174int UnitTest::total_test_case_count() const {
5175 return impl()->total_test_suite_count();
5176}
5177int UnitTest::test_case_to_run_count() const {
5178 return impl()->test_suite_to_run_count();
5179}
5180#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5181
5182// Gets the number of successful tests.
5183int UnitTest::successful_test_count() const {
5184 return impl()->successful_test_count();
5185}
5186
5187// Gets the number of skipped tests.
5188int UnitTest::skipped_test_count() const {
5189 return impl()->skipped_test_count();
5190}
5191
5192// Gets the number of failed tests.
5193int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5194
5195// Gets the number of disabled tests that will be reported in the XML report.
5196int UnitTest::reportable_disabled_test_count() const {
5197 return impl()->reportable_disabled_test_count();
5198}
5199
5200// Gets the number of disabled tests.
5201int UnitTest::disabled_test_count() const {
5202 return impl()->disabled_test_count();
5203}
5204
5205// Gets the number of tests to be printed in the XML report.
5206int UnitTest::reportable_test_count() const {
5207 return impl()->reportable_test_count();
5208}
5209
5210// Gets the number of all tests.
5211int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5212
5213// Gets the number of tests that should run.
5214int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5215
5216// Gets the time of the test program start, in ms from the start of the
5217// UNIX epoch.
5218internal::TimeInMillis UnitTest::start_timestamp() const {
5219 return impl()->start_timestamp();
5220}
5221
5222// Gets the elapsed time, in milliseconds.
5223internal::TimeInMillis UnitTest::elapsed_time() const {
5224 return impl()->elapsed_time();
5225}
5226
5227// Returns true if and only if the unit test passed (i.e. all test suites
5228// passed).
5229bool UnitTest::Passed() const { return impl()->Passed(); }
5230
5231// Returns true if and only if the unit test failed (i.e. some test suite
5232// failed or something outside of all tests failed).
5233bool UnitTest::Failed() const { return impl()->Failed(); }
5234
5235// Gets the i-th test suite among all the test suites. i can range from 0 to
5236// total_test_suite_count() - 1. If i is not in that range, returns NULL.
5237const TestSuite* UnitTest::GetTestSuite(int i) const {
5238 return impl()->GetTestSuite(i);
5239}
5240
5241// Legacy API is deprecated but still available
5242#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5243const TestCase* UnitTest::GetTestCase(int i) const {
5244 return impl()->GetTestCase(i);
5245}
5246#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5247
5248// Returns the TestResult containing information on test failures and
5249// properties logged outside of individual test suites.
5250const TestResult& UnitTest::ad_hoc_test_result() const {
5251 return *impl()->ad_hoc_test_result();
5252}
5253
5254// Gets the i-th test suite among all the test suites. i can range from 0 to
5255// total_test_suite_count() - 1. If i is not in that range, returns NULL.
5256TestSuite* UnitTest::GetMutableTestSuite(int i) {
5257 return impl()->GetMutableSuiteCase(i);
5258}
5259
5260// Returns the list of event listeners that can be used to track events
5261// inside Google Test.
5262TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
5263
5264// Registers and returns a global test environment. When a test
5265// program is run, all global test environments will be set-up in the
5266// order they were registered. After all tests in the program have
5267// finished, all global test environments will be torn-down in the
5268// *reverse* order they were registered.
5269//
5270// The UnitTest object takes ownership of the given environment.
5271//
5272// We don't protect this under mutex_, as we only support calling it
5273// from the main thread.
5274Environment* UnitTest::AddEnvironment(Environment* env) {
5275 if (env == nullptr) {
5276 return nullptr;
5277 }
5278
5279 impl_->environments().push_back(env);
5280 return env;
5281}
5282
5283// Adds a TestPartResult to the current TestResult object. All Google Test
5284// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5285// this to report their results. The user code should use the
5286// assertion macros instead of calling this directly.
5287void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5288 const char* file_name, int line_number,
5289 const std::string& message,
5290 const std::string& os_stack_trace)
5291 GTEST_LOCK_EXCLUDED_(mutex_) {
5292 Message msg;
5293 msg << message;
5294
5295 internal::MutexLock lock(&mutex_);
5296 if (impl_->gtest_trace_stack().size() > 0) {
5297 msg << "\n" << GTEST_NAME_ << " trace:";
5298
5299 for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
5300 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5301 msg << "\n"
5302 << internal::FormatFileLocation(trace.file, trace.line) << " "
5303 << trace.message;
5304 }
5305 }
5306
5307 if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
5308 msg << internal::kStackTraceMarker << os_stack_trace;
5309 }
5310
5311 const TestPartResult result = TestPartResult(
5312 result_type, file_name, line_number, msg.GetString().c_str());
5313 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5314 result);
5315
5316 if (result_type != TestPartResult::kSuccess &&
5317 result_type != TestPartResult::kSkip) {
5318 // gtest_break_on_failure takes precedence over
5319 // gtest_throw_on_failure. This allows a user to set the latter
5320 // in the code (perhaps in order to use Google Test assertions
5321 // with another testing framework) and specify the former on the
5322 // command line for debugging.
5323 if (GTEST_FLAG_GET(break_on_failure)) {
5324#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5325 // Using DebugBreak on Windows allows gtest to still break into a debugger
5326 // when a failure happens and both the --gtest_break_on_failure and
5327 // the --gtest_catch_exceptions flags are specified.
5328 DebugBreak();
5329#elif (!defined(__native_client__)) && \
5330 ((defined(__clang__) || defined(__GNUC__)) && \
5331 (defined(__x86_64__) || defined(__i386__)))
5332 // with clang/gcc we can achieve the same effect on x86 by invoking int3
5333 asm("int3");
5334#else
5335 // Dereference nullptr through a volatile pointer to prevent the compiler
5336 // from removing. We use this rather than abort() or __builtin_trap() for
5337 // portability: some debuggers don't correctly trap abort().
5338 *static_cast<volatile int*>(nullptr) = 1;
5339#endif // GTEST_OS_WINDOWS
5340 } else if (GTEST_FLAG_GET(throw_on_failure)) {
5341#if GTEST_HAS_EXCEPTIONS
5342 throw internal::GoogleTestFailureException(result);
5343#else
5344 // We cannot call abort() as it generates a pop-up in debug mode
5345 // that cannot be suppressed in VC 7.1 or below.
5346 exit(1);
5347#endif
5348 }
5349 }
5350}
5351
5352// Adds a TestProperty to the current TestResult object when invoked from
5353// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
5354// from SetUpTestSuite or TearDownTestSuite, or to the global property set
5355// when invoked elsewhere. If the result already contains a property with
5356// the same key, the value will be updated.
5357void UnitTest::RecordProperty(const std::string& key,
5358 const std::string& value) {
5359 impl_->RecordProperty(TestProperty(key, value));
5360}
5361
5362// Runs all tests in this UnitTest object and prints the result.
5363// Returns 0 if successful, or 1 otherwise.
5364//
5365// We don't protect this under mutex_, as we only support calling it
5366// from the main thread.
5367int UnitTest::Run() {
5368 const bool in_death_test_child_process =
5369 GTEST_FLAG_GET(internal_run_death_test).length() > 0;
5370
5371 // Google Test implements this protocol for catching that a test
5372 // program exits before returning control to Google Test:
5373 //
5374 // 1. Upon start, Google Test creates a file whose absolute path
5375 // is specified by the environment variable
5376 // TEST_PREMATURE_EXIT_FILE.
5377 // 2. When Google Test has finished its work, it deletes the file.
5378 //
5379 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5380 // running a Google-Test-based test program and check the existence
5381 // of the file at the end of the test execution to see if it has
5382 // exited prematurely.
5383
5384 // If we are in the child process of a death test, don't
5385 // create/delete the premature exit file, as doing so is unnecessary
5386 // and will confuse the parent process. Otherwise, create/delete
5387 // the file upon entering/leaving this function. If the program
5388 // somehow exits before this function has a chance to return, the
5389 // premature-exit file will be left undeleted, causing a test runner
5390 // that understands the premature-exit-file protocol to report the
5391 // test as having failed.
5392 const internal::ScopedPrematureExitFile premature_exit_file(
5393 in_death_test_child_process
5394 ? nullptr
5395 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5396
5397 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5398 // used for the duration of the program.
5399 impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
5400
5401#if GTEST_OS_WINDOWS
5402 // Either the user wants Google Test to catch exceptions thrown by the
5403 // tests or this is executing in the context of death test child
5404 // process. In either case the user does not want to see pop-up dialogs
5405 // about crashes - they are expected.
5406 if (impl()->catch_exceptions() || in_death_test_child_process) {
5407#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5408 // SetErrorMode doesn't exist on CE.
5409 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5410 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5411#endif // !GTEST_OS_WINDOWS_MOBILE
5412
5413#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5414 // Death test children can be terminated with _abort(). On Windows,
5415 // _abort() can show a dialog with a warning message. This forces the
5416 // abort message to go to stderr instead.
5417 _set_error_mode(_OUT_TO_STDERR);
5418#endif
5419
5420#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
5421 // In the debug version, Visual Studio pops up a separate dialog
5422 // offering a choice to debug the aborted program. We need to suppress
5423 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5424 // executed. Google Test will notify the user of any unexpected
5425 // failure via stderr.
5426 if (!GTEST_FLAG_GET(break_on_failure))
5427 _set_abort_behavior(
5428 0x0, // Clear the following flags:
5429 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5430
5431 // In debug mode, the Windows CRT can crash with an assertion over invalid
5432 // input (e.g. passing an invalid file descriptor). The default handling
5433 // for these assertions is to pop up a dialog and wait for user input.
5434 // Instead ask the CRT to dump such assertions to stderr non-interactively.
5435 if (!IsDebuggerPresent()) {
5436 (void)_CrtSetReportMode(_CRT_ASSERT,
5437 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5438 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5439 }
5440#endif
5441 }
5442#endif // GTEST_OS_WINDOWS
5443
5446 "auxiliary test code (environments or event listeners)")
5447 ? 0
5448 : 1;
5449}
5450
5451// Returns the working directory when the first TEST() or TEST_F() was
5452// executed.
5453const char* UnitTest::original_working_dir() const {
5454 return impl_->original_working_dir_.c_str();
5455}
5456
5457// Returns the TestSuite object for the test that's currently running,
5458// or NULL if no test is running.
5459const TestSuite* UnitTest::current_test_suite() const
5460 GTEST_LOCK_EXCLUDED_(mutex_) {
5461 internal::MutexLock lock(&mutex_);
5462 return impl_->current_test_suite();
5463}
5464
5465// Legacy API is still available but deprecated
5466#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5467const TestCase* UnitTest::current_test_case() const
5468 GTEST_LOCK_EXCLUDED_(mutex_) {
5469 internal::MutexLock lock(&mutex_);
5470 return impl_->current_test_suite();
5471}
5472#endif
5473
5474// Returns the TestInfo object for the test that's currently running,
5475// or NULL if no test is running.
5476const TestInfo* UnitTest::current_test_info() const
5477 GTEST_LOCK_EXCLUDED_(mutex_) {
5478 internal::MutexLock lock(&mutex_);
5479 return impl_->current_test_info();
5480}
5481
5482// Returns the random seed used at the start of the current test run.
5483int UnitTest::random_seed() const { return impl_->random_seed(); }
5484
5485// Returns ParameterizedTestSuiteRegistry object used to keep track of
5486// value-parameterized tests and instantiate and register them.
5487internal::ParameterizedTestSuiteRegistry&
5488UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
5489 return impl_->parameterized_test_registry();
5490}
5491
5492// Creates an empty UnitTest.
5493UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
5494
5495// Destructor of UnitTest.
5496UnitTest::~UnitTest() { delete impl_; }
5497
5498// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5499// Google Test trace stack.
5500void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5501 GTEST_LOCK_EXCLUDED_(mutex_) {
5502 internal::MutexLock lock(&mutex_);
5503 impl_->gtest_trace_stack().push_back(trace);
5504}
5505
5506// Pops a trace from the per-thread Google Test trace stack.
5507void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5508 internal::MutexLock lock(&mutex_);
5509 impl_->gtest_trace_stack().pop_back();
5510}
5511
5512namespace internal {
5513
5514UnitTestImpl::UnitTestImpl(UnitTest* parent)
5515 : parent_(parent),
5516 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5517 default_global_test_part_result_reporter_(this),
5518 default_per_thread_test_part_result_reporter_(this),
5519 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
5520 &default_global_test_part_result_reporter_),
5521 per_thread_test_part_result_reporter_(
5522 &default_per_thread_test_part_result_reporter_),
5523 parameterized_test_registry_(),
5524 parameterized_tests_registered_(false),
5525 last_death_test_suite_(-1),
5526 current_test_suite_(nullptr),
5527 current_test_info_(nullptr),
5528 ad_hoc_test_result_(),
5529 os_stack_trace_getter_(nullptr),
5530 post_flag_parse_init_performed_(false),
5531 random_seed_(0), // Will be overridden by the flag before first use.
5532 random_(0), // Will be reseeded before first use.
5533 start_timestamp_(0),
5534 elapsed_time_(0),
5535#if GTEST_HAS_DEATH_TEST
5536 death_test_factory_(new DefaultDeathTestFactory),
5537#endif
5538 // Will be overridden by the flag before first use.
5539 catch_exceptions_(false) {
5540 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5541}
5542
5544 // Deletes every TestSuite.
5545 ForEach(test_suites_, internal::Delete<TestSuite>);
5546
5547 // Deletes every Environment.
5548 ForEach(environments_, internal::Delete<Environment>);
5549
5550 delete os_stack_trace_getter_;
5551}
5552
5553// Adds a TestProperty to the current TestResult object when invoked in a
5554// context of a test, to current test suite's ad_hoc_test_result when invoke
5555// from SetUpTestSuite/TearDownTestSuite, or to the global property set
5556// otherwise. If the result already contains a property with the same key,
5557// the value will be updated.
5558void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5559 std::string xml_element;
5560 TestResult* test_result; // TestResult appropriate for property recording.
5561
5562 if (current_test_info_ != nullptr) {
5563 xml_element = "testcase";
5564 test_result = &(current_test_info_->result_);
5565 } else if (current_test_suite_ != nullptr) {
5566 xml_element = "testsuite";
5567 test_result = &(current_test_suite_->ad_hoc_test_result_);
5568 } else {
5569 xml_element = "testsuites";
5570 test_result = &ad_hoc_test_result_;
5571 }
5572 test_result->RecordProperty(xml_element, test_property);
5573}
5574
5575#if GTEST_HAS_DEATH_TEST
5576// Disables event forwarding if the control is currently in a death test
5577// subprocess. Must not be called before InitGoogleTest.
5578void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5579 if (internal_run_death_test_flag_.get() != nullptr)
5580 listeners()->SuppressEventForwarding();
5581}
5582#endif // GTEST_HAS_DEATH_TEST
5583
5584// Initializes event listeners performing XML output as specified by
5585// UnitTestOptions. Must not be called before InitGoogleTest.
5587 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5588 if (output_format == "xml") {
5589 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5591 } else if (output_format == "json") {
5592 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
5594 } else if (output_format != "") {
5595 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
5596 << output_format << "\" ignored.";
5597 }
5598}
5599
5600#if GTEST_CAN_STREAM_RESULTS_
5601// Initializes event listeners for streaming test results in string form.
5602// Must not be called before InitGoogleTest.
5603void UnitTestImpl::ConfigureStreamingOutput() {
5604 const std::string& target = GTEST_FLAG_GET(stream_result_to);
5605 if (!target.empty()) {
5606 const size_t pos = target.find(':');
5607 if (pos != std::string::npos) {
5608 listeners()->Append(
5609 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5610 } else {
5611 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
5612 << "\" ignored.";
5613 }
5614 }
5615}
5616#endif // GTEST_CAN_STREAM_RESULTS_
5617
5618// Performs initialization dependent upon flag values obtained in
5619// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5620// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5621// this function is also called from RunAllTests. Since this function can be
5622// called more than once, it has to be idempotent.
5624 // Ensures that this function does not execute more than once.
5625 if (!post_flag_parse_init_performed_) {
5626 post_flag_parse_init_performed_ = true;
5627
5628#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5629 // Register to send notifications about key process state changes.
5630 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5631#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5632
5633#if GTEST_HAS_DEATH_TEST
5634 InitDeathTestSubprocessControlInfo();
5635 SuppressTestEventsIfInSubprocess();
5636#endif // GTEST_HAS_DEATH_TEST
5637
5638 // Registers parameterized tests. This makes parameterized tests
5639 // available to the UnitTest reflection API without running
5640 // RUN_ALL_TESTS.
5642
5643 // Configures listeners for XML output. This makes it possible for users
5644 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5646
5647 if (GTEST_FLAG_GET(brief)) {
5648 listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
5649 }
5650
5651#if GTEST_CAN_STREAM_RESULTS_
5652 // Configures listeners for streaming test results to the specified server.
5653 ConfigureStreamingOutput();
5654#endif // GTEST_CAN_STREAM_RESULTS_
5655
5656#if GTEST_HAS_ABSL
5657 if (GTEST_FLAG_GET(install_failure_signal_handler)) {
5658 absl::FailureSignalHandlerOptions options;
5659 absl::InstallFailureSignalHandler(options);
5660 }
5661#endif // GTEST_HAS_ABSL
5662 }
5663}
5664
5665// A predicate that checks the name of a TestSuite against a known
5666// value.
5667//
5668// This is used for implementation of the UnitTest class only. We put
5669// it in the anonymous namespace to prevent polluting the outer
5670// namespace.
5671//
5672// TestSuiteNameIs is copyable.
5674 public:
5675 // Constructor.
5676 explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
5677
5678 // Returns true if and only if the name of test_suite matches name_.
5679 bool operator()(const TestSuite* test_suite) const {
5680 return test_suite != nullptr &&
5681 strcmp(test_suite->name(), name_.c_str()) == 0;
5682 }
5683
5684 private:
5685 std::string name_;
5686};
5687
5688// Finds and returns a TestSuite with the given name. If one doesn't
5689// exist, creates one and returns it. It's the CALLER'S
5690// RESPONSIBILITY to ensure that this function is only called WHEN THE
5691// TESTS ARE NOT SHUFFLED.
5692//
5693// Arguments:
5694//
5695// test_suite_name: name of the test suite
5696// type_param: the name of the test suite's type parameter, or NULL if
5697// this is not a typed or a type-parameterized test suite.
5698// set_up_tc: pointer to the function that sets up the test suite
5699// tear_down_tc: pointer to the function that tears down the test suite
5701 const char* test_suite_name, const char* type_param,
5702 internal::SetUpTestSuiteFunc set_up_tc,
5703 internal::TearDownTestSuiteFunc tear_down_tc) {
5704 // Can we find a TestSuite with the given name?
5705 const auto test_suite =
5706 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
5707 TestSuiteNameIs(test_suite_name));
5708
5709 if (test_suite != test_suites_.rend()) return *test_suite;
5710
5711 // No. Let's create one.
5712 auto* const new_test_suite =
5713 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5714
5715 const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);
5716 // Is this a death test suite?
5717 if (death_test_suite_filter.MatchesName(test_suite_name)) {
5718 // Yes. Inserts the test suite after the last death test suite
5719 // defined so far. This only works when the test suites haven't
5720 // been shuffled. Otherwise we may end up running a death test
5721 // after a non-death test.
5722 ++last_death_test_suite_;
5723 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5724 new_test_suite);
5725 } else {
5726 // No. Appends to the end of the list.
5727 test_suites_.push_back(new_test_suite);
5728 }
5729
5730 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
5731 return new_test_suite;
5732}
5733
5734// Helpers for setting up / tearing down the given environment. They
5735// are for use in the ForEach() function.
5736static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5737static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5738
5739// Runs all tests in this UnitTest object, prints the result, and
5740// returns true if all tests are successful. If any exception is
5741// thrown during a test, the test is considered to be failed, but the
5742// rest of the tests will still be run.
5743//
5744// When parameterized tests are enabled, it expands and registers
5745// parameterized tests first in RegisterParameterizedTests().
5746// All other functions called from RunAllTests() may safely assume that
5747// parameterized tests are ready to be counted and run.
5749 // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
5750 // called.
5751 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
5752
5753 // Do not run any test if the --help flag was specified.
5754 if (g_help_flag) return true;
5755
5756 // Repeats the call to the post-flag parsing initialization in case the
5757 // user didn't call InitGoogleTest.
5759
5760 // Even if sharding is not on, test runners may want to use the
5761 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5762 // protocol.
5764
5765 // True if and only if we are in a subprocess for running a thread-safe-style
5766 // death test.
5767 bool in_subprocess_for_death_test = false;
5768
5769#if GTEST_HAS_DEATH_TEST
5770 in_subprocess_for_death_test =
5771 (internal_run_death_test_flag_.get() != nullptr);
5772#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5773 if (in_subprocess_for_death_test) {
5774 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5775 }
5776#endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5777#endif // GTEST_HAS_DEATH_TEST
5778
5779 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5780 in_subprocess_for_death_test);
5781
5782 // Compares the full test names with the filter to decide which
5783 // tests to run.
5784 const bool has_tests_to_run =
5787
5788 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5789 if (GTEST_FLAG_GET(list_tests)) {
5790 // This must be called *after* FilterTests() has been called.
5792 return true;
5793 }
5794
5795 random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));
5796
5797 // True if and only if at least one test has failed.
5798 bool failed = false;
5799
5800 TestEventListener* repeater = listeners()->repeater();
5801
5802 start_timestamp_ = GetTimeInMillis();
5803 repeater->OnTestProgramStart(*parent_);
5804
5805 // How many times to repeat the tests? We don't want to repeat them
5806 // when we are inside the subprocess of a death test.
5807 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
5808
5809 // Repeats forever if the repeat count is negative.
5810 const bool gtest_repeat_forever = repeat < 0;
5811
5812 // Should test environments be set up and torn down for each repeat, or only
5813 // set up on the first and torn down on the last iteration? If there is no
5814 // "last" iteration because the tests will repeat forever, always recreate the
5815 // environments to avoid leaks in case one of the environments is using
5816 // resources that are external to this process. Without this check there would
5817 // be no way to clean up those external resources automatically.
5818 const bool recreate_environments_when_repeating =
5819 GTEST_FLAG_GET(recreate_environments_when_repeating) ||
5820 gtest_repeat_forever;
5821
5822 for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
5823 // We want to preserve failures generated by ad-hoc test
5824 // assertions executed before RUN_ALL_TESTS().
5826
5827 Timer timer;
5828
5829 // Shuffles test suites and tests if requested.
5830 if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
5831 random()->Reseed(static_cast<uint32_t>(random_seed_));
5832 // This should be done before calling OnTestIterationStart(),
5833 // such that a test event listener can see the actual test order
5834 // in the event.
5835 ShuffleTests();
5836 }
5837
5838 // Tells the unit test event listeners that the tests are about to start.
5839 repeater->OnTestIterationStart(*parent_, i);
5840
5841 // Runs each test suite if there is at least one test to run.
5842 if (has_tests_to_run) {
5843 // Sets up all environments beforehand. If test environments aren't
5844 // recreated for each iteration, only do so on the first iteration.
5845 if (i == 0 || recreate_environments_when_repeating) {
5846 repeater->OnEnvironmentsSetUpStart(*parent_);
5847 ForEach(environments_, SetUpEnvironment);
5848 repeater->OnEnvironmentsSetUpEnd(*parent_);
5849 }
5850
5851 // Runs the tests only if there was no fatal failure or skip triggered
5852 // during global set-up.
5853 if (Test::IsSkipped()) {
5854 // Emit diagnostics when global set-up calls skip, as it will not be
5855 // emitted by default.
5856 TestResult& test_result =
5858 for (int j = 0; j < test_result.total_part_count(); ++j) {
5859 const TestPartResult& test_part_result =
5860 test_result.GetTestPartResult(j);
5861 if (test_part_result.type() == TestPartResult::kSkip) {
5862 const std::string& result = test_part_result.message();
5863 printf("%s\n", result.c_str());
5864 }
5865 }
5866 fflush(stdout);
5867 } else if (!Test::HasFatalFailure()) {
5868 for (int test_index = 0; test_index < total_test_suite_count();
5869 test_index++) {
5870 GetMutableSuiteCase(test_index)->Run();
5871 if (GTEST_FLAG_GET(fail_fast) &&
5872 GetMutableSuiteCase(test_index)->Failed()) {
5873 for (int j = test_index + 1; j < total_test_suite_count(); j++) {
5874 GetMutableSuiteCase(j)->Skip();
5875 }
5876 break;
5877 }
5878 }
5879 } else if (Test::HasFatalFailure()) {
5880 // If there was a fatal failure during the global setup then we know we
5881 // aren't going to run any tests. Explicitly mark all of the tests as
5882 // skipped to make this obvious in the output.
5883 for (int test_index = 0; test_index < total_test_suite_count();
5884 test_index++) {
5885 GetMutableSuiteCase(test_index)->Skip();
5886 }
5887 }
5888
5889 // Tears down all environments in reverse order afterwards. If test
5890 // environments aren't recreated for each iteration, only do so on the
5891 // last iteration.
5892 if (i == repeat - 1 || recreate_environments_when_repeating) {
5893 repeater->OnEnvironmentsTearDownStart(*parent_);
5894 std::for_each(environments_.rbegin(), environments_.rend(),
5896 repeater->OnEnvironmentsTearDownEnd(*parent_);
5897 }
5898 }
5899
5900 elapsed_time_ = timer.Elapsed();
5901
5902 // Tells the unit test event listener that the tests have just finished.
5903 repeater->OnTestIterationEnd(*parent_, i);
5904
5905 // Gets the result and clears it.
5906 if (!Passed()) {
5907 failed = true;
5908 }
5909
5910 // Restores the original test order after the iteration. This
5911 // allows the user to quickly repro a failure that happens in the
5912 // N-th iteration without repeating the first (N - 1) iterations.
5913 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5914 // case the user somehow changes the value of the flag somewhere
5915 // (it's always safe to unshuffle the tests).
5917
5918 if (GTEST_FLAG_GET(shuffle)) {
5919 // Picks a new random seed for each iteration.
5920 random_seed_ = GetNextRandomSeed(random_seed_);
5921 }
5922 }
5923
5924 repeater->OnTestProgramEnd(*parent_);
5925
5926 if (!gtest_is_initialized_before_run_all_tests) {
5928 GTestColor::kRed,
5929 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5930 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5931 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5932 " will start to enforce the valid usage. "
5933 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
5934#if GTEST_FOR_GOOGLE_
5935 ColoredPrintf(GTestColor::kRed,
5936 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5937#endif // GTEST_FOR_GOOGLE_
5938 }
5939
5940 return !failed;
5941}
5942
5943// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5944// if the variable is present. If a file already exists at this location, this
5945// function will write over it. If the variable is present, but the file cannot
5946// be created, prints an error and exits.
5948 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5949 if (test_shard_file != nullptr) {
5950 FILE* const file = posix::FOpen(test_shard_file, "w");
5951 if (file == nullptr) {
5952 ColoredPrintf(GTestColor::kRed,
5953 "Could not write to the test shard status file \"%s\" "
5954 "specified by the %s environment variable.\n",
5955 test_shard_file, kTestShardStatusFile);
5956 fflush(stdout);
5957 exit(EXIT_FAILURE);
5958 }
5959 fclose(file);
5960 }
5961}
5962
5963// Checks whether sharding is enabled by examining the relevant
5964// environment variable values. If the variables are present,
5965// but inconsistent (i.e., shard_index >= total_shards), prints
5966// an error and exits. If in_subprocess_for_death_test, sharding is
5967// disabled because it must only be applied to the original test
5968// process. Otherwise, we could filter out death tests we intended to execute.
5969bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
5970 bool in_subprocess_for_death_test) {
5971 if (in_subprocess_for_death_test) {
5972 return false;
5973 }
5974
5975 const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5976 const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5977
5978 if (total_shards == -1 && shard_index == -1) {
5979 return false;
5980 } else if (total_shards == -1 && shard_index != -1) {
5981 const Message msg = Message() << "Invalid environment variables: you have "
5982 << kTestShardIndex << " = " << shard_index
5983 << ", but have left " << kTestTotalShards
5984 << " unset.\n";
5985 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
5986 fflush(stdout);
5987 exit(EXIT_FAILURE);
5988 } else if (total_shards != -1 && shard_index == -1) {
5989 const Message msg = Message()
5990 << "Invalid environment variables: you have "
5991 << kTestTotalShards << " = " << total_shards
5992 << ", but have left " << kTestShardIndex << " unset.\n";
5993 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
5994 fflush(stdout);
5995 exit(EXIT_FAILURE);
5996 } else if (shard_index < 0 || shard_index >= total_shards) {
5997 const Message msg =
5998 Message() << "Invalid environment variables: we require 0 <= "
5999 << kTestShardIndex << " < " << kTestTotalShards
6000 << ", but you have " << kTestShardIndex << "=" << shard_index
6001 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6002 ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
6003 fflush(stdout);
6004 exit(EXIT_FAILURE);
6005 }
6006
6007 return total_shards > 1;
6008}
6009
6010// Parses the environment variable var as an Int32. If it is unset,
6011// returns default_val. If it is not an Int32, prints an error
6012// and aborts.
6013int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
6014 const char* str_val = posix::GetEnv(var);
6015 if (str_val == nullptr) {
6016 return default_val;
6017 }
6018
6019 int32_t result;
6020 if (!ParseInt32(Message() << "The value of environment variable " << var,
6021 str_val, &result)) {
6022 exit(EXIT_FAILURE);
6023 }
6024 return result;
6025}
6026
6027// Given the total number of shards, the shard index, and the test id,
6028// returns true if and only if the test should be run on this shard. The test id
6029// is some arbitrary but unique non-negative integer assigned to each test
6030// method. Assumes that 0 <= shard_index < total_shards.
6031bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6032 return (test_id % total_shards) == shard_index;
6033}
6034
6035// Compares the name of each test with the user-specified filter to
6036// decide whether the test should be run, then records the result in
6037// each TestSuite and TestInfo object.
6038// If shard_tests == true, further filters tests based on sharding
6039// variables in the environment - see
6040// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6041// . Returns the number of tests that should run.
6043 const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
6045 : -1;
6046 const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
6048 : -1;
6049
6050 const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6051 GTEST_FLAG_GET(filter));
6052 const UnitTestFilter disable_test_filter(kDisableTestFilter);
6053 // num_runnable_tests are the number of tests that will
6054 // run across all shards (i.e., match filter and are not disabled).
6055 // num_selected_tests are the number of tests to be run on
6056 // this shard.
6057 int num_runnable_tests = 0;
6058 int num_selected_tests = 0;
6059 for (auto* test_suite : test_suites_) {
6060 const std::string& test_suite_name = test_suite->name();
6061 test_suite->set_should_run(false);
6062
6063 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6064 TestInfo* const test_info = test_suite->test_info_list()[j];
6065 const std::string test_name(test_info->name());
6066 // A test is disabled if test suite name or test name matches
6067 // kDisableTestFilter.
6068 const bool is_disabled =
6069 disable_test_filter.MatchesName(test_suite_name) ||
6070 disable_test_filter.MatchesName(test_name);
6071 test_info->is_disabled_ = is_disabled;
6072
6073 const bool matches_filter =
6074 gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6075 test_info->matches_filter_ = matches_filter;
6076
6077 const bool is_runnable =
6078 (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
6079 matches_filter;
6080
6081 const bool is_in_another_shard =
6082 shard_tests != IGNORE_SHARDING_PROTOCOL &&
6083 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6084 test_info->is_in_another_shard_ = is_in_another_shard;
6085 const bool is_selected = is_runnable && !is_in_another_shard;
6086
6087 num_runnable_tests += is_runnable;
6088 num_selected_tests += is_selected;
6089
6090 test_info->should_run_ = is_selected;
6091 test_suite->set_should_run(test_suite->should_run() || is_selected);
6092 }
6093 }
6094 return num_selected_tests;
6095}
6096
6097// Prints the given C-string on a single line by replacing all '\n'
6098// characters with string "\\n". If the output takes more than
6099// max_length characters, only prints the first max_length characters
6100// and "...".
6101static void PrintOnOneLine(const char* str, int max_length) {
6102 if (str != nullptr) {
6103 for (int i = 0; *str != '\0'; ++str) {
6104 if (i >= max_length) {
6105 printf("...");
6106 break;
6107 }
6108 if (*str == '\n') {
6109 printf("\\n");
6110 i += 2;
6111 } else {
6112 printf("%c", *str);
6113 ++i;
6114 }
6115 }
6116 }
6117}
6118
6119// Prints the names of the tests matching the user-specified filter flag.
6121 // Print at most this many characters for each type/value parameter.
6122 const int kMaxParamLength = 250;
6123
6124 for (auto* test_suite : test_suites_) {
6125 bool printed_test_suite_name = false;
6126
6127 for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6128 const TestInfo* const test_info = test_suite->test_info_list()[j];
6129 if (test_info->matches_filter_) {
6130 if (!printed_test_suite_name) {
6131 printed_test_suite_name = true;
6132 printf("%s.", test_suite->name());
6133 if (test_suite->type_param() != nullptr) {
6134 printf(" # %s = ", kTypeParamLabel);
6135 // We print the type parameter on a single line to make
6136 // the output easy to parse by a program.
6137 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6138 }
6139 printf("\n");
6140 }
6141 printf(" %s", test_info->name());
6142 if (test_info->value_param() != nullptr) {
6143 printf(" # %s = ", kValueParamLabel);
6144 // We print the value parameter on a single line to make the
6145 // output easy to parse by a program.
6146 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6147 }
6148 printf("\n");
6149 }
6150 }
6151 }
6152 fflush(stdout);
6153 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6154 if (output_format == "xml" || output_format == "json") {
6155 FILE* fileout = OpenFileForWriting(
6157 std::stringstream stream;
6158 if (output_format == "xml") {
6161 .PrintXmlTestsList(&stream, test_suites_);
6162 } else if (output_format == "json") {
6165 .PrintJsonTestList(&stream, test_suites_);
6166 }
6167 fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6168 fclose(fileout);
6169 }
6170}
6171
6172// Sets the OS stack trace getter.
6173//
6174// Does nothing if the input and the current OS stack trace getter are
6175// the same; otherwise, deletes the old getter and makes the input the
6176// current getter.
6179 if (os_stack_trace_getter_ != getter) {
6180 delete os_stack_trace_getter_;
6181 os_stack_trace_getter_ = getter;
6182 }
6183}
6184
6185// Returns the current OS stack trace getter if it is not NULL;
6186// otherwise, creates an OsStackTraceGetter, makes it the current
6187// getter, and returns it.
6189 if (os_stack_trace_getter_ == nullptr) {
6190#ifdef GTEST_OS_STACK_TRACE_GETTER_
6191 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6192#else
6193 os_stack_trace_getter_ = new OsStackTraceGetter;
6194#endif // GTEST_OS_STACK_TRACE_GETTER_
6195 }
6196
6197 return os_stack_trace_getter_;
6198}
6199
6200// Returns the most specific TestResult currently running.
6202 if (current_test_info_ != nullptr) {
6203 return &current_test_info_->result_;
6204 }
6205 if (current_test_suite_ != nullptr) {
6206 return &current_test_suite_->ad_hoc_test_result_;
6207 }
6208 return &ad_hoc_test_result_;
6209}
6210
6211// Shuffles all test suites, and the tests within each test suite,
6212// making sure that death tests are still run first.
6214 // Shuffles the death test suites.
6215 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
6216
6217 // Shuffles the non-death test suites.
6218 ShuffleRange(random(), last_death_test_suite_ + 1,
6219 static_cast<int>(test_suites_.size()), &test_suite_indices_);
6220
6221 // Shuffles the tests inside each test suite.
6222 for (auto& test_suite : test_suites_) {
6223 test_suite->ShuffleTests(random());
6224 }
6225}
6226
6227// Restores the test suites and tests to their order before the first shuffle.
6229 for (size_t i = 0; i < test_suites_.size(); i++) {
6230 // Unshuffles the tests in each test suite.
6231 test_suites_[i]->UnshuffleTests();
6232 // Resets the index of each test suite.
6233 test_suite_indices_[i] = static_cast<int>(i);
6234 }
6235}
6236
6237// Returns the current OS stack trace as an std::string.
6238//
6239// The maximum number of stack frames to be included is specified by
6240// the gtest_stack_trace_depth flag. The skip_count parameter
6241// specifies the number of top frames to be skipped, which doesn't
6242// count against the number of frames to be included.
6243//
6244// For example, if Foo() calls Bar(), which in turn calls
6245// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6246// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6247GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
6248GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {
6249 // We pass skip_count + 1 to skip this wrapper function in addition
6250 // to what the user really wants to skip.
6251 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6252}
6253
6254// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6255// suppress unreachable code warnings.
6256namespace {
6257class ClassUniqueToAlwaysTrue {};
6258} // namespace
6259
6260bool IsTrue(bool condition) { return condition; }
6261
6263#if GTEST_HAS_EXCEPTIONS
6264 // This condition is always false so AlwaysTrue() never actually throws,
6265 // but it makes the compiler think that it may throw.
6266 if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
6267#endif // GTEST_HAS_EXCEPTIONS
6268 return true;
6269}
6270
6271// If *pstr starts with the given prefix, modifies *pstr to be right
6272// past the prefix and returns true; otherwise leaves *pstr unchanged
6273// and returns false. None of pstr, *pstr, and prefix can be NULL.
6274bool SkipPrefix(const char* prefix, const char** pstr) {
6275 const size_t prefix_len = strlen(prefix);
6276 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6277 *pstr += prefix_len;
6278 return true;
6279 }
6280 return false;
6281}
6282
6283// Parses a string as a command line flag. The string should have
6284// the format "--flag=value". When def_optional is true, the "=value"
6285// part can be omitted.
6286//
6287// Returns the value of the flag, or NULL if the parsing failed.
6288static const char* ParseFlagValue(const char* str, const char* flag_name,
6289 bool def_optional) {
6290 // str and flag must not be NULL.
6291 if (str == nullptr || flag_name == nullptr) return nullptr;
6292
6293 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6294 const std::string flag_str =
6295 std::string("--") + GTEST_FLAG_PREFIX_ + flag_name;
6296 const size_t flag_len = flag_str.length();
6297 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
6298
6299 // Skips the flag name.
6300 const char* flag_end = str + flag_len;
6301
6302 // When def_optional is true, it's OK to not have a "=value" part.
6303 if (def_optional && (flag_end[0] == '\0')) {
6304 return flag_end;
6305 }
6306
6307 // If def_optional is true and there are more characters after the
6308 // flag name, or if def_optional is false, there must be a '=' after
6309 // the flag name.
6310 if (flag_end[0] != '=') return nullptr;
6311
6312 // Returns the string after "=".
6313 return flag_end + 1;
6314}
6315
6316// Parses a string for a bool flag, in the form of either
6317// "--flag=value" or "--flag".
6318//
6319// In the former case, the value is taken as true as long as it does
6320// not start with '0', 'f', or 'F'.
6321//
6322// In the latter case, the value is taken as true.
6323//
6324// On success, stores the value of the flag in *value, and returns
6325// true. On failure, returns false without changing *value.
6326static bool ParseFlag(const char* str, const char* flag_name, bool* value) {
6327 // Gets the value of the flag as a string.
6328 const char* const value_str = ParseFlagValue(str, flag_name, true);
6329
6330 // Aborts if the parsing failed.
6331 if (value_str == nullptr) return false;
6332
6333 // Converts the string value to a bool.
6334 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6335 return true;
6336}
6337
6338// Parses a string for an int32_t flag, in the form of "--flag=value".
6339//
6340// On success, stores the value of the flag in *value, and returns
6341// true. On failure, returns false without changing *value.
6342bool ParseFlag(const char* str, const char* flag_name, int32_t* value) {
6343 // Gets the value of the flag as a string.
6344 const char* const value_str = ParseFlagValue(str, flag_name, false);
6345
6346 // Aborts if the parsing failed.
6347 if (value_str == nullptr) return false;
6348
6349 // Sets *value to the value of the flag.
6350 return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
6351 value);
6352}
6353
6354// Parses a string for a string flag, in the form of "--flag=value".
6355//
6356// On success, stores the value of the flag in *value, and returns
6357// true. On failure, returns false without changing *value.
6358template <typename String>
6359static bool ParseFlag(const char* str, const char* flag_name, String* value) {
6360 // Gets the value of the flag as a string.
6361 const char* const value_str = ParseFlagValue(str, flag_name, false);
6362
6363 // Aborts if the parsing failed.
6364 if (value_str == nullptr) return false;
6365
6366 // Sets *value to the value of the flag.
6367 *value = value_str;
6368 return true;
6369}
6370
6371// Determines whether a string has a prefix that Google Test uses for its
6372// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6373// If Google Test detects that a command line flag has its prefix but is not
6374// recognized, it will print its help message. Flags starting with
6375// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6376// internal flags and do not trigger the help message.
6377static bool HasGoogleTestFlagPrefix(const char* str) {
6378 return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
6379 SkipPrefix("/", &str)) &&
6380 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6381 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6382 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6383}
6384
6385// Prints a string containing code-encoded text. The following escape
6386// sequences can be used in the string to control the text color:
6387//
6388// @@ prints a single '@' character.
6389// @R changes the color to red.
6390// @G changes the color to green.
6391// @Y changes the color to yellow.
6392// @D changes to the default terminal text color.
6393//
6394static void PrintColorEncoded(const char* str) {
6395 GTestColor color = GTestColor::kDefault; // The current color.
6396
6397 // Conceptually, we split the string into segments divided by escape
6398 // sequences. Then we print one segment at a time. At the end of
6399 // each iteration, the str pointer advances to the beginning of the
6400 // next segment.
6401 for (;;) {
6402 const char* p = strchr(str, '@');
6403 if (p == nullptr) {
6404 ColoredPrintf(color, "%s", str);
6405 return;
6406 }
6407
6408 ColoredPrintf(color, "%s", std::string(str, p).c_str());
6409
6410 const char ch = p[1];
6411 str = p + 2;
6412 if (ch == '@') {
6413 ColoredPrintf(color, "@");
6414 } else if (ch == 'D') {
6415 color = GTestColor::kDefault;
6416 } else if (ch == 'R') {
6417 color = GTestColor::kRed;
6418 } else if (ch == 'G') {
6419 color = GTestColor::kGreen;
6420 } else if (ch == 'Y') {
6421 color = GTestColor::kYellow;
6422 } else {
6423 --str;
6424 }
6425 }
6426}
6427
6428static const char kColorEncodedHelpMessage[] =
6429 "This program contains tests written using " GTEST_NAME_
6430 ". You can use the\n"
6431 "following command line flags to control its behavior:\n"
6432 "\n"
6433 "Test Selection:\n"
6434 " @G--" GTEST_FLAG_PREFIX_
6435 "list_tests@D\n"
6436 " List the names of all tests instead of running them. The name of\n"
6437 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6438 " @G--" GTEST_FLAG_PREFIX_
6439 "filter=@YPOSITIVE_PATTERNS"
6440 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6441 " Run only the tests whose name matches one of the positive patterns "
6442 "but\n"
6443 " none of the negative patterns. '?' matches any single character; "
6444 "'*'\n"
6445 " matches any substring; ':' separates two patterns.\n"
6446 " @G--" GTEST_FLAG_PREFIX_
6447 "also_run_disabled_tests@D\n"
6448 " Run all disabled tests too.\n"
6449 "\n"
6450 "Test Execution:\n"
6451 " @G--" GTEST_FLAG_PREFIX_
6452 "repeat=@Y[COUNT]@D\n"
6453 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6454 " @G--" GTEST_FLAG_PREFIX_
6455 "shuffle@D\n"
6456 " Randomize tests' orders on every iteration.\n"
6457 " @G--" GTEST_FLAG_PREFIX_
6458 "random_seed=@Y[NUMBER]@D\n"
6459 " Random number seed to use for shuffling test orders (between 1 and\n"
6460 " 99999, or 0 to use a seed based on the current time).\n"
6461 " @G--" GTEST_FLAG_PREFIX_
6462 "recreate_environments_when_repeating@D\n"
6463 " Sets up and tears down the global test environment on each repeat\n"
6464 " of the test.\n"
6465 "\n"
6466 "Test Output:\n"
6467 " @G--" GTEST_FLAG_PREFIX_
6468 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6469 " Enable/disable colored output. The default is @Gauto@D.\n"
6470 " @G--" GTEST_FLAG_PREFIX_
6471 "brief=1@D\n"
6472 " Only print test failures.\n"
6473 " @G--" GTEST_FLAG_PREFIX_
6474 "print_time=0@D\n"
6475 " Don't print the elapsed time of each test.\n"
6476 " @G--" GTEST_FLAG_PREFIX_
6477 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6478 "@Y|@G:@YFILE_PATH]@D\n"
6479 " Generate a JSON or XML report in the given directory or with the "
6480 "given\n"
6481 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6482#if GTEST_CAN_STREAM_RESULTS_
6483 " @G--" GTEST_FLAG_PREFIX_
6484 "stream_result_to=@YHOST@G:@YPORT@D\n"
6485 " Stream test results to the given server.\n"
6486#endif // GTEST_CAN_STREAM_RESULTS_
6487 "\n"
6488 "Assertion Behavior:\n"
6489#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6490 " @G--" GTEST_FLAG_PREFIX_
6491 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6492 " Set the default death test style.\n"
6493#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6494 " @G--" GTEST_FLAG_PREFIX_
6495 "break_on_failure@D\n"
6496 " Turn assertion failures into debugger break-points.\n"
6497 " @G--" GTEST_FLAG_PREFIX_
6498 "throw_on_failure@D\n"
6499 " Turn assertion failures into C++ exceptions for use by an external\n"
6500 " test framework.\n"
6501 " @G--" GTEST_FLAG_PREFIX_
6502 "catch_exceptions=0@D\n"
6503 " Do not report exceptions as test failures. Instead, allow them\n"
6504 " to crash the program or throw a pop-up (on Windows).\n"
6505 "\n"
6506 "Except for @G--" GTEST_FLAG_PREFIX_
6507 "list_tests@D, you can alternatively set "
6508 "the corresponding\n"
6509 "environment variable of a flag (all letters in upper-case). For example, "
6510 "to\n"
6511 "disable colored text output, you can either specify "
6512 "@G--" GTEST_FLAG_PREFIX_
6513 "color=no@D or set\n"
6514 "the @G" GTEST_FLAG_PREFIX_UPPER_
6515 "COLOR@D environment variable to @Gno@D.\n"
6516 "\n"
6517 "For more information, please read the " GTEST_NAME_
6518 " documentation at\n"
6519 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
6520 "\n"
6521 "(not one in your own code or tests), please report it to\n"
6522 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6523
6524static bool ParseGoogleTestFlag(const char* const arg) {
6525#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6526 do { \
6527 auto value = GTEST_FLAG_GET(flag_name); \
6528 if (ParseFlag(arg, #flag_name, &value)) { \
6529 GTEST_FLAG_SET(flag_name, value); \
6530 return true; \
6531 } \
6532 } while (false)
6533
6534 GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);
6535 GTEST_INTERNAL_PARSE_FLAG(break_on_failure);
6536 GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);
6538 GTEST_INTERNAL_PARSE_FLAG(death_test_style);
6539 GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
6540 GTEST_INTERNAL_PARSE_FLAG(fail_fast);
6542 GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
6543 GTEST_INTERNAL_PARSE_FLAG(list_tests);
6546 GTEST_INTERNAL_PARSE_FLAG(print_time);
6547 GTEST_INTERNAL_PARSE_FLAG(print_utf8);
6548 GTEST_INTERNAL_PARSE_FLAG(random_seed);
6550 GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);
6552 GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);
6553 GTEST_INTERNAL_PARSE_FLAG(stream_result_to);
6554 GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);
6555 return false;
6556}
6557
6558#if GTEST_USE_OWN_FLAGFILE_FLAG_
6559static void LoadFlagsFromFile(const std::string& path) {
6560 FILE* flagfile = posix::FOpen(path.c_str(), "r");
6561 if (!flagfile) {
6562 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile)
6563 << "\"";
6564 }
6565 std::string contents(ReadEntireFile(flagfile));
6566 posix::FClose(flagfile);
6567 std::vector<std::string> lines;
6568 SplitString(contents, '\n', &lines);
6569 for (size_t i = 0; i < lines.size(); ++i) {
6570 if (lines[i].empty()) continue;
6571 if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
6572 }
6573}
6574#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6575
6576// Parses the command line for Google Test flags, without initializing
6577// other parts of Google Test. The type parameter CharType can be
6578// instantiated to either char or wchar_t.
6579template <typename CharType>
6580void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6581 std::string flagfile_value;
6582 for (int i = 1; i < *argc; i++) {
6583 const std::string arg_string = StreamableToString(argv[i]);
6584 const char* const arg = arg_string.c_str();
6585
6586 using internal::ParseFlag;
6587
6588 bool remove_flag = false;
6589 if (ParseGoogleTestFlag(arg)) {
6590 remove_flag = true;
6591#if GTEST_USE_OWN_FLAGFILE_FLAG_
6592 } else if (ParseFlag(arg, "flagfile", &flagfile_value)) {
6593 GTEST_FLAG_SET(flagfile, flagfile_value);
6594 LoadFlagsFromFile(flagfile_value);
6595 remove_flag = true;
6596#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6597 } else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) {
6598 // Both help flag and unrecognized Google Test flags (excluding
6599 // internal ones) trigger help display.
6600 g_help_flag = true;
6601 }
6602
6603 if (remove_flag) {
6604 // Shift the remainder of the argv list left by one. Note
6605 // that argv has (*argc + 1) elements, the last one always being
6606 // NULL. The following loop moves the trailing NULL element as
6607 // well.
6608 for (int j = i; j != *argc; j++) {
6609 argv[j] = argv[j + 1];
6610 }
6611
6612 // Decrements the argument count.
6613 (*argc)--;
6614
6615 // We also need to decrement the iterator as we just removed
6616 // an element.
6617 i--;
6618 }
6619 }
6620
6621 if (g_help_flag) {
6622 // We print the help here instead of in RUN_ALL_TESTS(), as the
6623 // latter may not be called at all if the user is using Google
6624 // Test with another testing framework.
6626 }
6627}
6628
6629// Parses the command line for Google Test flags, without initializing
6630// other parts of Google Test.
6631void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6632#if GTEST_HAS_ABSL
6633 if (*argc > 0) {
6634 // absl::ParseCommandLine() requires *argc > 0.
6635 auto positional_args = absl::flags_internal::ParseCommandLineImpl(
6636 *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
6637 absl::flags_internal::UsageFlagsAction::kHandleUsage,
6638 absl::flags_internal::OnUndefinedFlag::kReportUndefined);
6639 // Any command-line positional arguments not part of any command-line flag
6640 // (or arguments to a flag) are copied back out to argv, with the program
6641 // invocation name at position 0, and argc is resized. This includes
6642 // positional arguments after the flag-terminating delimiter '--'.
6643 // See https://abseil.io/docs/cpp/guides/flags.
6644 std::copy(positional_args.begin(), positional_args.end(), argv);
6645 if (static_cast<int>(positional_args.size()) < *argc) {
6646 argv[positional_args.size()] = nullptr;
6647 *argc = static_cast<int>(positional_args.size());
6648 }
6649 }
6650#else
6651 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6652#endif
6653
6654 // Fix the value of *_NSGetArgc() on macOS, but if and only if
6655 // *_NSGetArgv() == argv
6656 // Only applicable to char** version of argv
6657#if GTEST_OS_MAC
6658#ifndef GTEST_OS_IOS
6659 if (*_NSGetArgv() == argv) {
6660 *_NSGetArgc() = *argc;
6661 }
6662#endif
6663#endif
6664}
6665void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6666 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6667}
6668
6669// The internal implementation of InitGoogleTest().
6670//
6671// The type parameter CharType can be instantiated to either char or
6672// wchar_t.
6673template <typename CharType>
6674void InitGoogleTestImpl(int* argc, CharType** argv) {
6675 // We don't want to run the initialization code twice.
6676 if (GTestIsInitialized()) return;
6677
6678 if (*argc <= 0) return;
6679
6680 g_argvs.clear();
6681 for (int i = 0; i != *argc; i++) {
6682 g_argvs.push_back(StreamableToString(argv[i]));
6683 }
6684
6685#if GTEST_HAS_ABSL
6686 absl::InitializeSymbolizer(g_argvs[0].c_str());
6687
6688 // When using the Abseil Flags library, set the program usage message to the
6689 // help message, but remove the color-encoding from the message first.
6690 absl::SetProgramUsageMessage(absl::StrReplaceAll(
6692 {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}}));
6693#endif // GTEST_HAS_ABSL
6694
6695 ParseGoogleTestFlagsOnly(argc, argv);
6697}
6698
6699} // namespace internal
6700
6701// Initializes Google Test. This must be called before calling
6702// RUN_ALL_TESTS(). In particular, it parses a command line for the
6703// flags that Google Test recognizes. Whenever a Google Test flag is
6704// seen, it is removed from argv, and *argc is decremented.
6705//
6706// No value is returned. Instead, the Google Test flag variables are
6707// updated.
6708//
6709// Calling the function for the second time has no user-visible effect.
6710void InitGoogleTest(int* argc, char** argv) {
6711#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6712 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6713#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6714 internal::InitGoogleTestImpl(argc, argv);
6715#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6716}
6717
6718// This overloaded version can be used in Windows programs compiled in
6719// UNICODE mode.
6720void InitGoogleTest(int* argc, wchar_t** argv) {
6721#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6722 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6723#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6724 internal::InitGoogleTestImpl(argc, argv);
6725#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6726}
6727
6728// This overloaded version can be used on Arduino/embedded platforms where
6729// there is no argc/argv.
6731 // Since Arduino doesn't have a command line, fake out the argc/argv arguments
6732 int argc = 1;
6733 const auto arg0 = "dummy";
6734 char* argv0 = const_cast<char*>(arg0);
6735 char** argv = &argv0;
6736
6737#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6738 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6739#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6740 internal::InitGoogleTestImpl(&argc, argv);
6741#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6742}
6743
6744#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6745// Return value of first environment variable that is set and contains
6746// a non-empty string. If there are none, return the "fallback" string.
6747// Since we like the temporary directory to have a directory separator suffix,
6748// add it if not provided in the environment variable value.
6749static std::string GetTempDirFromEnv(
6750 std::initializer_list<const char*> environment_variables,
6751 const char* fallback, char separator) {
6752 for (const char* variable_name : environment_variables) {
6753 const char* value = internal::posix::GetEnv(variable_name);
6754 if (value != nullptr && value[0] != '\0') {
6755 if (value[strlen(value) - 1] != separator) {
6756 return std::string(value).append(1, separator);
6757 }
6758 return value;
6759 }
6760 }
6761 return fallback;
6762}
6763#endif
6764
6765std::string TempDir() {
6766#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6767 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6768#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE
6769 return GetTempDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
6770#elif GTEST_OS_LINUX_ANDROID
6771 return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
6772#else
6773 return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
6774#endif
6775}
6776
6777// Class ScopedTrace
6778
6779// Pushes the given source file location and message onto a per-thread
6780// trace stack maintained by Google Test.
6781void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
6782 internal::TraceInfo trace;
6783 trace.file = file;
6784 trace.line = line;
6785 trace.message.swap(message);
6786
6787 UnitTest::GetInstance()->PushGTestTrace(trace);
6788}
6789
6790// Pops the info pushed by the c'tor.
6791ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
6792 UnitTest::GetInstance()->PopGTestTrace();
6793}
6794
6795} // namespace testing
void OnEnvironmentsTearDownStart(const UnitTest &) override
Definition gtest.cc:3682
void OnTestIterationStart(const UnitTest &, int) override
Definition gtest.cc:3661
void OnTestCaseStart(const TestCase &) override
Definition gtest.cc:3666
void OnEnvironmentsSetUpStart(const UnitTest &) override
Definition gtest.cc:3663
void OnEnvironmentsTearDownEnd(const UnitTest &) override
Definition gtest.cc:3683
void OnTestProgramStart(const UnitTest &) override
Definition gtest.cc:3660
void OnTestProgramEnd(const UnitTest &) override
Definition gtest.cc:3685
static void PrintTestName(const char *test_suite, const char *test)
Definition gtest.cc:3655
void OnTestStart(const TestInfo &) override
Definition gtest.cc:3671
void OnTestCaseEnd(const TestCase &) override
Definition gtest.cc:3677
void OnTestDisabled(const TestInfo &) override
Definition gtest.cc:3672
void OnEnvironmentsSetUpEnd(const UnitTest &) override
Definition gtest.cc:3664
void ReportTestPartResult(const TestPartResult &result) override
Definition gtest.cc:992
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
Definition gtest.cc:998
void ReportTestPartResult(const TestPartResult &result) override
Definition gtest.cc:1002
JsonUnitTestResultPrinter(const char *output_file)
Definition gtest.cc:4498
static void PrintJsonTestList(::std::ostream *stream, const std::vector< TestSuite * > &test_suites)
Definition gtest.cc:4832
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
Definition gtest.cc:4505
std::string CurrentStackTrace(int max_depth, int skip_count) override
Definition gtest.cc:4948
virtual std::string CurrentStackTrace(int max_depth, int skip_count)=0
void OnTestProgramStart(const UnitTest &) override
Definition gtest.cc:3352
void OnTestProgramEnd(const UnitTest &) override
Definition gtest.cc:3376
void OnEnvironmentsTearDownEnd(const UnitTest &) override
Definition gtest.cc:3374
void OnEnvironmentsSetUpEnd(const UnitTest &) override
Definition gtest.cc:3355
static void PrintTestName(const char *test_suite, const char *test)
Definition gtest.cc:3347
ScopedPrematureExitFile(const char *premature_exit_filepath)
Definition gtest.cc:5014
void OnEnvironmentsTearDownEnd(const UnitTest &unit_test) override
void OnTestEnd(const TestInfo &test_info) override
void OnTestProgramEnd(const UnitTest &unit_test) override
void OnTestStart(const TestInfo &test_info) override
void OnTestSuiteEnd(const TestSuite &parameter) override
void OnEnvironmentsSetUpStart(const UnitTest &unit_test) override
void OnEnvironmentsSetUpEnd(const UnitTest &unit_test) override
void OnTestCaseStart(const TestSuite &parameter) override
void set_forwarding_enabled(bool enable)
Definition gtest.cc:3767
void OnTestCaseEnd(const TestCase &parameter) override
void OnEnvironmentsTearDownStart(const UnitTest &unit_test) override
void OnTestSuiteStart(const TestSuite &parameter) override
void OnTestPartResult(const TestPartResult &result) override
void OnTestProgramStart(const UnitTest &unit_test) override
void OnTestDisabled(const TestInfo &test_info) override
bool operator()(const TestSuite *test_suite) const
Definition gtest.cc:5679
TestSuiteNameIs(const std::string &name)
Definition gtest.cc:5676
TimeInMillis Elapsed()
Definition gtest.cc:1119
int reportable_disabled_test_count() const
Definition gtest.cc:1070
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
Definition gtest.cc:1028
void RecordProperty(const TestProperty &test_property)
Definition gtest.cc:5558
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
Definition gtest.cc:1009
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_
Definition gtest.cc:1105
int test_suite_to_run_count() const
Definition gtest.cc:1050
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
Definition gtest.cc:6177
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
Definition gtest.cc:1023
OsStackTraceGetterInterface * os_stack_trace_getter()
Definition gtest.cc:6188
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
Definition gtest.cc:1015
int successful_test_suite_count() const
Definition gtest.cc:1034
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo *test_info)
TestResult * current_test_result()
Definition gtest.cc:6201
int FilterTests(ReactionToSharding shard_tests)
Definition gtest.cc:6042
int failed_test_suite_count() const
Definition gtest.cc:1039
const TestSuite * GetTestSuite(int i) const
static std::string GetAbsolutePathToOutputFile()
Definition gtest.cc:642
static std::string GetOutputFormat()
Definition gtest.cc:630
static void PrintXmlTestsList(std::ostream *stream, const std::vector< TestSuite * > &test_suites)
Definition gtest.cc:4378
void ListTestsMatchingFilter(const std::vector< TestSuite * > &test_suites)
Definition gtest.cc:4000
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
Definition gtest.cc:3991
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
GTEST_DEFINE_bool_(fail_fast, testing::internal::BoolFromGTestEnv("fail_fast", testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution.")
#define GTEST_INTERNAL_PARSE_FLAG(flag_name)
GTEST_DEFINE_int32_(random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time.")
#define GTEST_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3824
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3834
GTEST_DEFINE_string_(color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors.")
std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
Definition gtest.cc:1266
std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context)
Definition gtest.cc:1441
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
Definition gtest.cc:2014
const char * StringFromGTestEnv(const char *flag, const char *default_value)
std::string OutputFlagAlsoCheckEnvVar()
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
Definition gtest.cc:5969
bool BoolFromGTestEnv(const char *flag, bool default_value)
static bool PatternMatchesString(const std::string &name_str, const char *pattern, const char *pattern_end)
Definition gtest.cc:677
::std::vector< std::string > GetArgvs()
Definition gtest.cc:602
static const char kColorEncodedHelpMessage[]
Definition gtest.cc:6428
static FILE * OpenFileForWriting(const std::string &output_file)
Definition gtest.cc:190
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
Definition gtest.cc:1637
void WriteToShardStatusFileIfNeeded()
Definition gtest.cc:5947
int GetRandomSeedFromFlag(int32_t random_seed_flag)
std::string StringStreamToString(::std::stringstream *ss)
Definition gtest.cc:2174
static void ColoredPrintf(GTestColor color, const char *fmt,...)
Definition gtest.cc:3277
static ::std::vector< std::string > g_argvs
Definition gtest.cc:600
int CountIf(const Container &c, Predicate predicate)
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
AssertionResult CmpHelperSTREQ(const char *lhs_expression, const char *rhs_expression, const char *lhs, const char *rhs)
Definition gtest.cc:1687
static std::string Indent(size_t width)
Definition gtest.cc:4579
bool SkipPrefix(const char *prefix, const char **pstr)
Definition gtest.cc:6274
static bool TestSuitePassed(const TestSuite *test_suite)
Definition gtest.cc:412
std::string ReadEntireFile(FILE *file)
static const char * ParseFlagValue(const char *str, const char *flag_name, bool def_optional)
Definition gtest.cc:6288
static bool ParseGoogleTestFlag(const char *const arg)
Definition gtest.cc:6524
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
void InsertSyntheticTestCase(const std::string &name, CodeLocation location, bool has_test_p)
Definition gtest.cc:491
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
Definition gtest.cc:6031
void RegisterTypeParameterizedTestSuite(const char *test_suite_name, CodeLocation code_location)
Definition gtest.cc:535
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
Definition gtest.cc:6631
static void PrintOnOneLine(const char *str, int max_length)
Definition gtest.cc:6101
static AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const std::string &substr)
Definition gtest.cc:936
bool ParseInt32(const Message &src_text, const char *str, int32_t *value)
AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
Definition gtest.cc:1596
bool IsTrue(bool condition)
Definition gtest.cc:6260
void ForEach(const Container &c, Functor functor)
static void PrintFullTestCommentIfPresent(const TestInfo &test_info)
Definition gtest.cc:3325
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
Definition gtest.cc:4121
static void SetUpEnvironment(Environment *env)
Definition gtest.cc:5736
std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
Definition gtest.cc:1583
static bool PortableLocaltime(time_t seconds, struct tm *out)
Definition gtest.cc:4100
uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:1988
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:1982
int GetNextRandomSeed(int seed)
static bool HasGoogleTestFlagPrefix(const char *str)
Definition gtest.cc:6377
E GetElementOr(const std::vector< E > &v, int i, E default_value)
GTEST_API_ FilePath GetCurrentExecutableName()
Definition gtest.cc:615
GTEST_API_ bool ParseFlag(const char *str, const char *flag, int32_t *value)
Definition gtest.cc:6342
static void PrintColorEncoded(const char *str)
Definition gtest.cc:6394
AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1724
void RegisterTypeParameterizedTestSuiteInstantiation(const char *case_name)
Definition gtest.cc:541
TestInfo * MakeAndRegisterTestInfo(const char *test_suite_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase *factory)
Definition gtest.cc:2749
constexpr uint32_t kMaxCodePoint3
Definition gtest.cc:1925
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
Definition gtest.cc:2447
void SplitString(const ::std::string &str, char delimiter, ::std::vector< ::std::string > *dest)
Definition gtest.cc:1209
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
Definition gtest.cc:4094
void Shuffle(internal::Random *random, std::vector< E > *v)
static bool GTestIsInitialized()
Definition gtest.cc:397
bool AlwaysTrue()
Definition gtest.cc:6262
GTEST_API_ bool g_help_flag
Definition gtest.cc:187
static int SumOverTestSuiteList(const std::vector< TestSuite * > &case_list, int(TestSuite::*method)() const)
Definition gtest.cc:402
UnitTestImpl * GetUnitTestImpl()
int32_t Int32FromGTestEnv(const char *flag, int32_t default_value)
GTEST_API_ int32_t Int32FromEnvOrDie(const char *env_var, int32_t default_val)
Definition gtest.cc:6013
AssertionResult EqFailure(const char *lhs_expression, const char *rhs_expression, const std::string &lhs_value, const std::string &rhs_value, bool ignoring_case)
Definition gtest.cc:1551
constexpr uint32_t kMaxCodePoint2
Definition gtest.cc:1922
void PrintTo(unsigned char c, ::std::ostream *os)
void ReportInvalidTestSuiteType(const char *test_suite_name, CodeLocation code_location)
Definition gtest.cc:2761
static bool ShouldRunTestSuite(const TestSuite *test_suite)
Definition gtest.cc:423
static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)
Definition gtest.cc:4566
AssertionResult CmpHelperSTRCASEEQ(const char *lhs_expression, const char *rhs_expression, const char *lhs, const char *rhs)
Definition gtest.cc:1699
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
Definition gtest.cc:3234
void InitGoogleTestImpl(int *argc, CharType **argv)
Definition gtest.cc:6674
static bool TestSuiteFailed(const TestSuite *test_suite)
Definition gtest.cc:417
static void TearDownEnvironment(Environment *env)
Definition gtest.cc:5737
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2580
static std::string FormatTimeInMillisAsDuration(TimeInMillis ms)
Definition gtest.cc:4558
static void PrintTestPartResult(const TestPartResult &test_part_result)
Definition gtest.cc:3148
const char kStackTraceMarker[]
Definition gtest.cc:183
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
Definition gtest.cc:931
TypeId GetTestTypeId()
Definition gtest.cc:927
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point)
Definition gtest.cc:1947
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
Definition gtest.cc:3136
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2607
std::string AppendUserMessage(const std::string &gtest_msg, const Message &user_msg)
Definition gtest.cc:2193
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
Definition gtest.cc:6580
static const char kValueParamLabel[]
Definition gtest.cc:3323
GTEST_API_ TimeInMillis GetTimeInMillis()
Definition gtest.cc:1132
constexpr uint32_t kMaxCodePoint1
Definition gtest.cc:1919
GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *, int skip_count)
Definition gtest.cc:6248
static const char kTypeParamLabel[]
Definition gtest.cc:3322
AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1711
constexpr uint32_t kMaxCodePoint4
Definition gtest.cc:1929
std::set< std::string > * GetIgnoredParameterizedTestSuites()
Definition gtest.cc:480
static const char * GetAnsiColorCode(GTestColor color)
Definition gtest.cc:3218
uint32_t ChopLowBits(uint32_t *bits, int n)
Definition gtest.cc:1935
static const char kDisableTestFilter[]
Definition gtest.cc:157
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
Definition gtest.cc:2288
static bool TestPartSkipped(const TestPartResult &result)
Definition gtest.cc:2363
AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1803
static const char kUniversalFilter[]
Definition gtest.cc:165
AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
Definition gtest.cc:1672
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
Definition gtest.cc:3091
AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1793
static std::string FormatWordList(const std::vector< std::string > &words)
Definition gtest.cc:2319
static const char kTestShardStatusFile[]
Definition gtest.cc:177
static const char kTestShardIndex[]
Definition gtest.cc:173
static bool GetDefaultFailFast()
Definition gtest.cc:219
static std::string FormatTestCount(int test_count)
Definition gtest.cc:3098
static const char kTestTotalShards[]
Definition gtest.cc:175
AssertionResult AssertionFailure()
static const char kDeathTestSuiteFilter[]
Definition gtest.cc:162
static std::string GetTempDirFromEnv(std::initializer_list< const char * > environment_variables, const char *fallback, char separator)
Definition gtest.cc:6749
static std::string FormatTestSuiteCount(int test_suite_count)
Definition gtest.cc:3103
static const char *const kReservedOutputTestCaseAttributes[]
Definition gtest.cc:2279
static const char kDefaultOutputFormat[]
Definition gtest.cc:168
static bool TestPartFatallyFailed(const TestPartResult &result)
Definition gtest.cc:2381
static const char * GetDefaultFilter()
Definition gtest.cc:208
static const char kDefaultOutputFile[]
Definition gtest.cc:170
std::string TempDir()
Definition gtest.cc:6765
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
Definition gtest.cc:2284
AssertionResult AssertionSuccess()
static std::vector< std::string > GetReservedOutputAttributesForElement(const std::string &xml_element)
Definition gtest.cc:2304
void InitGoogleTest()
Definition gtest.cc:6730
AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
Definition gtest.cc:1679
static const char *const kReservedTestCaseAttributes[]
Definition gtest.cc:2273
static bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
Definition gtest.cc:2333
static bool TestPartNonfatallyFailed(const TestPartResult &result)
Definition gtest.cc:2391
static const char *const kReservedTestSuiteAttributes[]
Definition gtest.cc:2268
static const char *const kReservedTestSuitesAttributes[]
Definition gtest.cc:2262
static const char * TestPartResultTypeToString(TestPartResult::Type type)
Definition gtest.cc:3111