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>
49
// TODO(kenton@google.com): Use autoconf to detect availability of
51
#define GTEST_HAS_GETTIMEOFDAY_ 1
56
// Declares vsnprintf(). This header is not available on Windows.
64
#elif GTEST_OS_SYMBIAN
65
#define GTEST_HAS_GETTIMEOFDAY_ 1
66
#include <sys/time.h> // NOLINT
69
#define GTEST_HAS_GETTIMEOFDAY_ 1
70
#include <sys/time.h> // NOLINT
72
// On z/OS we additionally need strings.h for strcasecmp.
73
#include <strings.h> // NOLINT
75
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
77
#include <windows.h> // NOLINT
79
#elif GTEST_OS_WINDOWS // We are on Windows proper.
81
#include <io.h> // NOLINT
82
#include <sys/timeb.h> // NOLINT
83
#include <sys/types.h> // NOLINT
84
#include <sys/stat.h> // NOLINT
86
#if GTEST_OS_WINDOWS_MINGW
87
// MinGW has gettimeofday() but not _ftime64().
88
// TODO(kenton@google.com): Use autoconf to detect availability of
90
// TODO(kenton@google.com): There are other ways to get the time on
91
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
92
// supports these. consider using them instead.
93
#define GTEST_HAS_GETTIMEOFDAY_ 1
94
#include <sys/time.h> // NOLINT
95
#endif // GTEST_OS_WINDOWS_MINGW
97
// cpplint thinks that the header is already included, so we want to
99
#include <windows.h> // NOLINT
103
// Assume other platforms have gettimeofday().
104
// TODO(kenton@google.com): Use autoconf to detect availability of
106
#define GTEST_HAS_GETTIMEOFDAY_ 1
108
// cpplint thinks that the header is already included, so we want to
110
#include <sys/time.h> // NOLINT
111
#include <unistd.h> // NOLINT
113
#endif // GTEST_OS_LINUX
115
#if GTEST_HAS_EXCEPTIONS
119
// Indicates that this translation unit is part of Google Test's
120
// implementation. It must come before gtest-internal-inl.h is
121
// included, or there will be a compiler error. This trick is to
122
// prevent a user from accidentally including gtest-internal-inl.h in
124
#define GTEST_IMPLEMENTATION_ 1
125
#include "src/gtest-internal-inl.h"
126
#undef GTEST_IMPLEMENTATION_
129
#define vsnprintf _vsnprintf
130
#endif // GTEST_OS_WINDOWS
136
// A test whose test case name or test name matches this filter is
137
// disabled and not run.
138
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
140
// A test case whose name matches this filter is considered a death
141
// test case and will be run before test cases whose name doesn't
142
// match this filter.
143
static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
145
// A test filter that matches everything.
146
static const char kUniversalFilter[] = "*";
148
// The default output file for XML output.
149
static const char kDefaultOutputFile[] = "test_detail.xml";
151
// The environment variable name for the test shard index.
152
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
153
// The environment variable name for the total number of test shards.
154
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
155
// The environment variable name for the test shard status file.
156
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
160
// The text used in failure messages to indicate the start of the
162
const char kStackTraceMarker[] = "\nStack trace:\n";
164
} // namespace internal
167
also_run_disabled_tests,
168
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
169
"Run disabled tests too, in addition to the tests normally being run.");
173
internal::BoolFromGTestEnv("break_on_failure", false),
174
"True iff a failed assertion should be a debugger break-point.");
178
internal::BoolFromGTestEnv("catch_exceptions", false),
179
"True iff " GTEST_NAME_
180
" should catch exceptions and treat them as test failures.");
182
GTEST_DEFINE_string_(
184
internal::StringFromGTestEnv("color", "auto"),
185
"Whether to use colors in the output. Valid values: yes, no, "
186
"and auto. 'auto' means to use colors if the output is "
187
"being sent to a terminal and the TERM environment variable "
188
"is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
190
GTEST_DEFINE_string_(
192
internal::StringFromGTestEnv("filter", kUniversalFilter),
193
"A colon-separated list of glob (not regex) patterns "
194
"for filtering the tests to run, optionally followed by a "
195
"'-' and a : separated list of negative patterns (tests to "
196
"exclude). A test is run if it matches one of the positive "
197
"patterns and does not match any of the negative patterns.");
199
GTEST_DEFINE_bool_(list_tests, false,
200
"List all tests without running them.");
202
GTEST_DEFINE_string_(
204
internal::StringFromGTestEnv("output", ""),
205
"A format (currently must be \"xml\"), optionally followed "
206
"by a colon and an output file name or directory. A directory "
207
"is indicated by a trailing pathname separator. "
208
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
209
"If a directory is specified, output files will be created "
210
"within that directory, with file-names based on the test "
211
"executable's name and, if necessary, made unique by adding "
216
internal::BoolFromGTestEnv("print_time", true),
217
"True iff " GTEST_NAME_
218
" should display elapsed time in text output.");
222
internal::Int32FromGTestEnv("random_seed", 0),
223
"Random number seed to use when shuffling test orders. Must be in range "
224
"[1, 99999], or 0 to use a seed based on the current time.");
228
internal::Int32FromGTestEnv("repeat", 1),
229
"How many times to repeat each test. Specify a negative number "
230
"for repeating forever. Useful for shaking out flaky tests.");
233
show_internal_stack_frames, false,
234
"True iff " GTEST_NAME_ " should include internal stack frames when "
235
"printing test failure stack traces.");
239
internal::BoolFromGTestEnv("shuffle", false),
240
"True iff " GTEST_NAME_
241
" should randomize tests' order on every run.");
245
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
246
"The maximum number of stack frames to print when an "
247
"assertion fails. The valid range is 0 through 100, inclusive.");
251
internal::BoolFromGTestEnv("throw_on_failure", false),
252
"When this flag is specified, a failed assertion will throw an exception "
253
"if exceptions are enabled or exit the program with a non-zero code "
258
// Generates a random number from [0, range), using a Linear
259
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
261
UInt32 Random::Generate(UInt32 range) {
262
// These constants are the same as are used in glibc's rand(3).
263
state_ = (1103515245U*state_ + 12345U) % kMaxRange;
265
GTEST_CHECK_(range > 0)
266
<< "Cannot generate a number in the range [0, 0).";
267
GTEST_CHECK_(range <= kMaxRange)
268
<< "Generation of a number in [0, " << range << ") was requested, "
269
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
271
// Converting via modulus introduces a bit of downward bias, but
272
// it's simple, and a linear congruential generator isn't too good
274
return state_ % range;
277
// g_help_flag is true iff the --help flag or an equivalent form is
278
// specified on the command line.
279
static bool g_help_flag = false;
281
// GTestIsInitialized() returns true iff the user has initialized
282
// Google Test. Useful for catching the user mistake of not initializing
283
// Google Test before calling RUN_ALL_TESTS().
285
// A user must call testing::InitGoogleTest() to initialize Google
286
// Test. g_init_gtest_count is set to the number of times
287
// InitGoogleTest() has been called. We don't protect this variable
288
// under a mutex as it is only accessed in the main thread.
289
int g_init_gtest_count = 0;
290
static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
292
// Iterates over a vector of TestCases, keeping a running sum of the
293
// results of calling a given int-returning method on each.
295
static int SumOverTestCaseList(const internal::Vector<TestCase*>& case_list,
296
int (TestCase::*method)() const) {
298
for (int i = 0; i < case_list.size(); i++) {
299
sum += (case_list.GetElement(i)->*method)();
304
// Returns true iff the test case passed.
305
static bool TestCasePassed(const TestCase* test_case) {
306
return test_case->should_run() && test_case->Passed();
309
// Returns true iff the test case failed.
310
static bool TestCaseFailed(const TestCase* test_case) {
311
return test_case->should_run() && test_case->Failed();
314
// Returns true iff test_case contains at least one test that should
316
static bool ShouldRunTestCase(const TestCase* test_case) {
317
return test_case->should_run();
320
// AssertHelper constructor.
321
AssertHelper::AssertHelper(TestPartResult::Type type,
325
: data_(new AssertHelperData(type, file, line, message)) {
328
AssertHelper::~AssertHelper() {
332
// Message assignment, for assertion streaming support.
333
void AssertHelper::operator=(const Message& message) const {
334
UnitTest::GetInstance()->
335
AddTestPartResult(data_->type, data_->file, data_->line,
336
AppendUserMessage(data_->message, message),
337
UnitTest::GetInstance()->impl()
338
->CurrentOsStackTraceExceptTop(1)
339
// Skips the stack frame for this function itself.
343
// Mutex for linked pointers.
344
Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
346
// Application pathname gotten in InitGoogleTest.
347
String g_executable_path;
349
// Returns the current application's name, removing directory path if that
351
FilePath GetCurrentExecutableName() {
355
result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
357
result.Set(FilePath(g_executable_path));
358
#endif // GTEST_OS_WINDOWS
360
return result.RemoveDirectoryName();
363
// Functions for processing the gtest_output flag.
365
// Returns the output format, or "" for normal printed output.
366
String UnitTestOptions::GetOutputFormat() {
367
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
368
if (gtest_output_flag == NULL) return String("");
370
const char* const colon = strchr(gtest_output_flag, ':');
371
return (colon == NULL) ?
372
String(gtest_output_flag) :
373
String(gtest_output_flag, colon - gtest_output_flag);
376
// Returns the name of the requested output file, or the default if none
377
// was explicitly specified.
378
String UnitTestOptions::GetAbsolutePathToOutputFile() {
379
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
380
if (gtest_output_flag == NULL)
383
const char* const colon = strchr(gtest_output_flag, ':');
385
return String(internal::FilePath::ConcatPaths(
387
UnitTest::GetInstance()->original_working_dir()),
388
internal::FilePath(kDefaultOutputFile)).ToString() );
390
internal::FilePath output_name(colon + 1);
391
if (!output_name.IsAbsolutePath())
392
// TODO(wan@google.com): on Windows \some\path is not an absolute
393
// path (as its meaning depends on the current drive), yet the
394
// following logic for turning it into an absolute path is wrong.
396
output_name = internal::FilePath::ConcatPaths(
397
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
398
internal::FilePath(colon + 1));
400
if (!output_name.IsDirectory())
401
return output_name.ToString();
403
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
404
output_name, internal::GetCurrentExecutableName(),
405
GetOutputFormat().c_str()));
406
return result.ToString();
409
// Returns true iff the wildcard pattern matches the string. The
410
// first ':' or '\0' character in pattern marks the end of it.
412
// This recursive algorithm isn't very efficient, but is clear and
413
// works well enough for matching test names, which are short.
414
bool UnitTestOptions::PatternMatchesString(const char *pattern,
418
case ':': // Either ':' or '\0' marks the end of the pattern.
420
case '?': // Matches any single character.
421
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
422
case '*': // Matches any string (possibly empty) of characters.
423
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
424
PatternMatchesString(pattern + 1, str);
425
default: // Non-special character. Matches itself.
426
return *pattern == *str &&
427
PatternMatchesString(pattern + 1, str + 1);
431
bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
432
const char *cur_pattern = filter;
434
if (PatternMatchesString(cur_pattern, name.c_str())) {
438
// Finds the next pattern in the filter.
439
cur_pattern = strchr(cur_pattern, ':');
441
// Returns if no more pattern can be found.
442
if (cur_pattern == NULL) {
446
// Skips the pattern separater (the ':' character).
451
// TODO(keithray): move String function implementations to gtest-string.cc.
453
// Returns true iff the user-specified filter matches the test case
454
// name and the test name.
455
bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
456
const String &test_name) {
457
const String& full_name = String::Format("%s.%s",
458
test_case_name.c_str(),
461
// Split --gtest_filter at '-', if there is one, to separate into
462
// positive filter and negative filter portions
463
const char* const p = GTEST_FLAG(filter).c_str();
464
const char* const dash = strchr(p, '-');
468
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
469
negative = String("");
471
positive = String(p, dash - p); // Everything up to the dash
472
negative = String(dash+1); // Everything after the dash
473
if (positive.empty()) {
474
// Treat '-test1' as the same as '*-test1'
475
positive = kUniversalFilter;
479
// A filter is a colon-separated list of patterns. It matches a
480
// test if any pattern in it matches the test.
481
return (MatchesFilter(full_name, positive.c_str()) &&
482
!MatchesFilter(full_name, negative.c_str()));
486
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
487
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
488
// This function is useful as an __except condition.
489
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
490
// Google Test should handle an exception if:
491
// 1. the user wants it to, AND
492
// 2. this is not a breakpoint exception.
493
return (GTEST_FLAG(catch_exceptions) &&
494
exception_code != EXCEPTION_BREAKPOINT) ?
495
EXCEPTION_EXECUTE_HANDLER :
496
EXCEPTION_CONTINUE_SEARCH;
498
#endif // GTEST_OS_WINDOWS
500
} // namespace internal
502
// The c'tor sets this object as the test part result reporter used by
503
// Google Test. The 'result' parameter specifies where to report the
504
// results. Intercepts only failures from the current thread.
505
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
506
TestPartResultArray* result)
507
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
512
// The c'tor sets this object as the test part result reporter used by
513
// Google Test. The 'result' parameter specifies where to report the
515
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
516
InterceptMode intercept_mode, TestPartResultArray* result)
517
: intercept_mode_(intercept_mode),
522
void ScopedFakeTestPartResultReporter::Init() {
523
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
524
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
525
old_reporter_ = impl->GetGlobalTestPartResultReporter();
526
impl->SetGlobalTestPartResultReporter(this);
528
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
529
impl->SetTestPartResultReporterForCurrentThread(this);
533
// The d'tor restores the test part result reporter used by Google Test
535
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
536
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
537
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
538
impl->SetGlobalTestPartResultReporter(old_reporter_);
540
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
544
// Increments the test part result count and remembers the result.
545
// This method is from the TestPartResultReporterInterface interface.
546
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
547
const TestPartResult& result) {
548
result_->Append(result);
553
// Returns the type ID of ::testing::Test. We should always call this
554
// instead of GetTypeId< ::testing::Test>() to get the type ID of
555
// testing::Test. This is to work around a suspected linker bug when
556
// using Google Test as a framework on Mac OS X. The bug causes
557
// GetTypeId< ::testing::Test>() to return different values depending
558
// on whether the call is from the Google Test framework itself or
559
// from user test code. GetTestTypeId() is guaranteed to always
560
// return the same value, as it always calls GetTypeId<>() from the
561
// gtest.cc, which is within the Google Test framework.
562
TypeId GetTestTypeId() {
563
return GetTypeId<Test>();
566
// The value of GetTestTypeId() as seen from within the Google Test
567
// library. This is solely for testing GetTestTypeId().
568
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
570
// This predicate-formatter checks that 'results' contains a test part
571
// failure of the given type and that the failure message contains the
573
AssertionResult HasOneFailure(const char* /* results_expr */,
574
const char* /* type_expr */,
575
const char* /* substr_expr */,
576
const TestPartResultArray& results,
577
TestPartResult::Type type,
578
const char* substr) {
579
const String expected(type == TestPartResult::kFatalFailure ?
581
"1 non-fatal failure");
583
if (results.size() != 1) {
584
msg << "Expected: " << expected << "\n"
585
<< " Actual: " << results.size() << " failures";
586
for (int i = 0; i < results.size(); i++) {
587
msg << "\n" << results.GetTestPartResult(i);
589
return AssertionFailure(msg);
592
const TestPartResult& r = results.GetTestPartResult(0);
593
if (r.type() != type) {
594
msg << "Expected: " << expected << "\n"
597
return AssertionFailure(msg);
600
if (strstr(r.message(), substr) == NULL) {
601
msg << "Expected: " << expected << " containing \""
605
return AssertionFailure(msg);
608
return AssertionSuccess();
611
// The constructor of SingleFailureChecker remembers where to look up
612
// test part results, what type of failure we expect, and what
613
// substring the failure message should contain.
614
SingleFailureChecker:: SingleFailureChecker(
615
const TestPartResultArray* results,
616
TestPartResult::Type type,
622
// The destructor of SingleFailureChecker verifies that the given
623
// TestPartResultArray contains exactly one failure that has the given
624
// type and contains the given substring. If that's not the case, a
625
// non-fatal failure will be generated.
626
SingleFailureChecker::~SingleFailureChecker() {
627
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
630
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
631
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
633
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
634
const TestPartResult& result) {
635
unit_test_->current_test_result()->AddTestPartResult(result);
636
unit_test_->listeners()->repeater()->OnTestPartResult(result);
639
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
640
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
642
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
643
const TestPartResult& result) {
644
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
647
// Returns the global test part result reporter.
648
TestPartResultReporterInterface*
649
UnitTestImpl::GetGlobalTestPartResultReporter() {
650
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
651
return global_test_part_result_repoter_;
654
// Sets the global test part result reporter.
655
void UnitTestImpl::SetGlobalTestPartResultReporter(
656
TestPartResultReporterInterface* reporter) {
657
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
658
global_test_part_result_repoter_ = reporter;
661
// Returns the test part result reporter for the current thread.
662
TestPartResultReporterInterface*
663
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
664
return per_thread_test_part_result_reporter_.get();
667
// Sets the test part result reporter for the current thread.
668
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
669
TestPartResultReporterInterface* reporter) {
670
per_thread_test_part_result_reporter_.set(reporter);
673
// Gets the number of successful test cases.
674
int UnitTestImpl::successful_test_case_count() const {
675
return test_cases_.CountIf(TestCasePassed);
678
// Gets the number of failed test cases.
679
int UnitTestImpl::failed_test_case_count() const {
680
return test_cases_.CountIf(TestCaseFailed);
683
// Gets the number of all test cases.
684
int UnitTestImpl::total_test_case_count() const {
685
return test_cases_.size();
688
// Gets the number of all test cases that contain at least one test
690
int UnitTestImpl::test_case_to_run_count() const {
691
return test_cases_.CountIf(ShouldRunTestCase);
694
// Gets the number of successful tests.
695
int UnitTestImpl::successful_test_count() const {
696
return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
699
// Gets the number of failed tests.
700
int UnitTestImpl::failed_test_count() const {
701
return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
704
// Gets the number of disabled tests.
705
int UnitTestImpl::disabled_test_count() const {
706
return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
709
// Gets the number of all tests.
710
int UnitTestImpl::total_test_count() const {
711
return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
714
// Gets the number of tests that should run.
715
int UnitTestImpl::test_to_run_count() const {
716
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
719
// Returns the current OS stack trace as a String.
721
// The maximum number of stack frames to be included is specified by
722
// the gtest_stack_trace_depth flag. The skip_count parameter
723
// specifies the number of top frames to be skipped, which doesn't
724
// count against the number of frames to be included.
726
// For example, if Foo() calls Bar(), which in turn calls
727
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
728
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
729
String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
734
// Returns the current time in milliseconds.
735
TimeInMillis GetTimeInMillis() {
736
#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
737
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
738
// http://analogous.blogspot.com/2005/04/epoch.html
739
const TimeInMillis kJavaEpochToWinFileTimeDelta =
740
static_cast<TimeInMillis>(116444736UL) * 100000UL;
741
const DWORD kTenthMicrosInMilliSecond = 10000;
743
SYSTEMTIME now_systime;
744
FILETIME now_filetime;
745
ULARGE_INTEGER now_int64;
746
// TODO(kenton@google.com): Shouldn't this just use
747
// GetSystemTimeAsFileTime()?
748
GetSystemTime(&now_systime);
749
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
750
now_int64.LowPart = now_filetime.dwLowDateTime;
751
now_int64.HighPart = now_filetime.dwHighDateTime;
752
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
753
kJavaEpochToWinFileTimeDelta;
754
return now_int64.QuadPart;
757
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
760
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
761
// (deprecated function) there.
762
// TODO(kenton@google.com): Use GetTickCount()? Or use
763
// SystemTimeToFileTime()
764
#pragma warning(push) // Saves the current warning state.
765
#pragma warning(disable:4996) // Temporarily disables warning 4996.
767
#pragma warning(pop) // Restores the warning state.
771
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
772
#elif GTEST_HAS_GETTIMEOFDAY_
774
gettimeofday(&now, NULL);
775
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
777
#error "Don't know how to get the current time on your system."
785
// Returns the input enclosed in double quotes if it's not NULL;
786
// otherwise returns "(null)". For example, "\"Hello\"" is returned
787
// for input "Hello".
789
// This is useful for printing a C string in the syntax of a literal.
791
// Known issue: escape sequences are not handled yet.
792
String String::ShowCStringQuoted(const char* c_str) {
793
return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
796
// Copies at most length characters from str into a newly-allocated
797
// piece of memory of size length+1. The memory is allocated with new[].
798
// A terminating null byte is written to the memory, and a pointer to it
799
// is returned. If str is NULL, NULL is returned.
800
static char* CloneString(const char* str, size_t length) {
804
char* const clone = new char[length + 1];
805
posix::StrNCpy(clone, str, length);
806
clone[length] = '\0';
811
// Clones a 0-terminated C string, allocating memory using new. The
812
// caller is responsible for deleting[] the return value. Returns the
813
// cloned string, or NULL if the input is NULL.
814
const char * String::CloneCString(const char* c_str) {
815
return (c_str == NULL) ?
816
NULL : CloneString(c_str, strlen(c_str));
819
#if GTEST_OS_WINDOWS_MOBILE
820
// Creates a UTF-16 wide string from the given ANSI string, allocating
821
// memory using new. The caller is responsible for deleting the return
822
// value using delete[]. Returns the wide string, or NULL if the
824
LPCWSTR String::AnsiToUtf16(const char* ansi) {
825
if (!ansi) return NULL;
826
const int length = strlen(ansi);
827
const int unicode_length =
828
MultiByteToWideChar(CP_ACP, 0, ansi, length,
830
WCHAR* unicode = new WCHAR[unicode_length + 1];
831
MultiByteToWideChar(CP_ACP, 0, ansi, length,
832
unicode, unicode_length);
833
unicode[unicode_length] = 0;
837
// Creates an ANSI string from the given wide string, allocating
838
// memory using new. The caller is responsible for deleting the return
839
// value using delete[]. Returns the ANSI string, or NULL if the
841
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
842
if (!utf16_str) return NULL;
843
const int ansi_length =
844
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
845
NULL, 0, NULL, NULL);
846
char* ansi = new char[ansi_length + 1];
847
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
848
ansi, ansi_length, NULL, NULL);
849
ansi[ansi_length] = 0;
853
#endif // GTEST_OS_WINDOWS_MOBILE
855
// Compares two C strings. Returns true iff they have the same content.
857
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
858
// C string is considered different to any non-NULL C string,
859
// including the empty string.
860
bool String::CStringEquals(const char * lhs, const char * rhs) {
861
if ( lhs == NULL ) return rhs == NULL;
863
if ( rhs == NULL ) return false;
865
return strcmp(lhs, rhs) == 0;
868
#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
870
// Converts an array of wide chars to a narrow string using the UTF-8
871
// encoding, and streams the result to the given Message object.
872
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
874
// TODO(wan): consider allowing a testing::String object to
875
// contain '\0'. This will make it behave more like std::string,
876
// and will allow ToUtf8String() to return the correct encoding
877
// for '\0' s.t. we can get rid of the conditional here (and in
878
// several other places).
879
for (size_t i = 0; i != length; ) { // NOLINT
880
if (wstr[i] != L'\0') {
881
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
882
while (i != length && wstr[i] != L'\0')
891
#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
893
} // namespace internal
895
#if GTEST_HAS_STD_WSTRING
896
// Converts the given wide string to a narrow string using the UTF-8
897
// encoding, and streams the result to this Message object.
898
Message& Message::operator <<(const ::std::wstring& wstr) {
899
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
902
#endif // GTEST_HAS_STD_WSTRING
904
#if GTEST_HAS_GLOBAL_WSTRING
905
// Converts the given wide string to a narrow string using the UTF-8
906
// encoding, and streams the result to this Message object.
907
Message& Message::operator <<(const ::wstring& wstr) {
908
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
911
#endif // GTEST_HAS_GLOBAL_WSTRING
915
// Formats a value to be used in a failure message.
917
// For a char value, we print it as a C++ char literal and as an
918
// unsigned integer (both in decimal and in hexadecimal).
919
String FormatForFailureMessage(char ch) {
920
const unsigned int ch_as_uint = ch;
921
// A String object cannot contain '\0', so we print "\\0" when ch is
923
return String::Format("'%s' (%u, 0x%X)",
924
ch ? String::Format("%c", ch).c_str() : "\\0",
925
ch_as_uint, ch_as_uint);
928
// For a wchar_t value, we print it as a C++ wchar_t literal and as an
929
// unsigned integer (both in decimal and in hexidecimal).
930
String FormatForFailureMessage(wchar_t wchar) {
931
// The C++ standard doesn't specify the exact size of the wchar_t
932
// type. It just says that it shall have the same size as another
933
// integral type, called its underlying type.
935
// Therefore, in order to print a wchar_t value in the numeric form,
936
// we first convert it to the largest integral type (UInt64) and
937
// then print the converted value.
939
// We use streaming to print the value as "%llu" doesn't work
940
// correctly with MSVC 7.1.
941
const UInt64 wchar_as_uint64 = wchar;
943
// A String object cannot contain '\0', so we print "\\0" when wchar is
945
char buffer[32]; // CodePointToUtf8 requires a buffer that big.
947
<< (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
948
<< "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
949
<< wchar_as_uint64 << ")";
950
return msg.GetString();
953
} // namespace internal
955
// AssertionResult constructor.
956
AssertionResult::AssertionResult(const internal::String& failure_message)
957
: failure_message_(failure_message) {
961
// Makes a successful assertion result.
962
AssertionResult AssertionSuccess() {
963
return AssertionResult();
967
// Makes a failed assertion result with the given failure message.
968
AssertionResult AssertionFailure(const Message& message) {
969
return AssertionResult(message.GetString());
974
// Constructs and returns the message for an equality assertion
975
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
977
// The first four parameters are the expressions used in the assertion
978
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
979
// where foo is 5 and bar is 6, we have:
981
// expected_expression: "foo"
982
// actual_expression: "bar"
983
// expected_value: "5"
986
// The ignoring_case parameter is true iff the assertion is a
987
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
988
// be inserted into the message.
989
AssertionResult EqFailure(const char* expected_expression,
990
const char* actual_expression,
991
const String& expected_value,
992
const String& actual_value,
993
bool ignoring_case) {
995
msg << "Value of: " << actual_expression;
996
if (actual_value != actual_expression) {
997
msg << "\n Actual: " << actual_value;
1000
msg << "\nExpected: " << expected_expression;
1001
if (ignoring_case) {
1002
msg << " (ignoring case)";
1004
if (expected_value != expected_expression) {
1005
msg << "\nWhich is: " << expected_value;
1008
return AssertionFailure(msg);
1012
// Helper function for implementing ASSERT_NEAR.
1013
AssertionResult DoubleNearPredFormat(const char* expr1,
1015
const char* abs_error_expr,
1019
const double diff = fabs(val1 - val2);
1020
if (diff <= abs_error) return AssertionSuccess();
1022
// TODO(wan): do not print the value of an expression if it's
1023
// already a literal.
1025
msg << "The difference between " << expr1 << " and " << expr2
1026
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1027
<< expr1 << " evaluates to " << val1 << ",\n"
1028
<< expr2 << " evaluates to " << val2 << ", and\n"
1029
<< abs_error_expr << " evaluates to " << abs_error << ".";
1030
return AssertionFailure(msg);
1034
// Helper template for implementing FloatLE() and DoubleLE().
1035
template <typename RawType>
1036
AssertionResult FloatingPointLE(const char* expr1,
1040
// Returns success if val1 is less than val2,
1042
return AssertionSuccess();
1045
// or if val1 is almost equal to val2.
1046
const FloatingPoint<RawType> lhs(val1), rhs(val2);
1047
if (lhs.AlmostEquals(rhs)) {
1048
return AssertionSuccess();
1051
// Note that the above two checks will both fail if either val1 or
1052
// val2 is NaN, as the IEEE floating-point standard requires that
1053
// any predicate involving a NaN must return false.
1056
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1060
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1064
msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1065
<< " Actual: " << StrStreamToString(&val1_ss) << " vs "
1066
<< StrStreamToString(&val2_ss);
1068
return AssertionFailure(msg);
1071
} // namespace internal
1073
// Asserts that val1 is less than, or almost equal to, val2. Fails
1074
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1075
AssertionResult FloatLE(const char* expr1, const char* expr2,
1076
float val1, float val2) {
1077
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1080
// Asserts that val1 is less than, or almost equal to, val2. Fails
1081
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1082
AssertionResult DoubleLE(const char* expr1, const char* expr2,
1083
double val1, double val2) {
1084
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1087
namespace internal {
1089
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1091
AssertionResult CmpHelperEQ(const char* expected_expression,
1092
const char* actual_expression,
1093
BiggestInt expected,
1094
BiggestInt actual) {
1095
if (expected == actual) {
1096
return AssertionSuccess();
1099
return EqFailure(expected_expression,
1101
FormatForComparisonFailureMessage(expected, actual),
1102
FormatForComparisonFailureMessage(actual, expected),
1106
// A macro for implementing the helper functions needed to implement
1107
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1108
// just to avoid copy-and-paste of similar code.
1109
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1110
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1111
BiggestInt val1, BiggestInt val2) {\
1112
if (val1 op val2) {\
1113
return AssertionSuccess();\
1116
msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1117
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1118
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
1119
return AssertionFailure(msg);\
1123
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1125
GTEST_IMPL_CMP_HELPER_(NE, !=)
1126
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1128
GTEST_IMPL_CMP_HELPER_(LE, <=)
1129
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1131
GTEST_IMPL_CMP_HELPER_(LT, < )
1132
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1134
GTEST_IMPL_CMP_HELPER_(GE, >=)
1135
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1137
GTEST_IMPL_CMP_HELPER_(GT, > )
1139
#undef GTEST_IMPL_CMP_HELPER_
1141
// The helper function for {ASSERT|EXPECT}_STREQ.
1142
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1143
const char* actual_expression,
1144
const char* expected,
1145
const char* actual) {
1146
if (String::CStringEquals(expected, actual)) {
1147
return AssertionSuccess();
1150
return EqFailure(expected_expression,
1152
String::ShowCStringQuoted(expected),
1153
String::ShowCStringQuoted(actual),
1157
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1158
AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1159
const char* actual_expression,
1160
const char* expected,
1161
const char* actual) {
1162
if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1163
return AssertionSuccess();
1166
return EqFailure(expected_expression,
1168
String::ShowCStringQuoted(expected),
1169
String::ShowCStringQuoted(actual),
1173
// The helper function for {ASSERT|EXPECT}_STRNE.
1174
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1175
const char* s2_expression,
1178
if (!String::CStringEquals(s1, s2)) {
1179
return AssertionSuccess();
1182
msg << "Expected: (" << s1_expression << ") != ("
1183
<< s2_expression << "), actual: \""
1184
<< s1 << "\" vs \"" << s2 << "\"";
1185
return AssertionFailure(msg);
1189
// The helper function for {ASSERT|EXPECT}_STRCASENE.
1190
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1191
const char* s2_expression,
1194
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1195
return AssertionSuccess();
1198
msg << "Expected: (" << s1_expression << ") != ("
1199
<< s2_expression << ") (ignoring case), actual: \""
1200
<< s1 << "\" vs \"" << s2 << "\"";
1201
return AssertionFailure(msg);
1205
} // namespace internal
1209
// Helper functions for implementing IsSubString() and IsNotSubstring().
1211
// This group of overloaded functions return true iff needle is a
1212
// substring of haystack. NULL is considered a substring of itself
1215
bool IsSubstringPred(const char* needle, const char* haystack) {
1216
if (needle == NULL || haystack == NULL)
1217
return needle == haystack;
1219
return strstr(haystack, needle) != NULL;
1222
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1223
if (needle == NULL || haystack == NULL)
1224
return needle == haystack;
1226
return wcsstr(haystack, needle) != NULL;
1229
// StringType here can be either ::std::string or ::std::wstring.
1230
template <typename StringType>
1231
bool IsSubstringPred(const StringType& needle,
1232
const StringType& haystack) {
1233
return haystack.find(needle) != StringType::npos;
1236
// This function implements either IsSubstring() or IsNotSubstring(),
1237
// depending on the value of the expected_to_be_substring parameter.
1238
// StringType here can be const char*, const wchar_t*, ::std::string,
1239
// or ::std::wstring.
1240
template <typename StringType>
1241
AssertionResult IsSubstringImpl(
1242
bool expected_to_be_substring,
1243
const char* needle_expr, const char* haystack_expr,
1244
const StringType& needle, const StringType& haystack) {
1245
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1246
return AssertionSuccess();
1248
const bool is_wide_string = sizeof(needle[0]) > 1;
1249
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1250
return AssertionFailure(
1252
<< "Value of: " << needle_expr << "\n"
1253
<< " Actual: " << begin_string_quote << needle << "\"\n"
1254
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
1255
<< "a substring of " << haystack_expr << "\n"
1256
<< "Which is: " << begin_string_quote << haystack << "\"");
1261
// IsSubstring() and IsNotSubstring() check whether needle is a
1262
// substring of haystack (NULL is considered a substring of itself
1263
// only), and return an appropriate error message when they fail.
1265
AssertionResult IsSubstring(
1266
const char* needle_expr, const char* haystack_expr,
1267
const char* needle, const char* haystack) {
1268
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1271
AssertionResult IsSubstring(
1272
const char* needle_expr, const char* haystack_expr,
1273
const wchar_t* needle, const wchar_t* haystack) {
1274
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1277
AssertionResult IsNotSubstring(
1278
const char* needle_expr, const char* haystack_expr,
1279
const char* needle, const char* haystack) {
1280
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1283
AssertionResult IsNotSubstring(
1284
const char* needle_expr, const char* haystack_expr,
1285
const wchar_t* needle, const wchar_t* haystack) {
1286
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1289
#if GTEST_HAS_STD_STRING
1290
AssertionResult IsSubstring(
1291
const char* needle_expr, const char* haystack_expr,
1292
const ::std::string& needle, const ::std::string& haystack) {
1293
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1296
AssertionResult IsNotSubstring(
1297
const char* needle_expr, const char* haystack_expr,
1298
const ::std::string& needle, const ::std::string& haystack) {
1299
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1301
#endif // GTEST_HAS_STD_STRING
1303
#if GTEST_HAS_STD_WSTRING
1304
AssertionResult IsSubstring(
1305
const char* needle_expr, const char* haystack_expr,
1306
const ::std::wstring& needle, const ::std::wstring& haystack) {
1307
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1310
AssertionResult IsNotSubstring(
1311
const char* needle_expr, const char* haystack_expr,
1312
const ::std::wstring& needle, const ::std::wstring& haystack) {
1313
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1315
#endif // GTEST_HAS_STD_WSTRING
1317
namespace internal {
1319
#if GTEST_OS_WINDOWS
1323
// Helper function for IsHRESULT{SuccessFailure} predicates
1324
AssertionResult HRESULTFailureHelper(const char* expr,
1325
const char* expected,
1326
long hr) { // NOLINT
1327
#if GTEST_OS_WINDOWS_MOBILE
1328
// Windows CE doesn't support FormatMessage.
1329
const char error_text[] = "";
1331
// Looks up the human-readable system message for the HRESULT code
1332
// and since we're not passing any params to FormatMessage, we don't
1333
// want inserts expanded.
1334
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1335
FORMAT_MESSAGE_IGNORE_INSERTS;
1336
const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1337
// Gets the system's human readable message string for this HRESULT.
1338
char error_text[kBufSize] = { '\0' };
1339
DWORD message_length = ::FormatMessageA(kFlags,
1340
0, // no source, we're asking system
1342
0, // no line width restrictions
1343
error_text, // output buffer
1344
kBufSize, // buf size
1345
NULL); // no arguments for inserts
1346
// Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1347
for (; message_length && isspace(error_text[message_length - 1]);
1349
error_text[message_length - 1] = '\0';
1351
#endif // GTEST_OS_WINDOWS_MOBILE
1353
const String error_hex(String::Format("0x%08X ", hr));
1355
msg << "Expected: " << expr << " " << expected << ".\n"
1356
<< " Actual: " << error_hex << error_text << "\n";
1358
return ::testing::AssertionFailure(msg);
1363
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1364
if (SUCCEEDED(hr)) {
1365
return AssertionSuccess();
1367
return HRESULTFailureHelper(expr, "succeeds", hr);
1370
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1372
return AssertionSuccess();
1374
return HRESULTFailureHelper(expr, "fails", hr);
1377
#endif // GTEST_OS_WINDOWS
1379
// Utility functions for encoding Unicode text (wide strings) in
1382
// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1385
// Code-point length Encoding
1386
// 0 - 7 bits 0xxxxxxx
1387
// 8 - 11 bits 110xxxxx 10xxxxxx
1388
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1389
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1391
// The maximum code-point a one-byte UTF-8 sequence can represent.
1392
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1394
// The maximum code-point a two-byte UTF-8 sequence can represent.
1395
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1397
// The maximum code-point a three-byte UTF-8 sequence can represent.
1398
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1400
// The maximum code-point a four-byte UTF-8 sequence can represent.
1401
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1403
// Chops off the n lowest bits from a bit pattern. Returns the n
1404
// lowest bits. As a side effect, the original bit pattern will be
1405
// shifted to the right by n bits.
1406
inline UInt32 ChopLowBits(UInt32* bits, int n) {
1407
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1412
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1413
// code_point parameter is of type UInt32 because wchar_t may not be
1414
// wide enough to contain a code point.
1415
// The output buffer str must containt at least 32 characters.
1416
// The function returns the address of the output buffer.
1417
// If the code_point is not a valid Unicode code point
1418
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1419
// as '(Invalid Unicode 0xXXXXXXXX)'.
1420
char* CodePointToUtf8(UInt32 code_point, char* str) {
1421
if (code_point <= kMaxCodePoint1) {
1423
str[0] = static_cast<char>(code_point); // 0xxxxxxx
1424
} else if (code_point <= kMaxCodePoint2) {
1426
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1427
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1428
} else if (code_point <= kMaxCodePoint3) {
1430
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1431
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1432
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1433
} else if (code_point <= kMaxCodePoint4) {
1435
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1436
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1437
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1438
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1440
// The longest string String::Format can produce when invoked
1441
// with these parameters is 28 character long (not including
1442
// the terminating nul character). We are asking for 32 character
1443
// buffer just in case. This is also enough for strncpy to
1444
// null-terminate the destination string.
1446
str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
1447
str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1448
// the result unterminated.
1453
// The following two functions only make sense if the the system
1454
// uses UTF-16 for wide string encoding. All supported systems
1455
// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1457
// Determines if the arguments constitute UTF-16 surrogate pair
1458
// and thus should be combined into a single Unicode code point
1459
// using CreateCodePointFromUtf16SurrogatePair.
1460
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1461
return sizeof(wchar_t) == 2 &&
1462
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1465
// Creates a Unicode code point from UTF16 surrogate pair.
1466
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1468
const UInt32 mask = (1 << 10) - 1;
1469
return (sizeof(wchar_t) == 2) ?
1470
(((first & mask) << 10) | (second & mask)) + 0x10000 :
1471
// This function should not be called when the condition is
1472
// false, but we provide a sensible default in case it is.
1473
static_cast<UInt32>(first);
1476
// Converts a wide string to a narrow string in UTF-8 encoding.
1477
// The wide string is assumed to have the following encoding:
1478
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1479
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1480
// Parameter str points to a null-terminated wide string.
1481
// Parameter num_chars may additionally limit the number
1482
// of wchar_t characters processed. -1 is used when the entire string
1483
// should be processed.
1484
// If the string contains code points that are not valid Unicode code points
1485
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1486
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1487
// and contains invalid UTF-16 surrogate pairs, values in those pairs
1488
// will be encoded as individual Unicode characters from Basic Normal Plane.
1489
String WideStringToUtf8(const wchar_t* str, int num_chars) {
1490
if (num_chars == -1)
1491
num_chars = static_cast<int>(wcslen(str));
1494
for (int i = 0; i < num_chars; ++i) {
1495
UInt32 unicode_code_point;
1497
if (str[i] == L'\0') {
1499
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1500
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1504
unicode_code_point = static_cast<UInt32>(str[i]);
1507
char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1508
stream << CodePointToUtf8(unicode_code_point, buffer);
1510
return StrStreamToString(&stream);
1513
// Converts a wide C string to a String using the UTF-8 encoding.
1514
// NULL will be converted to "(null)".
1515
String String::ShowWideCString(const wchar_t * wide_c_str) {
1516
if (wide_c_str == NULL) return String("(null)");
1518
return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1521
// Similar to ShowWideCString(), except that this function encloses
1522
// the converted string in double quotes.
1523
String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1524
if (wide_c_str == NULL) return String("(null)");
1526
return String::Format("L\"%s\"",
1527
String::ShowWideCString(wide_c_str).c_str());
1530
// Compares two wide C strings. Returns true iff they have the same
1533
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1534
// C string is considered different to any non-NULL C string,
1535
// including the empty string.
1536
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1537
if (lhs == NULL) return rhs == NULL;
1539
if (rhs == NULL) return false;
1541
return wcscmp(lhs, rhs) == 0;
1544
// Helper function for *_STREQ on wide strings.
1545
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1546
const char* actual_expression,
1547
const wchar_t* expected,
1548
const wchar_t* actual) {
1549
if (String::WideCStringEquals(expected, actual)) {
1550
return AssertionSuccess();
1553
return EqFailure(expected_expression,
1555
String::ShowWideCStringQuoted(expected),
1556
String::ShowWideCStringQuoted(actual),
1560
// Helper function for *_STRNE on wide strings.
1561
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1562
const char* s2_expression,
1564
const wchar_t* s2) {
1565
if (!String::WideCStringEquals(s1, s2)) {
1566
return AssertionSuccess();
1570
msg << "Expected: (" << s1_expression << ") != ("
1571
<< s2_expression << "), actual: "
1572
<< String::ShowWideCStringQuoted(s1)
1573
<< " vs " << String::ShowWideCStringQuoted(s2);
1574
return AssertionFailure(msg);
1577
// Compares two C strings, ignoring case. Returns true iff they have
1578
// the same content.
1580
// Unlike strcasecmp(), this function can handle NULL argument(s). A
1581
// NULL C string is considered different to any non-NULL C string,
1582
// including the empty string.
1583
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1588
return posix::StrCaseCmp(lhs, rhs) == 0;
1591
// Compares two wide C strings, ignoring case. Returns true iff they
1592
// have the same content.
1594
// Unlike wcscasecmp(), this function can handle NULL argument(s).
1595
// A NULL C string is considered different to any non-NULL wide C string,
1596
// including the empty string.
1597
// NB: The implementations on different platforms slightly differ.
1598
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1599
// environment variable. On GNU platform this method uses wcscasecmp
1600
// which compares according to LC_CTYPE category of the current locale.
1601
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1603
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1604
const wchar_t* rhs) {
1605
if ( lhs == NULL ) return rhs == NULL;
1607
if ( rhs == NULL ) return false;
1609
#if GTEST_OS_WINDOWS
1610
return _wcsicmp(lhs, rhs) == 0;
1611
#elif GTEST_OS_LINUX
1612
return wcscasecmp(lhs, rhs) == 0;
1614
// Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1615
// may not define it either.
1618
left = towlower(*lhs++);
1619
right = towlower(*rhs++);
1620
} while (left && left == right);
1621
return left == right;
1622
#endif // OS selector
1625
// Compares this with another String.
1626
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1627
// if this is greater than rhs.
1628
int String::Compare(const String & rhs) const {
1629
const char* const lhs_c_str = c_str();
1630
const char* const rhs_c_str = rhs.c_str();
1632
if (lhs_c_str == NULL) {
1633
return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1634
} else if (rhs_c_str == NULL) {
1638
const size_t shorter_str_len =
1639
length() <= rhs.length() ? length() : rhs.length();
1640
for (size_t i = 0; i != shorter_str_len; i++) {
1641
if (lhs_c_str[i] < rhs_c_str[i]) {
1643
} else if (lhs_c_str[i] > rhs_c_str[i]) {
1647
return (length() < rhs.length()) ? -1 :
1648
(length() > rhs.length()) ? 1 : 0;
1651
// Returns true iff this String ends with the given suffix. *Any*
1652
// String is considered to end with a NULL or empty suffix.
1653
bool String::EndsWith(const char* suffix) const {
1654
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1656
if (c_str() == NULL) return false;
1658
const size_t this_len = strlen(c_str());
1659
const size_t suffix_len = strlen(suffix);
1660
return (this_len >= suffix_len) &&
1661
CStringEquals(c_str() + this_len - suffix_len, suffix);
1664
// Returns true iff this String ends with the given suffix, ignoring case.
1665
// Any String is considered to end with a NULL or empty suffix.
1666
bool String::EndsWithCaseInsensitive(const char* suffix) const {
1667
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1669
if (c_str() == NULL) return false;
1671
const size_t this_len = strlen(c_str());
1672
const size_t suffix_len = strlen(suffix);
1673
return (this_len >= suffix_len) &&
1674
CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1677
// Formats a list of arguments to a String, using the same format
1678
// spec string as for printf.
1680
// We do not use the StringPrintf class as it is not universally
1683
// The result is limited to 4096 characters (including the tailing 0).
1684
// If 4096 characters are not enough to format the input, or if
1685
// there's an error, "<formatting error or buffer exceeded>" is
1687
String String::Format(const char * format, ...) {
1689
va_start(args, format);
1692
const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1694
// MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1695
// 4996 (deprecated function) there.
1696
#ifdef _MSC_VER // We are using MSVC.
1697
#pragma warning(push) // Saves the current warning state.
1698
#pragma warning(disable:4996) // Temporarily disables warning 4996.
1699
const int size = vsnprintf(buffer, kBufferSize, format, args);
1700
#pragma warning(pop) // Restores the warning state.
1701
#else // We are not using MSVC.
1702
const int size = vsnprintf(buffer, kBufferSize, format, args);
1706
// vsnprintf()'s behavior is not portable. When the buffer is not
1707
// big enough, it returns a negative value in MSVC, and returns the
1708
// needed buffer size on Linux. When there is an output error, it
1709
// always returns a negative value. For simplicity, we lump the two
1710
// error cases together.
1711
if (size < 0 || size >= kBufferSize) {
1712
return String("<formatting error or buffer exceeded>");
1714
return String(buffer, size);
1718
// Converts the buffer in a StrStream to a String, converting NUL
1719
// bytes to "\\0" along the way.
1720
String StrStreamToString(StrStream* ss) {
1721
#if GTEST_HAS_STD_STRING
1722
const ::std::string& str = ss->str();
1723
const char* const start = str.c_str();
1724
const char* const end = start + str.length();
1726
const char* const start = ss->str();
1727
const char* const end = start + ss->pcount();
1728
#endif // GTEST_HAS_STD_STRING
1730
// We need to use a helper StrStream to do this transformation
1731
// because String doesn't support push_back().
1733
for (const char* ch = start; ch != end; ++ch) {
1735
helper << "\\0"; // Replaces NUL with "\\0";
1741
#if GTEST_HAS_STD_STRING
1742
return String(helper.str().c_str());
1744
const String str(helper.str(), helper.pcount());
1745
helper.freeze(false);
1748
#endif // GTEST_HAS_STD_STRING
1751
// Appends the user-supplied message to the Google-Test-generated message.
1752
String AppendUserMessage(const String& gtest_msg,
1753
const Message& user_msg) {
1754
// Appends the user message if it's non-empty.
1755
const String user_msg_string = user_msg.GetString();
1756
if (user_msg_string.empty()) {
1761
msg << gtest_msg << "\n" << user_msg_string;
1763
return msg.GetString();
1766
} // namespace internal
1770
// Creates an empty TestResult.
1771
TestResult::TestResult()
1772
: test_part_results_(new internal::Vector<TestPartResult>),
1773
test_properties_(new internal::Vector<TestProperty>),
1774
death_test_count_(0),
1779
TestResult::~TestResult() {
1782
// Returns the i-th test part result among all the results. i can
1783
// range from 0 to total_part_count() - 1. If i is not in that range,
1784
// aborts the program.
1785
const TestPartResult& TestResult::GetTestPartResult(int i) const {
1786
return test_part_results_->GetElement(i);
1789
// Returns the i-th test property. i can range from 0 to
1790
// test_property_count() - 1. If i is not in that range, aborts the
1792
const TestProperty& TestResult::GetTestProperty(int i) const {
1793
return test_properties_->GetElement(i);
1796
// Clears the test part results.
1797
void TestResult::ClearTestPartResults() {
1798
test_part_results_->Clear();
1801
// Adds a test part result to the list.
1802
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1803
test_part_results_->PushBack(test_part_result);
1806
// Adds a test property to the list. If a property with the same key as the
1807
// supplied property is already represented, the value of this test_property
1808
// replaces the old value for that key.
1809
void TestResult::RecordProperty(const TestProperty& test_property) {
1810
if (!ValidateTestProperty(test_property)) {
1813
internal::MutexLock lock(&test_properites_mutex_);
1814
TestProperty* const property_with_matching_key =
1815
test_properties_->FindIf(
1816
internal::TestPropertyKeyIs(test_property.key()));
1817
if (property_with_matching_key == NULL) {
1818
test_properties_->PushBack(test_property);
1821
property_with_matching_key->SetValue(test_property.value());
1824
// Adds a failure if the key is a reserved attribute of Google Test
1825
// testcase tags. Returns true if the property is valid.
1826
bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1827
internal::String key(test_property.key());
1828
if (key == "name" || key == "status" || key == "time" || key == "classname") {
1830
<< "Reserved key used in RecordProperty(): "
1832
<< " ('name', 'status', 'time', and 'classname' are reserved by "
1833
<< GTEST_NAME_ << ")";
1839
// Clears the object.
1840
void TestResult::Clear() {
1841
test_part_results_->Clear();
1842
test_properties_->Clear();
1843
death_test_count_ = 0;
1847
// Returns true iff the test failed.
1848
bool TestResult::Failed() const {
1849
for (int i = 0; i < total_part_count(); ++i) {
1850
if (GetTestPartResult(i).failed())
1856
// Returns true iff the test part fatally failed.
1857
static bool TestPartFatallyFailed(const TestPartResult& result) {
1858
return result.fatally_failed();
1861
// Returns true iff the test fatally failed.
1862
bool TestResult::HasFatalFailure() const {
1863
return test_part_results_->CountIf(TestPartFatallyFailed) > 0;
1866
// Returns true iff the test part non-fatally failed.
1867
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1868
return result.nonfatally_failed();
1871
// Returns true iff the test has a non-fatal failure.
1872
bool TestResult::HasNonfatalFailure() const {
1873
return test_part_results_->CountIf(TestPartNonfatallyFailed) > 0;
1876
// Gets the number of all test parts. This is the sum of the number
1877
// of successful test parts and the number of failed test parts.
1878
int TestResult::total_part_count() const {
1879
return test_part_results_->size();
1882
// Returns the number of the test properties.
1883
int TestResult::test_property_count() const {
1884
return test_properties_->size();
1889
// Creates a Test object.
1891
// The c'tor saves the values of all Google Test flags.
1893
: gtest_flag_saver_(new internal::GTestFlagSaver) {
1896
// The d'tor restores the values of all Google Test flags.
1898
delete gtest_flag_saver_;
1901
// Sets up the test fixture.
1903
// A sub-class may override this.
1904
void Test::SetUp() {
1907
// Tears down the test fixture.
1909
// A sub-class may override this.
1910
void Test::TearDown() {
1913
// Allows user supplied key value pairs to be recorded for later output.
1914
void Test::RecordProperty(const char* key, const char* value) {
1915
UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1918
// Allows user supplied key value pairs to be recorded for later output.
1919
void Test::RecordProperty(const char* key, int value) {
1920
Message value_message;
1921
value_message << value;
1922
RecordProperty(key, value_message.GetString().c_str());
1925
namespace internal {
1927
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1928
const String& message) {
1929
// This function is a friend of UnitTest and as such has access to
1930
// AddTestPartResult.
1931
UnitTest::GetInstance()->AddTestPartResult(
1933
NULL, // No info about the source file where the exception occurred.
1934
-1, // We have no info on which line caused the exception.
1936
String()); // No stack trace, either.
1939
} // namespace internal
1941
#if GTEST_OS_WINDOWS
1942
// We are on Windows.
1944
// Adds an "exception thrown" fatal failure to the current test.
1945
static void AddExceptionThrownFailure(DWORD exception_code,
1946
const char* location) {
1948
message << "Exception thrown with code 0x" << std::setbase(16) <<
1949
exception_code << std::setbase(10) << " in " << location << ".";
1951
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1952
message.GetString());
1955
#endif // GTEST_OS_WINDOWS
1957
// Google Test requires all tests in the same test case to use the same test
1958
// fixture class. This function checks if the current test has the
1959
// same fixture class as the first test in the current test case. If
1960
// yes, it returns true; otherwise it generates a Google Test failure and
1962
bool Test::HasSameFixtureClass() {
1963
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1964
const TestCase* const test_case = impl->current_test_case();
1966
// Info about the first test in the current test case.
1967
const internal::TestInfoImpl* const first_test_info =
1968
test_case->test_info_list().GetElement(0)->impl();
1969
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1970
const char* const first_test_name = first_test_info->name();
1972
// Info about the current test.
1973
const internal::TestInfoImpl* const this_test_info =
1974
impl->current_test_info()->impl();
1975
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
1976
const char* const this_test_name = this_test_info->name();
1978
if (this_fixture_id != first_fixture_id) {
1979
// Is the first test defined using TEST?
1980
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
1981
// Is this test defined using TEST?
1982
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
1984
if (first_is_TEST || this_is_TEST) {
1985
// The user mixed TEST and TEST_F in this test case - we'll tell
1986
// him/her how to fix it.
1988
// Gets the name of the TEST and the name of the TEST_F. Note
1989
// that first_is_TEST and this_is_TEST cannot both be true, as
1990
// the fixture IDs are different for the two tests.
1991
const char* const TEST_name =
1992
first_is_TEST ? first_test_name : this_test_name;
1993
const char* const TEST_F_name =
1994
first_is_TEST ? this_test_name : first_test_name;
1997
<< "All tests in the same test case must use the same test fixture\n"
1998
<< "class, so mixing TEST_F and TEST in the same test case is\n"
1999
<< "illegal. In test case " << this_test_info->test_case_name()
2001
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
2002
<< "test " << TEST_name << " is defined using TEST. You probably\n"
2003
<< "want to change the TEST to TEST_F or move it to another test\n"
2006
// The user defined two fixture classes with the same name in
2007
// two namespaces - we'll tell him/her how to fix it.
2009
<< "All tests in the same test case must use the same test fixture\n"
2010
<< "class. However, in test case "
2011
<< this_test_info->test_case_name() << ",\n"
2012
<< "you defined test " << first_test_name
2013
<< " and test " << this_test_name << "\n"
2014
<< "using two different test fixture classes. This can happen if\n"
2015
<< "the two classes are from different namespaces or translation\n"
2016
<< "units and have the same name. You should probably rename one\n"
2017
<< "of the classes to put the tests into different test cases.";
2025
// Runs the test and updates the test result.
2027
if (!HasSameFixtureClass()) return;
2029
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2031
// Catch SEH-style exceptions.
2032
impl->os_stack_trace_getter()->UponLeavingGTest();
2035
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2036
GetExceptionCode())) {
2037
AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2040
// We will run the test only if SetUp() had no fatal failure.
2041
if (!HasFatalFailure()) {
2042
impl->os_stack_trace_getter()->UponLeavingGTest();
2045
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2046
GetExceptionCode())) {
2047
AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2051
// However, we want to clean up as much as possible. Hence we will
2052
// always call TearDown(), even if SetUp() or the test body has
2054
impl->os_stack_trace_getter()->UponLeavingGTest();
2057
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2058
GetExceptionCode())) {
2059
AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2062
#else // We are on a compiler or platform that doesn't support SEH.
2063
impl->os_stack_trace_getter()->UponLeavingGTest();
2066
// We will run the test only if SetUp() was successful.
2067
if (!HasFatalFailure()) {
2068
impl->os_stack_trace_getter()->UponLeavingGTest();
2072
// However, we want to clean up as much as possible. Hence we will
2073
// always call TearDown(), even if SetUp() or the test body has
2075
impl->os_stack_trace_getter()->UponLeavingGTest();
2077
#endif // GTEST_HAS_SEH
2081
// Returns true iff the current test has a fatal failure.
2082
bool Test::HasFatalFailure() {
2083
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2086
// Returns true iff the current test has a non-fatal failure.
2087
bool Test::HasNonfatalFailure() {
2088
return internal::GetUnitTestImpl()->current_test_result()->
2089
HasNonfatalFailure();
2094
// Constructs a TestInfo object. It assumes ownership of the test factory
2095
// object via impl_.
2096
TestInfo::TestInfo(const char* test_case_name,
2098
const char* test_case_comment,
2099
const char* comment,
2100
internal::TypeId fixture_class_id,
2101
internal::TestFactoryBase* factory) {
2102
impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2103
test_case_comment, comment,
2104
fixture_class_id, factory);
2107
// Destructs a TestInfo object.
2108
TestInfo::~TestInfo() {
2112
namespace internal {
2114
// Creates a new TestInfo object and registers it with Google Test;
2115
// returns the created object.
2119
// test_case_name: name of the test case
2120
// name: name of the test
2121
// test_case_comment: a comment on the test case that will be included in
2123
// comment: a comment on the test that will be included in the
2125
// fixture_class_id: ID of the test fixture class
2126
// set_up_tc: pointer to the function that sets up the test case
2127
// tear_down_tc: pointer to the function that tears down the test case
2128
// factory: pointer to the factory that creates a test object.
2129
// The newly created TestInfo instance will assume
2130
// ownership of the factory object.
2131
TestInfo* MakeAndRegisterTestInfo(
2132
const char* test_case_name, const char* name,
2133
const char* test_case_comment, const char* comment,
2134
TypeId fixture_class_id,
2135
SetUpTestCaseFunc set_up_tc,
2136
TearDownTestCaseFunc tear_down_tc,
2137
TestFactoryBase* factory) {
2138
TestInfo* const test_info =
2139
new TestInfo(test_case_name, name, test_case_comment, comment,
2140
fixture_class_id, factory);
2141
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2145
#if GTEST_HAS_PARAM_TEST
2146
void ReportInvalidTestCaseType(const char* test_case_name,
2147
const char* file, int line) {
2150
<< "Attempted redefinition of test case " << test_case_name << ".\n"
2151
<< "All tests in the same test case must use the same test fixture\n"
2152
<< "class. However, in test case " << test_case_name << ", you tried\n"
2153
<< "to define a test using a fixture class different from the one\n"
2154
<< "used earlier. This can happen if the two fixture classes are\n"
2155
<< "from different namespaces and have the same name. You should\n"
2156
<< "probably rename one of the classes to put the tests into different\n"
2159
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2160
errors.GetString().c_str());
2162
#endif // GTEST_HAS_PARAM_TEST
2164
} // namespace internal
2166
// Returns the test case name.
2167
const char* TestInfo::test_case_name() const {
2168
return impl_->test_case_name();
2171
// Returns the test name.
2172
const char* TestInfo::name() const {
2173
return impl_->name();
2176
// Returns the test case comment.
2177
const char* TestInfo::test_case_comment() const {
2178
return impl_->test_case_comment();
2181
// Returns the test comment.
2182
const char* TestInfo::comment() const {
2183
return impl_->comment();
2186
// Returns true if this test should run.
2187
bool TestInfo::should_run() const { return impl_->should_run(); }
2189
// Returns true if this test matches the user-specified filter.
2190
bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2192
// Returns the result of the test.
2193
const TestResult* TestInfo::result() const { return impl_->result(); }
2195
// Increments the number of death tests encountered in this test so
2197
int TestInfo::increment_death_test_count() {
2198
return impl_->result()->increment_death_test_count();
2203
// A predicate that checks the test name of a TestInfo against a known
2206
// This is used for implementation of the TestCase class only. We put
2207
// it in the anonymous namespace to prevent polluting the outer
2210
// TestNameIs is copyable.
2215
// TestNameIs has NO default constructor.
2216
explicit TestNameIs(const char* name)
2219
// Returns true iff the test name of test_info matches name_.
2220
bool operator()(const TestInfo * test_info) const {
2221
return test_info && internal::String(test_info->name()).Compare(name_) == 0;
2225
internal::String name_;
2230
namespace internal {
2232
// This method expands all parameterized tests registered with macros TEST_P
2233
// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2234
// This will be done just once during the program runtime.
2235
void UnitTestImpl::RegisterParameterizedTests() {
2236
#if GTEST_HAS_PARAM_TEST
2237
if (!parameterized_tests_registered_) {
2238
parameterized_test_registry_.RegisterTests();
2239
parameterized_tests_registered_ = true;
2244
// Creates the test object, runs it, records its result, and then
2246
void TestInfoImpl::Run() {
2247
if (!should_run_) return;
2249
// Tells UnitTest where to store test result.
2250
UnitTestImpl* const impl = internal::GetUnitTestImpl();
2251
impl->set_current_test_info(parent_);
2253
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2255
// Notifies the unit test event listeners that a test is about to start.
2256
repeater->OnTestStart(*parent_);
2258
const TimeInMillis start = GetTimeInMillis();
2260
impl->os_stack_trace_getter()->UponLeavingGTest();
2262
// Catch SEH-style exceptions.
2266
// Creates the test object.
2267
test = factory_->CreateTest();
2268
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2269
GetExceptionCode())) {
2270
AddExceptionThrownFailure(GetExceptionCode(),
2271
"the test fixture's constructor");
2274
#else // We are on a compiler or platform that doesn't support SEH.
2276
// TODO(wan): If test->Run() throws, test won't be deleted. This is
2277
// not a problem now as we don't use exceptions. If we were to
2278
// enable exceptions, we should revise the following to be
2281
// Creates the test object.
2282
Test* test = factory_->CreateTest();
2283
#endif // GTEST_HAS_SEH
2285
// Runs the test only if the constructor of the test fixture didn't
2286
// generate a fatal failure.
2287
if (!Test::HasFatalFailure()) {
2291
// Deletes the test object.
2292
impl->os_stack_trace_getter()->UponLeavingGTest();
2296
result_.set_elapsed_time(GetTimeInMillis() - start);
2298
// Notifies the unit test event listener that a test has just finished.
2299
repeater->OnTestEnd(*parent_);
2301
// Tells UnitTest to stop associating assertion results to this
2303
impl->set_current_test_info(NULL);
2306
} // namespace internal
2310
// Gets the number of successful tests in this test case.
2311
int TestCase::successful_test_count() const {
2312
return test_info_list_->CountIf(TestPassed);
2315
// Gets the number of failed tests in this test case.
2316
int TestCase::failed_test_count() const {
2317
return test_info_list_->CountIf(TestFailed);
2320
int TestCase::disabled_test_count() const {
2321
return test_info_list_->CountIf(TestDisabled);
2324
// Get the number of tests in this test case that should run.
2325
int TestCase::test_to_run_count() const {
2326
return test_info_list_->CountIf(ShouldRunTest);
2329
// Gets the number of all tests.
2330
int TestCase::total_test_count() const {
2331
return test_info_list_->size();
2334
// Creates a TestCase with the given name.
2338
// name: name of the test case
2339
// set_up_tc: pointer to the function that sets up the test case
2340
// tear_down_tc: pointer to the function that tears down the test case
2341
TestCase::TestCase(const char* name, const char* comment,
2342
Test::SetUpTestCaseFunc set_up_tc,
2343
Test::TearDownTestCaseFunc tear_down_tc)
2346
test_info_list_(new internal::Vector<TestInfo*>),
2347
test_indices_(new internal::Vector<int>),
2348
set_up_tc_(set_up_tc),
2349
tear_down_tc_(tear_down_tc),
2354
// Destructor of TestCase.
2355
TestCase::~TestCase() {
2356
// Deletes every Test in the collection.
2357
test_info_list_->ForEach(internal::Delete<TestInfo>);
2360
// Returns the i-th test among all the tests. i can range from 0 to
2361
// total_test_count() - 1. If i is not in that range, returns NULL.
2362
const TestInfo* TestCase::GetTestInfo(int i) const {
2363
const int index = test_indices_->GetElementOr(i, -1);
2364
return index < 0 ? NULL : test_info_list_->GetElement(index);
2367
// Returns the i-th test among all the tests. i can range from 0 to
2368
// total_test_count() - 1. If i is not in that range, returns NULL.
2369
TestInfo* TestCase::GetMutableTestInfo(int i) {
2370
const int index = test_indices_->GetElementOr(i, -1);
2371
return index < 0 ? NULL : test_info_list_->GetElement(index);
2374
// Adds a test to this test case. Will delete the test upon
2375
// destruction of the TestCase object.
2376
void TestCase::AddTestInfo(TestInfo * test_info) {
2377
test_info_list_->PushBack(test_info);
2378
test_indices_->PushBack(test_indices_->size());
2381
// Runs every test in this TestCase.
2382
void TestCase::Run() {
2383
if (!should_run_) return;
2385
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2386
impl->set_current_test_case(this);
2388
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2390
repeater->OnTestCaseStart(*this);
2391
impl->os_stack_trace_getter()->UponLeavingGTest();
2394
const internal::TimeInMillis start = internal::GetTimeInMillis();
2395
for (int i = 0; i < total_test_count(); i++) {
2396
GetMutableTestInfo(i)->impl()->Run();
2398
elapsed_time_ = internal::GetTimeInMillis() - start;
2400
impl->os_stack_trace_getter()->UponLeavingGTest();
2402
repeater->OnTestCaseEnd(*this);
2403
impl->set_current_test_case(NULL);
2406
// Clears the results of all tests in this test case.
2407
void TestCase::ClearResult() {
2408
test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2411
// Returns true iff test passed.
2412
bool TestCase::TestPassed(const TestInfo * test_info) {
2413
const internal::TestInfoImpl* const impl = test_info->impl();
2414
return impl->should_run() && impl->result()->Passed();
2417
// Returns true iff test failed.
2418
bool TestCase::TestFailed(const TestInfo * test_info) {
2419
const internal::TestInfoImpl* const impl = test_info->impl();
2420
return impl->should_run() && impl->result()->Failed();
2423
// Returns true iff test is disabled.
2424
bool TestCase::TestDisabled(const TestInfo * test_info) {
2425
return test_info->impl()->is_disabled();
2428
// Returns true if the given test should run.
2429
bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2430
return test_info->impl()->should_run();
2433
// Shuffles the tests in this test case.
2434
void TestCase::ShuffleTests(internal::Random* random) {
2435
test_indices_->Shuffle(random);
2438
// Restores the test order to before the first shuffle.
2439
void TestCase::UnshuffleTests() {
2440
for (int i = 0; i < test_indices_->size(); i++) {
2441
test_indices_->GetMutableElement(i) = i;
2445
// Formats a countable noun. Depending on its quantity, either the
2446
// singular form or the plural form is used. e.g.
2448
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2449
// FormatCountableNoun(5, "book", "books") returns "5 books".
2450
static internal::String FormatCountableNoun(int count,
2451
const char * singular_form,
2452
const char * plural_form) {
2453
return internal::String::Format("%d %s", count,
2454
count == 1 ? singular_form : plural_form);
2457
// Formats the count of tests.
2458
static internal::String FormatTestCount(int test_count) {
2459
return FormatCountableNoun(test_count, "test", "tests");
2462
// Formats the count of test cases.
2463
static internal::String FormatTestCaseCount(int test_case_count) {
2464
return FormatCountableNoun(test_case_count, "test case", "test cases");
2467
// Converts a TestPartResult::Type enum to human-friendly string
2468
// representation. Both kNonFatalFailure and kFatalFailure are translated
2469
// to "Failure", as the user usually doesn't care about the difference
2470
// between the two when viewing the test result.
2471
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2473
case TestPartResult::kSuccess:
2476
case TestPartResult::kNonFatalFailure:
2477
case TestPartResult::kFatalFailure:
2485
return "Unknown result type";
2488
// Prints a TestPartResult to a String.
2489
static internal::String PrintTestPartResultToString(
2490
const TestPartResult& test_part_result) {
2492
<< internal::FormatFileLocation(test_part_result.file_name(),
2493
test_part_result.line_number())
2494
<< " " << TestPartResultTypeToString(test_part_result.type())
2495
<< test_part_result.message()).GetString();
2498
// Prints a TestPartResult.
2499
static void PrintTestPartResult(const TestPartResult& test_part_result) {
2500
const internal::String& result =
2501
PrintTestPartResultToString(test_part_result);
2502
printf("%s\n", result.c_str());
2504
// If the test program runs in Visual Studio or a debugger, the
2505
// following statements add the test part result message to the Output
2506
// window such that the user can double-click on it to jump to the
2507
// corresponding source code location; otherwise they do nothing.
2508
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2509
// We don't call OutputDebugString*() on Windows Mobile, as printing
2510
// to stdout is done by OutputDebugString() there already - we don't
2511
// want the same message printed twice.
2512
::OutputDebugStringA(result.c_str());
2513
::OutputDebugStringA("\n");
2517
// class PrettyUnitTestResultPrinter
2519
namespace internal {
2528
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2530
// Returns the character attribute for the given color.
2531
WORD GetColorAttribute(GTestColor color) {
2533
case COLOR_RED: return FOREGROUND_RED;
2534
case COLOR_GREEN: return FOREGROUND_GREEN;
2535
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2542
// Returns the ANSI color code for the given color. COLOR_DEFAULT is
2543
// an invalid input.
2544
const char* GetAnsiColorCode(GTestColor color) {
2546
case COLOR_RED: return "1";
2547
case COLOR_GREEN: return "2";
2548
case COLOR_YELLOW: return "3";
2549
default: return NULL;
2553
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2555
// Returns true iff Google Test should use colors in the output.
2556
bool ShouldUseColor(bool stdout_is_tty) {
2557
const char* const gtest_color = GTEST_FLAG(color).c_str();
2559
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2560
#if GTEST_OS_WINDOWS
2561
// On Windows the TERM variable is usually not set, but the
2562
// console there does support colors.
2563
return stdout_is_tty;
2565
// On non-Windows platforms, we rely on the TERM variable.
2566
const char* const term = posix::GetEnv("TERM");
2567
const bool term_supports_color =
2568
String::CStringEquals(term, "xterm") ||
2569
String::CStringEquals(term, "xterm-color") ||
2570
String::CStringEquals(term, "xterm-256color") ||
2571
String::CStringEquals(term, "linux") ||
2572
String::CStringEquals(term, "cygwin");
2573
return stdout_is_tty && term_supports_color;
2574
#endif // GTEST_OS_WINDOWS
2577
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2578
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2579
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2580
String::CStringEquals(gtest_color, "1");
2581
// We take "yes", "true", "t", and "1" as meaning "yes". If the
2582
// value is neither one of these nor "auto", we treat it as "no" to
2586
// Helpers for printing colored strings to stdout. Note that on Windows, we
2587
// cannot simply emit special characters and have the terminal change colors.
2588
// This routine must actually emit the characters rather than return a string
2589
// that would be colored when printed, as can be done on Linux.
2590
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2592
va_start(args, fmt);
2594
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2595
const bool use_color = false;
2597
static const bool in_color_mode =
2598
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2599
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2600
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2601
// The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2609
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2610
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2612
// Gets the current text color.
2613
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2614
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2615
const WORD old_color_attrs = buffer_info.wAttributes;
2617
SetConsoleTextAttribute(stdout_handle,
2618
GetColorAttribute(color) | FOREGROUND_INTENSITY);
2621
// Restores the text color.
2622
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2624
printf("\033[0;3%sm", GetAnsiColorCode(color));
2626
printf("\033[m"); // Resets the terminal to default.
2627
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2631
// This class implements the TestEventListener interface.
2633
// Class PrettyUnitTestResultPrinter is copyable.
2634
class PrettyUnitTestResultPrinter : public TestEventListener {
2636
PrettyUnitTestResultPrinter() {}
2637
static void PrintTestName(const char * test_case, const char * test) {
2638
printf("%s.%s", test_case, test);
2641
// The following methods override what's in the TestEventListener class.
2642
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2643
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2644
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2645
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2646
virtual void OnTestCaseStart(const TestCase& test_case);
2647
virtual void OnTestStart(const TestInfo& test_info);
2648
virtual void OnTestPartResult(const TestPartResult& result);
2649
virtual void OnTestEnd(const TestInfo& test_info);
2650
virtual void OnTestCaseEnd(const TestCase& test_case);
2651
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2652
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2653
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2654
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
2657
static void PrintFailedTests(const UnitTest& unit_test);
2659
internal::String test_case_name_;
2662
// Fired before each iteration of tests starts.
2663
void PrettyUnitTestResultPrinter::OnTestIterationStart(
2664
const UnitTest& unit_test, int iteration) {
2665
if (GTEST_FLAG(repeat) != 1)
2666
printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2668
const char* const filter = GTEST_FLAG(filter).c_str();
2670
// Prints the filter if it's not *. This reminds the user that some
2671
// tests may be skipped.
2672
if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2673
ColoredPrintf(COLOR_YELLOW,
2674
"Note: %s filter = %s\n", GTEST_NAME_, filter);
2677
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2678
ColoredPrintf(COLOR_YELLOW,
2679
"Note: This is test shard %s of %s.\n",
2680
internal::posix::GetEnv(kTestShardIndex),
2681
internal::posix::GetEnv(kTestTotalShards));
2684
if (GTEST_FLAG(shuffle)) {
2685
ColoredPrintf(COLOR_YELLOW,
2686
"Note: Randomizing tests' orders with a seed of %d .\n",
2687
unit_test.random_seed());
2690
ColoredPrintf(COLOR_GREEN, "[==========] ");
2691
printf("Running %s from %s.\n",
2692
FormatTestCount(unit_test.test_to_run_count()).c_str(),
2693
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2697
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2698
const UnitTest& /*unit_test*/) {
2699
ColoredPrintf(COLOR_GREEN, "[----------] ");
2700
printf("Global test environment set-up.\n");
2704
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2705
test_case_name_ = test_case.name();
2706
const internal::String counts =
2707
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2708
ColoredPrintf(COLOR_GREEN, "[----------] ");
2709
printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2710
if (test_case.comment()[0] == '\0') {
2713
printf(", where %s\n", test_case.comment());
2718
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2719
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2720
PrintTestName(test_case_name_.c_str(), test_info.name());
2721
if (test_info.comment()[0] == '\0') {
2724
printf(", where %s\n", test_info.comment());
2729
// Called after an assertion failure.
2730
void PrettyUnitTestResultPrinter::OnTestPartResult(
2731
const TestPartResult& result) {
2732
// If the test part succeeded, we don't need to do anything.
2733
if (result.type() == TestPartResult::kSuccess)
2736
// Print failure message from the assertion (e.g. expected this and got that).
2737
PrintTestPartResult(result);
2741
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2742
if (test_info.result()->Passed()) {
2743
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2745
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2747
PrintTestName(test_case_name_.c_str(), test_info.name());
2748
if (GTEST_FLAG(print_time)) {
2749
printf(" (%s ms)\n", internal::StreamableToString(
2750
test_info.result()->elapsed_time()).c_str());
2757
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2758
if (!GTEST_FLAG(print_time)) return;
2760
test_case_name_ = test_case.name();
2761
const internal::String counts =
2762
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2763
ColoredPrintf(COLOR_GREEN, "[----------] ");
2764
printf("%s from %s (%s ms total)\n\n",
2765
counts.c_str(), test_case_name_.c_str(),
2766
internal::StreamableToString(test_case.elapsed_time()).c_str());
2770
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2771
const UnitTest& /*unit_test*/) {
2772
ColoredPrintf(COLOR_GREEN, "[----------] ");
2773
printf("Global test environment tear-down\n");
2777
// Internal helper for printing the list of failed tests.
2778
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2779
const int failed_test_count = unit_test.failed_test_count();
2780
if (failed_test_count == 0) {
2784
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2785
const TestCase& test_case = *unit_test.GetTestCase(i);
2786
if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
2789
for (int j = 0; j < test_case.total_test_count(); ++j) {
2790
const TestInfo& test_info = *test_case.GetTestInfo(j);
2791
if (!test_info.should_run() || test_info.result()->Passed()) {
2794
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2795
printf("%s.%s", test_case.name(), test_info.name());
2796
if (test_case.comment()[0] != '\0' ||
2797
test_info.comment()[0] != '\0') {
2798
printf(", where %s", test_case.comment());
2799
if (test_case.comment()[0] != '\0' &&
2800
test_info.comment()[0] != '\0') {
2804
printf("%s\n", test_info.comment());
2809
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2810
int /*iteration*/) {
2811
ColoredPrintf(COLOR_GREEN, "[==========] ");
2812
printf("%s from %s ran.",
2813
FormatTestCount(unit_test.test_to_run_count()).c_str(),
2814
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2815
if (GTEST_FLAG(print_time)) {
2816
printf(" (%s ms total)",
2817
internal::StreamableToString(unit_test.elapsed_time()).c_str());
2820
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2821
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
2823
int num_failures = unit_test.failed_test_count();
2824
if (!unit_test.Passed()) {
2825
const int failed_test_count = unit_test.failed_test_count();
2826
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2827
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2828
PrintFailedTests(unit_test);
2829
printf("\n%2d FAILED %s\n", num_failures,
2830
num_failures == 1 ? "TEST" : "TESTS");
2833
int num_disabled = unit_test.disabled_test_count();
2834
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
2835
if (!num_failures) {
2836
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2838
ColoredPrintf(COLOR_YELLOW,
2839
" YOU HAVE %d DISABLED %s\n\n",
2841
num_disabled == 1 ? "TEST" : "TESTS");
2843
// Ensure that Google Test output is printed before, e.g., heapchecker output.
2847
// End PrettyUnitTestResultPrinter
2849
// class TestEventRepeater
2851
// This class forwards events to other event listeners.
2852
class TestEventRepeater : public TestEventListener {
2854
TestEventRepeater() : forwarding_enabled_(true) {}
2855
virtual ~TestEventRepeater();
2856
void Append(TestEventListener *listener);
2857
TestEventListener* Release(TestEventListener* listener);
2859
// Controls whether events will be forwarded to listeners_. Set to false
2860
// in death test child processes.
2861
bool forwarding_enabled() const { return forwarding_enabled_; }
2862
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2864
virtual void OnTestProgramStart(const UnitTest& unit_test);
2865
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2866
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2867
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2868
virtual void OnTestCaseStart(const TestCase& test_case);
2869
virtual void OnTestStart(const TestInfo& test_info);
2870
virtual void OnTestPartResult(const TestPartResult& result);
2871
virtual void OnTestEnd(const TestInfo& test_info);
2872
virtual void OnTestCaseEnd(const TestCase& test_case);
2873
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2874
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2875
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2876
virtual void OnTestProgramEnd(const UnitTest& unit_test);
2879
// Controls whether events will be forwarded to listeners_. Set to false
2880
// in death test child processes.
2881
bool forwarding_enabled_;
2882
// The list of listeners that receive events.
2883
Vector<TestEventListener*> listeners_;
2885
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
2888
TestEventRepeater::~TestEventRepeater() {
2889
for (int i = 0; i < listeners_.size(); i++) {
2890
delete listeners_.GetElement(i);
2894
void TestEventRepeater::Append(TestEventListener *listener) {
2895
listeners_.PushBack(listener);
2898
// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2899
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
2900
for (int i = 0; i < listeners_.size(); ++i) {
2901
if (listeners_.GetElement(i) == listener) {
2902
listeners_.Erase(i);
2910
// Since most methods are very similar, use macros to reduce boilerplate.
2911
// This defines a member that forwards the call to all listeners.
2912
#define GTEST_REPEATER_METHOD_(Name, Type) \
2913
void TestEventRepeater::Name(const Type& parameter) { \
2914
if (forwarding_enabled_) { \
2915
for (int i = 0; i < listeners_.size(); i++) { \
2916
listeners_.GetElement(i)->Name(parameter); \
2920
// This defines a member that forwards the call to all listeners in reverse
2922
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2923
void TestEventRepeater::Name(const Type& parameter) { \
2924
if (forwarding_enabled_) { \
2925
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
2926
listeners_.GetElement(i)->Name(parameter); \
2931
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2932
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
2933
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2934
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2935
GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2936
GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2937
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2938
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2939
GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2940
GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2941
GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
2943
#undef GTEST_REPEATER_METHOD_
2944
#undef GTEST_REVERSE_REPEATER_METHOD_
2946
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2948
if (forwarding_enabled_) {
2949
for (int i = 0; i < listeners_.size(); i++) {
2950
listeners_.GetElement(i)->OnTestIterationStart(unit_test, iteration);
2955
void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2957
if (forwarding_enabled_) {
2958
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
2959
listeners_.GetElement(i)->OnTestIterationEnd(unit_test, iteration);
2964
// End TestEventRepeater
2966
// This class generates an XML output file.
2967
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
2969
explicit XmlUnitTestResultPrinter(const char* output_file);
2971
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2974
// Is c a whitespace character that is normalized to a space character
2975
// when it appears in an XML attribute value?
2976
static bool IsNormalizableWhitespace(char c) {
2977
return c == 0x9 || c == 0xA || c == 0xD;
2980
// May c appear in a well-formed XML document?
2981
static bool IsValidXmlCharacter(char c) {
2982
return IsNormalizableWhitespace(c) || c >= 0x20;
2985
// Returns an XML-escaped copy of the input string str. If
2986
// is_attribute is true, the text is meant to appear as an attribute
2987
// value, and normalizable whitespace is preserved by replacing it
2988
// with character references.
2989
static String EscapeXml(const char* str, bool is_attribute);
2991
// Returns the given string with all characters invalid in XML removed.
2992
static String RemoveInvalidXmlCharacters(const char* str);
2994
// Convenience wrapper around EscapeXml when str is an attribute value.
2995
static String EscapeXmlAttribute(const char* str) {
2996
return EscapeXml(str, true);
2999
// Convenience wrapper around EscapeXml when str is not an attribute value.
3000
static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
3002
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3003
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3005
// Streams an XML representation of a TestInfo object.
3006
static void OutputXmlTestInfo(::std::ostream* stream,
3007
const char* test_case_name,
3008
const TestInfo& test_info);
3010
// Prints an XML representation of a TestCase object
3011
static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
3013
// Prints an XML summary of unit_test to output stream out.
3014
static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
3016
// Produces a string representing the test properties in a result as space
3017
// delimited XML attributes based on the property key="value" pairs.
3018
// When the String is not empty, it includes a space at the beginning,
3019
// to delimit this attribute from prior attributes.
3020
static String TestPropertiesAsXmlAttributes(const TestResult& result);
3023
const String output_file_;
3025
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3028
// Creates a new XmlUnitTestResultPrinter.
3029
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3030
: output_file_(output_file) {
3031
if (output_file_.c_str() == NULL || output_file_.empty()) {
3032
fprintf(stderr, "XML output file may not be null\n");
3038
// Called after the unit test ends.
3039
void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3040
int /*iteration*/) {
3041
FILE* xmlout = NULL;
3042
FilePath output_file(output_file_);
3043
FilePath output_dir(output_file.RemoveFileName());
3045
if (output_dir.CreateDirectoriesRecursively()) {
3046
xmlout = posix::FOpen(output_file_.c_str(), "w");
3048
if (xmlout == NULL) {
3049
// TODO(wan): report the reason of the failure.
3051
// We don't do it for now as:
3053
// 1. There is no urgent need for it.
3054
// 2. It's a bit involved to make the errno variable thread-safe on
3055
// all three operating systems (Linux, Windows, and Mac OS).
3056
// 3. To interpret the meaning of errno in a thread-safe way,
3057
// we need the strerror_r() function, which is not available on
3060
"Unable to open file \"%s\"\n",
3061
output_file_.c_str());
3065
PrintXmlUnitTest(xmlout, unit_test);
3069
// Returns an XML-escaped copy of the input string str. If is_attribute
3070
// is true, the text is meant to appear as an attribute value, and
3071
// normalizable whitespace is preserved by replacing it with character
3074
// Invalid XML characters in str, if any, are stripped from the output.
3075
// It is expected that most, if not all, of the text processed by this
3076
// module will consist of ordinary English text.
3077
// If this module is ever modified to produce version 1.1 XML output,
3078
// most invalid characters can be retained using character references.
3079
// TODO(wan): It might be nice to have a minimally invasive, human-readable
3080
// escaping scheme for invalid characters, rather than dropping them.
3081
String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
3085
for (const char* src = str; *src; ++src) {
3109
if (IsValidXmlCharacter(*src)) {
3110
if (is_attribute && IsNormalizableWhitespace(*src))
3111
m << String::Format("&#x%02X;", unsigned(*src));
3120
return m.GetString();
3123
// Returns the given string with all characters invalid in XML removed.
3124
// Currently invalid characters are dropped from the string. An
3125
// alternative is to replace them with certain characters such as . or ?.
3126
String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3127
char* const output = new char[strlen(str) + 1];
3128
char* appender = output;
3129
for (char ch = *str; ch != '\0'; ch = *++str)
3130
if (IsValidXmlCharacter(ch))
3134
String ret_value(output);
3139
// The following routines generate an XML representation of a UnitTest
3142
// This is how Google Test concepts map to the DTD:
3144
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3145
// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3146
// <testcase name="test-name"> <-- corresponds to a TestInfo object
3147
// <failure message="...">...</failure>
3148
// <failure message="...">...</failure>
3149
// <failure message="...">...</failure>
3150
// <-- individual assertion failures
3155
// Formats the given time in milliseconds as seconds. The returned
3156
// C-string is owned by this function and cannot be released by the
3157
// caller. Calling the function again invalidates the previous
3159
const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3161
str = (Message() << (ms/1000.0)).GetString();
3165
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3166
void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3168
const char* segment = data;
3169
*stream << "<![CDATA[";
3171
const char* const next_segment = strstr(segment, "]]>");
3172
if (next_segment != NULL) {
3173
stream->write(segment, next_segment - segment);
3174
*stream << "]]>]]><![CDATA[";
3175
segment = next_segment + strlen("]]>");
3184
// Prints an XML representation of a TestInfo object.
3185
// TODO(wan): There is also value in printing properties with the plain printer.
3186
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3187
const char* test_case_name,
3188
const TestInfo& test_info) {
3189
const TestResult& result = *test_info.result();
3190
*stream << " <testcase name=\""
3191
<< EscapeXmlAttribute(test_info.name()).c_str()
3193
<< (test_info.should_run() ? "run" : "notrun")
3195
<< FormatTimeInMillisAsSeconds(result.elapsed_time())
3196
<< "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3197
<< "\"" << TestPropertiesAsXmlAttributes(result).c_str();
3200
for (int i = 0; i < result.total_part_count(); ++i) {
3201
const TestPartResult& part = result.GetTestPartResult(i);
3202
if (part.failed()) {
3203
if (++failures == 1)
3205
*stream << " <failure message=\""
3206
<< EscapeXmlAttribute(part.summary()).c_str()
3208
const String message = RemoveInvalidXmlCharacters(String::Format(
3210
part.file_name(), part.line_number(),
3211
part.message()).c_str());
3212
OutputXmlCDataSection(stream, message.c_str());
3213
*stream << "</failure>\n";
3220
*stream << " </testcase>\n";
3223
// Prints an XML representation of a TestCase object
3224
void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3225
const TestCase& test_case) {
3227
" <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3229
EscapeXmlAttribute(test_case.name()).c_str(),
3230
test_case.total_test_count(),
3231
test_case.failed_test_count(),
3232
test_case.disabled_test_count());
3234
"errors=\"0\" time=\"%s\">\n",
3235
FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3236
for (int i = 0; i < test_case.total_test_count(); ++i) {
3238
OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3239
fprintf(out, "%s", StrStreamToString(&stream).c_str());
3241
fprintf(out, " </testsuite>\n");
3244
// Prints an XML summary of unit_test to output stream out.
3245
void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3246
const UnitTest& unit_test) {
3247
fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3249
"<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3250
"errors=\"0\" time=\"%s\" ",
3251
unit_test.total_test_count(),
3252
unit_test.failed_test_count(),
3253
unit_test.disabled_test_count(),
3254
FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3255
if (GTEST_FLAG(shuffle)) {
3256
fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3258
fprintf(out, "name=\"AllTests\">\n");
3259
for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3260
PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3261
fprintf(out, "</testsuites>\n");
3264
// Produces a string representing the test properties in a result as space
3265
// delimited XML attributes based on the property key="value" pairs.
3266
String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3267
const TestResult& result) {
3269
for (int i = 0; i < result.test_property_count(); ++i) {
3270
const TestProperty& property = result.GetTestProperty(i);
3271
attributes << " " << property.key() << "="
3272
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
3274
return attributes.GetString();
3277
// End XmlUnitTestResultPrinter
3279
// Class ScopedTrace
3281
// Pushes the given source file location and message onto a per-thread
3282
// trace stack maintained by Google Test.
3283
// L < UnitTest::mutex_
3284
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3288
trace.message = message.GetString();
3290
UnitTest::GetInstance()->PushGTestTrace(trace);
3293
// Pops the info pushed by the c'tor.
3294
// L < UnitTest::mutex_
3295
ScopedTrace::~ScopedTrace() {
3296
UnitTest::GetInstance()->PopGTestTrace();
3300
// class OsStackTraceGetter
3302
// Returns the current OS stack trace as a String. Parameters:
3304
// max_depth - the maximum number of stack frames to be included
3306
// skip_count - the number of top frames to be skipped; doesn't count
3307
// against max_depth.
3310
// We use "L < mutex_" to denote that the function may acquire mutex_.
3311
String OsStackTraceGetter::CurrentStackTrace(int, int) {
3316
void OsStackTraceGetter::UponLeavingGTest() {
3320
OsStackTraceGetter::kElidedFramesMarker =
3321
"... " GTEST_NAME_ " internal frames ...";
3323
} // namespace internal
3325
// class TestEventListeners
3327
TestEventListeners::TestEventListeners()
3328
: repeater_(new internal::TestEventRepeater()),
3329
default_result_printer_(NULL),
3330
default_xml_generator_(NULL) {
3333
TestEventListeners::~TestEventListeners() { delete repeater_; }
3335
// Returns the standard listener responsible for the default console
3336
// output. Can be removed from the listeners list to shut down default
3337
// console output. Note that removing this object from the listener list
3338
// with Release transfers its ownership to the user.
3339
void TestEventListeners::Append(TestEventListener* listener) {
3340
repeater_->Append(listener);
3343
// Removes the given event listener from the list and returns it. It then
3344
// becomes the caller's responsibility to delete the listener. Returns
3345
// NULL if the listener is not found in the list.
3346
TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3347
if (listener == default_result_printer_)
3348
default_result_printer_ = NULL;
3349
else if (listener == default_xml_generator_)
3350
default_xml_generator_ = NULL;
3351
return repeater_->Release(listener);
3354
// Returns repeater that broadcasts the TestEventListener events to all
3356
TestEventListener* TestEventListeners::repeater() { return repeater_; }
3358
// Sets the default_result_printer attribute to the provided listener.
3359
// The listener is also added to the listener list and previous
3360
// default_result_printer is removed from it and deleted. The listener can
3361
// also be NULL in which case it will not be added to the list. Does
3362
// nothing if the previous and the current listener objects are the same.
3363
void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3364
if (default_result_printer_ != listener) {
3365
// It is an error to pass this method a listener that is already in the
3367
delete Release(default_result_printer_);
3368
default_result_printer_ = listener;
3369
if (listener != NULL)
3374
// Sets the default_xml_generator attribute to the provided listener. The
3375
// listener is also added to the listener list and previous
3376
// default_xml_generator is removed from it and deleted. The listener can
3377
// also be NULL in which case it will not be added to the list. Does
3378
// nothing if the previous and the current listener objects are the same.
3379
void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3380
if (default_xml_generator_ != listener) {
3381
// It is an error to pass this method a listener that is already in the
3383
delete Release(default_xml_generator_);
3384
default_xml_generator_ = listener;
3385
if (listener != NULL)
3390
// Controls whether events will be forwarded by the repeater to the
3391
// listeners in the list.
3392
bool TestEventListeners::EventForwardingEnabled() const {
3393
return repeater_->forwarding_enabled();
3396
void TestEventListeners::SuppressEventForwarding() {
3397
repeater_->set_forwarding_enabled(false);
3402
// Gets the singleton UnitTest object. The first time this method is
3403
// called, a UnitTest object is constructed and returned. Consecutive
3404
// calls will return the same object.
3406
// We don't protect this under mutex_ as a user is not supposed to
3407
// call this before main() starts, from which point on the return
3408
// value will never change.
3409
UnitTest * UnitTest::GetInstance() {
3410
// When compiled with MSVC 7.1 in optimized mode, destroying the
3411
// UnitTest object upon exiting the program messes up the exit code,
3412
// causing successful tests to appear failed. We have to use a
3413
// different implementation in this case to bypass the compiler bug.
3414
// This implementation makes the compiler happy, at the cost of
3415
// leaking the UnitTest object.
3417
// CodeGear C++Builder insists on a public destructor for the
3418
// default implementation. Use this implementation to keep good OO
3419
// design with private destructor.
3421
#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3422
static UnitTest* const instance = new UnitTest;
3425
static UnitTest instance;
3427
#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3430
// Gets the number of successful test cases.
3431
int UnitTest::successful_test_case_count() const {
3432
return impl()->successful_test_case_count();
3435
// Gets the number of failed test cases.
3436
int UnitTest::failed_test_case_count() const {
3437
return impl()->failed_test_case_count();
3440
// Gets the number of all test cases.
3441
int UnitTest::total_test_case_count() const {
3442
return impl()->total_test_case_count();
3445
// Gets the number of all test cases that contain at least one test
3447
int UnitTest::test_case_to_run_count() const {
3448
return impl()->test_case_to_run_count();
3451
// Gets the number of successful tests.
3452
int UnitTest::successful_test_count() const {
3453
return impl()->successful_test_count();
3456
// Gets the number of failed tests.
3457
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3459
// Gets the number of disabled tests.
3460
int UnitTest::disabled_test_count() const {
3461
return impl()->disabled_test_count();
3464
// Gets the number of all tests.
3465
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3467
// Gets the number of tests that should run.
3468
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3470
// Gets the elapsed time, in milliseconds.
3471
internal::TimeInMillis UnitTest::elapsed_time() const {
3472
return impl()->elapsed_time();
3475
// Returns true iff the unit test passed (i.e. all test cases passed).
3476
bool UnitTest::Passed() const { return impl()->Passed(); }
3478
// Returns true iff the unit test failed (i.e. some test case failed
3479
// or something outside of all tests failed).
3480
bool UnitTest::Failed() const { return impl()->Failed(); }
3482
// Gets the i-th test case among all the test cases. i can range from 0 to
3483
// total_test_case_count() - 1. If i is not in that range, returns NULL.
3484
const TestCase* UnitTest::GetTestCase(int i) const {
3485
return impl()->GetTestCase(i);
3488
// Gets the i-th test case among all the test cases. i can range from 0 to
3489
// total_test_case_count() - 1. If i is not in that range, returns NULL.
3490
TestCase* UnitTest::GetMutableTestCase(int i) {
3491
return impl()->GetMutableTestCase(i);
3494
// Returns the list of event listeners that can be used to track events
3495
// inside Google Test.
3496
TestEventListeners& UnitTest::listeners() {
3497
return *impl()->listeners();
3500
// Registers and returns a global test environment. When a test
3501
// program is run, all global test environments will be set-up in the
3502
// order they were registered. After all tests in the program have
3503
// finished, all global test environments will be torn-down in the
3504
// *reverse* order they were registered.
3506
// The UnitTest object takes ownership of the given environment.
3508
// We don't protect this under mutex_, as we only support calling it
3509
// from the main thread.
3510
Environment* UnitTest::AddEnvironment(Environment* env) {
3515
impl_->environments()->PushBack(env);
3516
impl_->environments_in_reverse_order()->PushFront(env);
3520
#if GTEST_HAS_EXCEPTIONS
3521
// A failed Google Test assertion will throw an exception of this type
3522
// when exceptions are enabled. We derive it from std::runtime_error,
3523
// which is for errors presumably detectable only at run time. Since
3524
// std::runtime_error inherits from std::exception, many testing
3525
// frameworks know how to extract and print the message inside it.
3526
class GoogleTestFailureException : public ::std::runtime_error {
3528
explicit GoogleTestFailureException(const TestPartResult& failure)
3529
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3533
// Adds a TestPartResult to the current TestResult object. All Google Test
3534
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3535
// this to report their results. The user code should use the
3536
// assertion macros instead of calling this directly.
3538
void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3539
const char* file_name,
3541
const internal::String& message,
3542
const internal::String& os_stack_trace) {
3546
internal::MutexLock lock(&mutex_);
3547
if (impl_->gtest_trace_stack()->size() > 0) {
3548
msg << "\n" << GTEST_NAME_ << " trace:";
3550
for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) {
3551
const internal::TraceInfo& trace =
3552
impl_->gtest_trace_stack()->GetElement(i);
3553
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3554
<< " " << trace.message;
3558
if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3559
msg << internal::kStackTraceMarker << os_stack_trace;
3562
const TestPartResult result =
3563
TestPartResult(result_type, file_name, line_number,
3564
msg.GetString().c_str());
3565
impl_->GetTestPartResultReporterForCurrentThread()->
3566
ReportTestPartResult(result);
3568
if (result_type != TestPartResult::kSuccess) {
3569
// gtest_break_on_failure takes precedence over
3570
// gtest_throw_on_failure. This allows a user to set the latter
3571
// in the code (perhaps in order to use Google Test assertions
3572
// with another testing framework) and specify the former on the
3573
// command line for debugging.
3574
if (GTEST_FLAG(break_on_failure)) {
3575
#if GTEST_OS_WINDOWS
3576
// Using DebugBreak on Windows allows gtest to still break into a debugger
3577
// when a failure happens and both the --gtest_break_on_failure and
3578
// the --gtest_catch_exceptions flags are specified.
3581
*static_cast<int*>(NULL) = 1;
3582
#endif // GTEST_OS_WINDOWS
3583
} else if (GTEST_FLAG(throw_on_failure)) {
3584
#if GTEST_HAS_EXCEPTIONS
3585
throw GoogleTestFailureException(result);
3587
// We cannot call abort() as it generates a pop-up in debug mode
3588
// that cannot be suppressed in VC 7.1 or below.
3595
// Creates and adds a property to the current TestResult. If a property matching
3596
// the supplied value already exists, updates its value instead.
3597
void UnitTest::RecordPropertyForCurrentTest(const char* key,
3598
const char* value) {
3599
const TestProperty test_property(key, value);
3600
impl_->current_test_result()->RecordProperty(test_property);
3603
// Runs all tests in this UnitTest object and prints the result.
3604
// Returns 0 if successful, or 1 otherwise.
3606
// We don't protect this under mutex_, as we only support calling it
3607
// from the main thread.
3608
int UnitTest::Run() {
3610
// Catch SEH-style exceptions.
3612
const bool in_death_test_child_process =
3613
internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3615
// Either the user wants Google Test to catch exceptions thrown by the
3616
// tests or this is executing in the context of death test child
3617
// process. In either case the user does not want to see pop-up dialogs
3618
// about crashes - they are expected..
3619
if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3620
#if !GTEST_OS_WINDOWS_MOBILE
3621
// SetErrorMode doesn't exist on CE.
3622
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3623
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3624
#endif // !GTEST_OS_WINDOWS_MOBILE
3626
#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3627
// Death test children can be terminated with _abort(). On Windows,
3628
// _abort() can show a dialog with a warning message. This forces the
3629
// abort message to go to stderr instead.
3630
_set_error_mode(_OUT_TO_STDERR);
3633
#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3634
// In the debug version, Visual Studio pops up a separate dialog
3635
// offering a choice to debug the aborted program. We need to suppress
3636
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3637
// executed. Google Test will notify the user of any unexpected
3638
// failure via stderr.
3640
// VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3641
// Users of prior VC versions shall suffer the agony and pain of
3642
// clicking through the countless debug dialogs.
3643
// TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3644
// debug mode when compiled with VC 7.1 or lower.
3645
if (!GTEST_FLAG(break_on_failure))
3646
_set_abort_behavior(
3647
0x0, // Clear the following flags:
3648
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
3653
return impl_->RunAllTests();
3654
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3655
GetExceptionCode())) {
3656
printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3661
#else // We are on a compiler or platform that doesn't support SEH.
3663
return impl_->RunAllTests();
3664
#endif // GTEST_HAS_SEH
3667
// Returns the working directory when the first TEST() or TEST_F() was
3669
const char* UnitTest::original_working_dir() const {
3670
return impl_->original_working_dir_.c_str();
3673
// Returns the TestCase object for the test that's currently running,
3674
// or NULL if no test is running.
3676
const TestCase* UnitTest::current_test_case() const {
3677
internal::MutexLock lock(&mutex_);
3678
return impl_->current_test_case();
3681
// Returns the TestInfo object for the test that's currently running,
3682
// or NULL if no test is running.
3684
const TestInfo* UnitTest::current_test_info() const {
3685
internal::MutexLock lock(&mutex_);
3686
return impl_->current_test_info();
3689
// Returns the random seed used at the start of the current test run.
3690
int UnitTest::random_seed() const { return impl_->random_seed(); }
3692
#if GTEST_HAS_PARAM_TEST
3693
// Returns ParameterizedTestCaseRegistry object used to keep track of
3694
// value-parameterized tests and instantiate and register them.
3696
internal::ParameterizedTestCaseRegistry&
3697
UnitTest::parameterized_test_registry() {
3698
return impl_->parameterized_test_registry();
3700
#endif // GTEST_HAS_PARAM_TEST
3702
// Creates an empty UnitTest.
3703
UnitTest::UnitTest() {
3704
impl_ = new internal::UnitTestImpl(this);
3707
// Destructor of UnitTest.
3708
UnitTest::~UnitTest() {
3712
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3713
// Google Test trace stack.
3715
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3716
internal::MutexLock lock(&mutex_);
3717
impl_->gtest_trace_stack()->PushFront(trace);
3720
// Pops a trace from the per-thread Google Test trace stack.
3722
void UnitTest::PopGTestTrace() {
3723
internal::MutexLock lock(&mutex_);
3724
impl_->gtest_trace_stack()->PopFront(NULL);
3727
namespace internal {
3729
UnitTestImpl::UnitTestImpl(UnitTest* parent)
3732
#pragma warning(push) // Saves the current warning state.
3733
#pragma warning(disable:4355) // Temporarily disables warning 4355
3734
// (using this in initializer).
3735
default_global_test_part_result_reporter_(this),
3736
default_per_thread_test_part_result_reporter_(this),
3737
#pragma warning(pop) // Restores the warning state again.
3739
default_global_test_part_result_reporter_(this),
3740
default_per_thread_test_part_result_reporter_(this),
3742
global_test_part_result_repoter_(
3743
&default_global_test_part_result_reporter_),
3744
per_thread_test_part_result_reporter_(
3745
&default_per_thread_test_part_result_reporter_),
3746
#if GTEST_HAS_PARAM_TEST
3747
parameterized_test_registry_(),
3748
parameterized_tests_registered_(false),
3749
#endif // GTEST_HAS_PARAM_TEST
3750
last_death_test_case_(-1),
3751
current_test_case_(NULL),
3752
current_test_info_(NULL),
3753
ad_hoc_test_result_(),
3754
os_stack_trace_getter_(NULL),
3755
post_flag_parse_init_performed_(false),
3756
random_seed_(0), // Will be overridden by the flag before first use.
3757
random_(0), // Will be reseeded before first use.
3758
#if GTEST_HAS_DEATH_TEST
3760
internal_run_death_test_flag_(NULL),
3761
death_test_factory_(new DefaultDeathTestFactory) {
3764
#endif // GTEST_HAS_DEATH_TEST
3765
listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
3768
UnitTestImpl::~UnitTestImpl() {
3769
// Deletes every TestCase.
3770
test_cases_.ForEach(internal::Delete<TestCase>);
3772
// Deletes every Environment.
3773
environments_.ForEach(internal::Delete<Environment>);
3775
delete os_stack_trace_getter_;
3778
#if GTEST_HAS_DEATH_TEST
3779
// Disables event forwarding if the control is currently in a death test
3780
// subprocess. Must not be called before InitGoogleTest.
3781
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3782
if (internal_run_death_test_flag_.get() != NULL)
3783
listeners()->SuppressEventForwarding();
3785
#endif // GTEST_HAS_DEATH_TEST
3787
// Initializes event listeners performing XML output as specified by
3788
// UnitTestOptions. Must not be called before InitGoogleTest.
3789
void UnitTestImpl::ConfigureXmlOutput() {
3790
const String& output_format = UnitTestOptions::GetOutputFormat();
3791
if (output_format == "xml") {
3792
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3793
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3794
} else if (output_format != "") {
3795
printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3796
output_format.c_str());
3801
// Performs initialization dependent upon flag values obtained in
3802
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
3803
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
3804
// this function is also called from RunAllTests. Since this function can be
3805
// called more than once, it has to be idempotent.
3806
void UnitTestImpl::PostFlagParsingInit() {
3807
// Ensures that this function does not execute more than once.
3808
if (!post_flag_parse_init_performed_) {
3809
post_flag_parse_init_performed_ = true;
3811
#if GTEST_HAS_DEATH_TEST
3812
InitDeathTestSubprocessControlInfo();
3813
SuppressTestEventsIfInSubprocess();
3814
#endif // GTEST_HAS_DEATH_TEST
3816
// Registers parameterized tests. This makes parameterized tests
3817
// available to the UnitTest reflection API without running
3819
RegisterParameterizedTests();
3821
// Configures listeners for XML output. This makes it possible for users
3822
// to shut down the default XML output before invoking RUN_ALL_TESTS.
3823
ConfigureXmlOutput();
3827
// A predicate that checks the name of a TestCase against a known
3830
// This is used for implementation of the UnitTest class only. We put
3831
// it in the anonymous namespace to prevent polluting the outer
3834
// TestCaseNameIs is copyable.
3835
class TestCaseNameIs {
3838
explicit TestCaseNameIs(const String& name)
3841
// Returns true iff the name of test_case matches name_.
3842
bool operator()(const TestCase* test_case) const {
3843
return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3850
// Finds and returns a TestCase with the given name. If one doesn't
3851
// exist, creates one and returns it. It's the CALLER'S
3852
// RESPONSIBILITY to ensure that this function is only called WHEN THE
3853
// TESTS ARE NOT SHUFFLED.
3857
// test_case_name: name of the test case
3858
// set_up_tc: pointer to the function that sets up the test case
3859
// tear_down_tc: pointer to the function that tears down the test case
3860
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3861
const char* comment,
3862
Test::SetUpTestCaseFunc set_up_tc,
3863
Test::TearDownTestCaseFunc tear_down_tc) {
3864
// Can we find a TestCase with the given name?
3865
TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name));
3867
if (test_case != NULL)
3870
// No. Let's create one.
3871
TestCase* const new_test_case =
3872
new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3874
// Is this a death test case?
3875
if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3876
kDeathTestCaseFilter)) {
3877
// Yes. Inserts the test case after the last death test case
3878
// defined so far. This only works when the test cases haven't
3879
// been shuffled. Otherwise we may end up running a death test
3880
// after a non-death test.
3881
test_cases_.Insert(new_test_case, ++last_death_test_case_);
3883
// No. Appends to the end of the list.
3884
test_cases_.PushBack(new_test_case);
3887
test_case_indices_.PushBack(test_case_indices_.size());
3888
return new_test_case;
3891
// Helpers for setting up / tearing down the given environment. They
3892
// are for use in the Vector::ForEach() method.
3893
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3894
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3896
// Runs all tests in this UnitTest object, prints the result, and
3897
// returns 0 if all tests are successful, or 1 otherwise. If any
3898
// exception is thrown during a test on Windows, this test is
3899
// considered to be failed, but the rest of the tests will still be
3900
// run. (We disable exceptions on Linux and Mac OS X, so the issue
3901
// doesn't apply there.)
3902
// When parameterized tests are enabled, it expands and registers
3903
// parameterized tests first in RegisterParameterizedTests().
3904
// All other functions called from RunAllTests() may safely assume that
3905
// parameterized tests are ready to be counted and run.
3906
int UnitTestImpl::RunAllTests() {
3907
// Makes sure InitGoogleTest() was called.
3908
if (!GTestIsInitialized()) {
3910
"\nThis test program did NOT call ::testing::InitGoogleTest "
3911
"before calling RUN_ALL_TESTS(). Please fix it.\n");
3915
// Do not run any test if the --help flag was specified.
3919
// Repeats the call to the post-flag parsing initialization in case the
3920
// user didn't call InitGoogleTest.
3921
PostFlagParsingInit();
3923
// Even if sharding is not on, test runners may want to use the
3924
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3926
internal::WriteToShardStatusFileIfNeeded();
3928
// True iff we are in a subprocess for running a thread-safe-style
3930
bool in_subprocess_for_death_test = false;
3932
#if GTEST_HAS_DEATH_TEST
3933
in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3934
#endif // GTEST_HAS_DEATH_TEST
3936
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3937
in_subprocess_for_death_test);
3939
// Compares the full test names with the filter to decide which
3941
const bool has_tests_to_run = FilterTests(should_shard
3942
? HONOR_SHARDING_PROTOCOL
3943
: IGNORE_SHARDING_PROTOCOL) > 0;
3945
// Lists the tests and exits if the --gtest_list_tests flag was specified.
3946
if (GTEST_FLAG(list_tests)) {
3947
// This must be called *after* FilterTests() has been called.
3948
ListTestsMatchingFilter();
3952
random_seed_ = GTEST_FLAG(shuffle) ?
3953
GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3955
// True iff at least one test has failed.
3956
bool failed = false;
3958
TestEventListener* repeater = listeners()->repeater();
3960
repeater->OnTestProgramStart(*parent_);
3962
// How many times to repeat the tests? We don't want to repeat them
3963
// when we are inside the subprocess of a death test.
3964
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3965
// Repeats forever if the repeat count is negative.
3966
const bool forever = repeat < 0;
3967
for (int i = 0; forever || i != repeat; i++) {
3970
const TimeInMillis start = GetTimeInMillis();
3972
// Shuffles test cases and tests if requested.
3973
if (has_tests_to_run && GTEST_FLAG(shuffle)) {
3974
random()->Reseed(random_seed_);
3975
// This should be done before calling OnTestIterationStart(),
3976
// such that a test event listener can see the actual test order
3981
// Tells the unit test event listeners that the tests are about to start.
3982
repeater->OnTestIterationStart(*parent_, i);
3984
// Runs each test case if there is at least one test to run.
3985
if (has_tests_to_run) {
3986
// Sets up all environments beforehand.
3987
repeater->OnEnvironmentsSetUpStart(*parent_);
3988
environments_.ForEach(SetUpEnvironment);
3989
repeater->OnEnvironmentsSetUpEnd(*parent_);
3991
// Runs the tests only if there was no fatal failure during global
3993
if (!Test::HasFatalFailure()) {
3994
for (int i = 0; i < total_test_case_count(); i++) {
3995
GetMutableTestCase(i)->Run();
3999
// Tears down all environments in reverse order afterwards.
4000
repeater->OnEnvironmentsTearDownStart(*parent_);
4001
environments_in_reverse_order_.ForEach(TearDownEnvironment);
4002
repeater->OnEnvironmentsTearDownEnd(*parent_);
4005
elapsed_time_ = GetTimeInMillis() - start;
4007
// Tells the unit test event listener that the tests have just finished.
4008
repeater->OnTestIterationEnd(*parent_, i);
4010
// Gets the result and clears it.
4015
// Restores the original test order after the iteration. This
4016
// allows the user to quickly repro a failure that happens in the
4017
// N-th iteration without repeating the first (N - 1) iterations.
4018
// This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4019
// case the user somehow changes the value of the flag somewhere
4020
// (it's always safe to unshuffle the tests).
4023
if (GTEST_FLAG(shuffle)) {
4024
// Picks a new random seed for each iteration.
4025
random_seed_ = GetNextRandomSeed(random_seed_);
4029
repeater->OnTestProgramEnd(*parent_);
4031
// Returns 0 if all tests passed, or 1 other wise.
4032
return failed ? 1 : 0;
4035
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4036
// if the variable is present. If a file already exists at this location, this
4037
// function will write over it. If the variable is present, but the file cannot
4038
// be created, prints an error and exits.
4039
void WriteToShardStatusFileIfNeeded() {
4040
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4041
if (test_shard_file != NULL) {
4042
FILE* const file = posix::FOpen(test_shard_file, "w");
4044
ColoredPrintf(COLOR_RED,
4045
"Could not write to the test shard status file \"%s\" "
4046
"specified by the %s environment variable.\n",
4047
test_shard_file, kTestShardStatusFile);
4055
// Checks whether sharding is enabled by examining the relevant
4056
// environment variable values. If the variables are present,
4057
// but inconsistent (i.e., shard_index >= total_shards), prints
4058
// an error and exits. If in_subprocess_for_death_test, sharding is
4059
// disabled because it must only be applied to the original test
4060
// process. Otherwise, we could filter out death tests we intended to execute.
4061
bool ShouldShard(const char* total_shards_env,
4062
const char* shard_index_env,
4063
bool in_subprocess_for_death_test) {
4064
if (in_subprocess_for_death_test) {
4068
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4069
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4071
if (total_shards == -1 && shard_index == -1) {
4073
} else if (total_shards == -1 && shard_index != -1) {
4074
const Message msg = Message()
4075
<< "Invalid environment variables: you have "
4076
<< kTestShardIndex << " = " << shard_index
4077
<< ", but have left " << kTestTotalShards << " unset.\n";
4078
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4081
} else if (total_shards != -1 && shard_index == -1) {
4082
const Message msg = Message()
4083
<< "Invalid environment variables: you have "
4084
<< kTestTotalShards << " = " << total_shards
4085
<< ", but have left " << kTestShardIndex << " unset.\n";
4086
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4089
} else if (shard_index < 0 || shard_index >= total_shards) {
4090
const Message msg = Message()
4091
<< "Invalid environment variables: we require 0 <= "
4092
<< kTestShardIndex << " < " << kTestTotalShards
4093
<< ", but you have " << kTestShardIndex << "=" << shard_index
4094
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
4095
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4100
return total_shards > 1;
4103
// Parses the environment variable var as an Int32. If it is unset,
4104
// returns default_val. If it is not an Int32, prints an error
4106
Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
4107
const char* str_val = posix::GetEnv(var);
4108
if (str_val == NULL) {
4113
if (!ParseInt32(Message() << "The value of environment variable " << var,
4114
str_val, &result)) {
4120
// Given the total number of shards, the shard index, and the test id,
4121
// returns true iff the test should be run on this shard. The test id is
4122
// some arbitrary but unique non-negative integer assigned to each test
4123
// method. Assumes that 0 <= shard_index < total_shards.
4124
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4125
return (test_id % total_shards) == shard_index;
4128
// Compares the name of each test with the user-specified filter to
4129
// decide whether the test should be run, then records the result in
4130
// each TestCase and TestInfo object.
4131
// If shard_tests == true, further filters tests based on sharding
4132
// variables in the environment - see
4133
// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4134
// Returns the number of tests that should run.
4135
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4136
const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4137
Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4138
const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4139
Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4141
// num_runnable_tests are the number of tests that will
4142
// run across all shards (i.e., match filter and are not disabled).
4143
// num_selected_tests are the number of tests to be run on
4145
int num_runnable_tests = 0;
4146
int num_selected_tests = 0;
4147
for (int i = 0; i < test_cases_.size(); i++) {
4148
TestCase* const test_case = test_cases_.GetElement(i);
4149
const String &test_case_name = test_case->name();
4150
test_case->set_should_run(false);
4152
for (int j = 0; j < test_case->test_info_list().size(); j++) {
4153
TestInfo* const test_info = test_case->test_info_list().GetElement(j);
4154
const String test_name(test_info->name());
4155
// A test is disabled if test case name or test name matches
4156
// kDisableTestFilter.
4157
const bool is_disabled =
4158
internal::UnitTestOptions::MatchesFilter(test_case_name,
4159
kDisableTestFilter) ||
4160
internal::UnitTestOptions::MatchesFilter(test_name,
4161
kDisableTestFilter);
4162
test_info->impl()->set_is_disabled(is_disabled);
4164
const bool matches_filter =
4165
internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4167
test_info->impl()->set_matches_filter(matches_filter);
4169
const bool is_runnable =
4170
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4173
const bool is_selected = is_runnable &&
4174
(shard_tests == IGNORE_SHARDING_PROTOCOL ||
4175
ShouldRunTestOnShard(total_shards, shard_index,
4176
num_runnable_tests));
4178
num_runnable_tests += is_runnable;
4179
num_selected_tests += is_selected;
4181
test_info->impl()->set_should_run(is_selected);
4182
test_case->set_should_run(test_case->should_run() || is_selected);
4185
return num_selected_tests;
4188
// Prints the names of the tests matching the user-specified filter flag.
4189
void UnitTestImpl::ListTestsMatchingFilter() {
4190
for (int i = 0; i < test_cases_.size(); i++) {
4191
const TestCase* const test_case = test_cases_.GetElement(i);
4192
bool printed_test_case_name = false;
4194
for (int j = 0; j < test_case->test_info_list().size(); j++) {
4195
const TestInfo* const test_info =
4196
test_case->test_info_list().GetElement(j);
4197
if (test_info->matches_filter()) {
4198
if (!printed_test_case_name) {
4199
printed_test_case_name = true;
4200
printf("%s.\n", test_case->name());
4202
printf(" %s\n", test_info->name());
4209
// Sets the OS stack trace getter.
4211
// Does nothing if the input and the current OS stack trace getter are
4212
// the same; otherwise, deletes the old getter and makes the input the
4214
void UnitTestImpl::set_os_stack_trace_getter(
4215
OsStackTraceGetterInterface* getter) {
4216
if (os_stack_trace_getter_ != getter) {
4217
delete os_stack_trace_getter_;
4218
os_stack_trace_getter_ = getter;
4222
// Returns the current OS stack trace getter if it is not NULL;
4223
// otherwise, creates an OsStackTraceGetter, makes it the current
4224
// getter, and returns it.
4225
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4226
if (os_stack_trace_getter_ == NULL) {
4227
os_stack_trace_getter_ = new OsStackTraceGetter;
4230
return os_stack_trace_getter_;
4233
// Returns the TestResult for the test that's currently running, or
4234
// the TestResult for the ad hoc test if no test is running.
4235
TestResult* UnitTestImpl::current_test_result() {
4236
return current_test_info_ ?
4237
current_test_info_->impl()->result() : &ad_hoc_test_result_;
4240
// Shuffles all test cases, and the tests within each test case,
4241
// making sure that death tests are still run first.
4242
void UnitTestImpl::ShuffleTests() {
4243
// Shuffles the death test cases.
4244
test_case_indices_.ShuffleRange(random(), 0, last_death_test_case_ + 1);
4246
// Shuffles the non-death test cases.
4247
test_case_indices_.ShuffleRange(random(), last_death_test_case_ + 1,
4248
test_cases_.size());
4250
// Shuffles the tests inside each test case.
4251
for (int i = 0; i < test_cases_.size(); i++) {
4252
test_cases_.GetElement(i)->ShuffleTests(random());
4256
// Restores the test cases and tests to their order before the first shuffle.
4257
void UnitTestImpl::UnshuffleTests() {
4258
for (int i = 0; i < test_cases_.size(); i++) {
4259
// Unshuffles the tests in each test case.
4260
test_cases_.GetElement(i)->UnshuffleTests();
4261
// Resets the index of each test case.
4262
test_case_indices_.GetMutableElement(i) = i;
4266
// TestInfoImpl constructor. The new instance assumes ownership of the test
4268
TestInfoImpl::TestInfoImpl(TestInfo* parent,
4269
const char* test_case_name,
4271
const char* test_case_comment,
4272
const char* comment,
4273
TypeId fixture_class_id,
4274
internal::TestFactoryBase* factory) :
4276
test_case_name_(String(test_case_name)),
4277
name_(String(name)),
4278
test_case_comment_(String(test_case_comment)),
4279
comment_(String(comment)),
4280
fixture_class_id_(fixture_class_id),
4282
is_disabled_(false),
4283
matches_filter_(false),
4287
// TestInfoImpl destructor.
4288
TestInfoImpl::~TestInfoImpl() {
4292
// Returns the current OS stack trace as a String.
4294
// The maximum number of stack frames to be included is specified by
4295
// the gtest_stack_trace_depth flag. The skip_count parameter
4296
// specifies the number of top frames to be skipped, which doesn't
4297
// count against the number of frames to be included.
4299
// For example, if Foo() calls Bar(), which in turn calls
4300
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4301
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4302
String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4304
// We pass skip_count + 1 to skip this wrapper function in addition
4305
// to what the user really wants to skip.
4306
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4309
// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4312
class ClassUniqueToAlwaysTrue {};
4315
bool IsTrue(bool condition) { return condition; }
4318
#if GTEST_HAS_EXCEPTIONS
4319
// This condition is always false so AlwaysTrue() never actually throws,
4320
// but it makes the compiler think that it may throw.
4322
throw ClassUniqueToAlwaysTrue();
4323
#endif // GTEST_HAS_EXCEPTIONS
4327
// Parses a string as a command line flag. The string should have
4328
// the format "--flag=value". When def_optional is true, the "=value"
4329
// part can be omitted.
4331
// Returns the value of the flag, or NULL if the parsing failed.
4332
const char* ParseFlagValue(const char* str,
4334
bool def_optional) {
4335
// str and flag must not be NULL.
4336
if (str == NULL || flag == NULL) return NULL;
4338
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4339
const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
4340
const size_t flag_len = flag_str.length();
4341
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4343
// Skips the flag name.
4344
const char* flag_end = str + flag_len;
4346
// When def_optional is true, it's OK to not have a "=value" part.
4347
if (def_optional && (flag_end[0] == '\0')) {
4351
// If def_optional is true and there are more characters after the
4352
// flag name, or if def_optional is false, there must be a '=' after
4354
if (flag_end[0] != '=') return NULL;
4356
// Returns the string after "=".
4357
return flag_end + 1;
4360
// Parses a string for a bool flag, in the form of either
4361
// "--flag=value" or "--flag".
4363
// In the former case, the value is taken as true as long as it does
4364
// not start with '0', 'f', or 'F'.
4366
// In the latter case, the value is taken as true.
4368
// On success, stores the value of the flag in *value, and returns
4369
// true. On failure, returns false without changing *value.
4370
bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4371
// Gets the value of the flag as a string.
4372
const char* const value_str = ParseFlagValue(str, flag, true);
4374
// Aborts if the parsing failed.
4375
if (value_str == NULL) return false;
4377
// Converts the string value to a bool.
4378
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4382
// Parses a string for an Int32 flag, in the form of
4385
// On success, stores the value of the flag in *value, and returns
4386
// true. On failure, returns false without changing *value.
4387
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4388
// Gets the value of the flag as a string.
4389
const char* const value_str = ParseFlagValue(str, flag, false);
4391
// Aborts if the parsing failed.
4392
if (value_str == NULL) return false;
4394
// Sets *value to the value of the flag.
4395
return ParseInt32(Message() << "The value of flag --" << flag,
4399
// Parses a string for a string flag, in the form of
4402
// On success, stores the value of the flag in *value, and returns
4403
// true. On failure, returns false without changing *value.
4404
bool ParseStringFlag(const char* str, const char* flag, String* value) {
4405
// Gets the value of the flag as a string.
4406
const char* const value_str = ParseFlagValue(str, flag, false);
4408
// Aborts if the parsing failed.
4409
if (value_str == NULL) return false;
4411
// Sets *value to the value of the flag.
4416
// Prints a string containing code-encoded text. The following escape
4417
// sequences can be used in the string to control the text color:
4419
// @@ prints a single '@' character.
4420
// @R changes the color to red.
4421
// @G changes the color to green.
4422
// @Y changes the color to yellow.
4423
// @D changes to the default terminal text color.
4425
// TODO(wan@google.com): Write tests for this once we add stdout
4426
// capturing to Google Test.
4427
static void PrintColorEncoded(const char* str) {
4428
GTestColor color = COLOR_DEFAULT; // The current color.
4430
// Conceptually, we split the string into segments divided by escape
4431
// sequences. Then we print one segment at a time. At the end of
4432
// each iteration, the str pointer advances to the beginning of the
4435
const char* p = strchr(str, '@');
4437
ColoredPrintf(color, "%s", str);
4441
ColoredPrintf(color, "%s", String(str, p - str).c_str());
4443
const char ch = p[1];
4446
ColoredPrintf(color, "@");
4447
} else if (ch == 'D') {
4448
color = COLOR_DEFAULT;
4449
} else if (ch == 'R') {
4451
} else if (ch == 'G') {
4452
color = COLOR_GREEN;
4453
} else if (ch == 'Y') {
4454
color = COLOR_YELLOW;
4461
static const char kColorEncodedHelpMessage[] =
4462
"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4463
"following command line flags to control its behavior:\n"
4466
" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4467
" List the names of all tests instead of running them. The name of\n"
4468
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
4469
" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4470
"[@G-@YNEGATIVE_PATTERNS]@D\n"
4471
" Run only the tests whose name matches one of the positive patterns but\n"
4472
" none of the negative patterns. '?' matches any single character; '*'\n"
4473
" matches any substring; ':' separates two patterns.\n"
4474
" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4475
" Run all disabled tests too.\n"
4478
" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4479
" Run the tests repeatedly; use a negative count to repeat forever.\n"
4480
" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4481
" Randomize tests' orders on every iteration.\n"
4482
" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4483
" Random number seed to use for shuffling test orders (between 1 and\n"
4484
" 99999, or 0 to use a seed based on the current time).\n"
4487
" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4488
" Enable/disable colored output. The default is @Gauto@D.\n"
4489
" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4490
" Don't print the elapsed time of each test.\n"
4491
" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4492
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4493
" Generate an XML report in the given directory or with the given file\n"
4494
" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4496
"Assertion Behavior:\n"
4497
#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4498
" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4499
" Set the default death test style.\n"
4500
#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4501
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4502
" Turn assertion failures into debugger break-points.\n"
4503
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4504
" Turn assertion failures into C++ exceptions.\n"
4505
#if GTEST_OS_WINDOWS
4506
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4507
" Suppress pop-ups caused by exceptions.\n"
4508
#endif // GTEST_OS_WINDOWS
4510
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4511
"the corresponding\n"
4512
"environment variable of a flag (all letters in upper-case). For example, to\n"
4513
"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4514
"color=no@D or set\n"
4515
"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
4517
"For more information, please read the " GTEST_NAME_ " documentation at\n"
4518
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4519
"(not one in your own code or tests), please report it to\n"
4520
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4522
// Parses the command line for Google Test flags, without initializing
4523
// other parts of Google Test. The type parameter CharType can be
4524
// instantiated to either char or wchar_t.
4525
template <typename CharType>
4526
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4527
for (int i = 1; i < *argc; i++) {
4528
const String arg_string = StreamableToString(argv[i]);
4529
const char* const arg = arg_string.c_str();
4531
using internal::ParseBoolFlag;
4532
using internal::ParseInt32Flag;
4533
using internal::ParseStringFlag;
4535
// Do we see a Google Test flag?
4536
if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4537
>EST_FLAG(also_run_disabled_tests)) ||
4538
ParseBoolFlag(arg, kBreakOnFailureFlag,
4539
>EST_FLAG(break_on_failure)) ||
4540
ParseBoolFlag(arg, kCatchExceptionsFlag,
4541
>EST_FLAG(catch_exceptions)) ||
4542
ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
4543
ParseStringFlag(arg, kDeathTestStyleFlag,
4544
>EST_FLAG(death_test_style)) ||
4545
ParseBoolFlag(arg, kDeathTestUseFork,
4546
>EST_FLAG(death_test_use_fork)) ||
4547
ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
4548
ParseStringFlag(arg, kInternalRunDeathTestFlag,
4549
>EST_FLAG(internal_run_death_test)) ||
4550
ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
4551
ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
4552
ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
4553
ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
4554
ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
4555
ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
4556
ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure))
4558
// Yes. Shift the remainder of the argv list left by one. Note
4559
// that argv has (*argc + 1) elements, the last one always being
4560
// NULL. The following loop moves the trailing NULL element as
4562
for (int j = i; j != *argc; j++) {
4563
argv[j] = argv[j + 1];
4566
// Decrements the argument count.
4569
// We also need to decrement the iterator as we just removed
4572
} else if (arg_string == "--help" || arg_string == "-h" ||
4573
arg_string == "-?" || arg_string == "/?") {
4579
// We print the help here instead of in RUN_ALL_TESTS(), as the
4580
// latter may not be called at all if the user is using Google
4581
// Test with another testing framework.
4582
PrintColorEncoded(kColorEncodedHelpMessage);
4586
// Parses the command line for Google Test flags, without initializing
4587
// other parts of Google Test.
4588
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4589
ParseGoogleTestFlagsOnlyImpl(argc, argv);
4591
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4592
ParseGoogleTestFlagsOnlyImpl(argc, argv);
4595
// The internal implementation of InitGoogleTest().
4597
// The type parameter CharType can be instantiated to either char or
4599
template <typename CharType>
4600
void InitGoogleTestImpl(int* argc, CharType** argv) {
4601
g_init_gtest_count++;
4603
// We don't want to run the initialization code twice.
4604
if (g_init_gtest_count != 1) return;
4606
if (*argc <= 0) return;
4608
internal::g_executable_path = internal::StreamableToString(argv[0]);
4610
#if GTEST_HAS_DEATH_TEST
4612
for (int i = 0; i != *argc; i++) {
4613
g_argvs.push_back(StreamableToString(argv[i]));
4615
#endif // GTEST_HAS_DEATH_TEST
4617
ParseGoogleTestFlagsOnly(argc, argv);
4618
GetUnitTestImpl()->PostFlagParsingInit();
4621
} // namespace internal
4623
// Initializes Google Test. This must be called before calling
4624
// RUN_ALL_TESTS(). In particular, it parses a command line for the
4625
// flags that Google Test recognizes. Whenever a Google Test flag is
4626
// seen, it is removed from argv, and *argc is decremented.
4628
// No value is returned. Instead, the Google Test flag variables are
4631
// Calling the function for the second time has no user-visible effect.
4632
void InitGoogleTest(int* argc, char** argv) {
4633
internal::InitGoogleTestImpl(argc, argv);
4636
// This overloaded version can be used in Windows programs compiled in
4638
void InitGoogleTest(int* argc, wchar_t** argv) {
4639
internal::InitGoogleTestImpl(argc, argv);
4642
} // namespace testing