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