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