Debian Codegraph @

LspCpp/third_party/uri/deps/googletest/src/gtest.cc

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