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