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