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