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


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:51