blob: e46e90a2c47c4cf18de4ce7f229037f76c74f29c [file] [log] [blame]
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001// 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/gtest-spi.h>
36
37#include <ctype.h>
38#include <math.h>
39#include <stdarg.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <wchar.h>
44#include <wctype.h>
45
46#ifdef GTEST_OS_LINUX
47
48// TODO(kenton@google.com): Use autoconf to detect availability of
49// gettimeofday().
50#define GTEST_HAS_GETTIMEOFDAY
51
52#include <fcntl.h>
53#include <limits.h>
54#include <sched.h>
55// Declares vsnprintf(). This header is not available on Windows.
56#include <strings.h>
57#include <sys/mman.h>
58#include <sys/time.h>
59#include <unistd.h>
60#include <string>
61#include <vector>
62
63#elif defined(GTEST_OS_SYMBIAN)
64#define GTEST_HAS_GETTIMEOFDAY
65#include <sys/time.h> // NOLINT
66
67#elif defined(GTEST_OS_ZOS)
68#define GTEST_HAS_GETTIMEOFDAY
69#include <sys/time.h> // NOLINT
70
71// On z/OS we additionally need strings.h for strcasecmp.
72#include <strings.h>
73
74#elif defined(_WIN32_WCE) // We are on Windows CE.
75
76#include <windows.h> // NOLINT
77
78#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
79
80#include <io.h> // NOLINT
81#include <sys/timeb.h> // NOLINT
82#include <sys/types.h> // NOLINT
83#include <sys/stat.h> // NOLINT
84
85#if defined(__MINGW__) || defined(__MINGW32__)
86// MinGW has gettimeofday() but not _ftime64().
87// TODO(kenton@google.com): Use autoconf to detect availability of
88// gettimeofday().
89// TODO(kenton@google.com): There are other ways to get the time on
90// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
91// supports these. consider using them instead.
92#define GTEST_HAS_GETTIMEOFDAY
93#include <sys/time.h> // NOLINT
94#endif
95
96// cpplint thinks that the header is already included, so we want to
97// silence it.
98#include <windows.h> // NOLINT
99
100#else
101
102// Assume other platforms have gettimeofday().
103// TODO(kenton@google.com): Use autoconf to detect availability of
104// gettimeofday().
105#define GTEST_HAS_GETTIMEOFDAY
106
107// cpplint thinks that the header is already included, so we want to
108// silence it.
109#include <sys/time.h> // NOLINT
110#include <unistd.h> // NOLINT
111
112#endif
113
114// Indicates that this translation unit is part of Google Test's
115// implementation. It must come before gtest-internal-inl.h is
116// included, or there will be a compiler error. This trick is to
117// prevent a user from accidentally including gtest-internal-inl.h in
118// his code.
119#define GTEST_IMPLEMENTATION
Misha Brukmane5f94712009-01-01 02:05:43 +0000120#include "gtest/internal/gtest-internal-inl.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000121#undef GTEST_IMPLEMENTATION
122
123#ifdef GTEST_OS_WINDOWS
124#define fileno _fileno
125#define isatty _isatty
126#define vsnprintf _vsnprintf
127#endif // GTEST_OS_WINDOWS
128
129namespace testing {
130
131// Constants.
132
133// A test whose test case name or test name matches this filter is
134// disabled and not run.
135static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
136
137// A test case whose name matches this filter is considered a death
138// test case and will be run before test cases whose name doesn't
139// match this filter.
140static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
141
142// A test filter that matches everything.
143static const char kUniversalFilter[] = "*";
144
145// The default output file for XML output.
146static const char kDefaultOutputFile[] = "test_detail.xml";
147
148namespace internal {
149
150// The text used in failure messages to indicate the start of the
151// stack trace.
152const char kStackTraceMarker[] = "\nStack trace:\n";
153
154} // namespace internal
155
156GTEST_DEFINE_bool_(
157 break_on_failure,
158 internal::BoolFromGTestEnv("break_on_failure", false),
159 "True iff a failed assertion should be a debugger break-point.");
160
161GTEST_DEFINE_bool_(
162 catch_exceptions,
163 internal::BoolFromGTestEnv("catch_exceptions", false),
164 "True iff " GTEST_NAME
165 " should catch exceptions and treat them as test failures.");
166
167GTEST_DEFINE_string_(
168 color,
169 internal::StringFromGTestEnv("color", "auto"),
170 "Whether to use colors in the output. Valid values: yes, no, "
171 "and auto. 'auto' means to use colors if the output is "
172 "being sent to a terminal and the TERM environment variable "
173 "is set to xterm or xterm-color.");
174
175GTEST_DEFINE_string_(
176 filter,
177 internal::StringFromGTestEnv("filter", kUniversalFilter),
178 "A colon-separated list of glob (not regex) patterns "
179 "for filtering the tests to run, optionally followed by a "
180 "'-' and a : separated list of negative patterns (tests to "
181 "exclude). A test is run if it matches one of the positive "
182 "patterns and does not match any of the negative patterns.");
183
184GTEST_DEFINE_bool_(list_tests, false,
185 "List all tests without running them.");
186
187GTEST_DEFINE_string_(
188 output,
189 internal::StringFromGTestEnv("output", ""),
190 "A format (currently must be \"xml\"), optionally followed "
191 "by a colon and an output file name or directory. A directory "
192 "is indicated by a trailing pathname separator. "
193 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
194 "If a directory is specified, output files will be created "
195 "within that directory, with file-names based on the test "
196 "executable's name and, if necessary, made unique by adding "
197 "digits.");
198
199GTEST_DEFINE_bool_(
200 print_time,
201 internal::BoolFromGTestEnv("print_time", false),
202 "True iff " GTEST_NAME
203 " should display elapsed time in text output.");
204
205GTEST_DEFINE_int32_(
206 repeat,
207 internal::Int32FromGTestEnv("repeat", 1),
208 "How many times to repeat each test. Specify a negative number "
209 "for repeating forever. Useful for shaking out flaky tests.");
210
211GTEST_DEFINE_int32_(
212 stack_trace_depth,
213 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
214 "The maximum number of stack frames to print when an "
215 "assertion fails. The valid range is 0 through 100, inclusive.");
216
217GTEST_DEFINE_bool_(
218 show_internal_stack_frames, false,
219 "True iff " GTEST_NAME " should include internal stack frames when "
220 "printing test failure stack traces.");
221
222namespace internal {
223
224// GTestIsInitialized() returns true iff the user has initialized
225// Google Test. Useful for catching the user mistake of not initializing
226// Google Test before calling RUN_ALL_TESTS().
227//
228// A user must call testing::InitGoogleTest() to initialize Google
229// Test. g_init_gtest_count is set to the number of times
230// InitGoogleTest() has been called. We don't protect this variable
231// under a mutex as it is only accessed in the main thread.
232int g_init_gtest_count = 0;
233static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
234
235// Iterates over a list of TestCases, keeping a running sum of the
236// results of calling a given int-returning method on each.
237// Returns the sum.
238static int SumOverTestCaseList(const internal::List<TestCase*>& case_list,
239 int (TestCase::*method)() const) {
240 int sum = 0;
241 for (const internal::ListNode<TestCase*>* node = case_list.Head();
242 node != NULL;
243 node = node->next()) {
244 sum += (node->element()->*method)();
245 }
246 return sum;
247}
248
249// Returns true iff the test case passed.
250static bool TestCasePassed(const TestCase* test_case) {
251 return test_case->should_run() && test_case->Passed();
252}
253
254// Returns true iff the test case failed.
255static bool TestCaseFailed(const TestCase* test_case) {
256 return test_case->should_run() && test_case->Failed();
257}
258
259// Returns true iff test_case contains at least one test that should
260// run.
261static bool ShouldRunTestCase(const TestCase* test_case) {
262 return test_case->should_run();
263}
264
265// AssertHelper constructor.
266AssertHelper::AssertHelper(TestPartResultType type, const char* file,
267 int line, const char* message)
268 : type_(type), file_(file), line_(line), message_(message) {
269}
270
271// Message assignment, for assertion streaming support.
272void AssertHelper::operator=(const Message& message) const {
273 UnitTest::GetInstance()->
274 AddTestPartResult(type_, file_, line_,
275 AppendUserMessage(message_, message),
276 UnitTest::GetInstance()->impl()
277 ->CurrentOsStackTraceExceptTop(1)
278 // Skips the stack frame for this function itself.
279 ); // NOLINT
280}
281
282// Mutex for linked pointers.
283Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
284
285// Application pathname gotten in InitGoogleTest.
286String g_executable_path;
287
288// Returns the current application's name, removing directory path if that
289// is present.
290FilePath GetCurrentExecutableName() {
291 FilePath result;
292
293#if defined(_WIN32_WCE) || defined(GTEST_OS_WINDOWS)
294 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
295#else
296 result.Set(FilePath(g_executable_path));
297#endif // _WIN32_WCE || GTEST_OS_WINDOWS
298
299 return result.RemoveDirectoryName();
300}
301
302// Functions for processing the gtest_output flag.
303
304// Returns the output format, or "" for normal printed output.
305String UnitTestOptions::GetOutputFormat() {
306 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
307 if (gtest_output_flag == NULL) return String("");
308
309 const char* const colon = strchr(gtest_output_flag, ':');
310 return (colon == NULL) ?
311 String(gtest_output_flag) :
312 String(gtest_output_flag, colon - gtest_output_flag);
313}
314
315// Returns the name of the requested output file, or the default if none
316// was explicitly specified.
317String UnitTestOptions::GetOutputFile() {
318 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
319 if (gtest_output_flag == NULL)
320 return String("");
321
322 const char* const colon = strchr(gtest_output_flag, ':');
323 if (colon == NULL)
324 return String(kDefaultOutputFile);
325
326 internal::FilePath output_name(colon + 1);
327 if (!output_name.IsDirectory())
328 return output_name.ToString();
329
330 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
331 output_name, internal::GetCurrentExecutableName(),
332 GetOutputFormat().c_str()));
333 return result.ToString();
334}
335
336// Returns true iff the wildcard pattern matches the string. The
337// first ':' or '\0' character in pattern marks the end of it.
338//
339// This recursive algorithm isn't very efficient, but is clear and
340// works well enough for matching test names, which are short.
341bool UnitTestOptions::PatternMatchesString(const char *pattern,
342 const char *str) {
343 switch (*pattern) {
344 case '\0':
345 case ':': // Either ':' or '\0' marks the end of the pattern.
346 return *str == '\0';
347 case '?': // Matches any single character.
348 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
349 case '*': // Matches any string (possibly empty) of characters.
350 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
351 PatternMatchesString(pattern + 1, str);
352 default: // Non-special character. Matches itself.
353 return *pattern == *str &&
354 PatternMatchesString(pattern + 1, str + 1);
355 }
356}
357
358bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
359 const char *cur_pattern = filter;
360 while (true) {
361 if (PatternMatchesString(cur_pattern, name.c_str())) {
362 return true;
363 }
364
365 // Finds the next pattern in the filter.
366 cur_pattern = strchr(cur_pattern, ':');
367
368 // Returns if no more pattern can be found.
369 if (cur_pattern == NULL) {
370 return false;
371 }
372
373 // Skips the pattern separater (the ':' character).
374 cur_pattern++;
375 }
376}
377
378// TODO(keithray): move String function implementations to gtest-string.cc.
379
380// Returns true iff the user-specified filter matches the test case
381// name and the test name.
382bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
383 const String &test_name) {
384 const String& full_name = String::Format("%s.%s",
385 test_case_name.c_str(),
386 test_name.c_str());
387
388 // Split --gtest_filter at '-', if there is one, to separate into
389 // positive filter and negative filter portions
390 const char* const p = GTEST_FLAG(filter).c_str();
391 const char* const dash = strchr(p, '-');
392 String positive;
393 String negative;
394 if (dash == NULL) {
395 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
396 negative = String("");
397 } else {
398 positive.Set(p, dash - p); // Everything up to the dash
399 negative = String(dash+1); // Everything after the dash
400 if (positive.empty()) {
401 // Treat '-test1' as the same as '*-test1'
402 positive = kUniversalFilter;
403 }
404 }
405
406 // A filter is a colon-separated list of patterns. It matches a
407 // test if any pattern in it matches the test.
408 return (MatchesFilter(full_name, positive.c_str()) &&
409 !MatchesFilter(full_name, negative.c_str()));
410}
411
412#ifdef GTEST_OS_WINDOWS
413// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
414// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
415// This function is useful as an __except condition.
416int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
417 // Google Test should handle an exception if:
418 // 1. the user wants it to, AND
419 // 2. this is not a breakpoint exception.
420 return (GTEST_FLAG(catch_exceptions) &&
421 exception_code != EXCEPTION_BREAKPOINT) ?
422 EXCEPTION_EXECUTE_HANDLER :
423 EXCEPTION_CONTINUE_SEARCH;
424}
425#endif // GTEST_OS_WINDOWS
426
427} // namespace internal
428
429// The interface for printing the result of a UnitTest
430class UnitTestEventListenerInterface {
431 public:
432 // The d'tor is pure virtual as this is an abstract class.
433 virtual ~UnitTestEventListenerInterface() = 0;
434
435 // Called before the unit test starts.
436 virtual void OnUnitTestStart(const UnitTest*) {}
437
438 // Called after the unit test ends.
439 virtual void OnUnitTestEnd(const UnitTest*) {}
440
441 // Called before the test case starts.
442 virtual void OnTestCaseStart(const TestCase*) {}
443
444 // Called after the test case ends.
445 virtual void OnTestCaseEnd(const TestCase*) {}
446
447 // Called before the global set-up starts.
448 virtual void OnGlobalSetUpStart(const UnitTest*) {}
449
450 // Called after the global set-up ends.
451 virtual void OnGlobalSetUpEnd(const UnitTest*) {}
452
453 // Called before the global tear-down starts.
454 virtual void OnGlobalTearDownStart(const UnitTest*) {}
455
456 // Called after the global tear-down ends.
457 virtual void OnGlobalTearDownEnd(const UnitTest*) {}
458
459 // Called before the test starts.
460 virtual void OnTestStart(const TestInfo*) {}
461
462 // Called after the test ends.
463 virtual void OnTestEnd(const TestInfo*) {}
464
465 // Called after an assertion.
466 virtual void OnNewTestPartResult(const TestPartResult*) {}
467};
468
469// The c'tor sets this object as the test part result reporter used by
470// Google Test. The 'result' parameter specifies where to report the
471// results. Intercepts only failures from the current thread.
472ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
473 TestPartResultArray* result)
474 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
475 result_(result) {
476 Init();
477}
478
479// The c'tor sets this object as the test part result reporter used by
480// Google Test. The 'result' parameter specifies where to report the
481// results.
482ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
483 InterceptMode intercept_mode, TestPartResultArray* result)
484 : intercept_mode_(intercept_mode),
485 result_(result) {
486 Init();
487}
488
489void ScopedFakeTestPartResultReporter::Init() {
490 internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl();
491 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
492 old_reporter_ = impl->GetGlobalTestPartResultReporter();
493 impl->SetGlobalTestPartResultReporter(this);
494 } else {
495 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
496 impl->SetTestPartResultReporterForCurrentThread(this);
497 }
498}
499
500// The d'tor restores the test part result reporter used by Google Test
501// before.
502ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
503 internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl();
504 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
505 impl->SetGlobalTestPartResultReporter(old_reporter_);
506 } else {
507 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
508 }
509}
510
511// Increments the test part result count and remembers the result.
512// This method is from the TestPartResultReporterInterface interface.
513void ScopedFakeTestPartResultReporter::ReportTestPartResult(
514 const TestPartResult& result) {
515 result_->Append(result);
516}
517
518namespace internal {
519
520// Returns the type ID of ::testing::Test. We should always call this
521// instead of GetTypeId< ::testing::Test>() to get the type ID of
522// testing::Test. This is to work around a suspected linker bug when
523// using Google Test as a framework on Mac OS X. The bug causes
524// GetTypeId< ::testing::Test>() to return different values depending
525// on whether the call is from the Google Test framework itself or
526// from user test code. GetTestTypeId() is guaranteed to always
527// return the same value, as it always calls GetTypeId<>() from the
528// gtest.cc, which is within the Google Test framework.
529TypeId GetTestTypeId() {
530 return GetTypeId<Test>();
531}
532
533// The value of GetTestTypeId() as seen from within the Google Test
534// library. This is solely for testing GetTestTypeId().
535extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
536
537// This predicate-formatter checks that 'results' contains a test part
538// failure of the given type and that the failure message contains the
539// given substring.
540AssertionResult HasOneFailure(const char* /* results_expr */,
541 const char* /* type_expr */,
542 const char* /* substr_expr */,
543 const TestPartResultArray& results,
544 TestPartResultType type,
545 const char* substr) {
546 const String expected(
547 type == TPRT_FATAL_FAILURE ? "1 fatal failure" :
548 "1 non-fatal failure");
549 Message msg;
550 if (results.size() != 1) {
551 msg << "Expected: " << expected << "\n"
552 << " Actual: " << results.size() << " failures";
553 for (int i = 0; i < results.size(); i++) {
554 msg << "\n" << results.GetTestPartResult(i);
555 }
556 return AssertionFailure(msg);
557 }
558
559 const TestPartResult& r = results.GetTestPartResult(0);
560 if (r.type() != type) {
561 msg << "Expected: " << expected << "\n"
562 << " Actual:\n"
563 << r;
564 return AssertionFailure(msg);
565 }
566
567 if (strstr(r.message(), substr) == NULL) {
568 msg << "Expected: " << expected << " containing \""
569 << substr << "\"\n"
570 << " Actual:\n"
571 << r;
572 return AssertionFailure(msg);
573 }
574
575 return AssertionSuccess();
576}
577
578// The constructor of SingleFailureChecker remembers where to look up
579// test part results, what type of failure we expect, and what
580// substring the failure message should contain.
581SingleFailureChecker:: SingleFailureChecker(
582 const TestPartResultArray* results,
583 TestPartResultType type,
584 const char* substr)
585 : results_(results),
586 type_(type),
587 substr_(substr) {}
588
589// The destructor of SingleFailureChecker verifies that the given
590// TestPartResultArray contains exactly one failure that has the given
591// type and contains the given substring. If that's not the case, a
592// non-fatal failure will be generated.
593SingleFailureChecker::~SingleFailureChecker() {
594 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
595}
596
597DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
598 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
599
600void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
601 const TestPartResult& result) {
602 unit_test_->current_test_result()->AddTestPartResult(result);
603 unit_test_->result_printer()->OnNewTestPartResult(&result);
604}
605
606DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
607 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
608
609void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
610 const TestPartResult& result) {
611 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
612}
613
614// Returns the global test part result reporter.
615TestPartResultReporterInterface*
616UnitTestImpl::GetGlobalTestPartResultReporter() {
617 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
618 return global_test_part_result_repoter_;
619}
620
621// Sets the global test part result reporter.
622void UnitTestImpl::SetGlobalTestPartResultReporter(
623 TestPartResultReporterInterface* reporter) {
624 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
625 global_test_part_result_repoter_ = reporter;
626}
627
628// Returns the test part result reporter for the current thread.
629TestPartResultReporterInterface*
630UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
631 return per_thread_test_part_result_reporter_.get();
632}
633
634// Sets the test part result reporter for the current thread.
635void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
636 TestPartResultReporterInterface* reporter) {
637 per_thread_test_part_result_reporter_.set(reporter);
638}
639
640// Gets the number of successful test cases.
641int UnitTestImpl::successful_test_case_count() const {
642 return test_cases_.CountIf(TestCasePassed);
643}
644
645// Gets the number of failed test cases.
646int UnitTestImpl::failed_test_case_count() const {
647 return test_cases_.CountIf(TestCaseFailed);
648}
649
650// Gets the number of all test cases.
651int UnitTestImpl::total_test_case_count() const {
652 return test_cases_.size();
653}
654
655// Gets the number of all test cases that contain at least one test
656// that should run.
657int UnitTestImpl::test_case_to_run_count() const {
658 return test_cases_.CountIf(ShouldRunTestCase);
659}
660
661// Gets the number of successful tests.
662int UnitTestImpl::successful_test_count() const {
663 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
664}
665
666// Gets the number of failed tests.
667int UnitTestImpl::failed_test_count() const {
668 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
669}
670
671// Gets the number of disabled tests.
672int UnitTestImpl::disabled_test_count() const {
673 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
674}
675
676// Gets the number of all tests.
677int UnitTestImpl::total_test_count() const {
678 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
679}
680
681// Gets the number of tests that should run.
682int UnitTestImpl::test_to_run_count() const {
683 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
684}
685
686// Returns the current OS stack trace as a String.
687//
688// The maximum number of stack frames to be included is specified by
689// the gtest_stack_trace_depth flag. The skip_count parameter
690// specifies the number of top frames to be skipped, which doesn't
691// count against the number of frames to be included.
692//
693// For example, if Foo() calls Bar(), which in turn calls
694// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
695// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
696String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
697 (void)skip_count;
698 return String("");
699}
700
701static TimeInMillis GetTimeInMillis() {
702#ifdef _WIN32_WCE // We are on Windows CE
703 // Difference between 1970-01-01 and 1601-01-01 in miliseconds.
704 // http://analogous.blogspot.com/2005/04/epoch.html
705 const TimeInMillis kJavaEpochToWinFileTimeDelta = 11644473600000UL;
706 const DWORD kTenthMicrosInMilliSecond = 10000;
707
708 SYSTEMTIME now_systime;
709 FILETIME now_filetime;
710 ULARGE_INTEGER now_int64;
711 // TODO(kenton@google.com): Shouldn't this just use
712 // GetSystemTimeAsFileTime()?
713 GetSystemTime(&now_systime);
714 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
715 now_int64.LowPart = now_filetime.dwLowDateTime;
716 now_int64.HighPart = now_filetime.dwHighDateTime;
717 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
718 kJavaEpochToWinFileTimeDelta;
719 return now_int64.QuadPart;
720 }
721 return 0;
722#elif defined(GTEST_OS_WINDOWS) && !defined(GTEST_HAS_GETTIMEOFDAY)
723 __timeb64 now;
724#ifdef _MSC_VER
725 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
726 // (deprecated function) there.
727 // TODO(kenton@google.com): Use GetTickCount()? Or use
728 // SystemTimeToFileTime()
729#pragma warning(push) // Saves the current warning state.
730#pragma warning(disable:4996) // Temporarily disables warning 4996.
731 _ftime64(&now);
732#pragma warning(pop) // Restores the warning state.
733#else
734 _ftime64(&now);
735#endif // _MSC_VER
736 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
737#elif defined(GTEST_HAS_GETTIMEOFDAY)
738 struct timeval now;
739 gettimeofday(&now, NULL);
740 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
741#else
742#error "Don't know how to get the current time on your system."
743#endif
744}
745
746// Utilities
747
748// class String
749
750// Returns the input enclosed in double quotes if it's not NULL;
751// otherwise returns "(null)". For example, "\"Hello\"" is returned
752// for input "Hello".
753//
754// This is useful for printing a C string in the syntax of a literal.
755//
756// Known issue: escape sequences are not handled yet.
757String String::ShowCStringQuoted(const char* c_str) {
758 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
759}
760
761// Copies at most length characters from str into a newly-allocated
762// piece of memory of size length+1. The memory is allocated with new[].
763// A terminating null byte is written to the memory, and a pointer to it
764// is returned. If str is NULL, NULL is returned.
765static char* CloneString(const char* str, size_t length) {
766 if (str == NULL) {
767 return NULL;
768 } else {
769 char* const clone = new char[length + 1];
770 // MSVC 8 deprecates strncpy(), so we want to suppress warning
771 // 4996 (deprecated function) there.
772#ifdef GTEST_OS_WINDOWS // We are on Windows.
773#pragma warning(push) // Saves the current warning state.
774#pragma warning(disable:4996) // Temporarily disables warning 4996.
775 strncpy(clone, str, length);
776#pragma warning(pop) // Restores the warning state.
777#else // We are on Linux or Mac OS.
778 strncpy(clone, str, length);
779#endif // GTEST_OS_WINDOWS
780 clone[length] = '\0';
781 return clone;
782 }
783}
784
785// Clones a 0-terminated C string, allocating memory using new. The
786// caller is responsible for deleting[] the return value. Returns the
787// cloned string, or NULL if the input is NULL.
788const char * String::CloneCString(const char* c_str) {
789 return (c_str == NULL) ?
790 NULL : CloneString(c_str, strlen(c_str));
791}
792
793#ifdef _WIN32_WCE
794// Creates a UTF-16 wide string from the given ANSI string, allocating
795// memory using new. The caller is responsible for deleting the return
796// value using delete[]. Returns the wide string, or NULL if the
797// input is NULL.
798LPCWSTR String::AnsiToUtf16(const char* ansi) {
799 if (!ansi) return NULL;
800 const int length = strlen(ansi);
801 const int unicode_length =
802 MultiByteToWideChar(CP_ACP, 0, ansi, length,
803 NULL, 0);
804 WCHAR* unicode = new WCHAR[unicode_length + 1];
805 MultiByteToWideChar(CP_ACP, 0, ansi, length,
806 unicode, unicode_length);
807 unicode[unicode_length] = 0;
808 return unicode;
809}
810
811// Creates an ANSI string from the given wide string, allocating
812// memory using new. The caller is responsible for deleting the return
813// value using delete[]. Returns the ANSI string, or NULL if the
814// input is NULL.
815const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
816 if (!utf16_str) return NULL;
817 const int ansi_length =
818 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
819 NULL, 0, NULL, NULL);
820 char* ansi = new char[ansi_length + 1];
821 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
822 ansi, ansi_length, NULL, NULL);
823 ansi[ansi_length] = 0;
824 return ansi;
825}
826
827#endif // _WIN32_WCE
828
829// Compares two C strings. Returns true iff they have the same content.
830//
831// Unlike strcmp(), this function can handle NULL argument(s). A NULL
832// C string is considered different to any non-NULL C string,
833// including the empty string.
834bool String::CStringEquals(const char * lhs, const char * rhs) {
835 if ( lhs == NULL ) return rhs == NULL;
836
837 if ( rhs == NULL ) return false;
838
839 return strcmp(lhs, rhs) == 0;
840}
841
842#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
843
844// Converts an array of wide chars to a narrow string using the UTF-8
845// encoding, and streams the result to the given Message object.
846static void StreamWideCharsToMessage(const wchar_t* wstr, size_t len,
847 Message* msg) {
848 // TODO(wan): consider allowing a testing::String object to
849 // contain '\0'. This will make it behave more like std::string,
850 // and will allow ToUtf8String() to return the correct encoding
851 // for '\0' s.t. we can get rid of the conditional here (and in
852 // several other places).
853 for (size_t i = 0; i != len; ) { // NOLINT
854 if (wstr[i] != L'\0') {
855 *msg << WideStringToUtf8(wstr + i, static_cast<int>(len - i));
856 while (i != len && wstr[i] != L'\0')
857 i++;
858 } else {
859 *msg << '\0';
860 i++;
861 }
862 }
863}
864
865#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
866
867} // namespace internal
868
869#if GTEST_HAS_STD_WSTRING
870// Converts the given wide string to a narrow string using the UTF-8
871// encoding, and streams the result to this Message object.
872Message& Message::operator <<(const ::std::wstring& wstr) {
873 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
874 return *this;
875}
876#endif // GTEST_HAS_STD_WSTRING
877
878#if GTEST_HAS_GLOBAL_WSTRING
879// Converts the given wide string to a narrow string using the UTF-8
880// encoding, and streams the result to this Message object.
881Message& Message::operator <<(const ::wstring& wstr) {
882 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
883 return *this;
884}
885#endif // GTEST_HAS_GLOBAL_WSTRING
886
887namespace internal {
888
889// Formats a value to be used in a failure message.
890
891// For a char value, we print it as a C++ char literal and as an
892// unsigned integer (both in decimal and in hexadecimal).
893String FormatForFailureMessage(char ch) {
894 const unsigned int ch_as_uint = ch;
895 // A String object cannot contain '\0', so we print "\\0" when ch is
896 // '\0'.
897 return String::Format("'%s' (%u, 0x%X)",
898 ch ? String::Format("%c", ch).c_str() : "\\0",
899 ch_as_uint, ch_as_uint);
900}
901
902// For a wchar_t value, we print it as a C++ wchar_t literal and as an
903// unsigned integer (both in decimal and in hexidecimal).
904String FormatForFailureMessage(wchar_t wchar) {
905 // The C++ standard doesn't specify the exact size of the wchar_t
906 // type. It just says that it shall have the same size as another
907 // integral type, called its underlying type.
908 //
909 // Therefore, in order to print a wchar_t value in the numeric form,
910 // we first convert it to the largest integral type (UInt64) and
911 // then print the converted value.
912 //
913 // We use streaming to print the value as "%llu" doesn't work
914 // correctly with MSVC 7.1.
915 const UInt64 wchar_as_uint64 = wchar;
916 Message msg;
917 // A String object cannot contain '\0', so we print "\\0" when wchar is
918 // L'\0'.
919 char buffer[32]; // CodePointToUtf8 requires a buffer that big.
920 msg << "L'"
921 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
922 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
923 << wchar_as_uint64 << ")";
924 return msg.GetString();
925}
926
927} // namespace internal
928
929// AssertionResult constructor.
930AssertionResult::AssertionResult(const internal::String& failure_message)
931 : failure_message_(failure_message) {
932}
933
934
935// Makes a successful assertion result.
936AssertionResult AssertionSuccess() {
937 return AssertionResult();
938}
939
940
941// Makes a failed assertion result with the given failure message.
942AssertionResult AssertionFailure(const Message& message) {
943 return AssertionResult(message.GetString());
944}
945
946namespace internal {
947
948// Constructs and returns the message for an equality assertion
949// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
950//
951// The first four parameters are the expressions used in the assertion
952// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
953// where foo is 5 and bar is 6, we have:
954//
955// expected_expression: "foo"
956// actual_expression: "bar"
957// expected_value: "5"
958// actual_value: "6"
959//
960// The ignoring_case parameter is true iff the assertion is a
961// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
962// be inserted into the message.
963AssertionResult EqFailure(const char* expected_expression,
964 const char* actual_expression,
965 const String& expected_value,
966 const String& actual_value,
967 bool ignoring_case) {
968 Message msg;
969 msg << "Value of: " << actual_expression;
970 if (actual_value != actual_expression) {
971 msg << "\n Actual: " << actual_value;
972 }
973
974 msg << "\nExpected: " << expected_expression;
975 if (ignoring_case) {
976 msg << " (ignoring case)";
977 }
978 if (expected_value != expected_expression) {
979 msg << "\nWhich is: " << expected_value;
980 }
981
982 return AssertionFailure(msg);
983}
984
985
986// Helper function for implementing ASSERT_NEAR.
987AssertionResult DoubleNearPredFormat(const char* expr1,
988 const char* expr2,
989 const char* abs_error_expr,
990 double val1,
991 double val2,
992 double abs_error) {
993 const double diff = fabs(val1 - val2);
994 if (diff <= abs_error) return AssertionSuccess();
995
996 // TODO(wan): do not print the value of an expression if it's
997 // already a literal.
998 Message msg;
999 msg << "The difference between " << expr1 << " and " << expr2
1000 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1001 << expr1 << " evaluates to " << val1 << ",\n"
1002 << expr2 << " evaluates to " << val2 << ", and\n"
1003 << abs_error_expr << " evaluates to " << abs_error << ".";
1004 return AssertionFailure(msg);
1005}
1006
1007
1008// Helper template for implementing FloatLE() and DoubleLE().
1009template <typename RawType>
1010AssertionResult FloatingPointLE(const char* expr1,
1011 const char* expr2,
1012 RawType val1,
1013 RawType val2) {
1014 // Returns success if val1 is less than val2,
1015 if (val1 < val2) {
1016 return AssertionSuccess();
1017 }
1018
1019 // or if val1 is almost equal to val2.
1020 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1021 if (lhs.AlmostEquals(rhs)) {
1022 return AssertionSuccess();
1023 }
1024
1025 // Note that the above two checks will both fail if either val1 or
1026 // val2 is NaN, as the IEEE floating-point standard requires that
1027 // any predicate involving a NaN must return false.
1028
1029 StrStream val1_ss;
1030 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1031 << val1;
1032
1033 StrStream val2_ss;
1034 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1035 << val2;
1036
1037 Message msg;
1038 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1039 << " Actual: " << StrStreamToString(&val1_ss) << " vs "
1040 << StrStreamToString(&val2_ss);
1041
1042 return AssertionFailure(msg);
1043}
1044
1045} // namespace internal
1046
1047// Asserts that val1 is less than, or almost equal to, val2. Fails
1048// otherwise. In particular, it fails if either val1 or val2 is NaN.
1049AssertionResult FloatLE(const char* expr1, const char* expr2,
1050 float val1, float val2) {
1051 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1052}
1053
1054// Asserts that val1 is less than, or almost equal to, val2. Fails
1055// otherwise. In particular, it fails if either val1 or val2 is NaN.
1056AssertionResult DoubleLE(const char* expr1, const char* expr2,
1057 double val1, double val2) {
1058 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1059}
1060
1061namespace internal {
1062
1063// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1064// arguments.
1065AssertionResult CmpHelperEQ(const char* expected_expression,
1066 const char* actual_expression,
1067 BiggestInt expected,
1068 BiggestInt actual) {
1069 if (expected == actual) {
1070 return AssertionSuccess();
1071 }
1072
1073 return EqFailure(expected_expression,
1074 actual_expression,
1075 FormatForComparisonFailureMessage(expected, actual),
1076 FormatForComparisonFailureMessage(actual, expected),
1077 false);
1078}
1079
1080// A macro for implementing the helper functions needed to implement
1081// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1082// just to avoid copy-and-paste of similar code.
1083#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1084AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1085 BiggestInt val1, BiggestInt val2) {\
1086 if (val1 op val2) {\
1087 return AssertionSuccess();\
1088 } else {\
1089 Message msg;\
1090 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1091 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1092 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1093 return AssertionFailure(msg);\
1094 }\
1095}
1096
1097// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1098// enum arguments.
1099GTEST_IMPL_CMP_HELPER_(NE, !=)
1100// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1101// enum arguments.
1102GTEST_IMPL_CMP_HELPER_(LE, <=)
1103// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1104// enum arguments.
1105GTEST_IMPL_CMP_HELPER_(LT, < )
1106// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1107// enum arguments.
1108GTEST_IMPL_CMP_HELPER_(GE, >=)
1109// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1110// enum arguments.
1111GTEST_IMPL_CMP_HELPER_(GT, > )
1112
1113#undef GTEST_IMPL_CMP_HELPER_
1114
1115// The helper function for {ASSERT|EXPECT}_STREQ.
1116AssertionResult CmpHelperSTREQ(const char* expected_expression,
1117 const char* actual_expression,
1118 const char* expected,
1119 const char* actual) {
1120 if (String::CStringEquals(expected, actual)) {
1121 return AssertionSuccess();
1122 }
1123
1124 return EqFailure(expected_expression,
1125 actual_expression,
1126 String::ShowCStringQuoted(expected),
1127 String::ShowCStringQuoted(actual),
1128 false);
1129}
1130
1131// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1132AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1133 const char* actual_expression,
1134 const char* expected,
1135 const char* actual) {
1136 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1137 return AssertionSuccess();
1138 }
1139
1140 return EqFailure(expected_expression,
1141 actual_expression,
1142 String::ShowCStringQuoted(expected),
1143 String::ShowCStringQuoted(actual),
1144 true);
1145}
1146
1147// The helper function for {ASSERT|EXPECT}_STRNE.
1148AssertionResult CmpHelperSTRNE(const char* s1_expression,
1149 const char* s2_expression,
1150 const char* s1,
1151 const char* s2) {
1152 if (!String::CStringEquals(s1, s2)) {
1153 return AssertionSuccess();
1154 } else {
1155 Message msg;
1156 msg << "Expected: (" << s1_expression << ") != ("
1157 << s2_expression << "), actual: \""
1158 << s1 << "\" vs \"" << s2 << "\"";
1159 return AssertionFailure(msg);
1160 }
1161}
1162
1163// The helper function for {ASSERT|EXPECT}_STRCASENE.
1164AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1165 const char* s2_expression,
1166 const char* s1,
1167 const char* s2) {
1168 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1169 return AssertionSuccess();
1170 } else {
1171 Message msg;
1172 msg << "Expected: (" << s1_expression << ") != ("
1173 << s2_expression << ") (ignoring case), actual: \""
1174 << s1 << "\" vs \"" << s2 << "\"";
1175 return AssertionFailure(msg);
1176 }
1177}
1178
1179} // namespace internal
1180
1181namespace {
1182
1183// Helper functions for implementing IsSubString() and IsNotSubstring().
1184
1185// This group of overloaded functions return true iff needle is a
1186// substring of haystack. NULL is considered a substring of itself
1187// only.
1188
1189bool IsSubstringPred(const char* needle, const char* haystack) {
1190 if (needle == NULL || haystack == NULL)
1191 return needle == haystack;
1192
1193 return strstr(haystack, needle) != NULL;
1194}
1195
1196bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1197 if (needle == NULL || haystack == NULL)
1198 return needle == haystack;
1199
1200 return wcsstr(haystack, needle) != NULL;
1201}
1202
1203// StringType here can be either ::std::string or ::std::wstring.
1204template <typename StringType>
1205bool IsSubstringPred(const StringType& needle,
1206 const StringType& haystack) {
1207 return haystack.find(needle) != StringType::npos;
1208}
1209
1210// This function implements either IsSubstring() or IsNotSubstring(),
1211// depending on the value of the expected_to_be_substring parameter.
1212// StringType here can be const char*, const wchar_t*, ::std::string,
1213// or ::std::wstring.
1214template <typename StringType>
1215AssertionResult IsSubstringImpl(
1216 bool expected_to_be_substring,
1217 const char* needle_expr, const char* haystack_expr,
1218 const StringType& needle, const StringType& haystack) {
1219 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1220 return AssertionSuccess();
1221
1222 const bool is_wide_string = sizeof(needle[0]) > 1;
1223 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1224 return AssertionFailure(
1225 Message()
1226 << "Value of: " << needle_expr << "\n"
1227 << " Actual: " << begin_string_quote << needle << "\"\n"
1228 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1229 << "a substring of " << haystack_expr << "\n"
1230 << "Which is: " << begin_string_quote << haystack << "\"");
1231}
1232
1233} // namespace
1234
1235// IsSubstring() and IsNotSubstring() check whether needle is a
1236// substring of haystack (NULL is considered a substring of itself
1237// only), and return an appropriate error message when they fail.
1238
1239AssertionResult IsSubstring(
1240 const char* needle_expr, const char* haystack_expr,
1241 const char* needle, const char* haystack) {
1242 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1243}
1244
1245AssertionResult IsSubstring(
1246 const char* needle_expr, const char* haystack_expr,
1247 const wchar_t* needle, const wchar_t* haystack) {
1248 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1249}
1250
1251AssertionResult IsNotSubstring(
1252 const char* needle_expr, const char* haystack_expr,
1253 const char* needle, const char* haystack) {
1254 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1255}
1256
1257AssertionResult IsNotSubstring(
1258 const char* needle_expr, const char* haystack_expr,
1259 const wchar_t* needle, const wchar_t* haystack) {
1260 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1261}
1262
1263#if GTEST_HAS_STD_STRING
1264AssertionResult IsSubstring(
1265 const char* needle_expr, const char* haystack_expr,
1266 const ::std::string& needle, const ::std::string& haystack) {
1267 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1268}
1269
1270AssertionResult IsNotSubstring(
1271 const char* needle_expr, const char* haystack_expr,
1272 const ::std::string& needle, const ::std::string& haystack) {
1273 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1274}
1275#endif // GTEST_HAS_STD_STRING
1276
1277#if GTEST_HAS_STD_WSTRING
1278AssertionResult IsSubstring(
1279 const char* needle_expr, const char* haystack_expr,
1280 const ::std::wstring& needle, const ::std::wstring& haystack) {
1281 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1282}
1283
1284AssertionResult IsNotSubstring(
1285 const char* needle_expr, const char* haystack_expr,
1286 const ::std::wstring& needle, const ::std::wstring& haystack) {
1287 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1288}
1289#endif // GTEST_HAS_STD_WSTRING
1290
1291namespace internal {
1292
1293#ifdef GTEST_OS_WINDOWS
1294
1295namespace {
1296
1297// Helper function for IsHRESULT{SuccessFailure} predicates
1298AssertionResult HRESULTFailureHelper(const char* expr,
1299 const char* expected,
1300 long hr) { // NOLINT
1301#ifdef _WIN32_WCE
1302 // Windows CE doesn't support FormatMessage.
1303 const char error_text[] = "";
1304#else
1305 // Looks up the human-readable system message for the HRESULT code
1306 // and since we're not passing any params to FormatMessage, we don't
1307 // want inserts expanded.
1308 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1309 FORMAT_MESSAGE_IGNORE_INSERTS;
1310 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1311 // Gets the system's human readable message string for this HRESULT.
1312 char error_text[kBufSize] = { '\0' };
1313 DWORD message_length = ::FormatMessageA(kFlags,
1314 0, // no source, we're asking system
1315 hr, // the error
1316 0, // no line width restrictions
1317 error_text, // output buffer
1318 kBufSize, // buf size
1319 NULL); // no arguments for inserts
1320 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1321 for (; message_length && isspace(error_text[message_length - 1]);
1322 --message_length) {
1323 error_text[message_length - 1] = '\0';
1324 }
1325#endif // _WIN32_WCE
1326
1327 const String error_hex(String::Format("0x%08X ", hr));
1328 Message msg;
1329 msg << "Expected: " << expr << " " << expected << ".\n"
1330 << " Actual: " << error_hex << error_text << "\n";
1331
1332 return ::testing::AssertionFailure(msg);
1333}
1334
1335} // namespace
1336
1337AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1338 if (SUCCEEDED(hr)) {
1339 return AssertionSuccess();
1340 }
1341 return HRESULTFailureHelper(expr, "succeeds", hr);
1342}
1343
1344AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1345 if (FAILED(hr)) {
1346 return AssertionSuccess();
1347 }
1348 return HRESULTFailureHelper(expr, "fails", hr);
1349}
1350
1351#endif // GTEST_OS_WINDOWS
1352
1353// Utility functions for encoding Unicode text (wide strings) in
1354// UTF-8.
1355
1356// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1357// like this:
1358//
1359// Code-point length Encoding
1360// 0 - 7 bits 0xxxxxxx
1361// 8 - 11 bits 110xxxxx 10xxxxxx
1362// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1363// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1364
1365// The maximum code-point a one-byte UTF-8 sequence can represent.
1366const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1367
1368// The maximum code-point a two-byte UTF-8 sequence can represent.
1369const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1370
1371// The maximum code-point a three-byte UTF-8 sequence can represent.
1372const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1373
1374// The maximum code-point a four-byte UTF-8 sequence can represent.
1375const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1376
1377// Chops off the n lowest bits from a bit pattern. Returns the n
1378// lowest bits. As a side effect, the original bit pattern will be
1379// shifted to the right by n bits.
1380inline UInt32 ChopLowBits(UInt32* bits, int n) {
1381 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1382 *bits >>= n;
1383 return low_bits;
1384}
1385
1386// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1387// code_point parameter is of type UInt32 because wchar_t may not be
1388// wide enough to contain a code point.
1389// The output buffer str must containt at least 32 characters.
1390// The function returns the address of the output buffer.
1391// If the code_point is not a valid Unicode code point
1392// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1393// as '(Invalid Unicode 0xXXXXXXXX)'.
1394char* CodePointToUtf8(UInt32 code_point, char* str) {
1395 if (code_point <= kMaxCodePoint1) {
1396 str[1] = '\0';
1397 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1398 } else if (code_point <= kMaxCodePoint2) {
1399 str[2] = '\0';
1400 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1401 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1402 } else if (code_point <= kMaxCodePoint3) {
1403 str[3] = '\0';
1404 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1405 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1406 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1407 } else if (code_point <= kMaxCodePoint4) {
1408 str[4] = '\0';
1409 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1410 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1411 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1412 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1413 } else {
1414 // The longest string String::Format can produce when invoked
1415 // with these parameters is 28 character long (not including
1416 // the terminating nul character). We are asking for 32 character
1417 // buffer just in case. This is also enough for strncpy to
1418 // null-terminate the destination string.
1419 // MSVC 8 deprecates strncpy(), so we want to suppress warning
1420 // 4996 (deprecated function) there.
1421#ifdef GTEST_OS_WINDOWS // We are on Windows.
1422#pragma warning(push) // Saves the current warning state.
1423#pragma warning(disable:4996) // Temporarily disables warning 4996.
1424#endif
1425 strncpy(str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(),
1426 32);
1427#ifdef GTEST_OS_WINDOWS // We are on Windows.
1428#pragma warning(pop) // Restores the warning state.
1429#endif
1430 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1431 // the result unterminated.
1432 }
1433 return str;
1434}
1435
1436// The following two functions only make sense if the the system
1437// uses UTF-16 for wide string encoding. All supported systems
1438// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1439
1440// Determines if the arguments constitute UTF-16 surrogate pair
1441// and thus should be combined into a single Unicode code point
1442// using CreateCodePointFromUtf16SurrogatePair.
1443inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1444 if (sizeof(wchar_t) == 2)
1445 return (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1446 else
1447 return false;
1448}
1449
1450// Creates a Unicode code point from UTF16 surrogate pair.
1451inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1452 wchar_t second) {
1453 if (sizeof(wchar_t) == 2) {
1454 const UInt32 mask = (1 << 10) - 1;
1455 return (((first & mask) << 10) | (second & mask)) + 0x10000;
1456 } else {
1457 // This should not be called, but we provide a sensible default
1458 // in case it is.
1459 return static_cast<UInt32>(first);
1460 }
1461}
1462
1463// Converts a wide string to a narrow string in UTF-8 encoding.
1464// The wide string is assumed to have the following encoding:
1465// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1466// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1467// Parameter str points to a null-terminated wide string.
1468// Parameter num_chars may additionally limit the number
1469// of wchar_t characters processed. -1 is used when the entire string
1470// should be processed.
1471// If the string contains code points that are not valid Unicode code points
1472// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1473// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1474// and contains invalid UTF-16 surrogate pairs, values in those pairs
1475// will be encoded as individual Unicode characters from Basic Normal Plane.
1476String WideStringToUtf8(const wchar_t* str, int num_chars) {
1477 if (num_chars == -1)
1478 num_chars = static_cast<int>(wcslen(str));
1479
1480 StrStream stream;
1481 for (int i = 0; i < num_chars; ++i) {
1482 UInt32 unicode_code_point;
1483
1484 if (str[i] == L'\0') {
1485 break;
1486 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1487 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1488 str[i + 1]);
1489 i++;
1490 } else {
1491 unicode_code_point = static_cast<UInt32>(str[i]);
1492 }
1493
1494 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1495 stream << CodePointToUtf8(unicode_code_point, buffer);
1496 }
1497 return StrStreamToString(&stream);
1498}
1499
1500// Converts a wide C string to a String using the UTF-8 encoding.
1501// NULL will be converted to "(null)".
1502String String::ShowWideCString(const wchar_t * wide_c_str) {
1503 if (wide_c_str == NULL) return String("(null)");
1504
1505 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1506}
1507
1508// Similar to ShowWideCString(), except that this function encloses
1509// the converted string in double quotes.
1510String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1511 if (wide_c_str == NULL) return String("(null)");
1512
1513 return String::Format("L\"%s\"",
1514 String::ShowWideCString(wide_c_str).c_str());
1515}
1516
1517// Compares two wide C strings. Returns true iff they have the same
1518// content.
1519//
1520// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1521// C string is considered different to any non-NULL C string,
1522// including the empty string.
1523bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1524 if (lhs == NULL) return rhs == NULL;
1525
1526 if (rhs == NULL) return false;
1527
1528 return wcscmp(lhs, rhs) == 0;
1529}
1530
1531// Helper function for *_STREQ on wide strings.
1532AssertionResult CmpHelperSTREQ(const char* expected_expression,
1533 const char* actual_expression,
1534 const wchar_t* expected,
1535 const wchar_t* actual) {
1536 if (String::WideCStringEquals(expected, actual)) {
1537 return AssertionSuccess();
1538 }
1539
1540 return EqFailure(expected_expression,
1541 actual_expression,
1542 String::ShowWideCStringQuoted(expected),
1543 String::ShowWideCStringQuoted(actual),
1544 false);
1545}
1546
1547// Helper function for *_STRNE on wide strings.
1548AssertionResult CmpHelperSTRNE(const char* s1_expression,
1549 const char* s2_expression,
1550 const wchar_t* s1,
1551 const wchar_t* s2) {
1552 if (!String::WideCStringEquals(s1, s2)) {
1553 return AssertionSuccess();
1554 }
1555
1556 Message msg;
1557 msg << "Expected: (" << s1_expression << ") != ("
1558 << s2_expression << "), actual: "
1559 << String::ShowWideCStringQuoted(s1)
1560 << " vs " << String::ShowWideCStringQuoted(s2);
1561 return AssertionFailure(msg);
1562}
1563
1564// Compares two C strings, ignoring case. Returns true iff they have
1565// the same content.
1566//
1567// Unlike strcasecmp(), this function can handle NULL argument(s). A
1568// NULL C string is considered different to any non-NULL C string,
1569// including the empty string.
1570bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1571 if ( lhs == NULL ) return rhs == NULL;
1572
1573 if ( rhs == NULL ) return false;
1574
1575#ifdef GTEST_OS_WINDOWS
1576 return _stricmp(lhs, rhs) == 0;
1577#else // GTEST_OS_WINDOWS
1578 return strcasecmp(lhs, rhs) == 0;
1579#endif // GTEST_OS_WINDOWS
1580}
1581
1582 // Compares two wide C strings, ignoring case. Returns true iff they
1583 // have the same content.
1584 //
1585 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1586 // A NULL C string is considered different to any non-NULL wide C string,
1587 // including the empty string.
1588 // NB: The implementations on different platforms slightly differ.
1589 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1590 // environment variable. On GNU platform this method uses wcscasecmp
1591 // which compares according to LC_CTYPE category of the current locale.
1592 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1593 // current locale.
1594bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1595 const wchar_t* rhs) {
1596 if ( lhs == NULL ) return rhs == NULL;
1597
1598 if ( rhs == NULL ) return false;
1599
1600#ifdef GTEST_OS_WINDOWS
1601 return _wcsicmp(lhs, rhs) == 0;
1602#elif defined(GTEST_OS_LINUX)
1603 return wcscasecmp(lhs, rhs) == 0;
1604#else
1605 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1606 // may not define it either.
1607 wint_t left, right;
1608 do {
1609 left = towlower(*lhs++);
1610 right = towlower(*rhs++);
1611 } while (left && left == right);
1612 return left == right;
1613#endif // OS selector
1614}
1615
1616// Constructs a String by copying a given number of chars from a
1617// buffer. E.g. String("hello", 3) will create the string "hel".
1618String::String(const char * buffer, size_t len) {
1619 char * const temp = new char[ len + 1 ];
1620 memcpy(temp, buffer, len);
1621 temp[ len ] = '\0';
1622 c_str_ = temp;
1623}
1624
1625// Compares this with another String.
1626// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1627// if this is greater than rhs.
1628int String::Compare(const String & rhs) const {
1629 if ( c_str_ == NULL ) {
1630 return rhs.c_str_ == NULL ? 0 : -1; // NULL < anything except NULL
1631 }
1632
1633 return rhs.c_str_ == NULL ? 1 : strcmp(c_str_, rhs.c_str_);
1634}
1635
1636// Returns true iff this String ends with the given suffix. *Any*
1637// String is considered to end with a NULL or empty suffix.
1638bool String::EndsWith(const char* suffix) const {
1639 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1640
1641 if (c_str_ == NULL) return false;
1642
1643 const size_t this_len = strlen(c_str_);
1644 const size_t suffix_len = strlen(suffix);
1645 return (this_len >= suffix_len) &&
1646 CStringEquals(c_str_ + this_len - suffix_len, suffix);
1647}
1648
1649// Returns true iff this String ends with the given suffix, ignoring case.
1650// Any String is considered to end with a NULL or empty suffix.
1651bool String::EndsWithCaseInsensitive(const char* suffix) const {
1652 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1653
1654 if (c_str_ == NULL) return false;
1655
1656 const size_t this_len = strlen(c_str_);
1657 const size_t suffix_len = strlen(suffix);
1658 return (this_len >= suffix_len) &&
1659 CaseInsensitiveCStringEquals(c_str_ + this_len - suffix_len, suffix);
1660}
1661
1662// Sets the 0-terminated C string this String object represents. The
1663// old string in this object is deleted, and this object will own a
1664// clone of the input string. This function copies only up to length
1665// bytes (plus a terminating null byte), or until the first null byte,
1666// whichever comes first.
1667//
1668// This function works even when the c_str parameter has the same
1669// value as that of the c_str_ field.
1670void String::Set(const char * c_str, size_t length) {
1671 // Makes sure this works when c_str == c_str_
1672 const char* const temp = CloneString(c_str, length);
1673 delete[] c_str_;
1674 c_str_ = temp;
1675}
1676
1677// Assigns a C string to this object. Self-assignment works.
1678const String& String::operator=(const char* c_str) {
1679 // Makes sure this works when c_str == c_str_
1680 if (c_str != c_str_) {
1681 delete[] c_str_;
1682 c_str_ = CloneCString(c_str);
1683 }
1684 return *this;
1685}
1686
1687// Formats a list of arguments to a String, using the same format
1688// spec string as for printf.
1689//
1690// We do not use the StringPrintf class as it is not universally
1691// available.
1692//
1693// The result is limited to 4096 characters (including the tailing 0).
1694// If 4096 characters are not enough to format the input,
1695// "<buffer exceeded>" is returned.
1696String String::Format(const char * format, ...) {
1697 va_list args;
1698 va_start(args, format);
1699
1700 char buffer[4096];
1701 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1702 // 4996 (deprecated function) there.
1703#ifdef GTEST_OS_WINDOWS // We are on Windows.
1704#pragma warning(push) // Saves the current warning state.
1705#pragma warning(disable:4996) // Temporarily disables warning 4996.
1706 const int size =
1707 vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1708#pragma warning(pop) // Restores the warning state.
1709#else // We are on Linux or Mac OS.
1710 const int size =
1711 vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1712#endif // GTEST_OS_WINDOWS
1713 va_end(args);
1714
1715 return String(size >= 0 ? buffer : "<buffer exceeded>");
1716}
1717
1718// Converts the buffer in a StrStream to a String, converting NUL
1719// bytes to "\\0" along the way.
1720String StrStreamToString(StrStream* ss) {
1721#if GTEST_HAS_STD_STRING
1722 const ::std::string& str = ss->str();
1723 const char* const start = str.c_str();
1724 const char* const end = start + str.length();
1725#else
1726 const char* const start = ss->str();
1727 const char* const end = start + ss->pcount();
1728#endif // GTEST_HAS_STD_STRING
1729
1730 // We need to use a helper StrStream to do this transformation
1731 // because String doesn't support push_back().
1732 StrStream helper;
1733 for (const char* ch = start; ch != end; ++ch) {
1734 if (*ch == '\0') {
1735 helper << "\\0"; // Replaces NUL with "\\0";
1736 } else {
1737 helper.put(*ch);
1738 }
1739 }
1740
1741#if GTEST_HAS_STD_STRING
1742 return String(helper.str().c_str());
1743#else
1744 const String str(helper.str(), helper.pcount());
1745 helper.freeze(false);
1746 ss->freeze(false);
1747 return str;
1748#endif // GTEST_HAS_STD_STRING
1749}
1750
1751// Appends the user-supplied message to the Google-Test-generated message.
1752String AppendUserMessage(const String& gtest_msg,
1753 const Message& user_msg) {
1754 // Appends the user message if it's non-empty.
1755 const String user_msg_string = user_msg.GetString();
1756 if (user_msg_string.empty()) {
1757 return gtest_msg;
1758 }
1759
1760 Message msg;
1761 msg << gtest_msg << "\n" << user_msg_string;
1762
1763 return msg.GetString();
1764}
1765
1766// class TestResult
1767
1768// Creates an empty TestResult.
1769TestResult::TestResult()
1770 : death_test_count_(0),
1771 elapsed_time_(0) {
1772}
1773
1774// D'tor.
1775TestResult::~TestResult() {
1776}
1777
1778// Adds a test part result to the list.
1779void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1780 test_part_results_.PushBack(test_part_result);
1781}
1782
1783// Adds a test property to the list. If a property with the same key as the
1784// supplied property is already represented, the value of this test_property
1785// replaces the old value for that key.
1786void TestResult::RecordProperty(const TestProperty& test_property) {
1787 if (!ValidateTestProperty(test_property)) {
1788 return;
1789 }
1790 MutexLock lock(&test_properites_mutex_);
1791 ListNode<TestProperty>* const node_with_matching_key =
1792 test_properties_.FindIf(TestPropertyKeyIs(test_property.key()));
1793 if (node_with_matching_key == NULL) {
1794 test_properties_.PushBack(test_property);
1795 return;
1796 }
1797 TestProperty& property_with_matching_key = node_with_matching_key->element();
1798 property_with_matching_key.SetValue(test_property.value());
1799}
1800
1801// Adds a failure if the key is a reserved attribute of Google Test
1802// testcase tags. Returns true if the property is valid.
1803bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1804 String key(test_property.key());
1805 if (key == "name" || key == "status" || key == "time" || key == "classname") {
1806 ADD_FAILURE()
1807 << "Reserved key used in RecordProperty(): "
1808 << key
1809 << " ('name', 'status', 'time', and 'classname' are reserved by "
1810 << GTEST_NAME << ")";
1811 return false;
1812 }
1813 return true;
1814}
1815
1816// Clears the object.
1817void TestResult::Clear() {
1818 test_part_results_.Clear();
1819 test_properties_.Clear();
1820 death_test_count_ = 0;
1821 elapsed_time_ = 0;
1822}
1823
1824// Returns true iff the test part passed.
1825static bool TestPartPassed(const TestPartResult & result) {
1826 return result.passed();
1827}
1828
1829// Gets the number of successful test parts.
1830int TestResult::successful_part_count() const {
1831 return test_part_results_.CountIf(TestPartPassed);
1832}
1833
1834// Returns true iff the test part failed.
1835static bool TestPartFailed(const TestPartResult & result) {
1836 return result.failed();
1837}
1838
1839// Gets the number of failed test parts.
1840int TestResult::failed_part_count() const {
1841 return test_part_results_.CountIf(TestPartFailed);
1842}
1843
1844// Returns true iff the test part fatally failed.
1845static bool TestPartFatallyFailed(const TestPartResult & result) {
1846 return result.fatally_failed();
1847}
1848
1849// Returns true iff the test fatally failed.
1850bool TestResult::HasFatalFailure() const {
1851 return test_part_results_.CountIf(TestPartFatallyFailed) > 0;
1852}
1853
1854// Gets the number of all test parts. This is the sum of the number
1855// of successful test parts and the number of failed test parts.
1856int TestResult::total_part_count() const {
1857 return test_part_results_.size();
1858}
1859
1860} // namespace internal
1861
1862// class Test
1863
1864// Creates a Test object.
1865
1866// The c'tor saves the values of all Google Test flags.
1867Test::Test()
1868 : gtest_flag_saver_(new internal::GTestFlagSaver) {
1869}
1870
1871// The d'tor restores the values of all Google Test flags.
1872Test::~Test() {
1873 delete gtest_flag_saver_;
1874}
1875
1876// Sets up the test fixture.
1877//
1878// A sub-class may override this.
1879void Test::SetUp() {
1880}
1881
1882// Tears down the test fixture.
1883//
1884// A sub-class may override this.
1885void Test::TearDown() {
1886}
1887
1888// Allows user supplied key value pairs to be recorded for later output.
1889void Test::RecordProperty(const char* key, const char* value) {
1890 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1891}
1892
1893// Allows user supplied key value pairs to be recorded for later output.
1894void Test::RecordProperty(const char* key, int value) {
1895 Message value_message;
1896 value_message << value;
1897 RecordProperty(key, value_message.GetString().c_str());
1898}
1899
1900#ifdef GTEST_OS_WINDOWS
1901// We are on Windows.
1902
1903// Adds an "exception thrown" fatal failure to the current test.
1904static void AddExceptionThrownFailure(DWORD exception_code,
1905 const char* location) {
1906 Message message;
1907 message << "Exception thrown with code 0x" << std::setbase(16) <<
1908 exception_code << std::setbase(10) << " in " << location << ".";
1909
1910 UnitTest* const unit_test = UnitTest::GetInstance();
1911 unit_test->AddTestPartResult(
1912 TPRT_FATAL_FAILURE,
1913 static_cast<const char *>(NULL),
1914 // We have no info about the source file where the exception
1915 // occurred.
1916 -1, // We have no info on which line caused the exception.
1917 message.GetString(),
1918 internal::String(""));
1919}
1920
1921#endif // GTEST_OS_WINDOWS
1922
1923// Google Test requires all tests in the same test case to use the same test
1924// fixture class. This function checks if the current test has the
1925// same fixture class as the first test in the current test case. If
1926// yes, it returns true; otherwise it generates a Google Test failure and
1927// returns false.
1928bool Test::HasSameFixtureClass() {
1929 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1930 const TestCase* const test_case = impl->current_test_case();
1931
1932 // Info about the first test in the current test case.
1933 const internal::TestInfoImpl* const first_test_info =
1934 test_case->test_info_list().Head()->element()->impl();
1935 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1936 const char* const first_test_name = first_test_info->name();
1937
1938 // Info about the current test.
1939 const internal::TestInfoImpl* const this_test_info =
1940 impl->current_test_info()->impl();
1941 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
1942 const char* const this_test_name = this_test_info->name();
1943
1944 if (this_fixture_id != first_fixture_id) {
1945 // Is the first test defined using TEST?
1946 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
1947 // Is this test defined using TEST?
1948 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
1949
1950 if (first_is_TEST || this_is_TEST) {
1951 // The user mixed TEST and TEST_F in this test case - we'll tell
1952 // him/her how to fix it.
1953
1954 // Gets the name of the TEST and the name of the TEST_F. Note
1955 // that first_is_TEST and this_is_TEST cannot both be true, as
1956 // the fixture IDs are different for the two tests.
1957 const char* const TEST_name =
1958 first_is_TEST ? first_test_name : this_test_name;
1959 const char* const TEST_F_name =
1960 first_is_TEST ? this_test_name : first_test_name;
1961
1962 ADD_FAILURE()
1963 << "All tests in the same test case must use the same test fixture\n"
1964 << "class, so mixing TEST_F and TEST in the same test case is\n"
1965 << "illegal. In test case " << this_test_info->test_case_name()
1966 << ",\n"
1967 << "test " << TEST_F_name << " is defined using TEST_F but\n"
1968 << "test " << TEST_name << " is defined using TEST. You probably\n"
1969 << "want to change the TEST to TEST_F or move it to another test\n"
1970 << "case.";
1971 } else {
1972 // The user defined two fixture classes with the same name in
1973 // two namespaces - we'll tell him/her how to fix it.
1974 ADD_FAILURE()
1975 << "All tests in the same test case must use the same test fixture\n"
1976 << "class. However, in test case "
1977 << this_test_info->test_case_name() << ",\n"
1978 << "you defined test " << first_test_name
1979 << " and test " << this_test_name << "\n"
1980 << "using two different test fixture classes. This can happen if\n"
1981 << "the two classes are from different namespaces or translation\n"
1982 << "units and have the same name. You should probably rename one\n"
1983 << "of the classes to put the tests into different test cases.";
1984 }
1985 return false;
1986 }
1987
1988 return true;
1989}
1990
1991// Runs the test and updates the test result.
1992void Test::Run() {
1993 if (!HasSameFixtureClass()) return;
1994
1995 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Julien Lerougee0a056b2009-02-12 08:02:35 +00001996#if defined(GTEST_OS_WINDOWS) && !defined(__MINGW32__)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001997 // We are on Windows.
1998 impl->os_stack_trace_getter()->UponLeavingGTest();
1999 __try {
2000 SetUp();
2001 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2002 GetExceptionCode())) {
2003 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2004 }
2005
2006 // We will run the test only if SetUp() had no fatal failure.
2007 if (!HasFatalFailure()) {
2008 impl->os_stack_trace_getter()->UponLeavingGTest();
2009 __try {
2010 TestBody();
2011 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2012 GetExceptionCode())) {
2013 AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2014 }
2015 }
2016
2017 // However, we want to clean up as much as possible. Hence we will
2018 // always call TearDown(), even if SetUp() or the test body has
2019 // failed.
2020 impl->os_stack_trace_getter()->UponLeavingGTest();
2021 __try {
2022 TearDown();
2023 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2024 GetExceptionCode())) {
2025 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2026 }
2027
Julien Lerougee0a056b2009-02-12 08:02:35 +00002028#else // We are on Linux, Mac or MingW - exceptions are disabled.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002029 impl->os_stack_trace_getter()->UponLeavingGTest();
2030 SetUp();
2031
2032 // We will run the test only if SetUp() was successful.
2033 if (!HasFatalFailure()) {
2034 impl->os_stack_trace_getter()->UponLeavingGTest();
2035 TestBody();
2036 }
2037
2038 // However, we want to clean up as much as possible. Hence we will
2039 // always call TearDown(), even if SetUp() or the test body has
2040 // failed.
2041 impl->os_stack_trace_getter()->UponLeavingGTest();
2042 TearDown();
2043#endif // GTEST_OS_WINDOWS
2044}
2045
2046
2047// Returns true iff the current test has a fatal failure.
2048bool Test::HasFatalFailure() {
2049 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2050}
2051
2052// class TestInfo
2053
2054// Constructs a TestInfo object. It assumes ownership of the test factory
2055// object via impl_.
2056TestInfo::TestInfo(const char* test_case_name,
2057 const char* name,
2058 const char* test_case_comment,
2059 const char* comment,
2060 internal::TypeId fixture_class_id,
2061 internal::TestFactoryBase* factory) {
2062 impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2063 test_case_comment, comment,
2064 fixture_class_id, factory);
2065}
2066
2067// Destructs a TestInfo object.
2068TestInfo::~TestInfo() {
2069 delete impl_;
2070}
2071
2072namespace internal {
2073
2074// Creates a new TestInfo object and registers it with Google Test;
2075// returns the created object.
2076//
2077// Arguments:
2078//
2079// test_case_name: name of the test case
2080// name: name of the test
2081// test_case_comment: a comment on the test case that will be included in
2082// the test output
2083// comment: a comment on the test that will be included in the
2084// test output
2085// fixture_class_id: ID of the test fixture class
2086// set_up_tc: pointer to the function that sets up the test case
2087// tear_down_tc: pointer to the function that tears down the test case
2088// factory: pointer to the factory that creates a test object.
2089// The newly created TestInfo instance will assume
2090// ownership of the factory object.
2091TestInfo* MakeAndRegisterTestInfo(
2092 const char* test_case_name, const char* name,
2093 const char* test_case_comment, const char* comment,
2094 TypeId fixture_class_id,
2095 SetUpTestCaseFunc set_up_tc,
2096 TearDownTestCaseFunc tear_down_tc,
2097 TestFactoryBase* factory) {
2098 TestInfo* const test_info =
2099 new TestInfo(test_case_name, name, test_case_comment, comment,
2100 fixture_class_id, factory);
2101 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2102 return test_info;
2103}
2104
2105#ifdef GTEST_HAS_PARAM_TEST
2106void ReportInvalidTestCaseType(const char* test_case_name,
2107 const char* file, int line) {
2108 Message errors;
2109 errors
2110 << "Attempted redefinition of test case " << test_case_name << ".\n"
2111 << "All tests in the same test case must use the same test fixture\n"
2112 << "class. However, in test case " << test_case_name << ", you tried\n"
2113 << "to define a test using a fixture class different from the one\n"
2114 << "used earlier. This can happen if the two fixture classes are\n"
2115 << "from different namespaces and have the same name. You should\n"
2116 << "probably rename one of the classes to put the tests into different\n"
2117 << "test cases.";
2118
2119 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2120 errors.GetString().c_str());
2121}
2122#endif // GTEST_HAS_PARAM_TEST
2123
2124} // namespace internal
2125
2126// Returns the test case name.
2127const char* TestInfo::test_case_name() const {
2128 return impl_->test_case_name();
2129}
2130
2131// Returns the test name.
2132const char* TestInfo::name() const {
2133 return impl_->name();
2134}
2135
2136// Returns the test case comment.
2137const char* TestInfo::test_case_comment() const {
2138 return impl_->test_case_comment();
2139}
2140
2141// Returns the test comment.
2142const char* TestInfo::comment() const {
2143 return impl_->comment();
2144}
2145
2146// Returns true if this test should run.
2147bool TestInfo::should_run() const { return impl_->should_run(); }
2148
2149// Returns the result of the test.
2150const internal::TestResult* TestInfo::result() const { return impl_->result(); }
2151
2152// Increments the number of death tests encountered in this test so
2153// far.
2154int TestInfo::increment_death_test_count() {
2155 return impl_->result()->increment_death_test_count();
2156}
2157
2158namespace {
2159
2160// A predicate that checks the test name of a TestInfo against a known
2161// value.
2162//
2163// This is used for implementation of the TestCase class only. We put
2164// it in the anonymous namespace to prevent polluting the outer
2165// namespace.
2166//
2167// TestNameIs is copyable.
2168class TestNameIs {
2169 public:
2170 // Constructor.
2171 //
2172 // TestNameIs has NO default constructor.
2173 explicit TestNameIs(const char* name)
2174 : name_(name) {}
2175
2176 // Returns true iff the test name of test_info matches name_.
2177 bool operator()(const TestInfo * test_info) const {
2178 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
2179 }
2180
2181 private:
2182 internal::String name_;
2183};
2184
2185} // namespace
2186
2187// Finds and returns a TestInfo with the given name. If one doesn't
2188// exist, returns NULL.
2189TestInfo * TestCase::GetTestInfo(const char* test_name) {
2190 // Can we find a TestInfo with the given name?
2191 internal::ListNode<TestInfo *> * const node = test_info_list_->FindIf(
2192 TestNameIs(test_name));
2193
2194 // Returns the TestInfo found.
2195 return node ? node->element() : NULL;
2196}
2197
2198namespace internal {
2199
2200// This method expands all parameterized tests registered with macros TEST_P
2201// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2202// This will be done just once during the program runtime.
2203void UnitTestImpl::RegisterParameterizedTests() {
2204#ifdef GTEST_HAS_PARAM_TEST
2205 if (!parameterized_tests_registered_) {
2206 parameterized_test_registry_.RegisterTests();
2207 parameterized_tests_registered_ = true;
2208 }
2209#endif
2210}
2211
2212// Creates the test object, runs it, records its result, and then
2213// deletes it.
2214void TestInfoImpl::Run() {
2215 if (!should_run_) return;
2216
2217 // Tells UnitTest where to store test result.
2218 UnitTestImpl* const impl = internal::GetUnitTestImpl();
2219 impl->set_current_test_info(parent_);
2220
2221 // Notifies the unit test event listener that a test is about to
2222 // start.
2223 UnitTestEventListenerInterface* const result_printer =
2224 impl->result_printer();
2225 result_printer->OnTestStart(parent_);
2226
2227 const TimeInMillis start = GetTimeInMillis();
2228
2229 impl->os_stack_trace_getter()->UponLeavingGTest();
Julien Lerougee0a056b2009-02-12 08:02:35 +00002230#if defined(GTEST_OS_WINDOWS) && !defined(__MINGW32__)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002231 // We are on Windows.
2232 Test* test = NULL;
2233
2234 __try {
2235 // Creates the test object.
2236 test = factory_->CreateTest();
2237 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2238 GetExceptionCode())) {
2239 AddExceptionThrownFailure(GetExceptionCode(),
2240 "the test fixture's constructor");
2241 return;
2242 }
Julien Lerougee0a056b2009-02-12 08:02:35 +00002243#else // We are on Linux, Mac OS or MingW - exceptions are disabled.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002244
2245 // TODO(wan): If test->Run() throws, test won't be deleted. This is
2246 // not a problem now as we don't use exceptions. If we were to
2247 // enable exceptions, we should revise the following to be
2248 // exception-safe.
2249
2250 // Creates the test object.
2251 Test* test = factory_->CreateTest();
2252#endif // GTEST_OS_WINDOWS
2253
2254 // Runs the test only if the constructor of the test fixture didn't
2255 // generate a fatal failure.
2256 if (!Test::HasFatalFailure()) {
2257 test->Run();
2258 }
2259
2260 // Deletes the test object.
2261 impl->os_stack_trace_getter()->UponLeavingGTest();
2262 delete test;
2263 test = NULL;
2264
2265 result_.set_elapsed_time(GetTimeInMillis() - start);
2266
2267 // Notifies the unit test event listener that a test has just finished.
2268 result_printer->OnTestEnd(parent_);
2269
2270 // Tells UnitTest to stop associating assertion results to this
2271 // test.
2272 impl->set_current_test_info(NULL);
2273}
2274
2275} // namespace internal
2276
2277// class TestCase
2278
2279// Gets the number of successful tests in this test case.
2280int TestCase::successful_test_count() const {
2281 return test_info_list_->CountIf(TestPassed);
2282}
2283
2284// Gets the number of failed tests in this test case.
2285int TestCase::failed_test_count() const {
2286 return test_info_list_->CountIf(TestFailed);
2287}
2288
2289int TestCase::disabled_test_count() const {
2290 return test_info_list_->CountIf(TestDisabled);
2291}
2292
2293// Get the number of tests in this test case that should run.
2294int TestCase::test_to_run_count() const {
2295 return test_info_list_->CountIf(ShouldRunTest);
2296}
2297
2298// Gets the number of all tests.
2299int TestCase::total_test_count() const {
2300 return test_info_list_->size();
2301}
2302
2303// Creates a TestCase with the given name.
2304//
2305// Arguments:
2306//
2307// name: name of the test case
2308// set_up_tc: pointer to the function that sets up the test case
2309// tear_down_tc: pointer to the function that tears down the test case
2310TestCase::TestCase(const char* name, const char* comment,
2311 Test::SetUpTestCaseFunc set_up_tc,
2312 Test::TearDownTestCaseFunc tear_down_tc)
2313 : name_(name),
2314 comment_(comment),
2315 set_up_tc_(set_up_tc),
2316 tear_down_tc_(tear_down_tc),
2317 should_run_(false),
2318 elapsed_time_(0) {
2319 test_info_list_ = new internal::List<TestInfo *>;
2320}
2321
2322// Destructor of TestCase.
2323TestCase::~TestCase() {
2324 // Deletes every Test in the collection.
2325 test_info_list_->ForEach(internal::Delete<TestInfo>);
2326
2327 // Then deletes the Test collection.
2328 delete test_info_list_;
2329 test_info_list_ = NULL;
2330}
2331
2332// Adds a test to this test case. Will delete the test upon
2333// destruction of the TestCase object.
2334void TestCase::AddTestInfo(TestInfo * test_info) {
2335 test_info_list_->PushBack(test_info);
2336}
2337
2338// Runs every test in this TestCase.
2339void TestCase::Run() {
2340 if (!should_run_) return;
2341
2342 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2343 impl->set_current_test_case(this);
2344
2345 UnitTestEventListenerInterface * const result_printer =
2346 impl->result_printer();
2347
2348 result_printer->OnTestCaseStart(this);
2349 impl->os_stack_trace_getter()->UponLeavingGTest();
2350 set_up_tc_();
2351
2352 const internal::TimeInMillis start = internal::GetTimeInMillis();
2353 test_info_list_->ForEach(internal::TestInfoImpl::RunTest);
2354 elapsed_time_ = internal::GetTimeInMillis() - start;
2355
2356 impl->os_stack_trace_getter()->UponLeavingGTest();
2357 tear_down_tc_();
2358 result_printer->OnTestCaseEnd(this);
2359 impl->set_current_test_case(NULL);
2360}
2361
2362// Clears the results of all tests in this test case.
2363void TestCase::ClearResult() {
2364 test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2365}
2366
2367
2368// class UnitTestEventListenerInterface
2369
2370// The virtual d'tor.
2371UnitTestEventListenerInterface::~UnitTestEventListenerInterface() {
2372}
2373
2374// A result printer that never prints anything. Used in the child process
2375// of an exec-style death test to avoid needless output clutter.
2376class NullUnitTestResultPrinter : public UnitTestEventListenerInterface {};
2377
2378// Formats a countable noun. Depending on its quantity, either the
2379// singular form or the plural form is used. e.g.
2380//
2381// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2382// FormatCountableNoun(5, "book", "books") returns "5 books".
2383static internal::String FormatCountableNoun(int count,
2384 const char * singular_form,
2385 const char * plural_form) {
2386 return internal::String::Format("%d %s", count,
2387 count == 1 ? singular_form : plural_form);
2388}
2389
2390// Formats the count of tests.
2391static internal::String FormatTestCount(int test_count) {
2392 return FormatCountableNoun(test_count, "test", "tests");
2393}
2394
2395// Formats the count of test cases.
2396static internal::String FormatTestCaseCount(int test_case_count) {
2397 return FormatCountableNoun(test_case_count, "test case", "test cases");
2398}
2399
2400// Converts a TestPartResultType enum to human-friendly string
2401// representation. Both TPRT_NONFATAL_FAILURE and TPRT_FATAL_FAILURE
2402// are translated to "Failure", as the user usually doesn't care about
2403// the difference between the two when viewing the test result.
2404static const char * TestPartResultTypeToString(TestPartResultType type) {
2405 switch (type) {
2406 case TPRT_SUCCESS:
2407 return "Success";
2408
2409 case TPRT_NONFATAL_FAILURE:
2410 case TPRT_FATAL_FAILURE:
2411#ifdef _MSC_VER
2412 return "error: ";
2413#else
2414 return "Failure\n";
2415#endif
2416 }
2417
2418 return "Unknown result type";
2419}
2420
2421// Prints a TestPartResult.
2422static void PrintTestPartResult(
2423 const TestPartResult & test_part_result) {
2424 printf("%s %s%s\n",
2425 internal::FormatFileLocation(test_part_result.file_name(),
2426 test_part_result.line_number()).c_str(),
2427 TestPartResultTypeToString(test_part_result.type()),
2428 test_part_result.message());
2429 fflush(stdout);
2430}
2431
2432// class PrettyUnitTestResultPrinter
2433
2434namespace internal {
2435
2436enum GTestColor {
2437 COLOR_RED,
2438 COLOR_GREEN,
2439 COLOR_YELLOW
2440};
2441
2442#if defined(GTEST_OS_WINDOWS) && !defined(_WIN32_WCE)
2443
2444// Returns the character attribute for the given color.
2445WORD GetColorAttribute(GTestColor color) {
2446 switch (color) {
2447 case COLOR_RED: return FOREGROUND_RED;
2448 case COLOR_GREEN: return FOREGROUND_GREEN;
2449 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2450 }
2451 return 0;
2452}
2453
2454#else
2455
2456// Returns the ANSI color code for the given color.
2457const char* GetAnsiColorCode(GTestColor color) {
2458 switch (color) {
2459 case COLOR_RED: return "1";
2460 case COLOR_GREEN: return "2";
2461 case COLOR_YELLOW: return "3";
2462 };
2463 return NULL;
2464}
2465
2466#endif // GTEST_OS_WINDOWS && !_WIN32_WCE
2467
2468// Returns true iff Google Test should use colors in the output.
2469bool ShouldUseColor(bool stdout_is_tty) {
2470 const char* const gtest_color = GTEST_FLAG(color).c_str();
2471
2472 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2473#ifdef GTEST_OS_WINDOWS
2474 // On Windows the TERM variable is usually not set, but the
2475 // console there does support colors.
2476 return stdout_is_tty;
2477#else
2478 // On non-Windows platforms, we rely on the TERM variable.
2479 const char* const term = GetEnv("TERM");
2480 const bool term_supports_color =
2481 String::CStringEquals(term, "xterm") ||
2482 String::CStringEquals(term, "xterm-color") ||
2483 String::CStringEquals(term, "cygwin");
2484 return stdout_is_tty && term_supports_color;
2485#endif // GTEST_OS_WINDOWS
2486 }
2487
2488 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2489 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2490 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2491 String::CStringEquals(gtest_color, "1");
2492 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2493 // value is neither one of these nor "auto", we treat it as "no" to
2494 // be conservative.
2495}
2496
2497// Helpers for printing colored strings to stdout. Note that on Windows, we
2498// cannot simply emit special characters and have the terminal change colors.
2499// This routine must actually emit the characters rather than return a string
2500// that would be colored when printed, as can be done on Linux.
2501void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2502 va_list args;
2503 va_start(args, fmt);
2504
2505#if defined(_WIN32_WCE) || defined(GTEST_OS_SYMBIAN) || defined(GTEST_OS_ZOS)
2506 static const bool use_color = false;
2507#else
2508 static const bool use_color = ShouldUseColor(isatty(fileno(stdout)) != 0);
2509#endif // !_WIN32_WCE
2510 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2511
2512 if (!use_color) {
2513 vprintf(fmt, args);
2514 va_end(args);
2515 return;
2516 }
2517
2518#if defined(GTEST_OS_WINDOWS) && !defined(_WIN32_WCE)
2519 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2520
2521 // Gets the current text color.
2522 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2523 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2524 const WORD old_color_attrs = buffer_info.wAttributes;
2525
2526 SetConsoleTextAttribute(stdout_handle,
2527 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2528 vprintf(fmt, args);
2529
2530 // Restores the text color.
2531 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2532#else
2533 printf("\033[0;3%sm", GetAnsiColorCode(color));
2534 vprintf(fmt, args);
2535 printf("\033[m"); // Resets the terminal to default.
2536#endif // GTEST_OS_WINDOWS && !_WIN32_WCE
2537 va_end(args);
2538}
2539
2540} // namespace internal
2541
2542using internal::ColoredPrintf;
2543using internal::COLOR_RED;
2544using internal::COLOR_GREEN;
2545using internal::COLOR_YELLOW;
2546
2547// This class implements the UnitTestEventListenerInterface interface.
2548//
2549// Class PrettyUnitTestResultPrinter is copyable.
2550class PrettyUnitTestResultPrinter : public UnitTestEventListenerInterface {
2551 public:
2552 PrettyUnitTestResultPrinter() {}
2553 static void PrintTestName(const char * test_case, const char * test) {
2554 printf("%s.%s", test_case, test);
2555 }
2556
2557 // The following methods override what's in the
2558 // UnitTestEventListenerInterface class.
2559 virtual void OnUnitTestStart(const UnitTest * unit_test);
2560 virtual void OnGlobalSetUpStart(const UnitTest*);
2561 virtual void OnTestCaseStart(const TestCase * test_case);
2562 virtual void OnTestCaseEnd(const TestCase * test_case);
2563 virtual void OnTestStart(const TestInfo * test_info);
2564 virtual void OnNewTestPartResult(const TestPartResult * result);
2565 virtual void OnTestEnd(const TestInfo * test_info);
2566 virtual void OnGlobalTearDownStart(const UnitTest*);
2567 virtual void OnUnitTestEnd(const UnitTest * unit_test);
2568
2569 private:
2570 internal::String test_case_name_;
2571};
2572
2573// Called before the unit test starts.
2574void PrettyUnitTestResultPrinter::OnUnitTestStart(
2575 const UnitTest * unit_test) {
2576 const char * const filter = GTEST_FLAG(filter).c_str();
2577
2578 // Prints the filter if it's not *. This reminds the user that some
2579 // tests may be skipped.
2580 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2581 ColoredPrintf(COLOR_YELLOW,
2582 "Note: %s filter = %s\n", GTEST_NAME, filter);
2583 }
2584
2585 const internal::UnitTestImpl* const impl = unit_test->impl();
2586 ColoredPrintf(COLOR_GREEN, "[==========] ");
2587 printf("Running %s from %s.\n",
2588 FormatTestCount(impl->test_to_run_count()).c_str(),
2589 FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2590 fflush(stdout);
2591}
2592
2593void PrettyUnitTestResultPrinter::OnGlobalSetUpStart(const UnitTest*) {
2594 ColoredPrintf(COLOR_GREEN, "[----------] ");
2595 printf("Global test environment set-up.\n");
2596 fflush(stdout);
2597}
2598
2599void PrettyUnitTestResultPrinter::OnTestCaseStart(
2600 const TestCase * test_case) {
2601 test_case_name_ = test_case->name();
2602 const internal::String counts =
2603 FormatCountableNoun(test_case->test_to_run_count(), "test", "tests");
2604 ColoredPrintf(COLOR_GREEN, "[----------] ");
2605 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2606 if (test_case->comment()[0] == '\0') {
2607 printf("\n");
2608 } else {
2609 printf(", where %s\n", test_case->comment());
2610 }
2611 fflush(stdout);
2612}
2613
2614void PrettyUnitTestResultPrinter::OnTestCaseEnd(
2615 const TestCase * test_case) {
2616 if (!GTEST_FLAG(print_time)) return;
2617
2618 test_case_name_ = test_case->name();
2619 const internal::String counts =
2620 FormatCountableNoun(test_case->test_to_run_count(), "test", "tests");
2621 ColoredPrintf(COLOR_GREEN, "[----------] ");
2622 printf("%s from %s (%s ms total)\n\n",
2623 counts.c_str(), test_case_name_.c_str(),
2624 internal::StreamableToString(test_case->elapsed_time()).c_str());
2625 fflush(stdout);
2626}
2627
2628void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo * test_info) {
2629 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2630 PrintTestName(test_case_name_.c_str(), test_info->name());
2631 if (test_info->comment()[0] == '\0') {
2632 printf("\n");
2633 } else {
2634 printf(", where %s\n", test_info->comment());
2635 }
2636 fflush(stdout);
2637}
2638
2639void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo * test_info) {
2640 if (test_info->result()->Passed()) {
2641 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2642 } else {
2643 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2644 }
2645 PrintTestName(test_case_name_.c_str(), test_info->name());
2646 if (GTEST_FLAG(print_time)) {
2647 printf(" (%s ms)\n", internal::StreamableToString(
2648 test_info->result()->elapsed_time()).c_str());
2649 } else {
2650 printf("\n");
2651 }
2652 fflush(stdout);
2653}
2654
2655// Called after an assertion failure.
2656void PrettyUnitTestResultPrinter::OnNewTestPartResult(
2657 const TestPartResult * result) {
2658 // If the test part succeeded, we don't need to do anything.
2659 if (result->type() == TPRT_SUCCESS)
2660 return;
2661
2662 // Print failure message from the assertion (e.g. expected this and got that).
2663 PrintTestPartResult(*result);
2664 fflush(stdout);
2665}
2666
2667void PrettyUnitTestResultPrinter::OnGlobalTearDownStart(const UnitTest*) {
2668 ColoredPrintf(COLOR_GREEN, "[----------] ");
2669 printf("Global test environment tear-down\n");
2670 fflush(stdout);
2671}
2672
2673namespace internal {
2674
2675// Internal helper for printing the list of failed tests.
2676static void PrintFailedTestsPretty(const UnitTestImpl* impl) {
2677 const int failed_test_count = impl->failed_test_count();
2678 if (failed_test_count == 0) {
2679 return;
2680 }
2681
2682 for (const internal::ListNode<TestCase*>* node = impl->test_cases()->Head();
2683 node != NULL; node = node->next()) {
2684 const TestCase* const tc = node->element();
2685 if (!tc->should_run() || (tc->failed_test_count() == 0)) {
2686 continue;
2687 }
2688 for (const internal::ListNode<TestInfo*>* tinode =
2689 tc->test_info_list().Head();
2690 tinode != NULL; tinode = tinode->next()) {
2691 const TestInfo* const ti = tinode->element();
2692 if (!tc->ShouldRunTest(ti) || tc->TestPassed(ti)) {
2693 continue;
2694 }
2695 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2696 printf("%s.%s", ti->test_case_name(), ti->name());
2697 if (ti->test_case_comment()[0] != '\0' ||
2698 ti->comment()[0] != '\0') {
2699 printf(", where %s", ti->test_case_comment());
2700 if (ti->test_case_comment()[0] != '\0' &&
2701 ti->comment()[0] != '\0') {
2702 printf(" and ");
2703 }
2704 }
2705 printf("%s\n", ti->comment());
2706 }
2707 }
2708}
2709
2710} // namespace internal
2711
2712void PrettyUnitTestResultPrinter::OnUnitTestEnd(
2713 const UnitTest * unit_test) {
2714 const internal::UnitTestImpl* const impl = unit_test->impl();
2715
2716 ColoredPrintf(COLOR_GREEN, "[==========] ");
2717 printf("%s from %s ran.",
2718 FormatTestCount(impl->test_to_run_count()).c_str(),
2719 FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2720 if (GTEST_FLAG(print_time)) {
2721 printf(" (%s ms total)",
2722 internal::StreamableToString(impl->elapsed_time()).c_str());
2723 }
2724 printf("\n");
2725 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2726 printf("%s.\n", FormatTestCount(impl->successful_test_count()).c_str());
2727
2728 int num_failures = impl->failed_test_count();
2729 if (!impl->Passed()) {
2730 const int failed_test_count = impl->failed_test_count();
2731 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2732 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2733 internal::PrintFailedTestsPretty(impl);
2734 printf("\n%2d FAILED %s\n", num_failures,
2735 num_failures == 1 ? "TEST" : "TESTS");
2736 }
2737
2738 int num_disabled = impl->disabled_test_count();
2739 if (num_disabled) {
2740 if (!num_failures) {
2741 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2742 }
2743 ColoredPrintf(COLOR_YELLOW,
2744 " YOU HAVE %d DISABLED %s\n\n",
2745 num_disabled,
2746 num_disabled == 1 ? "TEST" : "TESTS");
2747 }
2748 // Ensure that Google Test output is printed before, e.g., heapchecker output.
2749 fflush(stdout);
2750}
2751
2752// End PrettyUnitTestResultPrinter
2753
2754// class UnitTestEventsRepeater
2755//
2756// This class forwards events to other event listeners.
2757class UnitTestEventsRepeater : public UnitTestEventListenerInterface {
2758 public:
2759 typedef internal::List<UnitTestEventListenerInterface *> Listeners;
2760 typedef internal::ListNode<UnitTestEventListenerInterface *> ListenersNode;
2761 UnitTestEventsRepeater() {}
2762 virtual ~UnitTestEventsRepeater();
2763 void AddListener(UnitTestEventListenerInterface *listener);
2764
2765 virtual void OnUnitTestStart(const UnitTest* unit_test);
2766 virtual void OnUnitTestEnd(const UnitTest* unit_test);
2767 virtual void OnGlobalSetUpStart(const UnitTest* unit_test);
2768 virtual void OnGlobalSetUpEnd(const UnitTest* unit_test);
2769 virtual void OnGlobalTearDownStart(const UnitTest* unit_test);
2770 virtual void OnGlobalTearDownEnd(const UnitTest* unit_test);
2771 virtual void OnTestCaseStart(const TestCase* test_case);
2772 virtual void OnTestCaseEnd(const TestCase* test_case);
2773 virtual void OnTestStart(const TestInfo* test_info);
2774 virtual void OnTestEnd(const TestInfo* test_info);
2775 virtual void OnNewTestPartResult(const TestPartResult* result);
2776
2777 private:
2778 Listeners listeners_;
2779
2780 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestEventsRepeater);
2781};
2782
2783UnitTestEventsRepeater::~UnitTestEventsRepeater() {
2784 for (ListenersNode* listener = listeners_.Head();
2785 listener != NULL;
2786 listener = listener->next()) {
2787 delete listener->element();
2788 }
2789}
2790
2791void UnitTestEventsRepeater::AddListener(
2792 UnitTestEventListenerInterface *listener) {
2793 listeners_.PushBack(listener);
2794}
2795
2796// Since the methods are identical, use a macro to reduce boilerplate.
2797// This defines a member that repeats the call to all listeners.
2798#define GTEST_REPEATER_METHOD_(Name, Type) \
2799void UnitTestEventsRepeater::Name(const Type* parameter) { \
2800 for (ListenersNode* listener = listeners_.Head(); \
2801 listener != NULL; \
2802 listener = listener->next()) { \
2803 listener->element()->Name(parameter); \
2804 } \
2805}
2806
2807GTEST_REPEATER_METHOD_(OnUnitTestStart, UnitTest)
2808GTEST_REPEATER_METHOD_(OnUnitTestEnd, UnitTest)
2809GTEST_REPEATER_METHOD_(OnGlobalSetUpStart, UnitTest)
2810GTEST_REPEATER_METHOD_(OnGlobalSetUpEnd, UnitTest)
2811GTEST_REPEATER_METHOD_(OnGlobalTearDownStart, UnitTest)
2812GTEST_REPEATER_METHOD_(OnGlobalTearDownEnd, UnitTest)
2813GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2814GTEST_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2815GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2816GTEST_REPEATER_METHOD_(OnTestEnd, TestInfo)
2817GTEST_REPEATER_METHOD_(OnNewTestPartResult, TestPartResult)
2818
2819#undef GTEST_REPEATER_METHOD_
2820
2821// End PrettyUnitTestResultPrinter
2822
2823// This class generates an XML output file.
2824class XmlUnitTestResultPrinter : public UnitTestEventListenerInterface {
2825 public:
2826 explicit XmlUnitTestResultPrinter(const char* output_file);
2827
2828 virtual void OnUnitTestEnd(const UnitTest* unit_test);
2829
2830 private:
2831 // Is c a whitespace character that is normalized to a space character
2832 // when it appears in an XML attribute value?
2833 static bool IsNormalizableWhitespace(char c) {
2834 return c == 0x9 || c == 0xA || c == 0xD;
2835 }
2836
2837 // May c appear in a well-formed XML document?
2838 static bool IsValidXmlCharacter(char c) {
2839 return IsNormalizableWhitespace(c) || c >= 0x20;
2840 }
2841
2842 // Returns an XML-escaped copy of the input string str. If
2843 // is_attribute is true, the text is meant to appear as an attribute
2844 // value, and normalizable whitespace is preserved by replacing it
2845 // with character references.
2846 static internal::String EscapeXml(const char* str,
2847 bool is_attribute);
2848
2849 // Convenience wrapper around EscapeXml when str is an attribute value.
2850 static internal::String EscapeXmlAttribute(const char* str) {
2851 return EscapeXml(str, true);
2852 }
2853
2854 // Convenience wrapper around EscapeXml when str is not an attribute value.
2855 static internal::String EscapeXmlText(const char* str) {
2856 return EscapeXml(str, false);
2857 }
2858
2859 // Prints an XML representation of a TestInfo object.
2860 static void PrintXmlTestInfo(FILE* out,
2861 const char* test_case_name,
2862 const TestInfo* test_info);
2863
2864 // Prints an XML representation of a TestCase object
2865 static void PrintXmlTestCase(FILE* out, const TestCase* test_case);
2866
2867 // Prints an XML summary of unit_test to output stream out.
2868 static void PrintXmlUnitTest(FILE* out, const UnitTest* unit_test);
2869
2870 // Produces a string representing the test properties in a result as space
2871 // delimited XML attributes based on the property key="value" pairs.
2872 // When the String is not empty, it includes a space at the beginning,
2873 // to delimit this attribute from prior attributes.
2874 static internal::String TestPropertiesAsXmlAttributes(
2875 const internal::TestResult* result);
2876
2877 // The output file.
2878 const internal::String output_file_;
2879
2880 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
2881};
2882
2883// Creates a new XmlUnitTestResultPrinter.
2884XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
2885 : output_file_(output_file) {
2886 if (output_file_.c_str() == NULL || output_file_.empty()) {
2887 fprintf(stderr, "XML output file may not be null\n");
2888 fflush(stderr);
2889 exit(EXIT_FAILURE);
2890 }
2891}
2892
2893// Called after the unit test ends.
2894void XmlUnitTestResultPrinter::OnUnitTestEnd(const UnitTest* unit_test) {
2895 FILE* xmlout = NULL;
2896 internal::FilePath output_file(output_file_);
2897 internal::FilePath output_dir(output_file.RemoveFileName());
2898
2899 if (output_dir.CreateDirectoriesRecursively()) {
2900 // MSVC 8 deprecates fopen(), so we want to suppress warning 4996
2901 // (deprecated function) there.
2902#ifdef GTEST_OS_WINDOWS
2903 // We are on Windows.
2904#pragma warning(push) // Saves the current warning state.
2905#pragma warning(disable:4996) // Temporarily disables warning 4996.
2906 xmlout = fopen(output_file_.c_str(), "w");
2907#pragma warning(pop) // Restores the warning state.
2908#else // We are on Linux or Mac OS.
2909 xmlout = fopen(output_file_.c_str(), "w");
2910#endif // GTEST_OS_WINDOWS
2911 }
2912 if (xmlout == NULL) {
2913 // TODO(wan): report the reason of the failure.
2914 //
2915 // We don't do it for now as:
2916 //
2917 // 1. There is no urgent need for it.
2918 // 2. It's a bit involved to make the errno variable thread-safe on
2919 // all three operating systems (Linux, Windows, and Mac OS).
2920 // 3. To interpret the meaning of errno in a thread-safe way,
2921 // we need the strerror_r() function, which is not available on
2922 // Windows.
2923 fprintf(stderr,
2924 "Unable to open file \"%s\"\n",
2925 output_file_.c_str());
2926 fflush(stderr);
2927 exit(EXIT_FAILURE);
2928 }
2929 PrintXmlUnitTest(xmlout, unit_test);
2930 fclose(xmlout);
2931}
2932
2933// Returns an XML-escaped copy of the input string str. If is_attribute
2934// is true, the text is meant to appear as an attribute value, and
2935// normalizable whitespace is preserved by replacing it with character
2936// references.
2937//
2938// Invalid XML characters in str, if any, are stripped from the output.
2939// It is expected that most, if not all, of the text processed by this
2940// module will consist of ordinary English text.
2941// If this module is ever modified to produce version 1.1 XML output,
2942// most invalid characters can be retained using character references.
2943// TODO(wan): It might be nice to have a minimally invasive, human-readable
2944// escaping scheme for invalid characters, rather than dropping them.
2945internal::String XmlUnitTestResultPrinter::EscapeXml(const char* str,
2946 bool is_attribute) {
2947 Message m;
2948
2949 if (str != NULL) {
2950 for (const char* src = str; *src; ++src) {
2951 switch (*src) {
2952 case '<':
2953 m << "&lt;";
2954 break;
2955 case '>':
2956 m << "&gt;";
2957 break;
2958 case '&':
2959 m << "&amp;";
2960 break;
2961 case '\'':
2962 if (is_attribute)
2963 m << "&apos;";
2964 else
2965 m << '\'';
2966 break;
2967 case '"':
2968 if (is_attribute)
2969 m << "&quot;";
2970 else
2971 m << '"';
2972 break;
2973 default:
2974 if (IsValidXmlCharacter(*src)) {
2975 if (is_attribute && IsNormalizableWhitespace(*src))
2976 m << internal::String::Format("&#x%02X;", unsigned(*src));
2977 else
2978 m << *src;
2979 }
2980 break;
2981 }
2982 }
2983 }
2984
2985 return m.GetString();
2986}
2987
2988
2989// The following routines generate an XML representation of a UnitTest
2990// object.
2991//
2992// This is how Google Test concepts map to the DTD:
2993//
2994// <testsuite name="AllTests"> <-- corresponds to a UnitTest object
2995// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
2996// <testcase name="test-name"> <-- corresponds to a TestInfo object
2997// <failure message="...">...</failure>
2998// <failure message="...">...</failure>
2999// <failure message="...">...</failure>
3000// <-- individual assertion failures
3001// </testcase>
3002// </testsuite>
3003// </testsuite>
3004
3005namespace internal {
3006
3007// Formats the given time in milliseconds as seconds. The returned
3008// C-string is owned by this function and cannot be released by the
3009// caller. Calling the function again invalidates the previous
3010// result.
3011const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3012 static String str;
3013 str = (Message() << (ms/1000.0)).GetString();
3014 return str.c_str();
3015}
3016
3017} // namespace internal
3018
3019// Prints an XML representation of a TestInfo object.
3020// TODO(wan): There is also value in printing properties with the plain printer.
3021void XmlUnitTestResultPrinter::PrintXmlTestInfo(FILE* out,
3022 const char* test_case_name,
3023 const TestInfo* test_info) {
3024 const internal::TestResult * const result = test_info->result();
3025 const internal::List<TestPartResult> &results = result->test_part_results();
3026 fprintf(out,
3027 " <testcase name=\"%s\" status=\"%s\" time=\"%s\" "
3028 "classname=\"%s\"%s",
3029 EscapeXmlAttribute(test_info->name()).c_str(),
3030 test_info->should_run() ? "run" : "notrun",
3031 internal::FormatTimeInMillisAsSeconds(result->elapsed_time()),
3032 EscapeXmlAttribute(test_case_name).c_str(),
3033 TestPropertiesAsXmlAttributes(result).c_str());
3034
3035 int failures = 0;
3036 for (const internal::ListNode<TestPartResult>* part_node = results.Head();
3037 part_node != NULL;
3038 part_node = part_node->next()) {
3039 const TestPartResult& part = part_node->element();
3040 if (part.failed()) {
3041 const internal::String message =
3042 internal::String::Format("%s:%d\n%s", part.file_name(),
3043 part.line_number(), part.message());
3044 if (++failures == 1)
3045 fprintf(out, ">\n");
3046 fprintf(out,
3047 " <failure message=\"%s\" type=\"\"><![CDATA[%s]]>"
3048 "</failure>\n",
3049 EscapeXmlAttribute(part.summary()).c_str(), message.c_str());
3050 }
3051 }
3052
3053 if (failures == 0)
3054 fprintf(out, " />\n");
3055 else
3056 fprintf(out, " </testcase>\n");
3057}
3058
3059// Prints an XML representation of a TestCase object
3060void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3061 const TestCase* test_case) {
3062 fprintf(out,
3063 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3064 "disabled=\"%d\" ",
3065 EscapeXmlAttribute(test_case->name()).c_str(),
3066 test_case->total_test_count(),
3067 test_case->failed_test_count(),
3068 test_case->disabled_test_count());
3069 fprintf(out,
3070 "errors=\"0\" time=\"%s\">\n",
3071 internal::FormatTimeInMillisAsSeconds(test_case->elapsed_time()));
3072 for (const internal::ListNode<TestInfo*>* info_node =
3073 test_case->test_info_list().Head();
3074 info_node != NULL;
3075 info_node = info_node->next()) {
3076 PrintXmlTestInfo(out, test_case->name(), info_node->element());
3077 }
3078 fprintf(out, " </testsuite>\n");
3079}
3080
3081// Prints an XML summary of unit_test to output stream out.
3082void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3083 const UnitTest* unit_test) {
3084 const internal::UnitTestImpl* const impl = unit_test->impl();
3085 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3086 fprintf(out,
3087 "<testsuite tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3088 "errors=\"0\" time=\"%s\" ",
3089 impl->total_test_count(),
3090 impl->failed_test_count(),
3091 impl->disabled_test_count(),
3092 internal::FormatTimeInMillisAsSeconds(impl->elapsed_time()));
3093 fprintf(out, "name=\"AllTests\">\n");
3094 for (const internal::ListNode<TestCase*>* case_node =
3095 impl->test_cases()->Head();
3096 case_node != NULL;
3097 case_node = case_node->next()) {
3098 PrintXmlTestCase(out, case_node->element());
3099 }
3100 fprintf(out, "</testsuite>\n");
3101}
3102
3103// Produces a string representing the test properties in a result as space
3104// delimited XML attributes based on the property key="value" pairs.
3105internal::String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3106 const internal::TestResult* result) {
3107 using internal::TestProperty;
3108 Message attributes;
3109 const internal::List<TestProperty>& properties = result->test_properties();
3110 for (const internal::ListNode<TestProperty>* property_node =
3111 properties.Head();
3112 property_node != NULL;
3113 property_node = property_node->next()) {
3114 const TestProperty& property = property_node->element();
3115 attributes << " " << property.key() << "="
3116 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3117 }
3118 return attributes.GetString();
3119}
3120
3121// End XmlUnitTestResultPrinter
3122
3123namespace internal {
3124
3125// Class ScopedTrace
3126
3127// Pushes the given source file location and message onto a per-thread
3128// trace stack maintained by Google Test.
3129// L < UnitTest::mutex_
3130ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3131 TraceInfo trace;
3132 trace.file = file;
3133 trace.line = line;
3134 trace.message = message.GetString();
3135
3136 UnitTest::GetInstance()->PushGTestTrace(trace);
3137}
3138
3139// Pops the info pushed by the c'tor.
3140// L < UnitTest::mutex_
3141ScopedTrace::~ScopedTrace() {
3142 UnitTest::GetInstance()->PopGTestTrace();
3143}
3144
3145
3146// class OsStackTraceGetter
3147
3148// Returns the current OS stack trace as a String. Parameters:
3149//
3150// max_depth - the maximum number of stack frames to be included
3151// in the trace.
3152// skip_count - the number of top frames to be skipped; doesn't count
3153// against max_depth.
3154//
3155// L < mutex_
3156// We use "L < mutex_" to denote that the function may acquire mutex_.
3157String OsStackTraceGetter::CurrentStackTrace(int, int) {
3158 return String("");
3159}
3160
3161// L < mutex_
3162void OsStackTraceGetter::UponLeavingGTest() {
3163}
3164
3165const char* const
3166OsStackTraceGetter::kElidedFramesMarker =
3167 "... " GTEST_NAME " internal frames ...";
3168
3169} // namespace internal
3170
3171// class UnitTest
3172
3173// Gets the singleton UnitTest object. The first time this method is
3174// called, a UnitTest object is constructed and returned. Consecutive
3175// calls will return the same object.
3176//
3177// We don't protect this under mutex_ as a user is not supposed to
3178// call this before main() starts, from which point on the return
3179// value will never change.
3180UnitTest * UnitTest::GetInstance() {
3181 // When compiled with MSVC 7.1 in optimized mode, destroying the
3182 // UnitTest object upon exiting the program messes up the exit code,
3183 // causing successful tests to appear failed. We have to use a
3184 // different implementation in this case to bypass the compiler bug.
3185 // This implementation makes the compiler happy, at the cost of
3186 // leaking the UnitTest object.
3187#if _MSC_VER == 1310 && !defined(_DEBUG) // MSVC 7.1 and optimized build.
3188 static UnitTest* const instance = new UnitTest;
3189 return instance;
3190#else
3191 static UnitTest instance;
3192 return &instance;
3193#endif // _MSC_VER==1310 && !defined(_DEBUG)
3194}
3195
3196// Registers and returns a global test environment. When a test
3197// program is run, all global test environments will be set-up in the
3198// order they were registered. After all tests in the program have
3199// finished, all global test environments will be torn-down in the
3200// *reverse* order they were registered.
3201//
3202// The UnitTest object takes ownership of the given environment.
3203//
3204// We don't protect this under mutex_, as we only support calling it
3205// from the main thread.
3206Environment* UnitTest::AddEnvironment(Environment* env) {
3207 if (env == NULL) {
3208 return NULL;
3209 }
3210
3211 impl_->environments()->PushBack(env);
3212 impl_->environments_in_reverse_order()->PushFront(env);
3213 return env;
3214}
3215
3216// Adds a TestPartResult to the current TestResult object. All Google Test
3217// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3218// this to report their results. The user code should use the
3219// assertion macros instead of calling this directly.
3220// L < mutex_
3221void UnitTest::AddTestPartResult(TestPartResultType result_type,
3222 const char* file_name,
3223 int line_number,
3224 const internal::String& message,
3225 const internal::String& os_stack_trace) {
3226 Message msg;
3227 msg << message;
3228
3229 internal::MutexLock lock(&mutex_);
3230 if (impl_->gtest_trace_stack()->size() > 0) {
3231 msg << "\n" << GTEST_NAME << " trace:";
3232
3233 for (internal::ListNode<internal::TraceInfo>* node =
3234 impl_->gtest_trace_stack()->Head();
3235 node != NULL;
3236 node = node->next()) {
3237 const internal::TraceInfo& trace = node->element();
3238 msg << "\n" << trace.file << ":" << trace.line << ": " << trace.message;
3239 }
3240 }
3241
3242 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3243 msg << internal::kStackTraceMarker << os_stack_trace;
3244 }
3245
3246 const TestPartResult result =
3247 TestPartResult(result_type, file_name, line_number,
3248 msg.GetString().c_str());
3249 impl_->GetTestPartResultReporterForCurrentThread()->
3250 ReportTestPartResult(result);
3251
3252 // If this is a failure and the user wants the debugger to break on
3253 // failures ...
3254 if (result_type != TPRT_SUCCESS && GTEST_FLAG(break_on_failure)) {
3255 // ... then we generate a seg fault.
3256 *static_cast<int*>(NULL) = 1;
3257 }
3258}
3259
3260// Creates and adds a property to the current TestResult. If a property matching
3261// the supplied value already exists, updates its value instead.
3262void UnitTest::RecordPropertyForCurrentTest(const char* key,
3263 const char* value) {
3264 const internal::TestProperty test_property(key, value);
3265 impl_->current_test_result()->RecordProperty(test_property);
3266}
3267
3268// Runs all tests in this UnitTest object and prints the result.
3269// Returns 0 if successful, or 1 otherwise.
3270//
3271// We don't protect this under mutex_, as we only support calling it
3272// from the main thread.
3273int UnitTest::Run() {
Julien Lerougee0a056b2009-02-12 08:02:35 +00003274#if defined(GTEST_OS_WINDOWS) && !defined(__MINGW32__)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003275
3276#if !defined(_WIN32_WCE)
3277 // SetErrorMode doesn't exist on CE.
3278 if (GTEST_FLAG(catch_exceptions)) {
3279 // The user wants Google Test to catch exceptions thrown by the tests.
3280
3281 // This lets fatal errors be handled by us, instead of causing pop-ups.
3282 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3283 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3284 }
3285#endif // _WIN32_WCE
3286
3287 __try {
3288 return impl_->RunAllTests();
3289 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3290 GetExceptionCode())) {
3291 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3292 fflush(stdout);
3293 return 1;
3294 }
3295
3296#else
Julien Lerougee0a056b2009-02-12 08:02:35 +00003297 // We are on Linux, Mac OS or MingW. There is no exception of any kind.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003298
3299 return impl_->RunAllTests();
3300#endif // GTEST_OS_WINDOWS
3301}
3302
3303// Returns the working directory when the first TEST() or TEST_F() was
3304// executed.
3305const char* UnitTest::original_working_dir() const {
3306 return impl_->original_working_dir_.c_str();
3307}
3308
3309// Returns the TestCase object for the test that's currently running,
3310// or NULL if no test is running.
3311// L < mutex_
3312const TestCase* UnitTest::current_test_case() const {
3313 internal::MutexLock lock(&mutex_);
3314 return impl_->current_test_case();
3315}
3316
3317// Returns the TestInfo object for the test that's currently running,
3318// or NULL if no test is running.
3319// L < mutex_
3320const TestInfo* UnitTest::current_test_info() const {
3321 internal::MutexLock lock(&mutex_);
3322 return impl_->current_test_info();
3323}
3324
3325#ifdef GTEST_HAS_PARAM_TEST
3326// Returns ParameterizedTestCaseRegistry object used to keep track of
3327// value-parameterized tests and instantiate and register them.
3328// L < mutex_
3329internal::ParameterizedTestCaseRegistry&
3330 UnitTest::parameterized_test_registry() {
3331 return impl_->parameterized_test_registry();
3332}
3333#endif // GTEST_HAS_PARAM_TEST
3334
3335// Creates an empty UnitTest.
3336UnitTest::UnitTest() {
3337 impl_ = new internal::UnitTestImpl(this);
3338}
3339
3340// Destructor of UnitTest.
3341UnitTest::~UnitTest() {
3342 delete impl_;
3343}
3344
3345// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3346// Google Test trace stack.
3347// L < mutex_
3348void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3349 internal::MutexLock lock(&mutex_);
3350 impl_->gtest_trace_stack()->PushFront(trace);
3351}
3352
3353// Pops a trace from the per-thread Google Test trace stack.
3354// L < mutex_
3355void UnitTest::PopGTestTrace() {
3356 internal::MutexLock lock(&mutex_);
3357 impl_->gtest_trace_stack()->PopFront(NULL);
3358}
3359
3360namespace internal {
3361
3362UnitTestImpl::UnitTestImpl(UnitTest* parent)
3363 : parent_(parent),
3364#ifdef _MSC_VER
3365#pragma warning(push) // Saves the current warning state.
3366#pragma warning(disable:4355) // Temporarily disables warning 4355
3367 // (using this in initializer).
3368 default_global_test_part_result_reporter_(this),
3369 default_per_thread_test_part_result_reporter_(this),
3370#pragma warning(pop) // Restores the warning state again.
3371#else
3372 default_global_test_part_result_reporter_(this),
3373 default_per_thread_test_part_result_reporter_(this),
3374#endif // _MSC_VER
3375 global_test_part_result_repoter_(
3376 &default_global_test_part_result_reporter_),
3377 per_thread_test_part_result_reporter_(
3378 &default_per_thread_test_part_result_reporter_),
3379 test_cases_(),
3380#ifdef GTEST_HAS_PARAM_TEST
3381 parameterized_test_registry_(),
3382 parameterized_tests_registered_(false),
3383#endif // GTEST_HAS_PARAM_TEST
3384 last_death_test_case_(NULL),
3385 current_test_case_(NULL),
3386 current_test_info_(NULL),
3387 ad_hoc_test_result_(),
3388 result_printer_(NULL),
3389 os_stack_trace_getter_(NULL),
3390#ifdef GTEST_HAS_DEATH_TEST
3391 elapsed_time_(0),
3392 internal_run_death_test_flag_(NULL),
3393 death_test_factory_(new DefaultDeathTestFactory) {
3394#else
3395 elapsed_time_(0) {
3396#endif // GTEST_HAS_DEATH_TEST
3397}
3398
3399UnitTestImpl::~UnitTestImpl() {
3400 // Deletes every TestCase.
3401 test_cases_.ForEach(internal::Delete<TestCase>);
3402
3403 // Deletes every Environment.
3404 environments_.ForEach(internal::Delete<Environment>);
3405
3406 // Deletes the current test result printer.
3407 delete result_printer_;
3408
3409 delete os_stack_trace_getter_;
3410}
3411
3412// A predicate that checks the name of a TestCase against a known
3413// value.
3414//
3415// This is used for implementation of the UnitTest class only. We put
3416// it in the anonymous namespace to prevent polluting the outer
3417// namespace.
3418//
3419// TestCaseNameIs is copyable.
3420class TestCaseNameIs {
3421 public:
3422 // Constructor.
3423 explicit TestCaseNameIs(const String& name)
3424 : name_(name) {}
3425
3426 // Returns true iff the name of test_case matches name_.
3427 bool operator()(const TestCase* test_case) const {
3428 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3429 }
3430
3431 private:
3432 String name_;
3433};
3434
3435// Finds and returns a TestCase with the given name. If one doesn't
3436// exist, creates one and returns it.
3437//
3438// Arguments:
3439//
3440// test_case_name: name of the test case
3441// set_up_tc: pointer to the function that sets up the test case
3442// tear_down_tc: pointer to the function that tears down the test case
3443TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3444 const char* comment,
3445 Test::SetUpTestCaseFunc set_up_tc,
3446 Test::TearDownTestCaseFunc tear_down_tc) {
3447 // Can we find a TestCase with the given name?
3448 internal::ListNode<TestCase*>* node = test_cases_.FindIf(
3449 TestCaseNameIs(test_case_name));
3450
3451 if (node == NULL) {
3452 // No. Let's create one.
3453 TestCase* const test_case =
3454 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3455
3456 // Is this a death test case?
3457 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3458 kDeathTestCaseFilter)) {
3459 // Yes. Inserts the test case after the last death test case
3460 // defined so far.
3461 node = test_cases_.InsertAfter(last_death_test_case_, test_case);
3462 last_death_test_case_ = node;
3463 } else {
3464 // No. Appends to the end of the list.
3465 test_cases_.PushBack(test_case);
3466 node = test_cases_.Last();
3467 }
3468 }
3469
3470 // Returns the TestCase found.
3471 return node->element();
3472}
3473
3474// Helpers for setting up / tearing down the given environment. They
3475// are for use in the List::ForEach() method.
3476static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3477static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3478
3479// Runs all tests in this UnitTest object, prints the result, and
3480// returns 0 if all tests are successful, or 1 otherwise. If any
3481// exception is thrown during a test on Windows, this test is
3482// considered to be failed, but the rest of the tests will still be
3483// run. (We disable exceptions on Linux and Mac OS X, so the issue
3484// doesn't apply there.)
3485// When parameterized tests are enabled, it explands and registers
3486// parameterized tests first in RegisterParameterizedTests().
3487// All other functions called from RunAllTests() may safely assume that
3488// parameterized tests are ready to be counted and run.
3489int UnitTestImpl::RunAllTests() {
3490 // Makes sure InitGoogleTest() was called.
3491 if (!GTestIsInitialized()) {
3492 printf("%s",
3493 "\nThis test program did NOT call ::testing::InitGoogleTest "
3494 "before calling RUN_ALL_TESTS(). Please fix it.\n");
3495 return 1;
3496 }
3497
3498 RegisterParameterizedTests();
3499
3500 // Lists all the tests and exits if the --gtest_list_tests
3501 // flag was specified.
3502 if (GTEST_FLAG(list_tests)) {
3503 ListAllTests();
3504 return 0;
3505 }
3506
3507 // True iff we are in a subprocess for running a thread-safe-style
3508 // death test.
3509 bool in_subprocess_for_death_test = false;
3510
3511#ifdef GTEST_HAS_DEATH_TEST
3512 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
3513 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3514#endif // GTEST_HAS_DEATH_TEST
3515
3516 UnitTestEventListenerInterface * const printer = result_printer();
3517
3518 // Compares the full test names with the filter to decide which
3519 // tests to run.
3520 const bool has_tests_to_run = FilterTests() > 0;
3521 // True iff at least one test has failed.
3522 bool failed = false;
3523
3524 // How many times to repeat the tests? We don't want to repeat them
3525 // when we are inside the subprocess of a death test.
3526 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3527 // Repeats forever if the repeat count is negative.
3528 const bool forever = repeat < 0;
3529 for (int i = 0; forever || i != repeat; i++) {
3530 if (repeat != 1) {
3531 printf("\nRepeating all tests (iteration %d) . . .\n\n", i + 1);
3532 }
3533
3534 // Tells the unit test event listener that the tests are about to
3535 // start.
3536 printer->OnUnitTestStart(parent_);
3537
3538 const TimeInMillis start = GetTimeInMillis();
3539
3540 // Runs each test case if there is at least one test to run.
3541 if (has_tests_to_run) {
3542 // Sets up all environments beforehand.
3543 printer->OnGlobalSetUpStart(parent_);
3544 environments_.ForEach(SetUpEnvironment);
3545 printer->OnGlobalSetUpEnd(parent_);
3546
3547 // Runs the tests only if there was no fatal failure during global
3548 // set-up.
3549 if (!Test::HasFatalFailure()) {
3550 test_cases_.ForEach(TestCase::RunTestCase);
3551 }
3552
3553 // Tears down all environments in reverse order afterwards.
3554 printer->OnGlobalTearDownStart(parent_);
3555 environments_in_reverse_order_.ForEach(TearDownEnvironment);
3556 printer->OnGlobalTearDownEnd(parent_);
3557 }
3558
3559 elapsed_time_ = GetTimeInMillis() - start;
3560
3561 // Tells the unit test event listener that the tests have just
3562 // finished.
3563 printer->OnUnitTestEnd(parent_);
3564
3565 // Gets the result and clears it.
3566 if (!Passed()) {
3567 failed = true;
3568 }
3569 ClearResult();
3570 }
3571
3572 // Returns 0 if all tests passed, or 1 other wise.
3573 return failed ? 1 : 0;
3574}
3575
3576// Compares the name of each test with the user-specified filter to
3577// decide whether the test should be run, then records the result in
3578// each TestCase and TestInfo object.
3579// Returns the number of tests that should run.
3580int UnitTestImpl::FilterTests() {
3581 int num_runnable_tests = 0;
3582 for (const internal::ListNode<TestCase *> *test_case_node =
3583 test_cases_.Head();
3584 test_case_node != NULL;
3585 test_case_node = test_case_node->next()) {
3586 TestCase * const test_case = test_case_node->element();
3587 const String &test_case_name = test_case->name();
3588 test_case->set_should_run(false);
3589
3590 for (const internal::ListNode<TestInfo *> *test_info_node =
3591 test_case->test_info_list().Head();
3592 test_info_node != NULL;
3593 test_info_node = test_info_node->next()) {
3594 TestInfo * const test_info = test_info_node->element();
3595 const String test_name(test_info->name());
3596 // A test is disabled if test case name or test name matches
3597 // kDisableTestFilter.
3598 const bool is_disabled =
3599 internal::UnitTestOptions::MatchesFilter(test_case_name,
3600 kDisableTestFilter) ||
3601 internal::UnitTestOptions::MatchesFilter(test_name,
3602 kDisableTestFilter);
3603 test_info->impl()->set_is_disabled(is_disabled);
3604
3605 const bool should_run = !is_disabled &&
3606 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
3607 test_name);
3608 test_info->impl()->set_should_run(should_run);
3609 test_case->set_should_run(test_case->should_run() || should_run);
3610 if (should_run) {
3611 num_runnable_tests++;
3612 }
3613 }
3614 }
3615 return num_runnable_tests;
3616}
3617
3618// Lists all tests by name.
3619void UnitTestImpl::ListAllTests() {
3620 for (const internal::ListNode<TestCase*>* test_case_node = test_cases_.Head();
3621 test_case_node != NULL;
3622 test_case_node = test_case_node->next()) {
3623 const TestCase* const test_case = test_case_node->element();
3624
3625 // Prints the test case name following by an indented list of test nodes.
3626 printf("%s.\n", test_case->name());
3627
3628 for (const internal::ListNode<TestInfo*>* test_info_node =
3629 test_case->test_info_list().Head();
3630 test_info_node != NULL;
3631 test_info_node = test_info_node->next()) {
3632 const TestInfo* const test_info = test_info_node->element();
3633
3634 printf(" %s\n", test_info->name());
3635 }
3636 }
3637 fflush(stdout);
3638}
3639
3640// Sets the unit test result printer.
3641//
3642// Does nothing if the input and the current printer object are the
3643// same; otherwise, deletes the old printer object and makes the
3644// input the current printer.
3645void UnitTestImpl::set_result_printer(
3646 UnitTestEventListenerInterface* result_printer) {
3647 if (result_printer_ != result_printer) {
3648 delete result_printer_;
3649 result_printer_ = result_printer;
3650 }
3651}
3652
3653// Returns the current unit test result printer if it is not NULL;
3654// otherwise, creates an appropriate result printer, makes it the
3655// current printer, and returns it.
3656UnitTestEventListenerInterface* UnitTestImpl::result_printer() {
3657 if (result_printer_ != NULL) {
3658 return result_printer_;
3659 }
3660
3661#ifdef GTEST_HAS_DEATH_TEST
3662 if (internal_run_death_test_flag_.get() != NULL) {
3663 result_printer_ = new NullUnitTestResultPrinter;
3664 return result_printer_;
3665 }
3666#endif // GTEST_HAS_DEATH_TEST
3667
3668 UnitTestEventsRepeater *repeater = new UnitTestEventsRepeater;
3669 const String& output_format = internal::UnitTestOptions::GetOutputFormat();
3670 if (output_format == "xml") {
3671 repeater->AddListener(new XmlUnitTestResultPrinter(
3672 internal::UnitTestOptions::GetOutputFile().c_str()));
3673 } else if (output_format != "") {
3674 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3675 output_format.c_str());
3676 fflush(stdout);
3677 }
3678 repeater->AddListener(new PrettyUnitTestResultPrinter);
3679 result_printer_ = repeater;
3680 return result_printer_;
3681}
3682
3683// Sets the OS stack trace getter.
3684//
3685// Does nothing if the input and the current OS stack trace getter are
3686// the same; otherwise, deletes the old getter and makes the input the
3687// current getter.
3688void UnitTestImpl::set_os_stack_trace_getter(
3689 OsStackTraceGetterInterface* getter) {
3690 if (os_stack_trace_getter_ != getter) {
3691 delete os_stack_trace_getter_;
3692 os_stack_trace_getter_ = getter;
3693 }
3694}
3695
3696// Returns the current OS stack trace getter if it is not NULL;
3697// otherwise, creates an OsStackTraceGetter, makes it the current
3698// getter, and returns it.
3699OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
3700 if (os_stack_trace_getter_ == NULL) {
3701 os_stack_trace_getter_ = new OsStackTraceGetter;
3702 }
3703
3704 return os_stack_trace_getter_;
3705}
3706
3707// Returns the TestResult for the test that's currently running, or
3708// the TestResult for the ad hoc test if no test is running.
3709internal::TestResult* UnitTestImpl::current_test_result() {
3710 return current_test_info_ ?
3711 current_test_info_->impl()->result() : &ad_hoc_test_result_;
3712}
3713
3714// TestInfoImpl constructor. The new instance assumes ownership of the test
3715// factory object.
3716TestInfoImpl::TestInfoImpl(TestInfo* parent,
3717 const char* test_case_name,
3718 const char* name,
3719 const char* test_case_comment,
3720 const char* comment,
3721 TypeId fixture_class_id,
3722 internal::TestFactoryBase* factory) :
3723 parent_(parent),
3724 test_case_name_(String(test_case_name)),
3725 name_(String(name)),
3726 test_case_comment_(String(test_case_comment)),
3727 comment_(String(comment)),
3728 fixture_class_id_(fixture_class_id),
3729 should_run_(false),
3730 is_disabled_(false),
3731 factory_(factory) {
3732}
3733
3734// TestInfoImpl destructor.
3735TestInfoImpl::~TestInfoImpl() {
3736 delete factory_;
3737}
3738
3739// Returns the current OS stack trace as a String.
3740//
3741// The maximum number of stack frames to be included is specified by
3742// the gtest_stack_trace_depth flag. The skip_count parameter
3743// specifies the number of top frames to be skipped, which doesn't
3744// count against the number of frames to be included.
3745//
3746// For example, if Foo() calls Bar(), which in turn calls
3747// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
3748// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
3749String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count) {
3750 // We pass skip_count + 1 to skip this wrapper function in addition
3751 // to what the user really wants to skip.
3752 return unit_test->impl()->CurrentOsStackTraceExceptTop(skip_count + 1);
3753}
3754
3755// Returns the number of failed test parts in the given test result object.
3756int GetFailedPartCount(const TestResult* result) {
3757 return result->failed_part_count();
3758}
3759
3760// Parses a string as a command line flag. The string should have
3761// the format "--flag=value". When def_optional is true, the "=value"
3762// part can be omitted.
3763//
3764// Returns the value of the flag, or NULL if the parsing failed.
3765const char* ParseFlagValue(const char* str,
3766 const char* flag,
3767 bool def_optional) {
3768 // str and flag must not be NULL.
3769 if (str == NULL || flag == NULL) return NULL;
3770
3771 // The flag must start with "--" followed by GTEST_FLAG_PREFIX.
3772 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX, flag);
3773 const size_t flag_len = flag_str.GetLength();
3774 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
3775
3776 // Skips the flag name.
3777 const char* flag_end = str + flag_len;
3778
3779 // When def_optional is true, it's OK to not have a "=value" part.
3780 if (def_optional && (flag_end[0] == '\0')) {
3781 return flag_end;
3782 }
3783
3784 // If def_optional is true and there are more characters after the
3785 // flag name, or if def_optional is false, there must be a '=' after
3786 // the flag name.
3787 if (flag_end[0] != '=') return NULL;
3788
3789 // Returns the string after "=".
3790 return flag_end + 1;
3791}
3792
3793// Parses a string for a bool flag, in the form of either
3794// "--flag=value" or "--flag".
3795//
3796// In the former case, the value is taken as true as long as it does
3797// not start with '0', 'f', or 'F'.
3798//
3799// In the latter case, the value is taken as true.
3800//
3801// On success, stores the value of the flag in *value, and returns
3802// true. On failure, returns false without changing *value.
3803bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
3804 // Gets the value of the flag as a string.
3805 const char* const value_str = ParseFlagValue(str, flag, true);
3806
3807 // Aborts if the parsing failed.
3808 if (value_str == NULL) return false;
3809
3810 // Converts the string value to a bool.
3811 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
3812 return true;
3813}
3814
3815// Parses a string for an Int32 flag, in the form of
3816// "--flag=value".
3817//
3818// On success, stores the value of the flag in *value, and returns
3819// true. On failure, returns false without changing *value.
3820bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
3821 // Gets the value of the flag as a string.
3822 const char* const value_str = ParseFlagValue(str, flag, false);
3823
3824 // Aborts if the parsing failed.
3825 if (value_str == NULL) return false;
3826
3827 // Sets *value to the value of the flag.
3828 return ParseInt32(Message() << "The value of flag --" << flag,
3829 value_str, value);
3830}
3831
3832// Parses a string for a string flag, in the form of
3833// "--flag=value".
3834//
3835// On success, stores the value of the flag in *value, and returns
3836// true. On failure, returns false without changing *value.
3837bool ParseStringFlag(const char* str, const char* flag, String* value) {
3838 // Gets the value of the flag as a string.
3839 const char* const value_str = ParseFlagValue(str, flag, false);
3840
3841 // Aborts if the parsing failed.
3842 if (value_str == NULL) return false;
3843
3844 // Sets *value to the value of the flag.
3845 *value = value_str;
3846 return true;
3847}
3848
3849// Parses the command line for Google Test flags, without initializing
3850// other parts of Google Test. The type parameter CharType can be
3851// instantiated to either char or wchar_t.
3852template <typename CharType>
3853void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
3854 for (int i = 1; i < *argc; i++) {
3855 const String arg_string = StreamableToString(argv[i]);
3856 const char* const arg = arg_string.c_str();
3857
3858 using internal::ParseBoolFlag;
3859 using internal::ParseInt32Flag;
3860 using internal::ParseStringFlag;
3861
3862 // Do we see a Google Test flag?
3863 if (ParseBoolFlag(arg, kBreakOnFailureFlag,
3864 &GTEST_FLAG(break_on_failure)) ||
3865 ParseBoolFlag(arg, kCatchExceptionsFlag,
3866 &GTEST_FLAG(catch_exceptions)) ||
3867 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
3868 ParseStringFlag(arg, kDeathTestStyleFlag,
3869 &GTEST_FLAG(death_test_style)) ||
3870 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
3871 ParseStringFlag(arg, kInternalRunDeathTestFlag,
3872 &GTEST_FLAG(internal_run_death_test)) ||
3873 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
3874 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
3875 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
3876 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat))
3877 ) {
3878 // Yes. Shift the remainder of the argv list left by one. Note
3879 // that argv has (*argc + 1) elements, the last one always being
3880 // NULL. The following loop moves the trailing NULL element as
3881 // well.
3882 for (int j = i; j != *argc; j++) {
3883 argv[j] = argv[j + 1];
3884 }
3885
3886 // Decrements the argument count.
3887 (*argc)--;
3888
3889 // We also need to decrement the iterator as we just removed
3890 // an element.
3891 i--;
3892 }
3893 }
3894}
3895
3896// Parses the command line for Google Test flags, without initializing
3897// other parts of Google Test.
3898void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
3899 ParseGoogleTestFlagsOnlyImpl(argc, argv);
3900}
3901void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
3902 ParseGoogleTestFlagsOnlyImpl(argc, argv);
3903}
3904
3905// The internal implementation of InitGoogleTest().
3906//
3907// The type parameter CharType can be instantiated to either char or
3908// wchar_t.
3909template <typename CharType>
3910void InitGoogleTestImpl(int* argc, CharType** argv) {
3911 g_init_gtest_count++;
3912
3913 // We don't want to run the initialization code twice.
3914 if (g_init_gtest_count != 1) return;
3915
3916 if (*argc <= 0) return;
3917
3918 internal::g_executable_path = internal::StreamableToString(argv[0]);
3919
3920#ifdef GTEST_HAS_DEATH_TEST
3921 g_argvs.clear();
3922 for (int i = 0; i != *argc; i++) {
3923 g_argvs.push_back(StreamableToString(argv[i]));
3924 }
3925#endif // GTEST_HAS_DEATH_TEST
3926
3927 ParseGoogleTestFlagsOnly(argc, argv);
3928}
3929
3930} // namespace internal
3931
3932// Initializes Google Test. This must be called before calling
3933// RUN_ALL_TESTS(). In particular, it parses a command line for the
3934// flags that Google Test recognizes. Whenever a Google Test flag is
3935// seen, it is removed from argv, and *argc is decremented.
3936//
3937// No value is returned. Instead, the Google Test flag variables are
3938// updated.
3939//
3940// Calling the function for the second time has no user-visible effect.
3941void InitGoogleTest(int* argc, char** argv) {
3942 internal::InitGoogleTestImpl(argc, argv);
3943}
3944
3945// This overloaded version can be used in Windows programs compiled in
3946// UNICODE mode.
3947void InitGoogleTest(int* argc, wchar_t** argv) {
3948 internal::InitGoogleTestImpl(argc, argv);
3949}
3950
3951} // namespace testing