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


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:53