1
// Copyright 2005, Google Inc.
2
// All rights reserved.
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
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
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.
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.
30
// Author: wan@google.com (Zhanyong Wan)
32
// The Google C++ Testing Framework (Google Test)
34
#include <gtest/gtest.h>
35
#include <gtest/gtest-spi.h>
46
// TODO(kenton): Use autoconf to detect availability of gettimeofday().
47
#define HAS_GETTIMEOFDAY
52
// Declares vsnprintf(). This header is not available on Windows.
60
#elif defined(_WIN32_WCE) // We are on Windows CE.
62
#include <windows.h> // NOLINT
64
#elif defined(_WIN32) // We are on Windows proper.
66
#include <io.h> // NOLINT
67
#include <sys/timeb.h> // NOLINT
68
#include <sys/types.h> // NOLINT
69
#include <sys/stat.h> // NOLINT
71
#if defined(__MINGW__) || defined(__MINGW32__)
72
// MinGW has gettimeofday() but not _ftime64()
73
// TODO(kenton): Use autoconf to detect availability of gettimeofday().
74
// TODO(kenton): There are other ways to get the time on Windows, like
75
// GetTickCount() or GetSystemTimeAsFileTime(). MinGW supports these.
76
// consider using them instead.
77
#define HAS_GETTIMEOFDAY
78
#include <sys/time.h> // NOLINT
81
// cpplint thinks that the header is already included, so we want to
83
#include <windows.h> // NOLINT
87
// Assume other platforms have gettimeofday().
88
// TODO(kenton): Use autoconf to detect availability of gettimeofday().
89
#define HAS_GETTIMEOFDAY
91
// cpplint thinks that the header is already included, so we want to
93
#include <sys/time.h> // NOLINT
94
#include <unistd.h> // NOLINT
98
// Indicates that this translation unit is part of Google Test's
99
// implementation. It must come before gtest-internal-inl.h is
100
// included, or there will be a compiler error. This trick is to
101
// prevent a user from accidentally including gtest-internal-inl.h in
103
#define GTEST_IMPLEMENTATION
104
#include <gtest/gtest-internal-inl.h>
105
#undef GTEST_IMPLEMENTATION
107
#ifdef GTEST_OS_WINDOWS
108
#define fileno _fileno
109
#define isatty _isatty
110
#define vsnprintf _vsnprintf
111
#endif // GTEST_OS_WINDOWS
117
// A test that matches this pattern is disabled and not run.
118
static const char kDisableTestPattern[] = "DISABLED_*";
120
// A test filter that matches everything.
121
static const char kUniversalFilter[] = "*";
123
// The default output file for XML output.
124
static const char kDefaultOutputFile[] = "test_detail.xml";
128
internal::BoolFromGTestEnv("break_on_failure", false),
129
"True iff a failed assertion should be a debugger break-point.");
133
internal::BoolFromGTestEnv("catch_exceptions", false),
134
"True iff " GTEST_NAME
135
" should catch exceptions and treat them as test failures.");
139
internal::StringFromGTestEnv("color", "auto"),
140
"Whether to use colors in the output. Valid values: yes, no, "
141
"and auto. 'auto' means to use colors if the output is "
142
"being sent to a terminal and the TERM environment variable "
143
"is set to xterm or xterm-color.");
147
internal::StringFromGTestEnv("filter", kUniversalFilter),
148
"A colon-separated list of glob (not regex) patterns "
149
"for filtering the tests to run, optionally followed by a "
150
"'-' and a : separated list of negative patterns (tests to "
151
"exclude). A test is run if it matches one of the positive "
152
"patterns and does not match any of the negative patterns.");
154
GTEST_DEFINE_bool(list_tests, false,
155
"List all tests without running them.");
159
internal::StringFromGTestEnv("output", ""),
160
"A format (currently must be \"xml\"), optionally followed "
161
"by a colon and an output file name or directory. A directory "
162
"is indicated by a trailing pathname separator. "
163
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
164
"If a directory is specified, output files will be created "
165
"within that directory, with file-names based on the test "
166
"executable's name and, if necessary, made unique by adding "
171
internal::Int32FromGTestEnv("repeat", 1),
172
"How many times to repeat each test. Specify a negative number "
173
"for repeating forever. Useful for shaking out flaky tests.");
177
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
178
"The maximum number of stack frames to print when an "
179
"assertion fails. The valid range is 0 through 100, inclusive.");
182
show_internal_stack_frames, false,
183
"True iff " GTEST_NAME " should include internal stack frames when "
184
"printing test failure stack traces.");
188
// GTestIsInitialized() returns true iff the user has initialized
189
// Google Test. Useful for catching the user mistake of not initializing
190
// Google Test before calling RUN_ALL_TESTS().
192
// A user must call testing::ParseGTestFlags() to initialize Google
193
// Test. g_parse_gtest_flags_called is set to true iff
194
// ParseGTestFlags() has been called. We don't protect this variable
195
// under a mutex as it is only accessed in the main thread.
196
static bool g_parse_gtest_flags_called = false;
197
static bool GTestIsInitialized() { return g_parse_gtest_flags_called; }
199
// Iterates over a list of TestCases, keeping a running sum of the
200
// results of calling a given int-returning method on each.
202
static int SumOverTestCaseList(const internal::List<TestCase*>& case_list,
203
int (TestCase::*method)() const) {
205
for (const internal::ListNode<TestCase*>* node = case_list.Head();
207
node = node->next()) {
208
sum += (node->element()->*method)();
213
// Returns true iff the test case passed.
214
static bool TestCasePassed(const TestCase* test_case) {
215
return test_case->should_run() && test_case->Passed();
218
// Returns true iff the test case failed.
219
static bool TestCaseFailed(const TestCase* test_case) {
220
return test_case->should_run() && test_case->Failed();
223
// Returns true iff test_case contains at least one test that should
225
static bool ShouldRunTestCase(const TestCase* test_case) {
226
return test_case->should_run();
230
// Windows CE has no C library. The abort() function is used in
231
// several places in Google Test. This implementation provides a reasonable
232
// imitation of standard behaviour.
233
static void abort() {
235
TerminateProcess(GetCurrentProcess(), 1);
239
// AssertHelper constructor.
240
AssertHelper::AssertHelper(TestPartResultType type, const char* file,
241
int line, const char* message)
242
: type_(type), file_(file), line_(line), message_(message) {
245
// Message assignment, for assertion streaming support.
246
void AssertHelper::operator=(const Message& message) const {
247
UnitTest::GetInstance()->
248
AddTestPartResult(type_, file_, line_,
249
AppendUserMessage(message_, message),
250
UnitTest::GetInstance()->impl()
251
->CurrentOsStackTraceExceptTop(1)
252
// Skips the stack frame for this function itself.
256
// Application pathname gotten in ParseGTestFlags.
257
String g_executable_path;
259
// Returns the current application's name, removing directory path if that
261
FilePath GetCurrentExecutableName() {
264
#if defined(_WIN32_WCE) || defined(_WIN32)
265
result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
267
result.Set(FilePath(g_executable_path));
268
#endif // _WIN32_WCE || _WIN32
270
return result.RemoveDirectoryName();
273
// Functions for processing the gtest_output flag.
275
// Returns the output format, or "" for normal printed output.
276
String UnitTestOptions::GetOutputFormat() {
277
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
278
if (gtest_output_flag == NULL) return String("");
280
const char* const colon = strchr(gtest_output_flag, ':');
281
return (colon == NULL) ?
282
String(gtest_output_flag) :
283
String(gtest_output_flag, colon - gtest_output_flag);
286
// Returns the name of the requested output file, or the default if none
287
// was explicitly specified.
288
String UnitTestOptions::GetOutputFile() {
289
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
290
if (gtest_output_flag == NULL)
293
const char* const colon = strchr(gtest_output_flag, ':');
295
return String(kDefaultOutputFile);
297
internal::FilePath output_name(colon + 1);
298
if (!output_name.IsDirectory())
299
return output_name.ToString();
301
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
302
output_name, internal::GetCurrentExecutableName(),
303
GetOutputFormat().c_str()));
304
return result.ToString();
307
// Returns true iff the wildcard pattern matches the string. The
308
// first ':' or '\0' character in pattern marks the end of it.
310
// This recursive algorithm isn't very efficient, but is clear and
311
// works well enough for matching test names, which are short.
312
bool UnitTestOptions::PatternMatchesString(const char *pattern,
316
case ':': // Either ':' or '\0' marks the end of the pattern.
318
case '?': // Matches any single character.
319
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
320
case '*': // Matches any string (possibly empty) of characters.
321
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
322
PatternMatchesString(pattern + 1, str);
323
default: // Non-special character. Matches itself.
324
return *pattern == *str &&
325
PatternMatchesString(pattern + 1, str + 1);
329
bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
330
const char *cur_pattern = filter;
332
if (PatternMatchesString(cur_pattern, name.c_str())) {
336
// Finds the next pattern in the filter.
337
cur_pattern = strchr(cur_pattern, ':');
339
// Returns if no more pattern can be found.
340
if (cur_pattern == NULL) {
344
// Skips the pattern separater (the ':' character).
349
// TODO(keithray): move String function implementations to gtest-string.cc.
351
// Returns true iff the user-specified filter matches the test case
352
// name and the test name.
353
bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
354
const String &test_name) {
355
const String& full_name = String::Format("%s.%s",
356
test_case_name.c_str(),
359
// Split --gtest_filter at '-', if there is one, to separate into
360
// positive filter and negative filter portions
361
const char* const p = GTEST_FLAG(filter).c_str();
362
const char* const dash = strchr(p, '-');
366
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
367
negative = String("");
369
positive.Set(p, dash - p); // Everything up to the dash
370
negative = String(dash+1); // Everything after the dash
371
if (positive.empty()) {
372
// Treat '-test1' as the same as '*-test1'
373
positive = kUniversalFilter;
377
// A filter is a colon-separated list of patterns. It matches a
378
// test if any pattern in it matches the test.
379
return (MatchesFilter(full_name, positive.c_str()) &&
380
!MatchesFilter(full_name, negative.c_str()));
383
#ifdef GTEST_OS_WINDOWS
384
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
385
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
386
// This function is useful as an __except condition.
387
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
388
// Google Test should handle an exception if:
389
// 1. the user wants it to, AND
390
// 2. this is not a breakpoint exception.
391
return (GTEST_FLAG(catch_exceptions) &&
392
exception_code != EXCEPTION_BREAKPOINT) ?
393
EXCEPTION_EXECUTE_HANDLER :
394
EXCEPTION_CONTINUE_SEARCH;
396
#endif // GTEST_OS_WINDOWS
398
} // namespace internal
400
// The interface for printing the result of a UnitTest
401
class UnitTestEventListenerInterface {
403
// The d'tor is pure virtual as this is an abstract class.
404
virtual ~UnitTestEventListenerInterface() = 0;
406
// Called before the unit test starts.
407
virtual void OnUnitTestStart(const UnitTest*) {}
409
// Called after the unit test ends.
410
virtual void OnUnitTestEnd(const UnitTest*) {}
412
// Called before the test case starts.
413
virtual void OnTestCaseStart(const TestCase*) {}
415
// Called after the test case ends.
416
virtual void OnTestCaseEnd(const TestCase*) {}
418
// Called before the global set-up starts.
419
virtual void OnGlobalSetUpStart(const UnitTest*) {}
421
// Called after the global set-up ends.
422
virtual void OnGlobalSetUpEnd(const UnitTest*) {}
424
// Called before the global tear-down starts.
425
virtual void OnGlobalTearDownStart(const UnitTest*) {}
427
// Called after the global tear-down ends.
428
virtual void OnGlobalTearDownEnd(const UnitTest*) {}
430
// Called before the test starts.
431
virtual void OnTestStart(const TestInfo*) {}
433
// Called after the test ends.
434
virtual void OnTestEnd(const TestInfo*) {}
436
// Called after an assertion.
437
virtual void OnNewTestPartResult(const TestPartResult*) {}
440
// Constructs an empty TestPartResultArray.
441
TestPartResultArray::TestPartResultArray()
442
: list_(new internal::List<TestPartResult>) {
445
// Destructs a TestPartResultArray.
446
TestPartResultArray::~TestPartResultArray() {
450
// Appends a TestPartResult to the array.
451
void TestPartResultArray::Append(const TestPartResult& result) {
452
list_->PushBack(result);
455
// Returns the TestPartResult at the given index (0-based).
456
const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
457
if (index < 0 || index >= size()) {
458
printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
462
const internal::ListNode<TestPartResult>* p = list_->Head();
463
for (int i = 0; i < index; i++) {
470
// Returns the number of TestPartResult objects in the array.
471
int TestPartResultArray::size() const {
472
return list_->size();
475
// The c'tor sets this object as the test part result reporter used by
476
// Google Test. The 'result' parameter specifies where to report the
478
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
479
TestPartResultArray* result)
480
: old_reporter_(UnitTest::GetInstance()->impl()->
481
test_part_result_reporter()),
483
internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl();
484
impl->set_test_part_result_reporter(this);
487
// The d'tor restores the test part result reporter used by Google Test
489
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
490
UnitTest::GetInstance()->impl()->
491
set_test_part_result_reporter(old_reporter_);
494
// Increments the test part result count and remembers the result.
495
// This method is from the TestPartResultReporterInterface interface.
496
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
497
const TestPartResult& result) {
498
result_->Append(result);
503
// This predicate-formatter checks that 'results' contains a test part
504
// failure of the given type and that the failure message contains the
506
AssertionResult HasOneFailure(const char* /* results_expr */,
507
const char* /* type_expr */,
508
const char* /* substr_expr */,
509
const TestPartResultArray& results,
510
TestPartResultType type,
511
const char* substr) {
512
const String expected(
513
type == TPRT_FATAL_FAILURE ? "1 fatal failure" :
514
"1 non-fatal failure");
516
if (results.size() != 1) {
517
msg << "Expected: " << expected << "\n"
518
<< " Actual: " << results.size() << " failures";
519
for (int i = 0; i < results.size(); i++) {
520
msg << "\n" << results.GetTestPartResult(i);
522
return AssertionFailure(msg);
525
const TestPartResult& r = results.GetTestPartResult(0);
526
if (r.type() != type) {
527
msg << "Expected: " << expected << "\n"
530
return AssertionFailure(msg);
533
if (strstr(r.message(), substr) == NULL) {
534
msg << "Expected: " << expected << " containing \""
538
return AssertionFailure(msg);
541
return AssertionSuccess();
544
// The constructor of SingleFailureChecker remembers where to look up
545
// test part results, what type of failure we expect, and what
546
// substring the failure message should contain.
547
SingleFailureChecker:: SingleFailureChecker(
548
const TestPartResultArray* results,
549
TestPartResultType type,
555
// The destructor of SingleFailureChecker verifies that the given
556
// TestPartResultArray contains exactly one failure that has the given
557
// type and contains the given substring. If that's not the case, a
558
// non-fatal failure will be generated.
559
SingleFailureChecker::~SingleFailureChecker() {
560
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
563
// Reports a test part result.
564
void UnitTestImpl::ReportTestPartResult(const TestPartResult& result) {
565
current_test_result()->AddTestPartResult(result);
566
result_printer()->OnNewTestPartResult(&result);
569
// Returns the current test part result reporter.
570
TestPartResultReporterInterface* UnitTestImpl::test_part_result_reporter() {
571
return test_part_result_reporter_;
574
// Sets the current test part result reporter.
575
void UnitTestImpl::set_test_part_result_reporter(
576
TestPartResultReporterInterface* reporter) {
577
test_part_result_reporter_ = reporter;
580
// Gets the number of successful test cases.
581
int UnitTestImpl::successful_test_case_count() const {
582
return test_cases_.CountIf(TestCasePassed);
585
// Gets the number of failed test cases.
586
int UnitTestImpl::failed_test_case_count() const {
587
return test_cases_.CountIf(TestCaseFailed);
590
// Gets the number of all test cases.
591
int UnitTestImpl::total_test_case_count() const {
592
return test_cases_.size();
595
// Gets the number of all test cases that contain at least one test
597
int UnitTestImpl::test_case_to_run_count() const {
598
return test_cases_.CountIf(ShouldRunTestCase);
601
// Gets the number of successful tests.
602
int UnitTestImpl::successful_test_count() const {
603
return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
606
// Gets the number of failed tests.
607
int UnitTestImpl::failed_test_count() const {
608
return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
611
// Gets the number of disabled tests.
612
int UnitTestImpl::disabled_test_count() const {
613
return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
616
// Gets the number of all tests.
617
int UnitTestImpl::total_test_count() const {
618
return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
621
// Gets the number of tests that should run.
622
int UnitTestImpl::test_to_run_count() const {
623
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
626
// Returns the current OS stack trace as a String.
628
// The maximum number of stack frames to be included is specified by
629
// the gtest_stack_trace_depth flag. The skip_count parameter
630
// specifies the number of top frames to be skipped, which doesn't
631
// count against the number of frames to be included.
633
// For example, if Foo() calls Bar(), which in turn calls
634
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
635
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
636
String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
641
static TimeInMillis GetTimeInMillis() {
642
#ifdef _WIN32_WCE // We are on Windows CE
643
// Difference between 1970-01-01 and 1601-01-01 in miliseconds.
644
// http://analogous.blogspot.com/2005/04/epoch.html
645
const TimeInMillis kJavaEpochToWinFileTimeDelta = 11644473600000UL;
646
const DWORD kTenthMicrosInMilliSecond = 10000;
648
SYSTEMTIME now_systime;
649
FILETIME now_filetime;
650
ULARGE_INTEGER now_int64;
651
// TODO(kenton): Shouldn't this just use GetSystemTimeAsFileTime()?
652
GetSystemTime(&now_systime);
653
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
654
now_int64.LowPart = now_filetime.dwLowDateTime;
655
now_int64.HighPart = now_filetime.dwHighDateTime;
656
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
657
kJavaEpochToWinFileTimeDelta;
658
return now_int64.QuadPart;
661
#elif defined(_WIN32) && !defined(HAS_GETTIMEOFDAY)
664
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
665
// (deprecated function) there.
666
// TODO(kenton): Use GetTickCount()? Or use SystemTimeToFileTime()
667
#pragma warning(push) // Saves the current warning state.
668
#pragma warning(disable:4996) // Temporarily disables warning 4996.
670
#pragma warning(pop) // Restores the warning state.
674
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
675
#elif defined(HAS_GETTIMEOFDAY)
677
gettimeofday(&now, NULL);
678
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
680
#error "Don't know how to get the current time on your system."
689
// Returns the input enclosed in double quotes if it's not NULL;
690
// otherwise returns "(null)". For example, "\"Hello\"" is returned
691
// for input "Hello".
693
// This is useful for printing a C string in the syntax of a literal.
695
// Known issue: escape sequences are not handled yet.
696
String String::ShowCStringQuoted(const char* c_str) {
697
return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
700
// Copies at most length characters from str into a newly-allocated
701
// piece of memory of size length+1. The memory is allocated with new[].
702
// A terminating null byte is written to the memory, and a pointer to it
703
// is returned. If str is NULL, NULL is returned.
704
static char* CloneString(const char* str, size_t length) {
708
char* const clone = new char[length + 1];
709
// MSVC 8 deprecates strncpy(), so we want to suppress warning
710
// 4996 (deprecated function) there.
711
#ifdef GTEST_OS_WINDOWS // We are on Windows.
712
#pragma warning(push) // Saves the current warning state.
713
#pragma warning(disable:4996) // Temporarily disables warning 4996.
714
strncpy(clone, str, length);
715
#pragma warning(pop) // Restores the warning state.
716
#else // We are on Linux or Mac OS.
717
strncpy(clone, str, length);
718
#endif // GTEST_OS_WINDOWS
719
clone[length] = '\0';
724
// Clones a 0-terminated C string, allocating memory using new. The
725
// caller is responsible for deleting[] the return value. Returns the
726
// cloned string, or NULL if the input is NULL.
727
const char * String::CloneCString(const char* c_str) {
728
return (c_str == NULL) ?
729
NULL : CloneString(c_str, strlen(c_str));
732
// Compares two C strings. Returns true iff they have the same content.
734
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
735
// C string is considered different to any non-NULL C string,
736
// including the empty string.
737
bool String::CStringEquals(const char * lhs, const char * rhs) {
738
if ( lhs == NULL ) return rhs == NULL;
740
if ( rhs == NULL ) return false;
742
return strcmp(lhs, rhs) == 0;
745
#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
747
// Converts an array of wide chars to a narrow string using the UTF-8
748
// encoding, and streams the result to the given Message object.
749
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t len,
751
for (size_t i = 0; i != len; i++) {
752
// TODO(wan): consider allowing a testing::String object to
753
// contain '\0'. This will make it behave more like std::string,
754
// and will allow ToUtf8String() to return the correct encoding
755
// for '\0' s.t. we can get rid of the conditional here (and in
756
// several other places).
758
*msg << internal::ToUtf8String(wstr[i]);
765
#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
767
} // namespace internal
769
#if GTEST_HAS_STD_WSTRING
770
// Converts the given wide string to a narrow string using the UTF-8
771
// encoding, and streams the result to this Message object.
772
Message& Message::operator <<(const ::std::wstring& wstr) {
773
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
776
#endif // GTEST_HAS_STD_WSTRING
778
#if GTEST_HAS_GLOBAL_WSTRING
779
// Converts the given wide string to a narrow string using the UTF-8
780
// encoding, and streams the result to this Message object.
781
Message& Message::operator <<(const ::wstring& wstr) {
782
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
785
#endif // GTEST_HAS_GLOBAL_WSTRING
789
// Formats a value to be used in a failure message.
791
// For a char value, we print it as a C++ char literal and as an
792
// unsigned integer (both in decimal and in hexadecimal).
793
String FormatForFailureMessage(char ch) {
794
const unsigned int ch_as_uint = ch;
795
// A String object cannot contain '\0', so we print "\\0" when ch is
797
return String::Format("'%s' (%u, 0x%X)",
798
ch ? String::Format("%c", ch).c_str() : "\\0",
799
ch_as_uint, ch_as_uint);
802
// For a wchar_t value, we print it as a C++ wchar_t literal and as an
803
// unsigned integer (both in decimal and in hexidecimal).
804
String FormatForFailureMessage(wchar_t wchar) {
805
// The C++ standard doesn't specify the exact size of the wchar_t
806
// type. It just says that it shall have the same size as another
807
// integral type, called its underlying type.
809
// Therefore, in order to print a wchar_t value in the numeric form,
810
// we first convert it to the largest integral type (UInt64) and
811
// then print the converted value.
813
// We use streaming to print the value as "%llu" doesn't work
814
// correctly with MSVC 7.1.
815
const UInt64 wchar_as_uint64 = wchar;
817
// A String object cannot contain '\0', so we print "\\0" when wchar is
819
msg << "L'" << (wchar ? ToUtf8String(wchar).c_str() : "\\0") << "' ("
820
<< wchar_as_uint64 << ", 0x" << ::std::setbase(16)
821
<< wchar_as_uint64 << ")";
822
return msg.GetString();
825
} // namespace internal
827
// AssertionResult constructor.
828
AssertionResult::AssertionResult(const internal::String& failure_message)
829
: failure_message_(failure_message) {
833
// Makes a successful assertion result.
834
AssertionResult AssertionSuccess() {
835
return AssertionResult();
839
// Makes a failed assertion result with the given failure message.
840
AssertionResult AssertionFailure(const Message& message) {
841
return AssertionResult(message.GetString());
846
// Constructs and returns the message for an equality assertion
847
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
849
// The first four parameters are the expressions used in the assertion
850
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
851
// where foo is 5 and bar is 6, we have:
853
// expected_expression: "foo"
854
// actual_expression: "bar"
855
// expected_value: "5"
858
// The ignoring_case parameter is true iff the assertion is a
859
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
860
// be inserted into the message.
861
AssertionResult EqFailure(const char* expected_expression,
862
const char* actual_expression,
863
const String& expected_value,
864
const String& actual_value,
865
bool ignoring_case) {
867
msg << "Value of: " << actual_expression;
868
if (actual_value != actual_expression) {
869
msg << "\n Actual: " << actual_value;
872
msg << "\nExpected: " << expected_expression;
874
msg << " (ignoring case)";
876
if (expected_value != expected_expression) {
877
msg << "\nWhich is: " << expected_value;
880
return AssertionFailure(msg);
884
// Helper function for implementing ASSERT_NEAR.
885
AssertionResult DoubleNearPredFormat(const char* expr1,
887
const char* abs_error_expr,
891
const double diff = fabs(val1 - val2);
892
if (diff <= abs_error) return AssertionSuccess();
894
// TODO(wan): do not print the value of an expression if it's
895
// already a literal.
897
msg << "The difference between " << expr1 << " and " << expr2
898
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
899
<< expr1 << " evaluates to " << val1 << ",\n"
900
<< expr2 << " evaluates to " << val2 << ", and\n"
901
<< abs_error_expr << " evaluates to " << abs_error << ".";
902
return AssertionFailure(msg);
906
// Helper template for implementing FloatLE() and DoubleLE().
907
template <typename RawType>
908
AssertionResult FloatingPointLE(const char* expr1,
912
// Returns success if val1 is less than val2,
914
return AssertionSuccess();
917
// or if val1 is almost equal to val2.
918
const FloatingPoint<RawType> lhs(val1), rhs(val2);
919
if (lhs.AlmostEquals(rhs)) {
920
return AssertionSuccess();
923
// Note that the above two checks will both fail if either val1 or
924
// val2 is NaN, as the IEEE floating-point standard requires that
925
// any predicate involving a NaN must return false.
928
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
932
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
936
msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
937
<< " Actual: " << StrStreamToString(&val1_ss) << " vs "
938
<< StrStreamToString(&val2_ss);
940
return AssertionFailure(msg);
943
} // namespace internal
945
// Asserts that val1 is less than, or almost equal to, val2. Fails
946
// otherwise. In particular, it fails if either val1 or val2 is NaN.
947
AssertionResult FloatLE(const char* expr1, const char* expr2,
948
float val1, float val2) {
949
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
952
// Asserts that val1 is less than, or almost equal to, val2. Fails
953
// otherwise. In particular, it fails if either val1 or val2 is NaN.
954
AssertionResult DoubleLE(const char* expr1, const char* expr2,
955
double val1, double val2) {
956
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
961
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
963
AssertionResult CmpHelperEQ(const char* expected_expression,
964
const char* actual_expression,
967
if (expected == actual) {
968
return AssertionSuccess();
971
return EqFailure(expected_expression,
973
FormatForComparisonFailureMessage(expected, actual),
974
FormatForComparisonFailureMessage(actual, expected),
978
// A macro for implementing the helper functions needed to implement
979
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
980
// just to avoid copy-and-paste of similar code.
981
#define GTEST_IMPL_CMP_HELPER(op_name, op)\
982
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
983
BiggestInt val1, BiggestInt val2) {\
985
return AssertionSuccess();\
988
msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
989
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
990
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
991
return AssertionFailure(msg);\
995
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
997
GTEST_IMPL_CMP_HELPER(NE, !=)
998
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1000
GTEST_IMPL_CMP_HELPER(LE, <=)
1001
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1003
GTEST_IMPL_CMP_HELPER(LT, < )
1004
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1006
GTEST_IMPL_CMP_HELPER(GE, >=)
1007
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1009
GTEST_IMPL_CMP_HELPER(GT, > )
1011
#undef GTEST_IMPL_CMP_HELPER
1013
// The helper function for {ASSERT|EXPECT}_STREQ.
1014
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1015
const char* actual_expression,
1016
const char* expected,
1017
const char* actual) {
1018
if (String::CStringEquals(expected, actual)) {
1019
return AssertionSuccess();
1022
return EqFailure(expected_expression,
1024
String::ShowCStringQuoted(expected),
1025
String::ShowCStringQuoted(actual),
1029
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1030
AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1031
const char* actual_expression,
1032
const char* expected,
1033
const char* actual) {
1034
if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1035
return AssertionSuccess();
1038
return EqFailure(expected_expression,
1040
String::ShowCStringQuoted(expected),
1041
String::ShowCStringQuoted(actual),
1045
// The helper function for {ASSERT|EXPECT}_STRNE.
1046
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1047
const char* s2_expression,
1050
if (!String::CStringEquals(s1, s2)) {
1051
return AssertionSuccess();
1054
msg << "Expected: (" << s1_expression << ") != ("
1055
<< s2_expression << "), actual: \""
1056
<< s1 << "\" vs \"" << s2 << "\"";
1057
return AssertionFailure(msg);
1061
// The helper function for {ASSERT|EXPECT}_STRCASENE.
1062
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1063
const char* s2_expression,
1066
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1067
return AssertionSuccess();
1070
msg << "Expected: (" << s1_expression << ") != ("
1071
<< s2_expression << ") (ignoring case), actual: \""
1072
<< s1 << "\" vs \"" << s2 << "\"";
1073
return AssertionFailure(msg);
1077
} // namespace internal
1081
// Helper functions for implementing IsSubString() and IsNotSubstring().
1083
// This group of overloaded functions return true iff needle is a
1084
// substring of haystack. NULL is considered a substring of itself
1087
bool IsSubstringPred(const char* needle, const char* haystack) {
1088
if (needle == NULL || haystack == NULL)
1089
return needle == haystack;
1091
return strstr(haystack, needle) != NULL;
1094
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1095
if (needle == NULL || haystack == NULL)
1096
return needle == haystack;
1098
return wcsstr(haystack, needle) != NULL;
1101
// StringType here can be either ::std::string or ::std::wstring.
1102
template <typename StringType>
1103
bool IsSubstringPred(const StringType& needle,
1104
const StringType& haystack) {
1105
return haystack.find(needle) != StringType::npos;
1108
// This function implements either IsSubstring() or IsNotSubstring(),
1109
// depending on the value of the expected_to_be_substring parameter.
1110
// StringType here can be const char*, const wchar_t*, ::std::string,
1111
// or ::std::wstring.
1112
template <typename StringType>
1113
AssertionResult IsSubstringImpl(
1114
bool expected_to_be_substring,
1115
const char* needle_expr, const char* haystack_expr,
1116
const StringType& needle, const StringType& haystack) {
1117
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1118
return AssertionSuccess();
1120
const bool is_wide_string = sizeof(needle[0]) > 1;
1121
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1122
return AssertionFailure(
1124
<< "Value of: " << needle_expr << "\n"
1125
<< " Actual: " << begin_string_quote << needle << "\"\n"
1126
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
1127
<< "a substring of " << haystack_expr << "\n"
1128
<< "Which is: " << begin_string_quote << haystack << "\"");
1133
// IsSubstring() and IsNotSubstring() check whether needle is a
1134
// substring of haystack (NULL is considered a substring of itself
1135
// only), and return an appropriate error message when they fail.
1137
AssertionResult IsSubstring(
1138
const char* needle_expr, const char* haystack_expr,
1139
const char* needle, const char* haystack) {
1140
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1143
AssertionResult IsSubstring(
1144
const char* needle_expr, const char* haystack_expr,
1145
const wchar_t* needle, const wchar_t* haystack) {
1146
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1149
AssertionResult IsNotSubstring(
1150
const char* needle_expr, const char* haystack_expr,
1151
const char* needle, const char* haystack) {
1152
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1155
AssertionResult IsNotSubstring(
1156
const char* needle_expr, const char* haystack_expr,
1157
const wchar_t* needle, const wchar_t* haystack) {
1158
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1161
#if GTEST_HAS_STD_STRING
1162
AssertionResult IsSubstring(
1163
const char* needle_expr, const char* haystack_expr,
1164
const ::std::string& needle, const ::std::string& haystack) {
1165
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1168
AssertionResult IsNotSubstring(
1169
const char* needle_expr, const char* haystack_expr,
1170
const ::std::string& needle, const ::std::string& haystack) {
1171
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1173
#endif // GTEST_HAS_STD_STRING
1175
#if GTEST_HAS_STD_WSTRING
1176
AssertionResult IsSubstring(
1177
const char* needle_expr, const char* haystack_expr,
1178
const ::std::wstring& needle, const ::std::wstring& haystack) {
1179
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1182
AssertionResult IsNotSubstring(
1183
const char* needle_expr, const char* haystack_expr,
1184
const ::std::wstring& needle, const ::std::wstring& haystack) {
1185
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1187
#endif // GTEST_HAS_STD_WSTRING
1189
namespace internal {
1191
#ifdef GTEST_OS_WINDOWS
1195
// Helper function for IsHRESULT{SuccessFailure} predicates
1196
AssertionResult HRESULTFailureHelper(const char* expr,
1197
const char* expected,
1198
long hr) { // NOLINT
1200
// Windows CE doesn't support FormatMessage.
1201
const char error_text[] = "";
1203
// Looks up the human-readable system message for the HRESULT code
1204
// and since we're not passing any params to FormatMessage, we don't
1205
// want inserts expanded.
1206
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1207
FORMAT_MESSAGE_IGNORE_INSERTS;
1208
const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1209
// Gets the system's human readable message string for this HRESULT.
1210
char error_text[kBufSize] = { '\0' };
1211
DWORD message_length = ::FormatMessageA(kFlags,
1212
0, // no source, we're asking system
1214
0, // no line width restrictions
1215
error_text, // output buffer
1216
kBufSize, // buf size
1217
NULL); // no arguments for inserts
1218
// Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1219
for (; message_length && isspace(error_text[message_length - 1]);
1221
error_text[message_length - 1] = '\0';
1223
#endif // _WIN32_WCE
1225
const String error_hex(String::Format("0x%08X ", hr));
1227
msg << "Expected: " << expr << " " << expected << ".\n"
1228
<< " Actual: " << error_hex << error_text << "\n";
1230
return ::testing::AssertionFailure(msg);
1235
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1236
if (SUCCEEDED(hr)) {
1237
return AssertionSuccess();
1239
return HRESULTFailureHelper(expr, "succeeds", hr);
1242
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1244
return AssertionSuccess();
1246
return HRESULTFailureHelper(expr, "fails", hr);
1249
#endif // GTEST_OS_WINDOWS
1251
// Utility functions for encoding Unicode text (wide strings) in
1254
// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1257
// Code-point length Encoding
1258
// 0 - 7 bits 0xxxxxxx
1259
// 8 - 11 bits 110xxxxx 10xxxxxx
1260
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1261
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1263
// The maximum code-point a one-byte UTF-8 sequence can represent.
1264
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1266
// The maximum code-point a two-byte UTF-8 sequence can represent.
1267
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1269
// The maximum code-point a three-byte UTF-8 sequence can represent.
1270
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1272
// The maximum code-point a four-byte UTF-8 sequence can represent.
1273
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1275
// Chops off the n lowest bits from a bit pattern. Returns the n
1276
// lowest bits. As a side effect, the original bit pattern will be
1277
// shifted to the right by n bits.
1278
inline UInt32 ChopLowBits(UInt32* bits, int n) {
1279
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1284
// Converts a Unicode code-point to its UTF-8 encoding.
1285
String ToUtf8String(wchar_t wchar) {
1286
char str[5] = {}; // Initializes str to all '\0' characters.
1288
UInt32 code = static_cast<UInt32>(wchar);
1289
if (code <= kMaxCodePoint1) {
1290
str[0] = static_cast<char>(code); // 0xxxxxxx
1291
} else if (code <= kMaxCodePoint2) {
1292
str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1293
str[0] = static_cast<char>(0xC0 | code); // 110xxxxx
1294
} else if (code <= kMaxCodePoint3) {
1295
str[2] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1296
str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1297
str[0] = static_cast<char>(0xE0 | code); // 1110xxxx
1298
} else if (code <= kMaxCodePoint4) {
1299
str[3] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1300
str[2] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1301
str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6)); // 10xxxxxx
1302
str[0] = static_cast<char>(0xF0 | code); // 11110xxx
1304
return String::Format("(Invalid Unicode 0x%llX)",
1305
static_cast<UInt64>(wchar));
1311
// Converts a wide C string to a String using the UTF-8 encoding.
1312
// NULL will be converted to "(null)".
1313
String String::ShowWideCString(const wchar_t * wide_c_str) {
1314
if (wide_c_str == NULL) return String("(null)");
1317
while (*wide_c_str) {
1318
ss << internal::ToUtf8String(*wide_c_str++);
1321
return internal::StrStreamToString(&ss);
1324
// Similar to ShowWideCString(), except that this function encloses
1325
// the converted string in double quotes.
1326
String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1327
if (wide_c_str == NULL) return String("(null)");
1329
return String::Format("L\"%s\"",
1330
String::ShowWideCString(wide_c_str).c_str());
1333
// Compares two wide C strings. Returns true iff they have the same
1336
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1337
// C string is considered different to any non-NULL C string,
1338
// including the empty string.
1339
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1340
if (lhs == NULL) return rhs == NULL;
1342
if (rhs == NULL) return false;
1344
return wcscmp(lhs, rhs) == 0;
1347
// Helper function for *_STREQ on wide strings.
1348
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1349
const char* actual_expression,
1350
const wchar_t* expected,
1351
const wchar_t* actual) {
1352
if (String::WideCStringEquals(expected, actual)) {
1353
return AssertionSuccess();
1356
return EqFailure(expected_expression,
1358
String::ShowWideCStringQuoted(expected),
1359
String::ShowWideCStringQuoted(actual),
1363
// Helper function for *_STRNE on wide strings.
1364
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1365
const char* s2_expression,
1367
const wchar_t* s2) {
1368
if (!String::WideCStringEquals(s1, s2)) {
1369
return AssertionSuccess();
1373
msg << "Expected: (" << s1_expression << ") != ("
1374
<< s2_expression << "), actual: "
1375
<< String::ShowWideCStringQuoted(s1)
1376
<< " vs " << String::ShowWideCStringQuoted(s2);
1377
return AssertionFailure(msg);
1380
// Compares two C strings, ignoring case. Returns true iff they have
1381
// the same content.
1383
// Unlike strcasecmp(), this function can handle NULL argument(s). A
1384
// NULL C string is considered different to any non-NULL C string,
1385
// including the empty string.
1386
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1387
if ( lhs == NULL ) return rhs == NULL;
1389
if ( rhs == NULL ) return false;
1391
#ifdef GTEST_OS_WINDOWS
1392
return _stricmp(lhs, rhs) == 0;
1393
#else // GTEST_OS_WINDOWS
1394
return strcasecmp(lhs, rhs) == 0;
1395
#endif // GTEST_OS_WINDOWS
1398
// Constructs a String by copying a given number of chars from a
1399
// buffer. E.g. String("hello", 3) will create the string "hel".
1400
String::String(const char * buffer, size_t len) {
1401
char * const temp = new char[ len + 1 ];
1402
memcpy(temp, buffer, len);
1407
// Compares this with another String.
1408
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1409
// if this is greater than rhs.
1410
int String::Compare(const String & rhs) const {
1411
if ( c_str_ == NULL ) {
1412
return rhs.c_str_ == NULL ? 0 : -1; // NULL < anything except NULL
1415
return rhs.c_str_ == NULL ? 1 : strcmp(c_str_, rhs.c_str_);
1418
// Returns true iff this String ends with the given suffix. *Any*
1419
// String is considered to end with a NULL or empty suffix.
1420
bool String::EndsWith(const char* suffix) const {
1421
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1423
if (c_str_ == NULL) return false;
1425
const size_t this_len = strlen(c_str_);
1426
const size_t suffix_len = strlen(suffix);
1427
return (this_len >= suffix_len) &&
1428
CStringEquals(c_str_ + this_len - suffix_len, suffix);
1431
// Returns true iff this String ends with the given suffix, ignoring case.
1432
// Any String is considered to end with a NULL or empty suffix.
1433
bool String::EndsWithCaseInsensitive(const char* suffix) const {
1434
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1436
if (c_str_ == NULL) return false;
1438
const size_t this_len = strlen(c_str_);
1439
const size_t suffix_len = strlen(suffix);
1440
return (this_len >= suffix_len) &&
1441
CaseInsensitiveCStringEquals(c_str_ + this_len - suffix_len, suffix);
1444
// Sets the 0-terminated C string this String object represents. The
1445
// old string in this object is deleted, and this object will own a
1446
// clone of the input string. This function copies only up to length
1447
// bytes (plus a terminating null byte), or until the first null byte,
1448
// whichever comes first.
1450
// This function works even when the c_str parameter has the same
1451
// value as that of the c_str_ field.
1452
void String::Set(const char * c_str, size_t length) {
1453
// Makes sure this works when c_str == c_str_
1454
const char* const temp = CloneString(c_str, length);
1459
// Assigns a C string to this object. Self-assignment works.
1460
const String& String::operator=(const char* c_str) {
1461
// Makes sure this works when c_str == c_str_
1462
if (c_str != c_str_) {
1464
c_str_ = CloneCString(c_str);
1469
// Formats a list of arguments to a String, using the same format
1470
// spec string as for printf.
1472
// We do not use the StringPrintf class as it is not universally
1475
// The result is limited to 4096 characters (including the tailing 0).
1476
// If 4096 characters are not enough to format the input,
1477
// "<buffer exceeded>" is returned.
1478
String String::Format(const char * format, ...) {
1480
va_start(args, format);
1483
// MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1484
// 4996 (deprecated function) there.
1485
#ifdef GTEST_OS_WINDOWS // We are on Windows.
1486
#pragma warning(push) // Saves the current warning state.
1487
#pragma warning(disable:4996) // Temporarily disables warning 4996.
1489
vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1490
#pragma warning(pop) // Restores the warning state.
1491
#else // We are on Linux or Mac OS.
1493
vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1494
#endif // GTEST_OS_WINDOWS
1497
return String(size >= 0 ? buffer : "<buffer exceeded>");
1500
// Converts the buffer in a StrStream to a String, converting NUL
1501
// bytes to "\\0" along the way.
1502
String StrStreamToString(StrStream* ss) {
1503
#if GTEST_HAS_STD_STRING
1504
const ::std::string& str = ss->str();
1505
const char* const start = str.c_str();
1506
const char* const end = start + str.length();
1508
const char* const start = ss->str();
1509
const char* const end = start + ss->pcount();
1510
#endif // GTEST_HAS_STD_STRING
1512
// We need to use a helper StrStream to do this transformation
1513
// because String doesn't support push_back().
1515
for (const char* ch = start; ch != end; ++ch) {
1517
helper << "\\0"; // Replaces NUL with "\\0";
1523
#if GTEST_HAS_STD_STRING
1524
return String(helper.str().c_str());
1526
const String str(helper.str(), helper.pcount());
1527
helper.freeze(false);
1530
#endif // GTEST_HAS_STD_STRING
1533
// Appends the user-supplied message to the Google-Test-generated message.
1534
String AppendUserMessage(const String& gtest_msg,
1535
const Message& user_msg) {
1536
// Appends the user message if it's non-empty.
1537
const String user_msg_string = user_msg.GetString();
1538
if (user_msg_string.empty()) {
1543
msg << gtest_msg << "\n" << user_msg_string;
1545
return msg.GetString();
1548
} // namespace internal
1550
// Prints a TestPartResult object.
1551
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
1552
return os << result.file_name() << ":"
1553
<< result.line_number() << ": "
1554
<< (result.type() == TPRT_SUCCESS ? "Success" :
1555
result.type() == TPRT_FATAL_FAILURE ? "Fatal failure" :
1556
"Non-fatal failure") << ":\n"
1557
<< result.message() << std::endl;
1560
namespace internal {
1563
// Creates an empty TestResult.
1564
TestResult::TestResult()
1565
: death_test_count_(0),
1570
TestResult::~TestResult() {
1573
// Adds a test part result to the list.
1574
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1575
test_part_results_.PushBack(test_part_result);
1578
// Adds a test property to the list. If a property with the same key as the
1579
// supplied property is already represented, the value of this test_property
1580
// replaces the old value for that key.
1581
void TestResult::RecordProperty(const TestProperty& test_property) {
1582
if (!ValidateTestProperty(test_property)) {
1585
MutexLock lock(&test_properites_mutex_);
1586
ListNode<TestProperty>* const node_with_matching_key =
1587
test_properties_.FindIf(TestPropertyKeyIs(test_property.key()));
1588
if (node_with_matching_key == NULL) {
1589
test_properties_.PushBack(test_property);
1592
TestProperty& property_with_matching_key = node_with_matching_key->element();
1593
property_with_matching_key.SetValue(test_property.value());
1596
// Adds a failure if the key is a reserved attribute of Google Test testcase tags.
1597
// Returns true if the property is valid.
1598
bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1599
String key(test_property.key());
1600
if (key == "name" || key == "status" || key == "time" || key == "classname") {
1602
<< "Reserved key used in RecordProperty(): "
1604
<< " ('name', 'status', 'time', and 'classname' are reserved by "
1605
<< GTEST_NAME << ")";
1611
// Clears the object.
1612
void TestResult::Clear() {
1613
test_part_results_.Clear();
1614
test_properties_.Clear();
1615
death_test_count_ = 0;
1619
// Returns true iff the test part passed.
1620
static bool TestPartPassed(const TestPartResult & result) {
1621
return result.passed();
1624
// Gets the number of successful test parts.
1625
int TestResult::successful_part_count() const {
1626
return test_part_results_.CountIf(TestPartPassed);
1629
// Returns true iff the test part failed.
1630
static bool TestPartFailed(const TestPartResult & result) {
1631
return result.failed();
1634
// Gets the number of failed test parts.
1635
int TestResult::failed_part_count() const {
1636
return test_part_results_.CountIf(TestPartFailed);
1639
// Returns true iff the test part fatally failed.
1640
static bool TestPartFatallyFailed(const TestPartResult & result) {
1641
return result.fatally_failed();
1644
// Returns true iff the test fatally failed.
1645
bool TestResult::HasFatalFailure() const {
1646
return test_part_results_.CountIf(TestPartFatallyFailed) > 0;
1649
// Gets the number of all test parts. This is the sum of the number
1650
// of successful test parts and the number of failed test parts.
1651
int TestResult::total_part_count() const {
1652
return test_part_results_.size();
1655
} // namespace internal
1659
// Creates a Test object.
1661
// The c'tor saves the values of all Google Test flags.
1663
: gtest_flag_saver_(new internal::GTestFlagSaver) {
1666
// The d'tor restores the values of all Google Test flags.
1668
delete gtest_flag_saver_;
1671
// Sets up the test fixture.
1673
// A sub-class may override this.
1674
void Test::SetUp() {
1677
// Tears down the test fixture.
1679
// A sub-class may override this.
1680
void Test::TearDown() {
1683
// Allows user supplied key value pairs to be recorded for later output.
1684
void Test::RecordProperty(const char* key, const char* value) {
1685
UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1688
// Allows user supplied key value pairs to be recorded for later output.
1689
void Test::RecordProperty(const char* key, int value) {
1690
Message value_message;
1691
value_message << value;
1692
RecordProperty(key, value_message.GetString().c_str());
1695
#ifdef GTEST_OS_WINDOWS
1696
// We are on Windows.
1698
// Adds an "exception thrown" fatal failure to the current test.
1699
static void AddExceptionThrownFailure(DWORD exception_code,
1700
const char* location) {
1702
message << "Exception thrown with code 0x" << std::setbase(16) <<
1703
exception_code << std::setbase(10) << " in " << location << ".";
1705
UnitTest* const unit_test = UnitTest::GetInstance();
1706
unit_test->AddTestPartResult(
1708
static_cast<const char *>(NULL),
1709
// We have no info about the source file where the exception
1711
-1, // We have no info on which line caused the exception.
1712
message.GetString(),
1713
internal::String(""));
1716
#endif // GTEST_OS_WINDOWS
1718
// Google Test requires all tests in the same test case to use the same test
1719
// fixture class. This function checks if the current test has the
1720
// same fixture class as the first test in the current test case. If
1721
// yes, it returns true; otherwise it generates a Google Test failure and
1723
bool Test::HasSameFixtureClass() {
1724
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1725
const TestCase* const test_case = impl->current_test_case();
1727
// Info about the first test in the current test case.
1728
const internal::TestInfoImpl* const first_test_info =
1729
test_case->test_info_list().Head()->element()->impl();
1730
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1731
const char* const first_test_name = first_test_info->name();
1733
// Info about the current test.
1734
const internal::TestInfoImpl* const this_test_info =
1735
impl->current_test_info()->impl();
1736
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
1737
const char* const this_test_name = this_test_info->name();
1739
if (this_fixture_id != first_fixture_id) {
1740
// Is the first test defined using TEST?
1741
const bool first_is_TEST = first_fixture_id == internal::GetTypeId<Test>();
1742
// Is this test defined using TEST?
1743
const bool this_is_TEST = this_fixture_id == internal::GetTypeId<Test>();
1745
if (first_is_TEST || this_is_TEST) {
1746
// The user mixed TEST and TEST_F in this test case - we'll tell
1747
// him/her how to fix it.
1749
// Gets the name of the TEST and the name of the TEST_F. Note
1750
// that first_is_TEST and this_is_TEST cannot both be true, as
1751
// the fixture IDs are different for the two tests.
1752
const char* const TEST_name =
1753
first_is_TEST ? first_test_name : this_test_name;
1754
const char* const TEST_F_name =
1755
first_is_TEST ? this_test_name : first_test_name;
1758
<< "All tests in the same test case must use the same test fixture\n"
1759
<< "class, so mixing TEST_F and TEST in the same test case is\n"
1760
<< "illegal. In test case " << this_test_info->test_case_name()
1762
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
1763
<< "test " << TEST_name << " is defined using TEST. You probably\n"
1764
<< "want to change the TEST to TEST_F or move it to another test\n"
1767
// The user defined two fixture classes with the same name in
1768
// two namespaces - we'll tell him/her how to fix it.
1770
<< "All tests in the same test case must use the same test fixture\n"
1771
<< "class. However, in test case "
1772
<< this_test_info->test_case_name() << ",\n"
1773
<< "you defined test " << first_test_name
1774
<< " and test " << this_test_name << "\n"
1775
<< "using two different test fixture classes. This can happen if\n"
1776
<< "the two classes are from different namespaces or translation\n"
1777
<< "units and have the same name. You should probably rename one\n"
1778
<< "of the classes to put the tests into different test cases.";
1786
// Runs the test and updates the test result.
1788
if (!HasSameFixtureClass()) return;
1790
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1791
#ifdef GTEST_OS_WINDOWS
1792
// We are on Windows.
1793
impl->os_stack_trace_getter()->UponLeavingGTest();
1796
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1797
GetExceptionCode())) {
1798
AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
1801
// We will run the test only if SetUp() had no fatal failure.
1802
if (!HasFatalFailure()) {
1803
impl->os_stack_trace_getter()->UponLeavingGTest();
1806
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1807
GetExceptionCode())) {
1808
AddExceptionThrownFailure(GetExceptionCode(), "the test body");
1812
// However, we want to clean up as much as possible. Hence we will
1813
// always call TearDown(), even if SetUp() or the test body has
1815
impl->os_stack_trace_getter()->UponLeavingGTest();
1818
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1819
GetExceptionCode())) {
1820
AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
1823
#else // We are on Linux or Mac - exceptions are disabled.
1824
impl->os_stack_trace_getter()->UponLeavingGTest();
1827
// We will run the test only if SetUp() was successful.
1828
if (!HasFatalFailure()) {
1829
impl->os_stack_trace_getter()->UponLeavingGTest();
1833
// However, we want to clean up as much as possible. Hence we will
1834
// always call TearDown(), even if SetUp() or the test body has
1836
impl->os_stack_trace_getter()->UponLeavingGTest();
1838
#endif // GTEST_OS_WINDOWS
1842
// Returns true iff the current test has a fatal failure.
1843
bool Test::HasFatalFailure() {
1844
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
1849
// Constructs a TestInfo object.
1850
TestInfo::TestInfo(const char* test_case_name,
1852
internal::TypeId fixture_class_id,
1854
impl_ = new internal::TestInfoImpl(this, test_case_name, name,
1855
fixture_class_id, maker);
1858
// Destructs a TestInfo object.
1859
TestInfo::~TestInfo() {
1863
// Creates a TestInfo object and registers it with the UnitTest
1864
// singleton; returns the created object.
1868
// test_case_name: name of the test case
1869
// name: name of the test
1870
// set_up_tc: pointer to the function that sets up the test case
1871
// tear_down_tc: pointer to the function that tears down the test case
1872
// maker: pointer to the function that creates a test object
1873
TestInfo* TestInfo::MakeAndRegisterInstance(
1874
const char* test_case_name,
1876
internal::TypeId fixture_class_id,
1877
Test::SetUpTestCaseFunc set_up_tc,
1878
Test::TearDownTestCaseFunc tear_down_tc,
1880
TestInfo* const test_info =
1881
new TestInfo(test_case_name, name, fixture_class_id, maker);
1882
internal::GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
1886
// Returns the test case name.
1887
const char* TestInfo::test_case_name() const {
1888
return impl_->test_case_name();
1891
// Returns the test name.
1892
const char* TestInfo::name() const {
1893
return impl_->name();
1896
// Returns true if this test should run.
1897
bool TestInfo::should_run() const { return impl_->should_run(); }
1899
// Returns the result of the test.
1900
const internal::TestResult* TestInfo::result() const { return impl_->result(); }
1902
// Increments the number of death tests encountered in this test so
1904
int TestInfo::increment_death_test_count() {
1905
return impl_->result()->increment_death_test_count();
1910
// A predicate that checks the test name of a TestInfo against a known
1913
// This is used for implementation of the TestCase class only. We put
1914
// it in the anonymous namespace to prevent polluting the outer
1917
// TestNameIs is copyable.
1922
// TestNameIs has NO default constructor.
1923
explicit TestNameIs(const char* name)
1926
// Returns true iff the test name of test_info matches name_.
1927
bool operator()(const TestInfo * test_info) const {
1928
return test_info && internal::String(test_info->name()).Compare(name_) == 0;
1932
internal::String name_;
1937
// Finds and returns a TestInfo with the given name. If one doesn't
1938
// exist, returns NULL.
1939
TestInfo * TestCase::GetTestInfo(const char* test_name) {
1940
// Can we find a TestInfo with the given name?
1941
internal::ListNode<TestInfo *> * const node = test_info_list_->FindIf(
1942
TestNameIs(test_name));
1944
// Returns the TestInfo found.
1945
return node ? node->element() : NULL;
1948
namespace internal {
1950
// Creates the test object, runs it, records its result, and then
1952
void TestInfoImpl::Run() {
1953
if (!should_run_) return;
1955
// Tells UnitTest where to store test result.
1956
UnitTestImpl* const impl = internal::GetUnitTestImpl();
1957
impl->set_current_test_info(parent_);
1959
// Notifies the unit test event listener that a test is about to
1961
UnitTestEventListenerInterface* const result_printer =
1962
impl->result_printer();
1963
result_printer->OnTestStart(parent_);
1965
const TimeInMillis start = GetTimeInMillis();
1967
impl->os_stack_trace_getter()->UponLeavingGTest();
1968
#ifdef GTEST_OS_WINDOWS
1969
// We are on Windows.
1973
// Creates the test object.
1975
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1976
GetExceptionCode())) {
1977
AddExceptionThrownFailure(GetExceptionCode(),
1978
"the test fixture's constructor");
1981
#else // We are on Linux or Mac OS - exceptions are disabled.
1983
// TODO(wan): If test->Run() throws, test won't be deleted. This is
1984
// not a problem now as we don't use exceptions. If we were to
1985
// enable exceptions, we should revise the following to be
1988
// Creates the test object.
1989
Test* test = (*maker_)();
1990
#endif // GTEST_OS_WINDOWS
1992
// Runs the test only if the constructor of the test fixture didn't
1993
// generate a fatal failure.
1994
if (!Test::HasFatalFailure()) {
1998
// Deletes the test object.
1999
impl->os_stack_trace_getter()->UponLeavingGTest();
2003
result_.set_elapsed_time(GetTimeInMillis() - start);
2005
// Notifies the unit test event listener that a test has just finished.
2006
result_printer->OnTestEnd(parent_);
2008
// Tells UnitTest to stop associating assertion results to this
2010
impl->set_current_test_info(NULL);
2013
} // namespace internal
2017
// Gets the number of successful tests in this test case.
2018
int TestCase::successful_test_count() const {
2019
return test_info_list_->CountIf(TestPassed);
2022
// Gets the number of failed tests in this test case.
2023
int TestCase::failed_test_count() const {
2024
return test_info_list_->CountIf(TestFailed);
2027
int TestCase::disabled_test_count() const {
2028
return test_info_list_->CountIf(TestDisabled);
2031
// Get the number of tests in this test case that should run.
2032
int TestCase::test_to_run_count() const {
2033
return test_info_list_->CountIf(ShouldRunTest);
2036
// Gets the number of all tests.
2037
int TestCase::total_test_count() const {
2038
return test_info_list_->size();
2041
// Creates a TestCase with the given name.
2045
// name: name of the test case
2046
// set_up_tc: pointer to the function that sets up the test case
2047
// tear_down_tc: pointer to the function that tears down the test case
2048
TestCase::TestCase(const char* name,
2049
Test::SetUpTestCaseFunc set_up_tc,
2050
Test::TearDownTestCaseFunc tear_down_tc)
2052
set_up_tc_(set_up_tc),
2053
tear_down_tc_(tear_down_tc),
2056
test_info_list_ = new internal::List<TestInfo *>;
2059
// Destructor of TestCase.
2060
TestCase::~TestCase() {
2061
// Deletes every Test in the collection.
2062
test_info_list_->ForEach(internal::Delete<TestInfo>);
2064
// Then deletes the Test collection.
2065
delete test_info_list_;
2066
test_info_list_ = NULL;
2069
// Adds a test to this test case. Will delete the test upon
2070
// destruction of the TestCase object.
2071
void TestCase::AddTestInfo(TestInfo * test_info) {
2072
test_info_list_->PushBack(test_info);
2075
// Runs every test in this TestCase.
2076
void TestCase::Run() {
2077
if (!should_run_) return;
2079
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2080
impl->set_current_test_case(this);
2082
UnitTestEventListenerInterface * const result_printer =
2083
impl->result_printer();
2085
result_printer->OnTestCaseStart(this);
2086
impl->os_stack_trace_getter()->UponLeavingGTest();
2089
const internal::TimeInMillis start = internal::GetTimeInMillis();
2090
test_info_list_->ForEach(internal::TestInfoImpl::RunTest);
2091
elapsed_time_ = internal::GetTimeInMillis() - start;
2093
impl->os_stack_trace_getter()->UponLeavingGTest();
2095
result_printer->OnTestCaseEnd(this);
2096
impl->set_current_test_case(NULL);
2099
// Clears the results of all tests in this test case.
2100
void TestCase::ClearResult() {
2101
test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2105
// class UnitTestEventListenerInterface
2107
// The virtual d'tor.
2108
UnitTestEventListenerInterface::~UnitTestEventListenerInterface() {
2111
// A result printer that never prints anything. Used in the child process
2112
// of an exec-style death test to avoid needless output clutter.
2113
class NullUnitTestResultPrinter : public UnitTestEventListenerInterface {};
2115
// Formats a countable noun. Depending on its quantity, either the
2116
// singular form or the plural form is used. e.g.
2118
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2119
// FormatCountableNoun(5, "book", "books") returns "5 books".
2120
static internal::String FormatCountableNoun(int count,
2121
const char * singular_form,
2122
const char * plural_form) {
2123
return internal::String::Format("%d %s", count,
2124
count == 1 ? singular_form : plural_form);
2127
// Formats the count of tests.
2128
static internal::String FormatTestCount(int test_count) {
2129
return FormatCountableNoun(test_count, "test", "tests");
2132
// Formats the count of test cases.
2133
static internal::String FormatTestCaseCount(int test_case_count) {
2134
return FormatCountableNoun(test_case_count, "test case", "test cases");
2137
// Converts a TestPartResultType enum to human-friendly string
2138
// representation. Both TPRT_NONFATAL_FAILURE and TPRT_FATAL_FAILURE
2139
// are translated to "Failure", as the user usually doesn't care about
2140
// the difference between the two when viewing the test result.
2141
static const char * TestPartResultTypeToString(TestPartResultType type) {
2146
case TPRT_NONFATAL_FAILURE:
2147
case TPRT_FATAL_FAILURE:
2151
return "Unknown result type";
2154
// Prints a TestPartResult.
2155
static void PrintTestPartResult(
2156
const TestPartResult & test_part_result) {
2157
const char * const file_name = test_part_result.file_name();
2159
printf("%s", file_name == NULL ? "unknown file" : file_name);
2160
if (test_part_result.line_number() >= 0) {
2161
printf(":%d", test_part_result.line_number());
2163
printf(": %s\n", TestPartResultTypeToString(test_part_result.type()));
2164
printf("%s\n", test_part_result.message());
2168
// class PrettyUnitTestResultPrinter
2170
namespace internal {
2180
// Returns the character attribute for the given color.
2181
WORD GetColorAttribute(GTestColor color) {
2183
case COLOR_RED: return FOREGROUND_RED;
2184
case COLOR_GREEN: return FOREGROUND_GREEN;
2185
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2192
// Returns the ANSI color code for the given color.
2193
const char* GetAnsiColorCode(GTestColor color) {
2195
case COLOR_RED: return "1";
2196
case COLOR_GREEN: return "2";
2197
case COLOR_YELLOW: return "3";
2204
// Returns true iff Google Test should use colors in the output.
2205
bool ShouldUseColor(bool stdout_is_tty) {
2206
const char* const gtest_color = GTEST_FLAG(color).c_str();
2208
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2210
// On Windows the TERM variable is usually not set, but the
2211
// console there does support colors.
2212
return stdout_is_tty;
2214
// On non-Windows platforms, we rely on the TERM variable.
2215
const char* const term = GetEnv("TERM");
2216
const bool term_supports_color =
2217
String::CStringEquals(term, "xterm") ||
2218
String::CStringEquals(term, "xterm-color") ||
2219
String::CStringEquals(term, "cygwin");
2220
return stdout_is_tty && term_supports_color;
2224
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2225
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2226
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2227
String::CStringEquals(gtest_color, "1");
2228
// We take "yes", "true", "t", and "1" as meaning "yes". If the
2229
// value is neither one of these nor "auto", we treat it as "no" to
2233
// Helpers for printing colored strings to stdout. Note that on Windows, we
2234
// cannot simply emit special characters and have the terminal change colors.
2235
// This routine must actually emit the characters rather than return a string
2236
// that would be colored when printed, as can be done on Linux.
2237
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2239
va_start(args, fmt);
2241
static const bool use_color = ShouldUseColor(isatty(fileno(stdout)) != 0);
2242
// The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2251
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2253
// Gets the current text color.
2254
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2255
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2256
const WORD old_color_attrs = buffer_info.wAttributes;
2258
SetConsoleTextAttribute(stdout_handle,
2259
GetColorAttribute(color) | FOREGROUND_INTENSITY);
2262
// Restores the text color.
2263
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2265
printf("\033[0;3%sm", GetAnsiColorCode(color));
2267
printf("\033[m"); // Resets the terminal to default.
2272
} // namespace internal
2274
using internal::ColoredPrintf;
2275
using internal::COLOR_RED;
2276
using internal::COLOR_GREEN;
2277
using internal::COLOR_YELLOW;
2279
// This class implements the UnitTestEventListenerInterface interface.
2281
// Class PrettyUnitTestResultPrinter is copyable.
2282
class PrettyUnitTestResultPrinter : public UnitTestEventListenerInterface {
2284
PrettyUnitTestResultPrinter() {}
2285
static void PrintTestName(const char * test_case, const char * test) {
2286
printf("%s.%s", test_case, test);
2289
// The following methods override what's in the
2290
// UnitTestEventListenerInterface class.
2291
virtual void OnUnitTestStart(const UnitTest * unit_test);
2292
virtual void OnGlobalSetUpStart(const UnitTest*);
2293
virtual void OnTestCaseStart(const TestCase * test_case);
2294
virtual void OnTestStart(const TestInfo * test_info);
2295
virtual void OnNewTestPartResult(const TestPartResult * result);
2296
virtual void OnTestEnd(const TestInfo * test_info);
2297
virtual void OnGlobalTearDownStart(const UnitTest*);
2298
virtual void OnUnitTestEnd(const UnitTest * unit_test);
2301
internal::String test_case_name_;
2304
// Called before the unit test starts.
2305
void PrettyUnitTestResultPrinter::OnUnitTestStart(
2306
const UnitTest * unit_test) {
2307
const char * const filter = GTEST_FLAG(filter).c_str();
2309
// Prints the filter if it's not *. This reminds the user that some
2310
// tests may be skipped.
2311
if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2312
ColoredPrintf(COLOR_YELLOW,
2313
"Note: %s filter = %s\n", GTEST_NAME, filter);
2316
const internal::UnitTestImpl* const impl = unit_test->impl();
2317
ColoredPrintf(COLOR_GREEN, "[==========] ");
2318
printf("Running %s from %s.\n",
2319
FormatTestCount(impl->test_to_run_count()).c_str(),
2320
FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2324
void PrettyUnitTestResultPrinter::OnGlobalSetUpStart(const UnitTest*) {
2325
ColoredPrintf(COLOR_GREEN, "[----------] ");
2326
printf("Global test environment set-up.\n");
2330
void PrettyUnitTestResultPrinter::OnTestCaseStart(
2331
const TestCase * test_case) {
2332
test_case_name_ = test_case->name();
2333
const internal::String counts =
2334
FormatCountableNoun(test_case->test_to_run_count(), "test", "tests");
2335
ColoredPrintf(COLOR_GREEN, "[----------] ");
2336
printf("%s from %s\n", counts.c_str(), test_case_name_.c_str());
2340
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo * test_info) {
2341
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2342
PrintTestName(test_case_name_.c_str(), test_info->name());
2347
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo * test_info) {
2348
if (test_info->result()->Passed()) {
2349
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2351
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2353
PrintTestName(test_case_name_.c_str(), test_info->name());
2358
// Called after an assertion failure.
2359
void PrettyUnitTestResultPrinter::OnNewTestPartResult(
2360
const TestPartResult * result) {
2361
// If the test part succeeded, we don't need to do anything.
2362
if (result->type() == TPRT_SUCCESS)
2365
// Print failure message from the assertion (e.g. expected this and got that).
2366
PrintTestPartResult(*result);
2370
void PrettyUnitTestResultPrinter::OnGlobalTearDownStart(const UnitTest*) {
2371
ColoredPrintf(COLOR_GREEN, "[----------] ");
2372
printf("Global test environment tear-down\n");
2376
namespace internal {
2378
// Internal helper for printing the list of failed tests.
2379
static void PrintFailedTestsPretty(const UnitTestImpl* impl) {
2380
const int failed_test_count = impl->failed_test_count();
2381
if (failed_test_count == 0) {
2385
for (const internal::ListNode<TestCase*>* node = impl->test_cases()->Head();
2386
node != NULL; node = node->next()) {
2387
const TestCase* const tc = node->element();
2388
if (!tc->should_run() || (tc->failed_test_count() == 0)) {
2391
for (const internal::ListNode<TestInfo*>* tinode =
2392
tc->test_info_list().Head();
2393
tinode != NULL; tinode = tinode->next()) {
2394
const TestInfo* const ti = tinode->element();
2395
if (!tc->ShouldRunTest(ti) || tc->TestPassed(ti)) {
2398
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2399
printf("%s.%s\n", ti->test_case_name(), ti->name());
2404
} // namespace internal
2406
void PrettyUnitTestResultPrinter::OnUnitTestEnd(
2407
const UnitTest * unit_test) {
2408
const internal::UnitTestImpl* const impl = unit_test->impl();
2410
ColoredPrintf(COLOR_GREEN, "[==========] ");
2411
printf("%s from %s ran.\n",
2412
FormatTestCount(impl->test_to_run_count()).c_str(),
2413
FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2414
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2415
printf("%s.\n", FormatTestCount(impl->successful_test_count()).c_str());
2417
int num_failures = impl->failed_test_count();
2418
if (!impl->Passed()) {
2419
const int failed_test_count = impl->failed_test_count();
2420
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2421
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2422
internal::PrintFailedTestsPretty(impl);
2423
printf("\n%2d FAILED %s\n", num_failures,
2424
num_failures == 1 ? "TEST" : "TESTS");
2427
int num_disabled = impl->disabled_test_count();
2429
if (!num_failures) {
2430
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2432
ColoredPrintf(COLOR_YELLOW,
2433
" YOU HAVE %d DISABLED %s\n\n",
2435
num_disabled == 1 ? "TEST" : "TESTS");
2437
// Ensure that Google Test output is printed before, e.g., heapchecker output.
2441
// End PrettyUnitTestResultPrinter
2443
// class UnitTestEventsRepeater
2445
// This class forwards events to other event listeners.
2446
class UnitTestEventsRepeater : public UnitTestEventListenerInterface {
2448
typedef internal::List<UnitTestEventListenerInterface *> Listeners;
2449
typedef internal::ListNode<UnitTestEventListenerInterface *> ListenersNode;
2450
UnitTestEventsRepeater() {}
2451
virtual ~UnitTestEventsRepeater();
2452
void AddListener(UnitTestEventListenerInterface *listener);
2454
virtual void OnUnitTestStart(const UnitTest* unit_test);
2455
virtual void OnUnitTestEnd(const UnitTest* unit_test);
2456
virtual void OnGlobalSetUpStart(const UnitTest* unit_test);
2457
virtual void OnGlobalSetUpEnd(const UnitTest* unit_test);
2458
virtual void OnGlobalTearDownStart(const UnitTest* unit_test);
2459
virtual void OnGlobalTearDownEnd(const UnitTest* unit_test);
2460
virtual void OnTestCaseStart(const TestCase* test_case);
2461
virtual void OnTestCaseEnd(const TestCase* test_case);
2462
virtual void OnTestStart(const TestInfo* test_info);
2463
virtual void OnTestEnd(const TestInfo* test_info);
2464
virtual void OnNewTestPartResult(const TestPartResult* result);
2467
Listeners listeners_;
2469
GTEST_DISALLOW_COPY_AND_ASSIGN(UnitTestEventsRepeater);
2472
UnitTestEventsRepeater::~UnitTestEventsRepeater() {
2473
for (ListenersNode* listener = listeners_.Head();
2475
listener = listener->next()) {
2476
delete listener->element();
2480
void UnitTestEventsRepeater::AddListener(
2481
UnitTestEventListenerInterface *listener) {
2482
listeners_.PushBack(listener);
2485
// Since the methods are identical, use a macro to reduce boilerplate.
2486
// This defines a member that repeats the call to all listeners.
2487
#define GTEST_REPEATER_METHOD(Name, Type) \
2488
void UnitTestEventsRepeater::Name(const Type* parameter) { \
2489
for (ListenersNode* listener = listeners_.Head(); \
2491
listener = listener->next()) { \
2492
listener->element()->Name(parameter); \
2496
GTEST_REPEATER_METHOD(OnUnitTestStart, UnitTest)
2497
GTEST_REPEATER_METHOD(OnUnitTestEnd, UnitTest)
2498
GTEST_REPEATER_METHOD(OnGlobalSetUpStart, UnitTest)
2499
GTEST_REPEATER_METHOD(OnGlobalSetUpEnd, UnitTest)
2500
GTEST_REPEATER_METHOD(OnGlobalTearDownStart, UnitTest)
2501
GTEST_REPEATER_METHOD(OnGlobalTearDownEnd, UnitTest)
2502
GTEST_REPEATER_METHOD(OnTestCaseStart, TestCase)
2503
GTEST_REPEATER_METHOD(OnTestCaseEnd, TestCase)
2504
GTEST_REPEATER_METHOD(OnTestStart, TestInfo)
2505
GTEST_REPEATER_METHOD(OnTestEnd, TestInfo)
2506
GTEST_REPEATER_METHOD(OnNewTestPartResult, TestPartResult)
2508
#undef GTEST_REPEATER_METHOD
2510
// End PrettyUnitTestResultPrinter
2512
// This class generates an XML output file.
2513
class XmlUnitTestResultPrinter : public UnitTestEventListenerInterface {
2515
explicit XmlUnitTestResultPrinter(const char* output_file);
2517
virtual void OnUnitTestEnd(const UnitTest* unit_test);
2520
// Is c a whitespace character that is normalized to a space character
2521
// when it appears in an XML attribute value?
2522
static bool IsNormalizableWhitespace(char c) {
2523
return c == 0x9 || c == 0xA || c == 0xD;
2526
// May c appear in a well-formed XML document?
2527
static bool IsValidXmlCharacter(char c) {
2528
return IsNormalizableWhitespace(c) || c >= 0x20;
2531
// Returns an XML-escaped copy of the input string str. If
2532
// is_attribute is true, the text is meant to appear as an attribute
2533
// value, and normalizable whitespace is preserved by replacing it
2534
// with character references.
2535
static internal::String EscapeXml(const char* str,
2538
// Convenience wrapper around EscapeXml when str is an attribute value.
2539
static internal::String EscapeXmlAttribute(const char* str) {
2540
return EscapeXml(str, true);
2543
// Convenience wrapper around EscapeXml when str is not an attribute value.
2544
static internal::String EscapeXmlText(const char* str) {
2545
return EscapeXml(str, false);
2548
// Prints an XML representation of a TestInfo object.
2549
static void PrintXmlTestInfo(FILE* out,
2550
const char* test_case_name,
2551
const TestInfo* test_info);
2553
// Prints an XML representation of a TestCase object
2554
static void PrintXmlTestCase(FILE* out, const TestCase* test_case);
2556
// Prints an XML summary of unit_test to output stream out.
2557
static void PrintXmlUnitTest(FILE* out, const UnitTest* unit_test);
2559
// Produces a string representing the test properties in a result as space
2560
// delimited XML attributes based on the property key="value" pairs.
2561
// When the String is not empty, it includes a space at the beginning,
2562
// to delimit this attribute from prior attributes.
2563
static internal::String TestPropertiesAsXmlAttributes(
2564
const internal::TestResult* result);
2567
const internal::String output_file_;
2569
GTEST_DISALLOW_COPY_AND_ASSIGN(XmlUnitTestResultPrinter);
2572
// Creates a new XmlUnitTestResultPrinter.
2573
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
2574
: output_file_(output_file) {
2575
if (output_file_.c_str() == NULL || output_file_.empty()) {
2576
fprintf(stderr, "XML output file may not be null\n");
2582
// Called after the unit test ends.
2583
void XmlUnitTestResultPrinter::OnUnitTestEnd(const UnitTest* unit_test) {
2584
FILE* xmlout = NULL;
2585
internal::FilePath output_file(output_file_);
2586
internal::FilePath output_dir(output_file.RemoveFileName());
2588
if (output_dir.CreateDirectoriesRecursively()) {
2589
// MSVC 8 deprecates fopen(), so we want to suppress warning 4996
2590
// (deprecated function) there.
2591
#ifdef GTEST_OS_WINDOWS
2592
// We are on Windows.
2593
#pragma warning(push) // Saves the current warning state.
2594
#pragma warning(disable:4996) // Temporarily disables warning 4996.
2595
xmlout = fopen(output_file_.c_str(), "w");
2596
#pragma warning(pop) // Restores the warning state.
2597
#else // We are on Linux or Mac OS.
2598
xmlout = fopen(output_file_.c_str(), "w");
2599
#endif // GTEST_OS_WINDOWS
2601
if (xmlout == NULL) {
2602
// TODO(wan): report the reason of the failure.
2604
// We don't do it for now as:
2606
// 1. There is no urgent need for it.
2607
// 2. It's a bit involved to make the errno variable thread-safe on
2608
// all three operating systems (Linux, Windows, and Mac OS).
2609
// 3. To interpret the meaning of errno in a thread-safe way,
2610
// we need the strerror_r() function, which is not available on
2613
"Unable to open file \"%s\"\n",
2614
output_file_.c_str());
2618
PrintXmlUnitTest(xmlout, unit_test);
2622
// Returns an XML-escaped copy of the input string str. If is_attribute
2623
// is true, the text is meant to appear as an attribute value, and
2624
// normalizable whitespace is preserved by replacing it with character
2627
// Invalid XML characters in str, if any, are stripped from the output.
2628
// It is expected that most, if not all, of the text processed by this
2629
// module will consist of ordinary English text.
2630
// If this module is ever modified to produce version 1.1 XML output,
2631
// most invalid characters can be retained using character references.
2632
// TODO(wan): It might be nice to have a minimally invasive, human-readable
2633
// escaping scheme for invalid characters, rather than dropping them.
2634
internal::String XmlUnitTestResultPrinter::EscapeXml(const char* str,
2635
bool is_attribute) {
2639
for (const char* src = str; *src; ++src) {
2663
if (IsValidXmlCharacter(*src)) {
2664
if (is_attribute && IsNormalizableWhitespace(*src))
2665
m << internal::String::Format("&#x%02X;", unsigned(*src));
2674
return m.GetString();
2678
// The following routines generate an XML representation of a UnitTest
2681
// This is how Google Test concepts map to the DTD:
2683
// <testsuite name="AllTests"> <-- corresponds to a UnitTest object
2684
// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
2685
// <testcase name="test-name"> <-- corresponds to a TestInfo object
2686
// <failure message="..." />
2687
// <failure message="..." /> <-- individual assertion failures
2688
// <failure message="..." />
2693
// Prints an XML representation of a TestInfo object.
2694
// TODO(wan): There is also value in printing properties with the plain printer.
2695
void XmlUnitTestResultPrinter::PrintXmlTestInfo(FILE* out,
2696
const char* test_case_name,
2697
const TestInfo* test_info) {
2698
const internal::TestResult * const result = test_info->result();
2699
const internal::List<TestPartResult> &results = result->test_part_results();
2701
" <testcase name=\"%s\" status=\"%s\" time=\"%s\" "
2702
"classname=\"%s\"%s",
2703
EscapeXmlAttribute(test_info->name()).c_str(),
2704
test_info->should_run() ? "run" : "notrun",
2705
internal::StreamableToString(result->elapsed_time()).c_str(),
2706
EscapeXmlAttribute(test_case_name).c_str(),
2707
TestPropertiesAsXmlAttributes(result).c_str());
2710
for (const internal::ListNode<TestPartResult>* part_node = results.Head();
2712
part_node = part_node->next()) {
2713
const TestPartResult& part = part_node->element();
2714
if (part.failed()) {
2715
const internal::String message =
2716
internal::String::Format("%s:%d\n%s", part.file_name(),
2717
part.line_number(), part.message());
2718
if (++failures == 1)
2719
fprintf(out, ">\n");
2721
" <failure message=\"%s\" type=\"\"/>\n",
2722
EscapeXmlAttribute(message.c_str()).c_str());
2727
fprintf(out, " />\n");
2729
fprintf(out, " </testcase>\n");
2732
// Prints an XML representation of a TestCase object
2733
void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
2734
const TestCase* test_case) {
2736
" <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
2738
EscapeXmlAttribute(test_case->name()).c_str(),
2739
test_case->total_test_count(),
2740
test_case->failed_test_count(),
2741
test_case->disabled_test_count());
2743
"errors=\"0\" time=\"%s\">\n",
2744
internal::StreamableToString(test_case->elapsed_time()).c_str());
2745
for (const internal::ListNode<TestInfo*>* info_node =
2746
test_case->test_info_list().Head();
2748
info_node = info_node->next()) {
2749
PrintXmlTestInfo(out, test_case->name(), info_node->element());
2751
fprintf(out, " </testsuite>\n");
2754
// Prints an XML summary of unit_test to output stream out.
2755
void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
2756
const UnitTest* unit_test) {
2757
const internal::UnitTestImpl* const impl = unit_test->impl();
2758
fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2760
"<testsuite tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
2761
"errors=\"0\" time=\"%s\" ",
2762
impl->total_test_count(),
2763
impl->failed_test_count(),
2764
impl->disabled_test_count(),
2765
internal::StreamableToString(impl->elapsed_time()).c_str());
2766
fprintf(out, "name=\"AllTests\">\n");
2767
for (const internal::ListNode<TestCase*>* case_node =
2768
impl->test_cases()->Head();
2770
case_node = case_node->next()) {
2771
PrintXmlTestCase(out, case_node->element());
2773
fprintf(out, "</testsuite>\n");
2776
// Produces a string representing the test properties in a result as space
2777
// delimited XML attributes based on the property key="value" pairs.
2778
internal::String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
2779
const internal::TestResult* result) {
2780
using internal::TestProperty;
2782
const internal::List<TestProperty>& properties = result->test_properties();
2783
for (const internal::ListNode<TestProperty>* property_node =
2785
property_node != NULL;
2786
property_node = property_node->next()) {
2787
const TestProperty& property = property_node->element();
2788
attributes << " " << property.key() << "="
2789
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
2791
return attributes.GetString();
2794
// End XmlUnitTestResultPrinter
2796
namespace internal {
2798
// Class ScopedTrace
2800
// Pushes the given source file location and message onto a per-thread
2801
// trace stack maintained by Google Test.
2802
// L < UnitTest::mutex_
2803
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
2807
trace.message = message.GetString();
2809
UnitTest::GetInstance()->PushGTestTrace(trace);
2812
// Pops the info pushed by the c'tor.
2813
// L < UnitTest::mutex_
2814
ScopedTrace::~ScopedTrace() {
2815
UnitTest::GetInstance()->PopGTestTrace();
2819
// class OsStackTraceGetter
2821
// Returns the current OS stack trace as a String. Parameters:
2823
// max_depth - the maximum number of stack frames to be included
2825
// skip_count - the number of top frames to be skipped; doesn't count
2826
// against max_depth.
2829
// We use "L < mutex_" to denote that the function may acquire mutex_.
2830
String OsStackTraceGetter::CurrentStackTrace(int, int) {
2835
void OsStackTraceGetter::UponLeavingGTest() {
2839
OsStackTraceGetter::kElidedFramesMarker =
2840
"... " GTEST_NAME " internal frames ...";
2842
} // namespace internal
2846
// Gets the singleton UnitTest object. The first time this method is
2847
// called, a UnitTest object is constructed and returned. Consecutive
2848
// calls will return the same object.
2850
// We don't protect this under mutex_ as a user is not supposed to
2851
// call this before main() starts, from which point on the return
2852
// value will never change.
2853
UnitTest * UnitTest::GetInstance() {
2854
// When compiled with MSVC 7.1 in optimized mode, destroying the
2855
// UnitTest object upon exiting the program messes up the exit code,
2856
// causing successful tests to appear failed. We have to use a
2857
// different implementation in this case to bypass the compiler bug.
2858
// This implementation makes the compiler happy, at the cost of
2859
// leaking the UnitTest object.
2860
#if _MSC_VER == 1310 && !defined(_DEBUG) // MSVC 7.1 and optimized build.
2861
static UnitTest* const instance = new UnitTest;
2864
static UnitTest instance;
2866
#endif // _MSC_VER==1310 && !defined(_DEBUG)
2869
// Registers and returns a global test environment. When a test
2870
// program is run, all global test environments will be set-up in the
2871
// order they were registered. After all tests in the program have
2872
// finished, all global test environments will be torn-down in the
2873
// *reverse* order they were registered.
2875
// The UnitTest object takes ownership of the given environment.
2877
// We don't protect this under mutex_, as we only support calling it
2878
// from the main thread.
2879
Environment* UnitTest::AddEnvironment(Environment* env) {
2884
impl_->environments()->PushBack(env);
2885
impl_->environments_in_reverse_order()->PushFront(env);
2889
// Adds a TestPartResult to the current TestResult object. All Google Test
2890
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
2891
// this to report their results. The user code should use the
2892
// assertion macros instead of calling this directly.
2894
void UnitTest::AddTestPartResult(TestPartResultType result_type,
2895
const char* file_name,
2897
const internal::String& message,
2898
const internal::String& os_stack_trace) {
2902
internal::MutexLock lock(&mutex_);
2903
if (impl_->gtest_trace_stack()->size() > 0) {
2904
msg << "\n" << GTEST_NAME << " trace:";
2906
for (internal::ListNode<internal::TraceInfo>* node =
2907
impl_->gtest_trace_stack()->Head();
2909
node = node->next()) {
2910
const internal::TraceInfo& trace = node->element();
2911
msg << "\n" << trace.file << ":" << trace.line << ": " << trace.message;
2915
if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
2916
msg << "\nStack trace:\n" << os_stack_trace;
2919
const TestPartResult result =
2920
TestPartResult(result_type, file_name, line_number,
2921
msg.GetString().c_str());
2922
impl_->test_part_result_reporter()->ReportTestPartResult(result);
2924
// If this is a failure and the user wants the debugger to break on
2926
if (result_type != TPRT_SUCCESS && GTEST_FLAG(break_on_failure)) {
2927
// ... then we generate a seg fault.
2928
*static_cast<int*>(NULL) = 1;
2932
// Creates and adds a property to the current TestResult. If a property matching
2933
// the supplied value already exists, updates its value instead.
2934
void UnitTest::RecordPropertyForCurrentTest(const char* key,
2935
const char* value) {
2936
const internal::TestProperty test_property(key, value);
2937
impl_->current_test_result()->RecordProperty(test_property);
2940
// Runs all tests in this UnitTest object and prints the result.
2941
// Returns 0 if successful, or 1 otherwise.
2943
// We don't protect this under mutex_, as we only support calling it
2944
// from the main thread.
2945
int UnitTest::Run() {
2946
#ifdef GTEST_OS_WINDOWS
2948
#if !defined(_WIN32_WCE)
2949
// SetErrorMode doesn't exist on CE.
2950
if (GTEST_FLAG(catch_exceptions)) {
2951
// The user wants Google Test to catch exceptions thrown by the tests.
2953
// This lets fatal errors be handled by us, instead of causing pop-ups.
2954
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
2955
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
2957
#endif // _WIN32_WCE
2960
return impl_->RunAllTests();
2961
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2962
GetExceptionCode())) {
2963
printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
2969
// We are on Linux or Mac OS. There is no exception of any kind.
2971
return impl_->RunAllTests();
2972
#endif // GTEST_OS_WINDOWS
2975
// Returns the TestCase object for the test that's currently running,
2976
// or NULL if no test is running.
2978
const TestCase* UnitTest::current_test_case() const {
2979
internal::MutexLock lock(&mutex_);
2980
return impl_->current_test_case();
2983
// Returns the TestInfo object for the test that's currently running,
2984
// or NULL if no test is running.
2986
const TestInfo* UnitTest::current_test_info() const {
2987
internal::MutexLock lock(&mutex_);
2988
return impl_->current_test_info();
2991
// Creates an empty UnitTest.
2992
UnitTest::UnitTest() {
2993
impl_ = new internal::UnitTestImpl(this);
2996
// Destructor of UnitTest.
2997
UnitTest::~UnitTest() {
3001
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3002
// Google Test trace stack.
3004
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3005
internal::MutexLock lock(&mutex_);
3006
impl_->gtest_trace_stack()->PushFront(trace);
3009
// Pops a trace from the per-thread Google Test trace stack.
3011
void UnitTest::PopGTestTrace() {
3012
internal::MutexLock lock(&mutex_);
3013
impl_->gtest_trace_stack()->PopFront(NULL);
3016
namespace internal {
3018
UnitTestImpl::UnitTestImpl(UnitTest* parent)
3021
last_death_test_case_(NULL),
3022
current_test_case_(NULL),
3023
current_test_info_(NULL),
3024
ad_hoc_test_result_(),
3025
result_printer_(NULL),
3026
os_stack_trace_getter_(NULL),
3027
#ifdef GTEST_HAS_DEATH_TEST
3029
internal_run_death_test_flag_(NULL),
3030
death_test_factory_(new DefaultDeathTestFactory) {
3033
#endif // GTEST_HAS_DEATH_TEST
3034
// We do the assignment here instead of in the initializer list, as
3035
// doing that latter causes MSVC to issue a warning about using
3036
// 'this' in initializers.
3037
test_part_result_reporter_ = this;
3040
UnitTestImpl::~UnitTestImpl() {
3041
// Deletes every TestCase.
3042
test_cases_.ForEach(internal::Delete<TestCase>);
3044
// Deletes every Environment.
3045
environments_.ForEach(internal::Delete<Environment>);
3047
// Deletes the current test result printer.
3048
delete result_printer_;
3050
delete os_stack_trace_getter_;
3053
// A predicate that checks the name of a TestCase against a known
3056
// This is used for implementation of the UnitTest class only. We put
3057
// it in the anonymous namespace to prevent polluting the outer
3060
// TestCaseNameIs is copyable.
3061
class TestCaseNameIs {
3064
explicit TestCaseNameIs(const String& name)
3067
// Returns true iff the name of test_case matches name_.
3068
bool operator()(const TestCase* test_case) const {
3069
return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3076
// Finds and returns a TestCase with the given name. If one doesn't
3077
// exist, creates one and returns it.
3081
// test_case_name: name of the test case
3082
// set_up_tc: pointer to the function that sets up the test case
3083
// tear_down_tc: pointer to the function that tears down the test case
3084
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3085
Test::SetUpTestCaseFunc set_up_tc,
3086
Test::TearDownTestCaseFunc tear_down_tc) {
3087
// Can we find a TestCase with the given name?
3088
internal::ListNode<TestCase*>* node = test_cases_.FindIf(
3089
TestCaseNameIs(test_case_name));
3092
// No. Let's create one.
3093
TestCase* const test_case =
3094
new TestCase(test_case_name, set_up_tc, tear_down_tc);
3096
// Is this a death test case?
3097
if (String(test_case_name).EndsWith("DeathTest")) {
3098
// Yes. Inserts the test case after the last death test case
3100
node = test_cases_.InsertAfter(last_death_test_case_, test_case);
3101
last_death_test_case_ = node;
3103
// No. Appends to the end of the list.
3104
test_cases_.PushBack(test_case);
3105
node = test_cases_.Last();
3109
// Returns the TestCase found.
3110
return node->element();
3113
// Helpers for setting up / tearing down the given environment. They
3114
// are for use in the List::ForEach() method.
3115
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3116
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3118
// Runs all tests in this UnitTest object, prints the result, and
3119
// returns 0 if all tests are successful, or 1 otherwise. If any
3120
// exception is thrown during a test on Windows, this test is
3121
// considered to be failed, but the rest of the tests will still be
3122
// run. (We disable exceptions on Linux and Mac OS X, so the issue
3123
// doesn't apply there.)
3124
int UnitTestImpl::RunAllTests() {
3125
// True iff Google Test is initialized before RUN_ALL_TESTS() is called.
3126
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
3128
// Lists all the tests and exits if the --gtest_list_tests
3129
// flag was specified.
3130
if (GTEST_FLAG(list_tests)) {
3135
// True iff we are in a subprocess for running a thread-safe-style
3137
bool in_subprocess_for_death_test = false;
3139
#ifdef GTEST_HAS_DEATH_TEST
3140
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
3141
in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3142
#endif // GTEST_HAS_DEATH_TEST
3144
UnitTestEventListenerInterface * const printer = result_printer();
3146
// Compares the full test names with the filter to decide which
3148
const bool has_tests_to_run = FilterTests() > 0;
3149
// True iff at least one test has failed.
3150
bool failed = false;
3152
// How many times to repeat the tests? We don't want to repeat them
3153
// when we are inside the subprocess of a death test.
3154
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3155
// Repeats forever if the repeat count is negative.
3156
const bool forever = repeat < 0;
3157
for (int i = 0; forever || i != repeat; i++) {
3159
printf("\nRepeating all tests (iteration %d) . . .\n\n", i + 1);
3162
// Tells the unit test event listener that the tests are about to
3164
printer->OnUnitTestStart(parent_);
3166
const TimeInMillis start = GetTimeInMillis();
3168
// Runs each test case if there is at least one test to run.
3169
if (has_tests_to_run) {
3170
// Sets up all environments beforehand.
3171
printer->OnGlobalSetUpStart(parent_);
3172
environments_.ForEach(SetUpEnvironment);
3173
printer->OnGlobalSetUpEnd(parent_);
3175
// Runs the tests only if there was no fatal failure during global
3177
if (!Test::HasFatalFailure()) {
3178
test_cases_.ForEach(TestCase::RunTestCase);
3181
// Tears down all environments in reverse order afterwards.
3182
printer->OnGlobalTearDownStart(parent_);
3183
environments_in_reverse_order_.ForEach(TearDownEnvironment);
3184
printer->OnGlobalTearDownEnd(parent_);
3187
elapsed_time_ = GetTimeInMillis() - start;
3189
// Tells the unit test event listener that the tests have just
3191
printer->OnUnitTestEnd(parent_);
3193
// Gets the result and clears it.
3200
if (!gtest_is_initialized_before_run_all_tests) {
3202
COLOR_RED, "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
3203
"This test program did NOT call %s() before calling RUN_ALL_TESTS(). "
3204
"This is INVALID. Soon " GTEST_NAME
3205
" will start to enforce the valid usage. "
3206
"Please fix it ASAP, or IT WILL START TO FAIL.\n",
3207
"testing::ParseGTestFlags"
3211
// Returns 0 if all tests passed, or 1 other wise.
3212
return failed ? 1 : 0;
3215
// Compares the name of each test with the user-specified filter to
3216
// decide whether the test should be run, then records the result in
3217
// each TestCase and TestInfo object.
3218
// Returns the number of tests that should run.
3219
int UnitTestImpl::FilterTests() {
3220
int num_runnable_tests = 0;
3221
for (const internal::ListNode<TestCase *> *test_case_node =
3223
test_case_node != NULL;
3224
test_case_node = test_case_node->next()) {
3225
TestCase * const test_case = test_case_node->element();
3226
const String &test_case_name = test_case->name();
3227
test_case->set_should_run(false);
3229
for (const internal::ListNode<TestInfo *> *test_info_node =
3230
test_case->test_info_list().Head();
3231
test_info_node != NULL;
3232
test_info_node = test_info_node->next()) {
3233
TestInfo * const test_info = test_info_node->element();
3234
const String test_name(test_info->name());
3235
// A test is disabled if test case name or test name matches
3236
// kDisableTestPattern.
3237
const bool is_disabled =
3238
internal::UnitTestOptions::PatternMatchesString(kDisableTestPattern,
3239
test_case_name.c_str()) ||
3240
internal::UnitTestOptions::PatternMatchesString(kDisableTestPattern,
3242
test_info->impl()->set_is_disabled(is_disabled);
3244
const bool should_run = !is_disabled &&
3245
internal::UnitTestOptions::FilterMatchesTest(test_case_name,
3247
test_info->impl()->set_should_run(should_run);
3248
test_case->set_should_run(test_case->should_run() || should_run);
3250
num_runnable_tests++;
3254
return num_runnable_tests;
3257
// Lists all tests by name.
3258
void UnitTestImpl::ListAllTests() {
3259
for (const internal::ListNode<TestCase*>* test_case_node = test_cases_.Head();
3260
test_case_node != NULL;
3261
test_case_node = test_case_node->next()) {
3262
const TestCase* const test_case = test_case_node->element();
3264
// Prints the test case name following by an indented list of test nodes.
3265
printf("%s.\n", test_case->name());
3267
for (const internal::ListNode<TestInfo*>* test_info_node =
3268
test_case->test_info_list().Head();
3269
test_info_node != NULL;
3270
test_info_node = test_info_node->next()) {
3271
const TestInfo* const test_info = test_info_node->element();
3273
printf(" %s\n", test_info->name());
3279
// Sets the unit test result printer.
3281
// Does nothing if the input and the current printer object are the
3282
// same; otherwise, deletes the old printer object and makes the
3283
// input the current printer.
3284
void UnitTestImpl::set_result_printer(
3285
UnitTestEventListenerInterface* result_printer) {
3286
if (result_printer_ != result_printer) {
3287
delete result_printer_;
3288
result_printer_ = result_printer;
3292
// Returns the current unit test result printer if it is not NULL;
3293
// otherwise, creates an appropriate result printer, makes it the
3294
// current printer, and returns it.
3295
UnitTestEventListenerInterface* UnitTestImpl::result_printer() {
3296
if (result_printer_ != NULL) {
3297
return result_printer_;
3300
#ifdef GTEST_HAS_DEATH_TEST
3301
if (internal_run_death_test_flag_.get() != NULL) {
3302
result_printer_ = new NullUnitTestResultPrinter;
3303
return result_printer_;
3305
#endif // GTEST_HAS_DEATH_TEST
3307
UnitTestEventsRepeater *repeater = new UnitTestEventsRepeater;
3308
const String& output_format = internal::UnitTestOptions::GetOutputFormat();
3309
if (output_format == "xml") {
3310
repeater->AddListener(new XmlUnitTestResultPrinter(
3311
internal::UnitTestOptions::GetOutputFile().c_str()));
3312
} else if (output_format != "") {
3313
printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3314
output_format.c_str());
3317
repeater->AddListener(new PrettyUnitTestResultPrinter);
3318
result_printer_ = repeater;
3319
return result_printer_;
3322
// Sets the OS stack trace getter.
3324
// Does nothing if the input and the current OS stack trace getter are
3325
// the same; otherwise, deletes the old getter and makes the input the
3327
void UnitTestImpl::set_os_stack_trace_getter(
3328
OsStackTraceGetterInterface* getter) {
3329
if (os_stack_trace_getter_ != getter) {
3330
delete os_stack_trace_getter_;
3331
os_stack_trace_getter_ = getter;
3335
// Returns the current OS stack trace getter if it is not NULL;
3336
// otherwise, creates an OsStackTraceGetter, makes it the current
3337
// getter, and returns it.
3338
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
3339
if (os_stack_trace_getter_ == NULL) {
3340
os_stack_trace_getter_ = new OsStackTraceGetter;
3343
return os_stack_trace_getter_;
3346
// Returns the TestResult for the test that's currently running, or
3347
// the TestResult for the ad hoc test if no test is running.
3348
internal::TestResult* UnitTestImpl::current_test_result() {
3349
return current_test_info_ ?
3350
current_test_info_->impl()->result() : &ad_hoc_test_result_;
3353
// TestInfoImpl constructor.
3354
TestInfoImpl::TestInfoImpl(TestInfo* parent,
3355
const char* test_case_name,
3357
TypeId fixture_class_id,
3360
test_case_name_(String(test_case_name)),
3361
name_(String(name)),
3362
fixture_class_id_(fixture_class_id),
3364
is_disabled_(false),
3368
// TestInfoImpl destructor.
3369
TestInfoImpl::~TestInfoImpl() {
3372
} // namespace internal
3374
namespace internal {
3376
// Parses a string as a command line flag. The string should have
3377
// the format "--flag=value". When def_optional is true, the "=value"
3378
// part can be omitted.
3380
// Returns the value of the flag, or NULL if the parsing failed.
3381
const char* ParseFlagValue(const char* str,
3383
bool def_optional) {
3384
// str and flag must not be NULL.
3385
if (str == NULL || flag == NULL) return NULL;
3387
// The flag must start with "--" followed by GTEST_FLAG_PREFIX.
3388
const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX, flag);
3389
const size_t flag_len = flag_str.GetLength();
3390
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
3392
// Skips the flag name.
3393
const char* flag_end = str + flag_len;
3395
// When def_optional is true, it's OK to not have a "=value" part.
3396
if (def_optional && (flag_end[0] == '\0')) {
3400
// If def_optional is true and there are more characters after the
3401
// flag name, or if def_optional is false, there must be a '=' after
3403
if (flag_end[0] != '=') return NULL;
3405
// Returns the string after "=".
3406
return flag_end + 1;
3409
// Parses a string for a bool flag, in the form of either
3410
// "--flag=value" or "--flag".
3412
// In the former case, the value is taken as true as long as it does
3413
// not start with '0', 'f', or 'F'.
3415
// In the latter case, the value is taken as true.
3417
// On success, stores the value of the flag in *value, and returns
3418
// true. On failure, returns false without changing *value.
3419
bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
3420
// Gets the value of the flag as a string.
3421
const char* const value_str = ParseFlagValue(str, flag, true);
3423
// Aborts if the parsing failed.
3424
if (value_str == NULL) return false;
3426
// Converts the string value to a bool.
3427
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
3431
// Parses a string for an Int32 flag, in the form of
3434
// On success, stores the value of the flag in *value, and returns
3435
// true. On failure, returns false without changing *value.
3436
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
3437
// Gets the value of the flag as a string.
3438
const char* const value_str = ParseFlagValue(str, flag, false);
3440
// Aborts if the parsing failed.
3441
if (value_str == NULL) return false;
3443
// Sets *value to the value of the flag.
3444
return ParseInt32(Message() << "The value of flag --" << flag,
3448
// Parses a string for a string flag, in the form of
3451
// On success, stores the value of the flag in *value, and returns
3452
// true. On failure, returns false without changing *value.
3453
bool ParseStringFlag(const char* str, const char* flag, String* value) {
3454
// Gets the value of the flag as a string.
3455
const char* const value_str = ParseFlagValue(str, flag, false);
3457
// Aborts if the parsing failed.
3458
if (value_str == NULL) return false;
3460
// Sets *value to the value of the flag.
3465
// The internal implementation of ParseGTestFlags().
3467
// The type parameter CharType can be instantiated to either char or
3469
template <typename CharType>
3470
void ParseGTestFlagsImpl(int* argc, CharType** argv) {
3471
g_parse_gtest_flags_called = true;
3472
if (*argc <= 0) return;
3474
#ifdef GTEST_HAS_DEATH_TEST
3476
for (int i = 0; i != *argc; i++) {
3477
g_argvs.push_back(StreamableToString(argv[i]));
3479
#endif // GTEST_HAS_DEATH_TEST
3481
for (int i = 1; i != *argc; i++) {
3482
const String arg_string = StreamableToString(argv[i]);
3483
const char* const arg = arg_string.c_str();
3485
using internal::ParseBoolFlag;
3486
using internal::ParseInt32Flag;
3487
using internal::ParseStringFlag;
3489
// Do we see a Google Test flag?
3490
if (ParseBoolFlag(arg, kBreakOnFailureFlag,
3491
>EST_FLAG(break_on_failure)) ||
3492
ParseBoolFlag(arg, kCatchExceptionsFlag,
3493
>EST_FLAG(catch_exceptions)) ||
3494
ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
3495
ParseStringFlag(arg, kDeathTestStyleFlag,
3496
>EST_FLAG(death_test_style)) ||
3497
ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
3498
ParseStringFlag(arg, kInternalRunDeathTestFlag,
3499
>EST_FLAG(internal_run_death_test)) ||
3500
ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
3501
ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
3502
ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat))
3504
// Yes. Shift the remainder of the argv list left by one. Note
3505
// that argv has (*argc + 1) elements, the last one always being
3506
// NULL. The following loop moves the trailing NULL element as
3508
for (int j = i; j != *argc; j++) {
3509
argv[j] = argv[j + 1];
3512
// Decrements the argument count.
3515
// We also need to decrement the iterator as we just removed
3522
} // namespace internal
3524
// Parses a command line for the flags that Google Test recognizes.
3525
// Whenever a Google Test flag is seen, it is removed from argv, and *argc
3528
// No value is returned. Instead, the Google Test flag variables are
3530
void ParseGTestFlags(int* argc, char** argv) {
3531
internal::g_executable_path = argv[0];
3532
internal::ParseGTestFlagsImpl(argc, argv);
3535
// This overloaded version can be used in Windows programs compiled in
3537
#ifdef GTEST_OS_WINDOWS
3538
void ParseGTestFlags(int* argc, wchar_t** argv) {
3539
// g_executable_path uses normal characters rather than wide chars, so call
3540
// StreamableToString to convert argv[0] to normal characters (utf8 encoding).
3541
internal::g_executable_path = internal::StreamableToString(argv[0]);
3542
internal::ParseGTestFlagsImpl(argc, argv);
3544
#endif // GTEST_OS_WINDOWS
3546
} // namespace testing