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