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