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