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