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