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>
47
// TODO(kenton@google.com): Use autoconf to detect availability of
49
#define GTEST_HAS_GETTIMEOFDAY_ 1
54
// Declares vsnprintf(). This header is not available on Windows.
62
#elif GTEST_OS_SYMBIAN
63
#define GTEST_HAS_GETTIMEOFDAY_ 1
64
#include <sys/time.h> // NOLINT
67
#define GTEST_HAS_GETTIMEOFDAY_ 1
68
#include <sys/time.h> // NOLINT
70
// On z/OS we additionally need strings.h for strcasecmp.
71
#include <strings.h> // NOLINT
73
#elif defined(_WIN32_WCE) // We are on Windows CE.
75
#include <windows.h> // NOLINT
77
#elif GTEST_OS_WINDOWS // We are on Windows proper.
79
#include <io.h> // NOLINT
80
#include <sys/timeb.h> // NOLINT
81
#include <sys/types.h> // NOLINT
82
#include <sys/stat.h> // NOLINT
84
#if defined(__MINGW__) || defined(__MINGW32__)
85
// MinGW has gettimeofday() but not _ftime64().
86
// TODO(kenton@google.com): Use autoconf to detect availability of
88
// TODO(kenton@google.com): There are other ways to get the time on
89
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
90
// supports these. consider using them instead.
91
#define GTEST_HAS_GETTIMEOFDAY_ 1
92
#include <sys/time.h> // NOLINT
93
#endif // defined(__MINGW__) || defined(__MINGW32__)
95
// cpplint thinks that the header is already included, so we want to
97
#include <windows.h> // NOLINT
101
// Assume other platforms have gettimeofday().
102
// TODO(kenton@google.com): Use autoconf to detect availability of
104
#define GTEST_HAS_GETTIMEOFDAY_ 1
106
// cpplint thinks that the header is already included, so we want to
108
#include <sys/time.h> // NOLINT
109
#include <unistd.h> // NOLINT
111
#endif // GTEST_OS_LINUX
113
#if GTEST_HAS_EXCEPTIONS
117
// Indicates that this translation unit is part of Google Test's
118
// implementation. It must come before gtest-internal-inl.h is
119
// included, or there will be a compiler error. This trick is to
120
// prevent a user from accidentally including gtest-internal-inl.h in
122
#define GTEST_IMPLEMENTATION_ 1
123
#include "src/gtest-internal-inl.h"
124
#undef GTEST_IMPLEMENTATION_
127
#define vsnprintf _vsnprintf
128
#endif // GTEST_OS_WINDOWS
132
using internal::TestCase;
133
using internal::TestProperty;
134
using internal::TestResult;
138
// A test whose test case name or test name matches this filter is
139
// disabled and not run.
140
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
142
// A test case whose name matches this filter is considered a death
143
// test case and will be run before test cases whose name doesn't
144
// match this filter.
145
static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
147
// A test filter that matches everything.
148
static const char kUniversalFilter[] = "*";
150
// The default output file for XML output.
151
static const char kDefaultOutputFile[] = "test_detail.xml";
153
// The environment variable name for the test shard index.
154
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
155
// The environment variable name for the total number of test shards.
156
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
157
// The environment variable name for the test shard status file.
158
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
162
// The text used in failure messages to indicate the start of the
164
const char kStackTraceMarker[] = "\nStack trace:\n";
166
} // namespace internal
169
also_run_disabled_tests,
170
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
171
"Run disabled tests too, in addition to the tests normally being run.");
175
internal::BoolFromGTestEnv("break_on_failure", false),
176
"True iff a failed assertion should be a debugger break-point.");
180
internal::BoolFromGTestEnv("catch_exceptions", false),
181
"True iff " GTEST_NAME_
182
" should catch exceptions and treat them as test failures.");
184
GTEST_DEFINE_string_(
186
internal::StringFromGTestEnv("color", "auto"),
187
"Whether to use colors in the output. Valid values: yes, no, "
188
"and auto. 'auto' means to use colors if the output is "
189
"being sent to a terminal and the TERM environment variable "
190
"is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
192
GTEST_DEFINE_string_(
194
internal::StringFromGTestEnv("filter", kUniversalFilter),
195
"A colon-separated list of glob (not regex) patterns "
196
"for filtering the tests to run, optionally followed by a "
197
"'-' and a : separated list of negative patterns (tests to "
198
"exclude). A test is run if it matches one of the positive "
199
"patterns and does not match any of the negative patterns.");
201
GTEST_DEFINE_bool_(list_tests, false,
202
"List all tests without running them.");
204
GTEST_DEFINE_string_(
206
internal::StringFromGTestEnv("output", ""),
207
"A format (currently must be \"xml\"), optionally followed "
208
"by a colon and an output file name or directory. A directory "
209
"is indicated by a trailing pathname separator. "
210
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
211
"If a directory is specified, output files will be created "
212
"within that directory, with file-names based on the test "
213
"executable's name and, if necessary, made unique by adding "
218
internal::BoolFromGTestEnv("print_time", true),
219
"True iff " GTEST_NAME_
220
" should display elapsed time in text output.");
224
internal::Int32FromGTestEnv("random_seed", 0),
225
"Random number seed to use when shuffling test orders. Must be in range "
226
"[1, 99999], or 0 to use a seed based on the current time.");
230
internal::Int32FromGTestEnv("repeat", 1),
231
"How many times to repeat each test. Specify a negative number "
232
"for repeating forever. Useful for shaking out flaky tests.");
235
show_internal_stack_frames, false,
236
"True iff " GTEST_NAME_ " should include internal stack frames when "
237
"printing test failure stack traces.");
241
internal::BoolFromGTestEnv("shuffle", false),
242
"True iff " GTEST_NAME_
243
" should randomize tests' order on every run.");
247
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
248
"The maximum number of stack frames to print when an "
249
"assertion fails. The valid range is 0 through 100, inclusive.");
253
internal::BoolFromGTestEnv("throw_on_failure", false),
254
"When this flag is specified, a failed assertion will throw an exception "
255
"if exceptions are enabled or exit the program with a non-zero code "
260
// g_help_flag is true iff the --help flag or an equivalent form is
261
// specified on the command line.
262
static bool g_help_flag = false;
264
// GTestIsInitialized() returns true iff the user has initialized
265
// Google Test. Useful for catching the user mistake of not initializing
266
// Google Test before calling RUN_ALL_TESTS().
268
// A user must call testing::InitGoogleTest() to initialize Google
269
// Test. g_init_gtest_count is set to the number of times
270
// InitGoogleTest() has been called. We don't protect this variable
271
// under a mutex as it is only accessed in the main thread.
272
int g_init_gtest_count = 0;
273
static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
275
// Iterates over a vector of TestCases, keeping a running sum of the
276
// results of calling a given int-returning method on each.
278
static int SumOverTestCaseList(const internal::Vector<TestCase*>& case_list,
279
int (TestCase::*method)() const) {
281
for (int i = 0; i < case_list.size(); i++) {
282
sum += (case_list.GetElement(i)->*method)();
287
// Returns true iff the test case passed.
288
static bool TestCasePassed(const TestCase* test_case) {
289
return test_case->should_run() && test_case->Passed();
292
// Returns true iff the test case failed.
293
static bool TestCaseFailed(const TestCase* test_case) {
294
return test_case->should_run() && test_case->Failed();
297
// Returns true iff test_case contains at least one test that should
299
static bool ShouldRunTestCase(const TestCase* test_case) {
300
return test_case->should_run();
303
// AssertHelper constructor.
304
AssertHelper::AssertHelper(TestPartResultType type, const char* file,
305
int line, const char* message)
306
: type_(type), file_(file), line_(line), message_(message) {
309
// Message assignment, for assertion streaming support.
310
void AssertHelper::operator=(const Message& message) const {
311
UnitTest::GetInstance()->
312
AddTestPartResult(type_, file_, line_,
313
AppendUserMessage(message_, message),
314
UnitTest::GetInstance()->impl()
315
->CurrentOsStackTraceExceptTop(1)
316
// Skips the stack frame for this function itself.
320
// Mutex for linked pointers.
321
Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
323
// Application pathname gotten in InitGoogleTest.
324
String g_executable_path;
326
// Returns the current application's name, removing directory path if that
328
FilePath GetCurrentExecutableName() {
331
#if defined(_WIN32_WCE) || GTEST_OS_WINDOWS
332
result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
334
result.Set(FilePath(g_executable_path));
335
#endif // _WIN32_WCE || GTEST_OS_WINDOWS
337
return result.RemoveDirectoryName();
340
// Functions for processing the gtest_output flag.
342
// Returns the output format, or "" for normal printed output.
343
String UnitTestOptions::GetOutputFormat() {
344
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
345
if (gtest_output_flag == NULL) return String("");
347
const char* const colon = strchr(gtest_output_flag, ':');
348
return (colon == NULL) ?
349
String(gtest_output_flag) :
350
String(gtest_output_flag, colon - gtest_output_flag);
353
// Returns the name of the requested output file, or the default if none
354
// was explicitly specified.
355
String UnitTestOptions::GetAbsolutePathToOutputFile() {
356
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
357
if (gtest_output_flag == NULL)
360
const char* const colon = strchr(gtest_output_flag, ':');
362
return String(internal::FilePath::ConcatPaths(
364
UnitTest::GetInstance()->original_working_dir()),
365
internal::FilePath(kDefaultOutputFile)).ToString() );
367
internal::FilePath output_name(colon + 1);
368
if (!output_name.IsAbsolutePath())
369
// TODO(wan@google.com): on Windows \some\path is not an absolute
370
// path (as its meaning depends on the current drive), yet the
371
// following logic for turning it into an absolute path is wrong.
373
output_name = internal::FilePath::ConcatPaths(
374
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
375
internal::FilePath(colon + 1));
377
if (!output_name.IsDirectory())
378
return output_name.ToString();
380
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
381
output_name, internal::GetCurrentExecutableName(),
382
GetOutputFormat().c_str()));
383
return result.ToString();
386
// Returns true iff the wildcard pattern matches the string. The
387
// first ':' or '\0' character in pattern marks the end of it.
389
// This recursive algorithm isn't very efficient, but is clear and
390
// works well enough for matching test names, which are short.
391
bool UnitTestOptions::PatternMatchesString(const char *pattern,
395
case ':': // Either ':' or '\0' marks the end of the pattern.
397
case '?': // Matches any single character.
398
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
399
case '*': // Matches any string (possibly empty) of characters.
400
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
401
PatternMatchesString(pattern + 1, str);
402
default: // Non-special character. Matches itself.
403
return *pattern == *str &&
404
PatternMatchesString(pattern + 1, str + 1);
408
bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
409
const char *cur_pattern = filter;
411
if (PatternMatchesString(cur_pattern, name.c_str())) {
415
// Finds the next pattern in the filter.
416
cur_pattern = strchr(cur_pattern, ':');
418
// Returns if no more pattern can be found.
419
if (cur_pattern == NULL) {
423
// Skips the pattern separater (the ':' character).
428
// TODO(keithray): move String function implementations to gtest-string.cc.
430
// Returns true iff the user-specified filter matches the test case
431
// name and the test name.
432
bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
433
const String &test_name) {
434
const String& full_name = String::Format("%s.%s",
435
test_case_name.c_str(),
438
// Split --gtest_filter at '-', if there is one, to separate into
439
// positive filter and negative filter portions
440
const char* const p = GTEST_FLAG(filter).c_str();
441
const char* const dash = strchr(p, '-');
445
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
446
negative = String("");
448
positive.Set(p, dash - p); // Everything up to the dash
449
negative = String(dash+1); // Everything after the dash
450
if (positive.empty()) {
451
// Treat '-test1' as the same as '*-test1'
452
positive = kUniversalFilter;
456
// A filter is a colon-separated list of patterns. It matches a
457
// test if any pattern in it matches the test.
458
return (MatchesFilter(full_name, positive.c_str()) &&
459
!MatchesFilter(full_name, negative.c_str()));
463
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
464
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
465
// This function is useful as an __except condition.
466
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
467
// Google Test should handle an exception if:
468
// 1. the user wants it to, AND
469
// 2. this is not a breakpoint exception.
470
return (GTEST_FLAG(catch_exceptions) &&
471
exception_code != EXCEPTION_BREAKPOINT) ?
472
EXCEPTION_EXECUTE_HANDLER :
473
EXCEPTION_CONTINUE_SEARCH;
475
#endif // GTEST_OS_WINDOWS
477
} // namespace internal
479
// The interface for printing the result of a UnitTest
480
class UnitTestEventListenerInterface {
482
// The d'tor is pure virtual as this is an abstract class.
483
virtual ~UnitTestEventListenerInterface() {}
485
// Called before the unit test starts.
486
virtual void OnUnitTestStart(const UnitTest& unit_test) = 0;
488
// Called after the unit test ends.
489
virtual void OnUnitTestEnd(const UnitTest& unit_test) = 0;
491
// Called before the test case starts.
492
virtual void OnTestCaseStart(const TestCase& test_case) = 0;
494
// Called after the test case ends.
495
virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
497
// Called before the global set-up starts.
498
virtual void OnGlobalSetUpStart(const UnitTest& unit_test) = 0;
500
// Called after the global set-up ends.
501
virtual void OnGlobalSetUpEnd(const UnitTest& unit_test) = 0;
503
// Called before the global tear-down starts.
504
virtual void OnGlobalTearDownStart(const UnitTest& unit_test) = 0;
506
// Called after the global tear-down ends.
507
virtual void OnGlobalTearDownEnd(const UnitTest& unit_test) = 0;
509
// Called before the test starts.
510
virtual void OnTestStart(const TestInfo& test_info) = 0;
512
// Called after the test ends.
513
virtual void OnTestEnd(const TestInfo& test_info) = 0;
515
// Called after an assertion.
516
virtual void OnNewTestPartResult(const TestPartResult& test_part_result) = 0;
519
// The convenience class for users who need to override just one or two
520
// methods and are not concerned that a possible change to a signature of
521
// the methods they override will not be caught during the build.
522
class EmptyTestEventListener : public UnitTestEventListenerInterface {
524
// Called before the unit test starts.
525
virtual void OnUnitTestStart(const UnitTest& /*unit_test*/) {}
527
// Called after the unit test ends.
528
virtual void OnUnitTestEnd(const UnitTest& /*unit_test*/) {}
530
// Called before the test case starts.
531
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
533
// Called after the test case ends.
534
virtual void OnTestCaseEnd(const TestCase& /*test_case&*/) {}
536
// Called before the global set-up starts.
537
virtual void OnGlobalSetUpStart(const UnitTest& /*unit_test*/) {}
539
// Called after the global set-up ends.
540
virtual void OnGlobalSetUpEnd(const UnitTest& /*unit_test*/) {}
542
// Called before the global tear-down starts.
543
virtual void OnGlobalTearDownStart(const UnitTest& /*unit_test*/) {}
545
// Called after the global tear-down ends.
546
virtual void OnGlobalTearDownEnd(const UnitTest& /*unit_test*/) {}
548
// Called before the test starts.
549
virtual void OnTestStart(const TestInfo& /*test_info*/) {}
551
// Called after the test ends.
552
virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
554
// Called after an assertion.
555
virtual void OnNewTestPartResult(const TestPartResult& /*test_part_result*/) {
559
// The c'tor sets this object as the test part result reporter used by
560
// Google Test. The 'result' parameter specifies where to report the
561
// results. Intercepts only failures from the current thread.
562
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
563
TestPartResultArray* result)
564
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
569
// The c'tor sets this object as the test part result reporter used by
570
// Google Test. The 'result' parameter specifies where to report the
572
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
573
InterceptMode intercept_mode, TestPartResultArray* result)
574
: intercept_mode_(intercept_mode),
579
void ScopedFakeTestPartResultReporter::Init() {
580
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
581
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
582
old_reporter_ = impl->GetGlobalTestPartResultReporter();
583
impl->SetGlobalTestPartResultReporter(this);
585
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
586
impl->SetTestPartResultReporterForCurrentThread(this);
590
// The d'tor restores the test part result reporter used by Google Test
592
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
593
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
594
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
595
impl->SetGlobalTestPartResultReporter(old_reporter_);
597
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
601
// Increments the test part result count and remembers the result.
602
// This method is from the TestPartResultReporterInterface interface.
603
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
604
const TestPartResult& result) {
605
result_->Append(result);
610
// Returns the type ID of ::testing::Test. We should always call this
611
// instead of GetTypeId< ::testing::Test>() to get the type ID of
612
// testing::Test. This is to work around a suspected linker bug when
613
// using Google Test as a framework on Mac OS X. The bug causes
614
// GetTypeId< ::testing::Test>() to return different values depending
615
// on whether the call is from the Google Test framework itself or
616
// from user test code. GetTestTypeId() is guaranteed to always
617
// return the same value, as it always calls GetTypeId<>() from the
618
// gtest.cc, which is within the Google Test framework.
619
TypeId GetTestTypeId() {
620
return GetTypeId<Test>();
623
// The value of GetTestTypeId() as seen from within the Google Test
624
// library. This is solely for testing GetTestTypeId().
625
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
627
// This predicate-formatter checks that 'results' contains a test part
628
// failure of the given type and that the failure message contains the
630
AssertionResult HasOneFailure(const char* /* results_expr */,
631
const char* /* type_expr */,
632
const char* /* substr_expr */,
633
const TestPartResultArray& results,
634
TestPartResultType type,
635
const char* substr) {
636
const String expected(
637
type == TPRT_FATAL_FAILURE ? "1 fatal failure" :
638
"1 non-fatal failure");
640
if (results.size() != 1) {
641
msg << "Expected: " << expected << "\n"
642
<< " Actual: " << results.size() << " failures";
643
for (int i = 0; i < results.size(); i++) {
644
msg << "\n" << results.GetTestPartResult(i);
646
return AssertionFailure(msg);
649
const TestPartResult& r = results.GetTestPartResult(0);
650
if (r.type() != type) {
651
msg << "Expected: " << expected << "\n"
654
return AssertionFailure(msg);
657
if (strstr(r.message(), substr) == NULL) {
658
msg << "Expected: " << expected << " containing \""
662
return AssertionFailure(msg);
665
return AssertionSuccess();
668
// The constructor of SingleFailureChecker remembers where to look up
669
// test part results, what type of failure we expect, and what
670
// substring the failure message should contain.
671
SingleFailureChecker:: SingleFailureChecker(
672
const TestPartResultArray* results,
673
TestPartResultType type,
679
// The destructor of SingleFailureChecker verifies that the given
680
// TestPartResultArray contains exactly one failure that has the given
681
// type and contains the given substring. If that's not the case, a
682
// non-fatal failure will be generated.
683
SingleFailureChecker::~SingleFailureChecker() {
684
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
687
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
688
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
690
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
691
const TestPartResult& result) {
692
unit_test_->current_test_result()->AddTestPartResult(result);
693
unit_test_->result_printer()->OnNewTestPartResult(result);
696
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
697
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
699
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
700
const TestPartResult& result) {
701
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
704
// Returns the global test part result reporter.
705
TestPartResultReporterInterface*
706
UnitTestImpl::GetGlobalTestPartResultReporter() {
707
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
708
return global_test_part_result_repoter_;
711
// Sets the global test part result reporter.
712
void UnitTestImpl::SetGlobalTestPartResultReporter(
713
TestPartResultReporterInterface* reporter) {
714
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
715
global_test_part_result_repoter_ = reporter;
718
// Returns the test part result reporter for the current thread.
719
TestPartResultReporterInterface*
720
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
721
return per_thread_test_part_result_reporter_.get();
724
// Sets the test part result reporter for the current thread.
725
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
726
TestPartResultReporterInterface* reporter) {
727
per_thread_test_part_result_reporter_.set(reporter);
730
// Gets the number of successful test cases.
731
int UnitTestImpl::successful_test_case_count() const {
732
return test_cases_.CountIf(TestCasePassed);
735
// Gets the number of failed test cases.
736
int UnitTestImpl::failed_test_case_count() const {
737
return test_cases_.CountIf(TestCaseFailed);
740
// Gets the number of all test cases.
741
int UnitTestImpl::total_test_case_count() const {
742
return test_cases_.size();
745
// Gets the number of all test cases that contain at least one test
747
int UnitTestImpl::test_case_to_run_count() const {
748
return test_cases_.CountIf(ShouldRunTestCase);
751
// Gets the number of successful tests.
752
int UnitTestImpl::successful_test_count() const {
753
return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
756
// Gets the number of failed tests.
757
int UnitTestImpl::failed_test_count() const {
758
return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
761
// Gets the number of disabled tests.
762
int UnitTestImpl::disabled_test_count() const {
763
return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
766
// Gets the number of all tests.
767
int UnitTestImpl::total_test_count() const {
768
return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
771
// Gets the number of tests that should run.
772
int UnitTestImpl::test_to_run_count() const {
773
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
776
// Returns the current OS stack trace as a String.
778
// The maximum number of stack frames to be included is specified by
779
// the gtest_stack_trace_depth flag. The skip_count parameter
780
// specifies the number of top frames to be skipped, which doesn't
781
// count against the number of frames to be included.
783
// For example, if Foo() calls Bar(), which in turn calls
784
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
785
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
786
String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
791
// Returns the current time in milliseconds.
792
TimeInMillis GetTimeInMillis() {
793
#if defined(_WIN32_WCE) || defined(__BORLANDC__)
794
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
795
// http://analogous.blogspot.com/2005/04/epoch.html
796
const TimeInMillis kJavaEpochToWinFileTimeDelta =
797
static_cast<TimeInMillis>(116444736UL) * 100000UL;
798
const DWORD kTenthMicrosInMilliSecond = 10000;
800
SYSTEMTIME now_systime;
801
FILETIME now_filetime;
802
ULARGE_INTEGER now_int64;
803
// TODO(kenton@google.com): Shouldn't this just use
804
// GetSystemTimeAsFileTime()?
805
GetSystemTime(&now_systime);
806
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
807
now_int64.LowPart = now_filetime.dwLowDateTime;
808
now_int64.HighPart = now_filetime.dwHighDateTime;
809
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
810
kJavaEpochToWinFileTimeDelta;
811
return now_int64.QuadPart;
814
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
817
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
818
// (deprecated function) there.
819
// TODO(kenton@google.com): Use GetTickCount()? Or use
820
// SystemTimeToFileTime()
821
#pragma warning(push) // Saves the current warning state.
822
#pragma warning(disable:4996) // Temporarily disables warning 4996.
824
#pragma warning(pop) // Restores the warning state.
828
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
829
#elif GTEST_HAS_GETTIMEOFDAY_
831
gettimeofday(&now, NULL);
832
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
834
#error "Don't know how to get the current time on your system."
842
// Returns the input enclosed in double quotes if it's not NULL;
843
// otherwise returns "(null)". For example, "\"Hello\"" is returned
844
// for input "Hello".
846
// This is useful for printing a C string in the syntax of a literal.
848
// Known issue: escape sequences are not handled yet.
849
String String::ShowCStringQuoted(const char* c_str) {
850
return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
853
// Copies at most length characters from str into a newly-allocated
854
// piece of memory of size length+1. The memory is allocated with new[].
855
// A terminating null byte is written to the memory, and a pointer to it
856
// is returned. If str is NULL, NULL is returned.
857
static char* CloneString(const char* str, size_t length) {
861
char* const clone = new char[length + 1];
862
posix::StrNCpy(clone, str, length);
863
clone[length] = '\0';
868
// Clones a 0-terminated C string, allocating memory using new. The
869
// caller is responsible for deleting[] the return value. Returns the
870
// cloned string, or NULL if the input is NULL.
871
const char * String::CloneCString(const char* c_str) {
872
return (c_str == NULL) ?
873
NULL : CloneString(c_str, strlen(c_str));
877
// Creates a UTF-16 wide string from the given ANSI string, allocating
878
// memory using new. The caller is responsible for deleting the return
879
// value using delete[]. Returns the wide string, or NULL if the
881
LPCWSTR String::AnsiToUtf16(const char* ansi) {
882
if (!ansi) return NULL;
883
const int length = strlen(ansi);
884
const int unicode_length =
885
MultiByteToWideChar(CP_ACP, 0, ansi, length,
887
WCHAR* unicode = new WCHAR[unicode_length + 1];
888
MultiByteToWideChar(CP_ACP, 0, ansi, length,
889
unicode, unicode_length);
890
unicode[unicode_length] = 0;
894
// Creates an ANSI string from the given wide string, allocating
895
// memory using new. The caller is responsible for deleting the return
896
// value using delete[]. Returns the ANSI string, or NULL if the
898
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
899
if (!utf16_str) return NULL;
900
const int ansi_length =
901
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
902
NULL, 0, NULL, NULL);
903
char* ansi = new char[ansi_length + 1];
904
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
905
ansi, ansi_length, NULL, NULL);
906
ansi[ansi_length] = 0;
912
// Compares two C strings. Returns true iff they have the same content.
914
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
915
// C string is considered different to any non-NULL C string,
916
// including the empty string.
917
bool String::CStringEquals(const char * lhs, const char * rhs) {
918
if ( lhs == NULL ) return rhs == NULL;
920
if ( rhs == NULL ) return false;
922
return strcmp(lhs, rhs) == 0;
925
#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
927
// Converts an array of wide chars to a narrow string using the UTF-8
928
// encoding, and streams the result to the given Message object.
929
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t len,
931
// TODO(wan): consider allowing a testing::String object to
932
// contain '\0'. This will make it behave more like std::string,
933
// and will allow ToUtf8String() to return the correct encoding
934
// for '\0' s.t. we can get rid of the conditional here (and in
935
// several other places).
936
for (size_t i = 0; i != len; ) { // NOLINT
937
if (wstr[i] != L'\0') {
938
*msg << WideStringToUtf8(wstr + i, static_cast<int>(len - i));
939
while (i != len && wstr[i] != L'\0')
948
#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
950
} // namespace internal
952
#if GTEST_HAS_STD_WSTRING
953
// Converts the given wide string to a narrow string using the UTF-8
954
// encoding, and streams the result to this Message object.
955
Message& Message::operator <<(const ::std::wstring& wstr) {
956
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
959
#endif // GTEST_HAS_STD_WSTRING
961
#if GTEST_HAS_GLOBAL_WSTRING
962
// Converts the given wide string to a narrow string using the UTF-8
963
// encoding, and streams the result to this Message object.
964
Message& Message::operator <<(const ::wstring& wstr) {
965
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
968
#endif // GTEST_HAS_GLOBAL_WSTRING
972
// Formats a value to be used in a failure message.
974
// For a char value, we print it as a C++ char literal and as an
975
// unsigned integer (both in decimal and in hexadecimal).
976
String FormatForFailureMessage(char ch) {
977
const unsigned int ch_as_uint = ch;
978
// A String object cannot contain '\0', so we print "\\0" when ch is
980
return String::Format("'%s' (%u, 0x%X)",
981
ch ? String::Format("%c", ch).c_str() : "\\0",
982
ch_as_uint, ch_as_uint);
985
// For a wchar_t value, we print it as a C++ wchar_t literal and as an
986
// unsigned integer (both in decimal and in hexidecimal).
987
String FormatForFailureMessage(wchar_t wchar) {
988
// The C++ standard doesn't specify the exact size of the wchar_t
989
// type. It just says that it shall have the same size as another
990
// integral type, called its underlying type.
992
// Therefore, in order to print a wchar_t value in the numeric form,
993
// we first convert it to the largest integral type (UInt64) and
994
// then print the converted value.
996
// We use streaming to print the value as "%llu" doesn't work
997
// correctly with MSVC 7.1.
998
const UInt64 wchar_as_uint64 = wchar;
1000
// A String object cannot contain '\0', so we print "\\0" when wchar is
1002
char buffer[32]; // CodePointToUtf8 requires a buffer that big.
1004
<< (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
1005
<< "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
1006
<< wchar_as_uint64 << ")";
1007
return msg.GetString();
1010
} // namespace internal
1012
// AssertionResult constructor.
1013
AssertionResult::AssertionResult(const internal::String& failure_message)
1014
: failure_message_(failure_message) {
1018
// Makes a successful assertion result.
1019
AssertionResult AssertionSuccess() {
1020
return AssertionResult();
1024
// Makes a failed assertion result with the given failure message.
1025
AssertionResult AssertionFailure(const Message& message) {
1026
return AssertionResult(message.GetString());
1029
namespace internal {
1031
// Constructs and returns the message for an equality assertion
1032
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1034
// The first four parameters are the expressions used in the assertion
1035
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1036
// where foo is 5 and bar is 6, we have:
1038
// expected_expression: "foo"
1039
// actual_expression: "bar"
1040
// expected_value: "5"
1041
// actual_value: "6"
1043
// The ignoring_case parameter is true iff the assertion is a
1044
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
1045
// be inserted into the message.
1046
AssertionResult EqFailure(const char* expected_expression,
1047
const char* actual_expression,
1048
const String& expected_value,
1049
const String& actual_value,
1050
bool ignoring_case) {
1052
msg << "Value of: " << actual_expression;
1053
if (actual_value != actual_expression) {
1054
msg << "\n Actual: " << actual_value;
1057
msg << "\nExpected: " << expected_expression;
1058
if (ignoring_case) {
1059
msg << " (ignoring case)";
1061
if (expected_value != expected_expression) {
1062
msg << "\nWhich is: " << expected_value;
1065
return AssertionFailure(msg);
1069
// Helper function for implementing ASSERT_NEAR.
1070
AssertionResult DoubleNearPredFormat(const char* expr1,
1072
const char* abs_error_expr,
1076
const double diff = fabs(val1 - val2);
1077
if (diff <= abs_error) return AssertionSuccess();
1079
// TODO(wan): do not print the value of an expression if it's
1080
// already a literal.
1082
msg << "The difference between " << expr1 << " and " << expr2
1083
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1084
<< expr1 << " evaluates to " << val1 << ",\n"
1085
<< expr2 << " evaluates to " << val2 << ", and\n"
1086
<< abs_error_expr << " evaluates to " << abs_error << ".";
1087
return AssertionFailure(msg);
1091
// Helper template for implementing FloatLE() and DoubleLE().
1092
template <typename RawType>
1093
AssertionResult FloatingPointLE(const char* expr1,
1097
// Returns success if val1 is less than val2,
1099
return AssertionSuccess();
1102
// or if val1 is almost equal to val2.
1103
const FloatingPoint<RawType> lhs(val1), rhs(val2);
1104
if (lhs.AlmostEquals(rhs)) {
1105
return AssertionSuccess();
1108
// Note that the above two checks will both fail if either val1 or
1109
// val2 is NaN, as the IEEE floating-point standard requires that
1110
// any predicate involving a NaN must return false.
1113
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1117
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1121
msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1122
<< " Actual: " << StrStreamToString(&val1_ss) << " vs "
1123
<< StrStreamToString(&val2_ss);
1125
return AssertionFailure(msg);
1128
} // namespace internal
1130
// Asserts that val1 is less than, or almost equal to, val2. Fails
1131
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1132
AssertionResult FloatLE(const char* expr1, const char* expr2,
1133
float val1, float val2) {
1134
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1137
// Asserts that val1 is less than, or almost equal to, val2. Fails
1138
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1139
AssertionResult DoubleLE(const char* expr1, const char* expr2,
1140
double val1, double val2) {
1141
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1144
namespace internal {
1146
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1148
AssertionResult CmpHelperEQ(const char* expected_expression,
1149
const char* actual_expression,
1150
BiggestInt expected,
1151
BiggestInt actual) {
1152
if (expected == actual) {
1153
return AssertionSuccess();
1156
return EqFailure(expected_expression,
1158
FormatForComparisonFailureMessage(expected, actual),
1159
FormatForComparisonFailureMessage(actual, expected),
1163
// A macro for implementing the helper functions needed to implement
1164
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1165
// just to avoid copy-and-paste of similar code.
1166
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1167
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1168
BiggestInt val1, BiggestInt val2) {\
1169
if (val1 op val2) {\
1170
return AssertionSuccess();\
1173
msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1174
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1175
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
1176
return AssertionFailure(msg);\
1180
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1182
GTEST_IMPL_CMP_HELPER_(NE, !=)
1183
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1185
GTEST_IMPL_CMP_HELPER_(LE, <=)
1186
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1188
GTEST_IMPL_CMP_HELPER_(LT, < )
1189
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1191
GTEST_IMPL_CMP_HELPER_(GE, >=)
1192
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1194
GTEST_IMPL_CMP_HELPER_(GT, > )
1196
#undef GTEST_IMPL_CMP_HELPER_
1198
// The helper function for {ASSERT|EXPECT}_STREQ.
1199
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1200
const char* actual_expression,
1201
const char* expected,
1202
const char* actual) {
1203
if (String::CStringEquals(expected, actual)) {
1204
return AssertionSuccess();
1207
return EqFailure(expected_expression,
1209
String::ShowCStringQuoted(expected),
1210
String::ShowCStringQuoted(actual),
1214
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1215
AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1216
const char* actual_expression,
1217
const char* expected,
1218
const char* actual) {
1219
if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1220
return AssertionSuccess();
1223
return EqFailure(expected_expression,
1225
String::ShowCStringQuoted(expected),
1226
String::ShowCStringQuoted(actual),
1230
// The helper function for {ASSERT|EXPECT}_STRNE.
1231
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1232
const char* s2_expression,
1235
if (!String::CStringEquals(s1, s2)) {
1236
return AssertionSuccess();
1239
msg << "Expected: (" << s1_expression << ") != ("
1240
<< s2_expression << "), actual: \""
1241
<< s1 << "\" vs \"" << s2 << "\"";
1242
return AssertionFailure(msg);
1246
// The helper function for {ASSERT|EXPECT}_STRCASENE.
1247
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1248
const char* s2_expression,
1251
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1252
return AssertionSuccess();
1255
msg << "Expected: (" << s1_expression << ") != ("
1256
<< s2_expression << ") (ignoring case), actual: \""
1257
<< s1 << "\" vs \"" << s2 << "\"";
1258
return AssertionFailure(msg);
1262
} // namespace internal
1266
// Helper functions for implementing IsSubString() and IsNotSubstring().
1268
// This group of overloaded functions return true iff needle is a
1269
// substring of haystack. NULL is considered a substring of itself
1272
bool IsSubstringPred(const char* needle, const char* haystack) {
1273
if (needle == NULL || haystack == NULL)
1274
return needle == haystack;
1276
return strstr(haystack, needle) != NULL;
1279
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1280
if (needle == NULL || haystack == NULL)
1281
return needle == haystack;
1283
return wcsstr(haystack, needle) != NULL;
1286
// StringType here can be either ::std::string or ::std::wstring.
1287
template <typename StringType>
1288
bool IsSubstringPred(const StringType& needle,
1289
const StringType& haystack) {
1290
return haystack.find(needle) != StringType::npos;
1293
// This function implements either IsSubstring() or IsNotSubstring(),
1294
// depending on the value of the expected_to_be_substring parameter.
1295
// StringType here can be const char*, const wchar_t*, ::std::string,
1296
// or ::std::wstring.
1297
template <typename StringType>
1298
AssertionResult IsSubstringImpl(
1299
bool expected_to_be_substring,
1300
const char* needle_expr, const char* haystack_expr,
1301
const StringType& needle, const StringType& haystack) {
1302
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1303
return AssertionSuccess();
1305
const bool is_wide_string = sizeof(needle[0]) > 1;
1306
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1307
return AssertionFailure(
1309
<< "Value of: " << needle_expr << "\n"
1310
<< " Actual: " << begin_string_quote << needle << "\"\n"
1311
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
1312
<< "a substring of " << haystack_expr << "\n"
1313
<< "Which is: " << begin_string_quote << haystack << "\"");
1318
// IsSubstring() and IsNotSubstring() check whether needle is a
1319
// substring of haystack (NULL is considered a substring of itself
1320
// only), and return an appropriate error message when they fail.
1322
AssertionResult IsSubstring(
1323
const char* needle_expr, const char* haystack_expr,
1324
const char* needle, const char* haystack) {
1325
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1328
AssertionResult IsSubstring(
1329
const char* needle_expr, const char* haystack_expr,
1330
const wchar_t* needle, const wchar_t* haystack) {
1331
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1334
AssertionResult IsNotSubstring(
1335
const char* needle_expr, const char* haystack_expr,
1336
const char* needle, const char* haystack) {
1337
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1340
AssertionResult IsNotSubstring(
1341
const char* needle_expr, const char* haystack_expr,
1342
const wchar_t* needle, const wchar_t* haystack) {
1343
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1346
#if GTEST_HAS_STD_STRING
1347
AssertionResult IsSubstring(
1348
const char* needle_expr, const char* haystack_expr,
1349
const ::std::string& needle, const ::std::string& haystack) {
1350
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1353
AssertionResult IsNotSubstring(
1354
const char* needle_expr, const char* haystack_expr,
1355
const ::std::string& needle, const ::std::string& haystack) {
1356
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1358
#endif // GTEST_HAS_STD_STRING
1360
#if GTEST_HAS_STD_WSTRING
1361
AssertionResult IsSubstring(
1362
const char* needle_expr, const char* haystack_expr,
1363
const ::std::wstring& needle, const ::std::wstring& haystack) {
1364
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1367
AssertionResult IsNotSubstring(
1368
const char* needle_expr, const char* haystack_expr,
1369
const ::std::wstring& needle, const ::std::wstring& haystack) {
1370
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1372
#endif // GTEST_HAS_STD_WSTRING
1374
namespace internal {
1376
#if GTEST_OS_WINDOWS
1380
// Helper function for IsHRESULT{SuccessFailure} predicates
1381
AssertionResult HRESULTFailureHelper(const char* expr,
1382
const char* expected,
1383
long hr) { // NOLINT
1385
// Windows CE doesn't support FormatMessage.
1386
const char error_text[] = "";
1388
// Looks up the human-readable system message for the HRESULT code
1389
// and since we're not passing any params to FormatMessage, we don't
1390
// want inserts expanded.
1391
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1392
FORMAT_MESSAGE_IGNORE_INSERTS;
1393
const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1394
// Gets the system's human readable message string for this HRESULT.
1395
char error_text[kBufSize] = { '\0' };
1396
DWORD message_length = ::FormatMessageA(kFlags,
1397
0, // no source, we're asking system
1399
0, // no line width restrictions
1400
error_text, // output buffer
1401
kBufSize, // buf size
1402
NULL); // no arguments for inserts
1403
// Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1404
for (; message_length && isspace(error_text[message_length - 1]);
1406
error_text[message_length - 1] = '\0';
1408
#endif // _WIN32_WCE
1410
const String error_hex(String::Format("0x%08X ", hr));
1412
msg << "Expected: " << expr << " " << expected << ".\n"
1413
<< " Actual: " << error_hex << error_text << "\n";
1415
return ::testing::AssertionFailure(msg);
1420
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1421
if (SUCCEEDED(hr)) {
1422
return AssertionSuccess();
1424
return HRESULTFailureHelper(expr, "succeeds", hr);
1427
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1429
return AssertionSuccess();
1431
return HRESULTFailureHelper(expr, "fails", hr);
1434
#endif // GTEST_OS_WINDOWS
1436
// Utility functions for encoding Unicode text (wide strings) in
1439
// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1442
// Code-point length Encoding
1443
// 0 - 7 bits 0xxxxxxx
1444
// 8 - 11 bits 110xxxxx 10xxxxxx
1445
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1446
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1448
// The maximum code-point a one-byte UTF-8 sequence can represent.
1449
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1451
// The maximum code-point a two-byte UTF-8 sequence can represent.
1452
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1454
// The maximum code-point a three-byte UTF-8 sequence can represent.
1455
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1457
// The maximum code-point a four-byte UTF-8 sequence can represent.
1458
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1460
// Chops off the n lowest bits from a bit pattern. Returns the n
1461
// lowest bits. As a side effect, the original bit pattern will be
1462
// shifted to the right by n bits.
1463
inline UInt32 ChopLowBits(UInt32* bits, int n) {
1464
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1469
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1470
// code_point parameter is of type UInt32 because wchar_t may not be
1471
// wide enough to contain a code point.
1472
// The output buffer str must containt at least 32 characters.
1473
// The function returns the address of the output buffer.
1474
// If the code_point is not a valid Unicode code point
1475
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1476
// as '(Invalid Unicode 0xXXXXXXXX)'.
1477
char* CodePointToUtf8(UInt32 code_point, char* str) {
1478
if (code_point <= kMaxCodePoint1) {
1480
str[0] = static_cast<char>(code_point); // 0xxxxxxx
1481
} else if (code_point <= kMaxCodePoint2) {
1483
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1484
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1485
} else if (code_point <= kMaxCodePoint3) {
1487
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1488
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1489
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1490
} else if (code_point <= kMaxCodePoint4) {
1492
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1493
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1494
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1495
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1497
// The longest string String::Format can produce when invoked
1498
// with these parameters is 28 character long (not including
1499
// the terminating nul character). We are asking for 32 character
1500
// buffer just in case. This is also enough for strncpy to
1501
// null-terminate the destination string.
1503
str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
1504
str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1505
// the result unterminated.
1510
// The following two functions only make sense if the the system
1511
// uses UTF-16 for wide string encoding. All supported systems
1512
// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1514
// Determines if the arguments constitute UTF-16 surrogate pair
1515
// and thus should be combined into a single Unicode code point
1516
// using CreateCodePointFromUtf16SurrogatePair.
1517
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1518
return sizeof(wchar_t) == 2 &&
1519
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1522
// Creates a Unicode code point from UTF16 surrogate pair.
1523
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1525
const UInt32 mask = (1 << 10) - 1;
1526
return (sizeof(wchar_t) == 2) ?
1527
(((first & mask) << 10) | (second & mask)) + 0x10000 :
1528
// This function should not be called when the condition is
1529
// false, but we provide a sensible default in case it is.
1530
static_cast<UInt32>(first);
1533
// Converts a wide string to a narrow string in UTF-8 encoding.
1534
// The wide string is assumed to have the following encoding:
1535
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1536
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1537
// Parameter str points to a null-terminated wide string.
1538
// Parameter num_chars may additionally limit the number
1539
// of wchar_t characters processed. -1 is used when the entire string
1540
// should be processed.
1541
// If the string contains code points that are not valid Unicode code points
1542
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1543
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1544
// and contains invalid UTF-16 surrogate pairs, values in those pairs
1545
// will be encoded as individual Unicode characters from Basic Normal Plane.
1546
String WideStringToUtf8(const wchar_t* str, int num_chars) {
1547
if (num_chars == -1)
1548
num_chars = static_cast<int>(wcslen(str));
1551
for (int i = 0; i < num_chars; ++i) {
1552
UInt32 unicode_code_point;
1554
if (str[i] == L'\0') {
1556
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1557
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1561
unicode_code_point = static_cast<UInt32>(str[i]);
1564
char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1565
stream << CodePointToUtf8(unicode_code_point, buffer);
1567
return StrStreamToString(&stream);
1570
// Converts a wide C string to a String using the UTF-8 encoding.
1571
// NULL will be converted to "(null)".
1572
String String::ShowWideCString(const wchar_t * wide_c_str) {
1573
if (wide_c_str == NULL) return String("(null)");
1575
return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1578
// Similar to ShowWideCString(), except that this function encloses
1579
// the converted string in double quotes.
1580
String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1581
if (wide_c_str == NULL) return String("(null)");
1583
return String::Format("L\"%s\"",
1584
String::ShowWideCString(wide_c_str).c_str());
1587
// Compares two wide C strings. Returns true iff they have the same
1590
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1591
// C string is considered different to any non-NULL C string,
1592
// including the empty string.
1593
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1594
if (lhs == NULL) return rhs == NULL;
1596
if (rhs == NULL) return false;
1598
return wcscmp(lhs, rhs) == 0;
1601
// Helper function for *_STREQ on wide strings.
1602
AssertionResult CmpHelperSTREQ(const char* expected_expression,
1603
const char* actual_expression,
1604
const wchar_t* expected,
1605
const wchar_t* actual) {
1606
if (String::WideCStringEquals(expected, actual)) {
1607
return AssertionSuccess();
1610
return EqFailure(expected_expression,
1612
String::ShowWideCStringQuoted(expected),
1613
String::ShowWideCStringQuoted(actual),
1617
// Helper function for *_STRNE on wide strings.
1618
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1619
const char* s2_expression,
1621
const wchar_t* s2) {
1622
if (!String::WideCStringEquals(s1, s2)) {
1623
return AssertionSuccess();
1627
msg << "Expected: (" << s1_expression << ") != ("
1628
<< s2_expression << "), actual: "
1629
<< String::ShowWideCStringQuoted(s1)
1630
<< " vs " << String::ShowWideCStringQuoted(s2);
1631
return AssertionFailure(msg);
1634
// Compares two C strings, ignoring case. Returns true iff they have
1635
// the same content.
1637
// Unlike strcasecmp(), this function can handle NULL argument(s). A
1638
// NULL C string is considered different to any non-NULL C string,
1639
// including the empty string.
1640
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1645
return posix::StrCaseCmp(lhs, rhs) == 0;
1648
// Compares two wide C strings, ignoring case. Returns true iff they
1649
// have the same content.
1651
// Unlike wcscasecmp(), this function can handle NULL argument(s).
1652
// A NULL C string is considered different to any non-NULL wide C string,
1653
// including the empty string.
1654
// NB: The implementations on different platforms slightly differ.
1655
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1656
// environment variable. On GNU platform this method uses wcscasecmp
1657
// which compares according to LC_CTYPE category of the current locale.
1658
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1660
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1661
const wchar_t* rhs) {
1662
if ( lhs == NULL ) return rhs == NULL;
1664
if ( rhs == NULL ) return false;
1666
#if GTEST_OS_WINDOWS
1667
return _wcsicmp(lhs, rhs) == 0;
1668
#elif GTEST_OS_LINUX
1669
return wcscasecmp(lhs, rhs) == 0;
1671
// Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1672
// may not define it either.
1675
left = towlower(*lhs++);
1676
right = towlower(*rhs++);
1677
} while (left && left == right);
1678
return left == right;
1679
#endif // OS selector
1682
// Constructs a String by copying a given number of chars from a
1683
// buffer. E.g. String("hello", 3) will create the string "hel".
1684
String::String(const char * buffer, size_t len) {
1685
char * const temp = new char[ len + 1 ];
1686
memcpy(temp, buffer, len);
1691
// Compares this with another String.
1692
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1693
// if this is greater than rhs.
1694
int String::Compare(const String & rhs) const {
1695
if ( c_str_ == NULL ) {
1696
return rhs.c_str_ == NULL ? 0 : -1; // NULL < anything except NULL
1699
return rhs.c_str_ == NULL ? 1 : strcmp(c_str_, rhs.c_str_);
1702
// Returns true iff this String ends with the given suffix. *Any*
1703
// String is considered to end with a NULL or empty suffix.
1704
bool String::EndsWith(const char* suffix) const {
1705
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1707
if (c_str_ == NULL) return false;
1709
const size_t this_len = strlen(c_str_);
1710
const size_t suffix_len = strlen(suffix);
1711
return (this_len >= suffix_len) &&
1712
CStringEquals(c_str_ + this_len - suffix_len, suffix);
1715
// Returns true iff this String ends with the given suffix, ignoring case.
1716
// Any String is considered to end with a NULL or empty suffix.
1717
bool String::EndsWithCaseInsensitive(const char* suffix) const {
1718
if (suffix == NULL || CStringEquals(suffix, "")) return true;
1720
if (c_str_ == NULL) return false;
1722
const size_t this_len = strlen(c_str_);
1723
const size_t suffix_len = strlen(suffix);
1724
return (this_len >= suffix_len) &&
1725
CaseInsensitiveCStringEquals(c_str_ + this_len - suffix_len, suffix);
1728
// Sets the 0-terminated C string this String object represents. The
1729
// old string in this object is deleted, and this object will own a
1730
// clone of the input string. This function copies only up to length
1731
// bytes (plus a terminating null byte), or until the first null byte,
1732
// whichever comes first.
1734
// This function works even when the c_str parameter has the same
1735
// value as that of the c_str_ field.
1736
void String::Set(const char * c_str, size_t length) {
1737
// Makes sure this works when c_str == c_str_
1738
const char* const temp = CloneString(c_str, length);
1743
// Assigns a C string to this object. Self-assignment works.
1744
const String& String::operator=(const char* c_str) {
1745
// Makes sure this works when c_str == c_str_
1746
if (c_str != c_str_) {
1748
c_str_ = CloneCString(c_str);
1753
// Formats a list of arguments to a String, using the same format
1754
// spec string as for printf.
1756
// We do not use the StringPrintf class as it is not universally
1759
// The result is limited to 4096 characters (including the tailing 0).
1760
// If 4096 characters are not enough to format the input,
1761
// "<buffer exceeded>" is returned.
1762
String String::Format(const char * format, ...) {
1764
va_start(args, format);
1767
// MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1768
// 4996 (deprecated function) there.
1769
#ifdef _MSC_VER // We are using MSVC.
1770
#pragma warning(push) // Saves the current warning state.
1771
#pragma warning(disable:4996) // Temporarily disables warning 4996.
1773
vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1774
#pragma warning(pop) // Restores the warning state.
1775
#else // We are not using MSVC.
1777
vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1781
return String(size >= 0 ? buffer : "<buffer exceeded>");
1784
// Converts the buffer in a StrStream to a String, converting NUL
1785
// bytes to "\\0" along the way.
1786
String StrStreamToString(StrStream* ss) {
1787
#if GTEST_HAS_STD_STRING
1788
const ::std::string& str = ss->str();
1789
const char* const start = str.c_str();
1790
const char* const end = start + str.length();
1792
const char* const start = ss->str();
1793
const char* const end = start + ss->pcount();
1794
#endif // GTEST_HAS_STD_STRING
1796
// We need to use a helper StrStream to do this transformation
1797
// because String doesn't support push_back().
1799
for (const char* ch = start; ch != end; ++ch) {
1801
helper << "\\0"; // Replaces NUL with "\\0";
1807
#if GTEST_HAS_STD_STRING
1808
return String(helper.str().c_str());
1810
const String str(helper.str(), helper.pcount());
1811
helper.freeze(false);
1814
#endif // GTEST_HAS_STD_STRING
1817
// Appends the user-supplied message to the Google-Test-generated message.
1818
String AppendUserMessage(const String& gtest_msg,
1819
const Message& user_msg) {
1820
// Appends the user message if it's non-empty.
1821
const String user_msg_string = user_msg.GetString();
1822
if (user_msg_string.empty()) {
1827
msg << gtest_msg << "\n" << user_msg_string;
1829
return msg.GetString();
1834
// Creates an empty TestResult.
1835
TestResult::TestResult()
1836
: test_part_results_(new internal::Vector<TestPartResult>),
1837
test_properties_(new internal::Vector<TestProperty>),
1838
death_test_count_(0),
1843
TestResult::~TestResult() {
1846
// Returns the i-th test part result among all the results. i can
1847
// range from 0 to total_part_count() - 1. If i is not in that range,
1848
// aborts the program.
1849
const TestPartResult& TestResult::GetTestPartResult(int i) const {
1850
return test_part_results_->GetElement(i);
1853
// Returns the i-th test property. i can range from 0 to
1854
// test_property_count() - 1. If i is not in that range, aborts the
1856
const TestProperty& TestResult::GetTestProperty(int i) const {
1857
return test_properties_->GetElement(i);
1860
// Clears the test part results.
1861
void TestResult::ClearTestPartResults() {
1862
test_part_results_->Clear();
1865
// Adds a test part result to the list.
1866
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1867
test_part_results_->PushBack(test_part_result);
1870
// Adds a test property to the list. If a property with the same key as the
1871
// supplied property is already represented, the value of this test_property
1872
// replaces the old value for that key.
1873
void TestResult::RecordProperty(const TestProperty& test_property) {
1874
if (!ValidateTestProperty(test_property)) {
1877
internal::MutexLock lock(&test_properites_mutex_);
1878
TestProperty* const property_with_matching_key =
1879
test_properties_->FindIf(
1880
internal::TestPropertyKeyIs(test_property.key()));
1881
if (property_with_matching_key == NULL) {
1882
test_properties_->PushBack(test_property);
1885
property_with_matching_key->SetValue(test_property.value());
1888
// Adds a failure if the key is a reserved attribute of Google Test
1889
// testcase tags. Returns true if the property is valid.
1890
bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1891
internal::String key(test_property.key());
1892
if (key == "name" || key == "status" || key == "time" || key == "classname") {
1894
<< "Reserved key used in RecordProperty(): "
1896
<< " ('name', 'status', 'time', and 'classname' are reserved by "
1897
<< GTEST_NAME_ << ")";
1903
// Clears the object.
1904
void TestResult::Clear() {
1905
test_part_results_->Clear();
1906
test_properties_->Clear();
1907
death_test_count_ = 0;
1911
// Returns true iff the test failed.
1912
bool TestResult::Failed() const {
1913
for (int i = 0; i < total_part_count(); ++i) {
1914
if (GetTestPartResult(i).failed())
1920
// Returns true iff the test part fatally failed.
1921
static bool TestPartFatallyFailed(const TestPartResult& result) {
1922
return result.fatally_failed();
1925
// Returns true iff the test fatally failed.
1926
bool TestResult::HasFatalFailure() const {
1927
return test_part_results_->CountIf(TestPartFatallyFailed) > 0;
1930
// Returns true iff the test part non-fatally failed.
1931
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1932
return result.nonfatally_failed();
1935
// Returns true iff the test has a non-fatal failure.
1936
bool TestResult::HasNonfatalFailure() const {
1937
return test_part_results_->CountIf(TestPartNonfatallyFailed) > 0;
1940
// Gets the number of all test parts. This is the sum of the number
1941
// of successful test parts and the number of failed test parts.
1942
int TestResult::total_part_count() const {
1943
return test_part_results_->size();
1946
// Returns the number of the test properties.
1947
int TestResult::test_property_count() const {
1948
return test_properties_->size();
1951
} // namespace internal
1955
// Creates a Test object.
1957
// The c'tor saves the values of all Google Test flags.
1959
: gtest_flag_saver_(new internal::GTestFlagSaver) {
1962
// The d'tor restores the values of all Google Test flags.
1964
delete gtest_flag_saver_;
1967
// Sets up the test fixture.
1969
// A sub-class may override this.
1970
void Test::SetUp() {
1973
// Tears down the test fixture.
1975
// A sub-class may override this.
1976
void Test::TearDown() {
1979
// Allows user supplied key value pairs to be recorded for later output.
1980
void Test::RecordProperty(const char* key, const char* value) {
1981
UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1984
// Allows user supplied key value pairs to be recorded for later output.
1985
void Test::RecordProperty(const char* key, int value) {
1986
Message value_message;
1987
value_message << value;
1988
RecordProperty(key, value_message.GetString().c_str());
1991
namespace internal {
1993
void ReportFailureInUnknownLocation(TestPartResultType result_type,
1994
const String& message) {
1995
// This function is a friend of UnitTest and as such has access to
1996
// AddTestPartResult.
1997
UnitTest::GetInstance()->AddTestPartResult(
1999
NULL, // No info about the source file where the exception occurred.
2000
-1, // We have no info on which line caused the exception.
2002
String()); // No stack trace, either.
2005
} // namespace internal
2007
#if GTEST_OS_WINDOWS
2008
// We are on Windows.
2010
// Adds an "exception thrown" fatal failure to the current test.
2011
static void AddExceptionThrownFailure(DWORD exception_code,
2012
const char* location) {
2014
message << "Exception thrown with code 0x" << std::setbase(16) <<
2015
exception_code << std::setbase(10) << " in " << location << ".";
2017
internal::ReportFailureInUnknownLocation(TPRT_FATAL_FAILURE,
2018
message.GetString());
2021
#endif // GTEST_OS_WINDOWS
2023
// Google Test requires all tests in the same test case to use the same test
2024
// fixture class. This function checks if the current test has the
2025
// same fixture class as the first test in the current test case. If
2026
// yes, it returns true; otherwise it generates a Google Test failure and
2028
bool Test::HasSameFixtureClass() {
2029
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2030
const TestCase* const test_case = impl->current_test_case();
2032
// Info about the first test in the current test case.
2033
const internal::TestInfoImpl* const first_test_info =
2034
test_case->test_info_list().GetElement(0)->impl();
2035
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
2036
const char* const first_test_name = first_test_info->name();
2038
// Info about the current test.
2039
const internal::TestInfoImpl* const this_test_info =
2040
impl->current_test_info()->impl();
2041
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
2042
const char* const this_test_name = this_test_info->name();
2044
if (this_fixture_id != first_fixture_id) {
2045
// Is the first test defined using TEST?
2046
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2047
// Is this test defined using TEST?
2048
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2050
if (first_is_TEST || this_is_TEST) {
2051
// The user mixed TEST and TEST_F in this test case - we'll tell
2052
// him/her how to fix it.
2054
// Gets the name of the TEST and the name of the TEST_F. Note
2055
// that first_is_TEST and this_is_TEST cannot both be true, as
2056
// the fixture IDs are different for the two tests.
2057
const char* const TEST_name =
2058
first_is_TEST ? first_test_name : this_test_name;
2059
const char* const TEST_F_name =
2060
first_is_TEST ? this_test_name : first_test_name;
2063
<< "All tests in the same test case must use the same test fixture\n"
2064
<< "class, so mixing TEST_F and TEST in the same test case is\n"
2065
<< "illegal. In test case " << this_test_info->test_case_name()
2067
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
2068
<< "test " << TEST_name << " is defined using TEST. You probably\n"
2069
<< "want to change the TEST to TEST_F or move it to another test\n"
2072
// The user defined two fixture classes with the same name in
2073
// two namespaces - we'll tell him/her how to fix it.
2075
<< "All tests in the same test case must use the same test fixture\n"
2076
<< "class. However, in test case "
2077
<< this_test_info->test_case_name() << ",\n"
2078
<< "you defined test " << first_test_name
2079
<< " and test " << this_test_name << "\n"
2080
<< "using two different test fixture classes. This can happen if\n"
2081
<< "the two classes are from different namespaces or translation\n"
2082
<< "units and have the same name. You should probably rename one\n"
2083
<< "of the classes to put the tests into different test cases.";
2091
// Runs the test and updates the test result.
2093
if (!HasSameFixtureClass()) return;
2095
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2097
// Catch SEH-style exceptions.
2098
impl->os_stack_trace_getter()->UponLeavingGTest();
2101
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2102
GetExceptionCode())) {
2103
AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2106
// We will run the test only if SetUp() had no fatal failure.
2107
if (!HasFatalFailure()) {
2108
impl->os_stack_trace_getter()->UponLeavingGTest();
2111
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2112
GetExceptionCode())) {
2113
AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2117
// However, we want to clean up as much as possible. Hence we will
2118
// always call TearDown(), even if SetUp() or the test body has
2120
impl->os_stack_trace_getter()->UponLeavingGTest();
2123
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2124
GetExceptionCode())) {
2125
AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2128
#else // We are on a compiler or platform that doesn't support SEH.
2129
impl->os_stack_trace_getter()->UponLeavingGTest();
2132
// We will run the test only if SetUp() was successful.
2133
if (!HasFatalFailure()) {
2134
impl->os_stack_trace_getter()->UponLeavingGTest();
2138
// However, we want to clean up as much as possible. Hence we will
2139
// always call TearDown(), even if SetUp() or the test body has
2141
impl->os_stack_trace_getter()->UponLeavingGTest();
2143
#endif // GTEST_HAS_SEH
2147
// Returns true iff the current test has a fatal failure.
2148
bool Test::HasFatalFailure() {
2149
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2152
// Returns true iff the current test has a non-fatal failure.
2153
bool Test::HasNonfatalFailure() {
2154
return internal::GetUnitTestImpl()->current_test_result()->
2155
HasNonfatalFailure();
2160
// Constructs a TestInfo object. It assumes ownership of the test factory
2161
// object via impl_.
2162
TestInfo::TestInfo(const char* test_case_name,
2164
const char* test_case_comment,
2165
const char* comment,
2166
internal::TypeId fixture_class_id,
2167
internal::TestFactoryBase* factory) {
2168
impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2169
test_case_comment, comment,
2170
fixture_class_id, factory);
2173
// Destructs a TestInfo object.
2174
TestInfo::~TestInfo() {
2178
namespace internal {
2180
// Creates a new TestInfo object and registers it with Google Test;
2181
// returns the created object.
2185
// test_case_name: name of the test case
2186
// name: name of the test
2187
// test_case_comment: a comment on the test case that will be included in
2189
// comment: a comment on the test that will be included in the
2191
// fixture_class_id: ID of the test fixture class
2192
// set_up_tc: pointer to the function that sets up the test case
2193
// tear_down_tc: pointer to the function that tears down the test case
2194
// factory: pointer to the factory that creates a test object.
2195
// The newly created TestInfo instance will assume
2196
// ownership of the factory object.
2197
TestInfo* MakeAndRegisterTestInfo(
2198
const char* test_case_name, const char* name,
2199
const char* test_case_comment, const char* comment,
2200
TypeId fixture_class_id,
2201
SetUpTestCaseFunc set_up_tc,
2202
TearDownTestCaseFunc tear_down_tc,
2203
TestFactoryBase* factory) {
2204
TestInfo* const test_info =
2205
new TestInfo(test_case_name, name, test_case_comment, comment,
2206
fixture_class_id, factory);
2207
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2211
#if GTEST_HAS_PARAM_TEST
2212
void ReportInvalidTestCaseType(const char* test_case_name,
2213
const char* file, int line) {
2216
<< "Attempted redefinition of test case " << test_case_name << ".\n"
2217
<< "All tests in the same test case must use the same test fixture\n"
2218
<< "class. However, in test case " << test_case_name << ", you tried\n"
2219
<< "to define a test using a fixture class different from the one\n"
2220
<< "used earlier. This can happen if the two fixture classes are\n"
2221
<< "from different namespaces and have the same name. You should\n"
2222
<< "probably rename one of the classes to put the tests into different\n"
2225
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2226
errors.GetString().c_str());
2228
#endif // GTEST_HAS_PARAM_TEST
2230
} // namespace internal
2232
// Returns the test case name.
2233
const char* TestInfo::test_case_name() const {
2234
return impl_->test_case_name();
2237
// Returns the test name.
2238
const char* TestInfo::name() const {
2239
return impl_->name();
2242
// Returns the test case comment.
2243
const char* TestInfo::test_case_comment() const {
2244
return impl_->test_case_comment();
2247
// Returns the test comment.
2248
const char* TestInfo::comment() const {
2249
return impl_->comment();
2252
// Returns true if this test should run.
2253
bool TestInfo::should_run() const { return impl_->should_run(); }
2255
// Returns true if this test matches the user-specified filter.
2256
bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2258
// Returns the result of the test.
2259
const TestResult* TestInfo::result() const { return impl_->result(); }
2261
// Increments the number of death tests encountered in this test so
2263
int TestInfo::increment_death_test_count() {
2264
return impl_->result()->increment_death_test_count();
2269
// A predicate that checks the test name of a TestInfo against a known
2272
// This is used for implementation of the TestCase class only. We put
2273
// it in the anonymous namespace to prevent polluting the outer
2276
// TestNameIs is copyable.
2281
// TestNameIs has NO default constructor.
2282
explicit TestNameIs(const char* name)
2285
// Returns true iff the test name of test_info matches name_.
2286
bool operator()(const TestInfo * test_info) const {
2287
return test_info && internal::String(test_info->name()).Compare(name_) == 0;
2291
internal::String name_;
2296
namespace internal {
2298
// This method expands all parameterized tests registered with macros TEST_P
2299
// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2300
// This will be done just once during the program runtime.
2301
void UnitTestImpl::RegisterParameterizedTests() {
2302
#if GTEST_HAS_PARAM_TEST
2303
if (!parameterized_tests_registered_) {
2304
parameterized_test_registry_.RegisterTests();
2305
parameterized_tests_registered_ = true;
2310
// Creates the test object, runs it, records its result, and then
2312
void TestInfoImpl::Run() {
2313
if (!should_run_) return;
2315
// Tells UnitTest where to store test result.
2316
UnitTestImpl* const impl = internal::GetUnitTestImpl();
2317
impl->set_current_test_info(parent_);
2319
// Notifies the unit test event listener that a test is about to
2321
UnitTestEventListenerInterface* const result_printer =
2322
impl->result_printer();
2323
result_printer->OnTestStart(*parent_);
2325
const TimeInMillis start = GetTimeInMillis();
2327
impl->os_stack_trace_getter()->UponLeavingGTest();
2329
// Catch SEH-style exceptions.
2333
// Creates the test object.
2334
test = factory_->CreateTest();
2335
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2336
GetExceptionCode())) {
2337
AddExceptionThrownFailure(GetExceptionCode(),
2338
"the test fixture's constructor");
2341
#else // We are on a compiler or platform that doesn't support SEH.
2343
// TODO(wan): If test->Run() throws, test won't be deleted. This is
2344
// not a problem now as we don't use exceptions. If we were to
2345
// enable exceptions, we should revise the following to be
2348
// Creates the test object.
2349
Test* test = factory_->CreateTest();
2350
#endif // GTEST_HAS_SEH
2352
// Runs the test only if the constructor of the test fixture didn't
2353
// generate a fatal failure.
2354
if (!Test::HasFatalFailure()) {
2358
// Deletes the test object.
2359
impl->os_stack_trace_getter()->UponLeavingGTest();
2363
result_.set_elapsed_time(GetTimeInMillis() - start);
2365
// Notifies the unit test event listener that a test has just finished.
2366
result_printer->OnTestEnd(*parent_);
2368
// Tells UnitTest to stop associating assertion results to this
2370
impl->set_current_test_info(NULL);
2375
// Gets the number of successful tests in this test case.
2376
int TestCase::successful_test_count() const {
2377
return test_info_list_->CountIf(TestPassed);
2380
// Gets the number of failed tests in this test case.
2381
int TestCase::failed_test_count() const {
2382
return test_info_list_->CountIf(TestFailed);
2385
int TestCase::disabled_test_count() const {
2386
return test_info_list_->CountIf(TestDisabled);
2389
// Get the number of tests in this test case that should run.
2390
int TestCase::test_to_run_count() const {
2391
return test_info_list_->CountIf(ShouldRunTest);
2394
// Gets the number of all tests.
2395
int TestCase::total_test_count() const {
2396
return test_info_list_->size();
2399
// Creates a TestCase with the given name.
2403
// name: name of the test case
2404
// set_up_tc: pointer to the function that sets up the test case
2405
// tear_down_tc: pointer to the function that tears down the test case
2406
TestCase::TestCase(const char* name, const char* comment,
2407
Test::SetUpTestCaseFunc set_up_tc,
2408
Test::TearDownTestCaseFunc tear_down_tc)
2411
set_up_tc_(set_up_tc),
2412
tear_down_tc_(tear_down_tc),
2415
test_info_list_ = new internal::Vector<TestInfo *>;
2418
// Destructor of TestCase.
2419
TestCase::~TestCase() {
2420
// Deletes every Test in the collection.
2421
test_info_list_->ForEach(internal::Delete<TestInfo>);
2423
// Then deletes the Test collection.
2424
delete test_info_list_;
2425
test_info_list_ = NULL;
2428
// Returns the i-th test among all the tests. i can range from 0 to
2429
// total_test_count() - 1. If i is not in that range, returns NULL.
2430
const TestInfo* TestCase::GetTestInfo(int i) const {
2431
return test_info_list_->GetElementOr(i, NULL);
2434
// Adds a test to this test case. Will delete the test upon
2435
// destruction of the TestCase object.
2436
void TestCase::AddTestInfo(TestInfo * test_info) {
2437
test_info_list_->PushBack(test_info);
2440
// Runs every test in this TestCase.
2441
void TestCase::Run() {
2442
if (!should_run_) return;
2444
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2445
impl->set_current_test_case(this);
2447
UnitTestEventListenerInterface * const result_printer =
2448
impl->result_printer();
2450
result_printer->OnTestCaseStart(*this);
2451
impl->os_stack_trace_getter()->UponLeavingGTest();
2454
const internal::TimeInMillis start = internal::GetTimeInMillis();
2455
test_info_list_->ForEach(internal::TestInfoImpl::RunTest);
2456
elapsed_time_ = internal::GetTimeInMillis() - start;
2458
impl->os_stack_trace_getter()->UponLeavingGTest();
2460
result_printer->OnTestCaseEnd(*this);
2461
impl->set_current_test_case(NULL);
2464
// Clears the results of all tests in this test case.
2465
void TestCase::ClearResult() {
2466
test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2469
// Returns true iff test passed.
2470
bool TestCase::TestPassed(const TestInfo * test_info) {
2471
const internal::TestInfoImpl* const impl = test_info->impl();
2472
return impl->should_run() && impl->result()->Passed();
2475
// Returns true iff test failed.
2476
bool TestCase::TestFailed(const TestInfo * test_info) {
2477
const internal::TestInfoImpl* const impl = test_info->impl();
2478
return impl->should_run() && impl->result()->Failed();
2481
// Returns true iff test is disabled.
2482
bool TestCase::TestDisabled(const TestInfo * test_info) {
2483
return test_info->impl()->is_disabled();
2486
// Returns true if the given test should run.
2487
bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2488
return test_info->impl()->should_run();
2491
} // namespace internal
2493
// A result printer that never prints anything. Used in the child process
2494
// of an exec-style death test to avoid needless output clutter.
2495
class NullUnitTestResultPrinter : public EmptyTestEventListener {};
2497
// Formats a countable noun. Depending on its quantity, either the
2498
// singular form or the plural form is used. e.g.
2500
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2501
// FormatCountableNoun(5, "book", "books") returns "5 books".
2502
static internal::String FormatCountableNoun(int count,
2503
const char * singular_form,
2504
const char * plural_form) {
2505
return internal::String::Format("%d %s", count,
2506
count == 1 ? singular_form : plural_form);
2509
// Formats the count of tests.
2510
static internal::String FormatTestCount(int test_count) {
2511
return FormatCountableNoun(test_count, "test", "tests");
2514
// Formats the count of test cases.
2515
static internal::String FormatTestCaseCount(int test_case_count) {
2516
return FormatCountableNoun(test_case_count, "test case", "test cases");
2519
// Converts a TestPartResultType enum to human-friendly string
2520
// representation. Both TPRT_NONFATAL_FAILURE and TPRT_FATAL_FAILURE
2521
// are translated to "Failure", as the user usually doesn't care about
2522
// the difference between the two when viewing the test result.
2523
static const char * TestPartResultTypeToString(TestPartResultType type) {
2528
case TPRT_NONFATAL_FAILURE:
2529
case TPRT_FATAL_FAILURE:
2537
return "Unknown result type";
2540
// Prints a TestPartResult to a String.
2541
static internal::String PrintTestPartResultToString(
2542
const TestPartResult& test_part_result) {
2544
<< internal::FormatFileLocation(test_part_result.file_name(),
2545
test_part_result.line_number())
2546
<< " " << TestPartResultTypeToString(test_part_result.type())
2547
<< test_part_result.message()).GetString();
2550
// Prints a TestPartResult.
2551
static void PrintTestPartResult(const TestPartResult& test_part_result) {
2552
const internal::String& result =
2553
PrintTestPartResultToString(test_part_result);
2554
printf("%s\n", result.c_str());
2556
// If the test program runs in Visual Studio or a debugger, the
2557
// following statements add the test part result message to the Output
2558
// window such that the user can double-click on it to jump to the
2559
// corresponding source code location; otherwise they do nothing.
2561
// Windows Mobile doesn't support the ANSI version of OutputDebugString,
2562
// it works only with UTF16 strings.
2563
::OutputDebugString(internal::String::AnsiToUtf16(result.c_str()));
2564
::OutputDebugString(L"\n");
2565
#elif GTEST_OS_WINDOWS
2566
::OutputDebugStringA(result.c_str());
2567
::OutputDebugStringA("\n");
2571
// class PrettyUnitTestResultPrinter
2573
namespace internal {
2582
#if GTEST_OS_WINDOWS && !defined(_WIN32_WCE)
2584
// Returns the character attribute for the given color.
2585
WORD GetColorAttribute(GTestColor color) {
2587
case COLOR_RED: return FOREGROUND_RED;
2588
case COLOR_GREEN: return FOREGROUND_GREEN;
2589
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2596
// Returns the ANSI color code for the given color. COLOR_DEFAULT is
2597
// an invalid input.
2598
const char* GetAnsiColorCode(GTestColor color) {
2600
case COLOR_RED: return "1";
2601
case COLOR_GREEN: return "2";
2602
case COLOR_YELLOW: return "3";
2603
default: return NULL;
2607
#endif // GTEST_OS_WINDOWS && !_WIN32_WCE
2609
// Returns true iff Google Test should use colors in the output.
2610
bool ShouldUseColor(bool stdout_is_tty) {
2611
const char* const gtest_color = GTEST_FLAG(color).c_str();
2613
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2614
#if GTEST_OS_WINDOWS
2615
// On Windows the TERM variable is usually not set, but the
2616
// console there does support colors.
2617
return stdout_is_tty;
2619
// On non-Windows platforms, we rely on the TERM variable.
2620
const char* const term = posix::GetEnv("TERM");
2621
const bool term_supports_color =
2622
String::CStringEquals(term, "xterm") ||
2623
String::CStringEquals(term, "xterm-color") ||
2624
String::CStringEquals(term, "xterm-256color") ||
2625
String::CStringEquals(term, "linux") ||
2626
String::CStringEquals(term, "cygwin");
2627
return stdout_is_tty && term_supports_color;
2628
#endif // GTEST_OS_WINDOWS
2631
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2632
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2633
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2634
String::CStringEquals(gtest_color, "1");
2635
// We take "yes", "true", "t", and "1" as meaning "yes". If the
2636
// value is neither one of these nor "auto", we treat it as "no" to
2640
// Helpers for printing colored strings to stdout. Note that on Windows, we
2641
// cannot simply emit special characters and have the terminal change colors.
2642
// This routine must actually emit the characters rather than return a string
2643
// that would be colored when printed, as can be done on Linux.
2644
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2646
va_start(args, fmt);
2648
#if defined(_WIN32_WCE) || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2649
const bool use_color = false;
2651
static const bool in_color_mode =
2652
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2653
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2654
#endif // defined(_WIN32_WCE) || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2655
// The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2663
#if GTEST_OS_WINDOWS && !defined(_WIN32_WCE)
2664
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2666
// Gets the current text color.
2667
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2668
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2669
const WORD old_color_attrs = buffer_info.wAttributes;
2671
SetConsoleTextAttribute(stdout_handle,
2672
GetColorAttribute(color) | FOREGROUND_INTENSITY);
2675
// Restores the text color.
2676
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2678
printf("\033[0;3%sm", GetAnsiColorCode(color));
2680
printf("\033[m"); // Resets the terminal to default.
2681
#endif // GTEST_OS_WINDOWS && !defined(_WIN32_WCE)
2685
} // namespace internal
2687
using internal::ColoredPrintf;
2688
using internal::COLOR_DEFAULT;
2689
using internal::COLOR_RED;
2690
using internal::COLOR_GREEN;
2691
using internal::COLOR_YELLOW;
2693
// This class implements the UnitTestEventListenerInterface interface.
2695
// Class PrettyUnitTestResultPrinter is copyable.
2696
class PrettyUnitTestResultPrinter : public UnitTestEventListenerInterface {
2698
PrettyUnitTestResultPrinter() {}
2699
static void PrintTestName(const char * test_case, const char * test) {
2700
printf("%s.%s", test_case, test);
2703
// The following methods override what's in the
2704
// UnitTestEventListenerInterface class.
2705
virtual void OnUnitTestStart(const UnitTest& unit_test);
2706
virtual void OnGlobalSetUpStart(const UnitTest& unit_test);
2707
virtual void OnGlobalSetUpEnd(const UnitTest& /*unit_test*/) {}
2708
virtual void OnTestCaseStart(const TestCase& test_case);
2709
virtual void OnTestCaseEnd(const TestCase& test_case);
2710
virtual void OnTestStart(const TestInfo& test_info);
2711
virtual void OnNewTestPartResult(const TestPartResult& result);
2712
virtual void OnTestEnd(const TestInfo& test_info);
2713
virtual void OnGlobalTearDownStart(const UnitTest& unit_test);
2714
virtual void OnGlobalTearDownEnd(const UnitTest& /*unit_test*/) {}
2715
virtual void OnUnitTestEnd(const UnitTest& unit_test);
2718
static void PrintFailedTests(const UnitTest& unit_test);
2720
internal::String test_case_name_;
2723
// Called before the unit test starts.
2724
void PrettyUnitTestResultPrinter::OnUnitTestStart(const UnitTest& unit_test) {
2725
const char* const filter = GTEST_FLAG(filter).c_str();
2727
// Prints the filter if it's not *. This reminds the user that some
2728
// tests may be skipped.
2729
if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2730
ColoredPrintf(COLOR_YELLOW,
2731
"Note: %s filter = %s\n", GTEST_NAME_, filter);
2734
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2735
ColoredPrintf(COLOR_YELLOW,
2736
"Note: This is test shard %s of %s.\n",
2737
internal::posix::GetEnv(kTestShardIndex),
2738
internal::posix::GetEnv(kTestTotalShards));
2741
if (GTEST_FLAG(shuffle)) {
2742
ColoredPrintf(COLOR_YELLOW,
2743
"Note: Randomizing tests' orders with a seed of %d .\n",
2744
unit_test.random_seed());
2747
ColoredPrintf(COLOR_GREEN, "[==========] ");
2748
printf("Running %s from %s.\n",
2749
FormatTestCount(unit_test.test_to_run_count()).c_str(),
2750
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2754
void PrettyUnitTestResultPrinter::OnGlobalSetUpStart(
2755
const UnitTest& /*unit_test*/) {
2756
ColoredPrintf(COLOR_GREEN, "[----------] ");
2757
printf("Global test environment set-up.\n");
2761
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2762
test_case_name_ = test_case.name();
2763
const internal::String counts =
2764
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2765
ColoredPrintf(COLOR_GREEN, "[----------] ");
2766
printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2767
if (test_case.comment()[0] == '\0') {
2770
printf(", where %s\n", test_case.comment());
2775
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2776
if (!GTEST_FLAG(print_time)) return;
2778
test_case_name_ = test_case.name();
2779
const internal::String counts =
2780
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2781
ColoredPrintf(COLOR_GREEN, "[----------] ");
2782
printf("%s from %s (%s ms total)\n\n",
2783
counts.c_str(), test_case_name_.c_str(),
2784
internal::StreamableToString(test_case.elapsed_time()).c_str());
2788
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2789
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2790
PrintTestName(test_case_name_.c_str(), test_info.name());
2791
if (test_info.comment()[0] == '\0') {
2794
printf(", where %s\n", test_info.comment());
2799
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2800
if (test_info.result()->Passed()) {
2801
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2803
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2805
PrintTestName(test_case_name_.c_str(), test_info.name());
2806
if (GTEST_FLAG(print_time)) {
2807
printf(" (%s ms)\n", internal::StreamableToString(
2808
test_info.result()->elapsed_time()).c_str());
2815
// Called after an assertion failure.
2816
void PrettyUnitTestResultPrinter::OnNewTestPartResult(
2817
const TestPartResult& result) {
2818
// If the test part succeeded, we don't need to do anything.
2819
if (result.type() == TPRT_SUCCESS)
2822
// Print failure message from the assertion (e.g. expected this and got that).
2823
PrintTestPartResult(result);
2827
void PrettyUnitTestResultPrinter::OnGlobalTearDownStart(
2828
const UnitTest& /*unit_test*/) {
2829
ColoredPrintf(COLOR_GREEN, "[----------] ");
2830
printf("Global test environment tear-down\n");
2834
// Internal helper for printing the list of failed tests.
2835
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2836
const int failed_test_count = unit_test.failed_test_count();
2837
if (failed_test_count == 0) {
2841
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2842
const TestCase& test_case = *unit_test.GetTestCase(i);
2843
if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
2846
for (int j = 0; j < test_case.total_test_count(); ++j) {
2847
const TestInfo& test_info = *test_case.GetTestInfo(j);
2848
if (!test_info.should_run() || test_info.result()->Passed()) {
2851
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2852
printf("%s.%s", test_case.name(), test_info.name());
2853
if (test_case.comment()[0] != '\0' ||
2854
test_info.comment()[0] != '\0') {
2855
printf(", where %s", test_case.comment());
2856
if (test_case.comment()[0] != '\0' &&
2857
test_info.comment()[0] != '\0') {
2861
printf("%s\n", test_info.comment());
2866
void PrettyUnitTestResultPrinter::OnUnitTestEnd(const UnitTest& unit_test) {
2867
ColoredPrintf(COLOR_GREEN, "[==========] ");
2868
printf("%s from %s ran.",
2869
FormatTestCount(unit_test.test_to_run_count()).c_str(),
2870
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2871
if (GTEST_FLAG(print_time)) {
2872
printf(" (%s ms total)",
2873
internal::StreamableToString(unit_test.elapsed_time()).c_str());
2876
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2877
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
2879
int num_failures = unit_test.failed_test_count();
2880
if (!unit_test.Passed()) {
2881
const int failed_test_count = unit_test.failed_test_count();
2882
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2883
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2884
PrintFailedTests(unit_test);
2885
printf("\n%2d FAILED %s\n", num_failures,
2886
num_failures == 1 ? "TEST" : "TESTS");
2889
int num_disabled = unit_test.disabled_test_count();
2890
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
2891
if (!num_failures) {
2892
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2894
ColoredPrintf(COLOR_YELLOW,
2895
" YOU HAVE %d DISABLED %s\n\n",
2897
num_disabled == 1 ? "TEST" : "TESTS");
2899
// Ensure that Google Test output is printed before, e.g., heapchecker output.
2903
// End PrettyUnitTestResultPrinter
2905
// class UnitTestEventsRepeater
2907
// This class forwards events to other event listeners.
2908
class UnitTestEventsRepeater : public UnitTestEventListenerInterface {
2910
typedef internal::Vector<UnitTestEventListenerInterface *> Listeners;
2911
UnitTestEventsRepeater() {}
2912
virtual ~UnitTestEventsRepeater();
2913
void AddListener(UnitTestEventListenerInterface *listener);
2915
virtual void OnUnitTestStart(const UnitTest& unit_test);
2916
virtual void OnUnitTestEnd(const UnitTest& unit_test);
2917
virtual void OnGlobalSetUpStart(const UnitTest& unit_test);
2918
virtual void OnGlobalSetUpEnd(const UnitTest& unit_test);
2919
virtual void OnGlobalTearDownStart(const UnitTest& unit_test);
2920
virtual void OnGlobalTearDownEnd(const UnitTest& unit_test);
2921
virtual void OnTestCaseStart(const TestCase& test_case);
2922
virtual void OnTestCaseEnd(const TestCase& test_case);
2923
virtual void OnTestStart(const TestInfo& test_info);
2924
virtual void OnTestEnd(const TestInfo& test_info);
2925
virtual void OnNewTestPartResult(const TestPartResult& result);
2928
Listeners listeners_;
2930
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestEventsRepeater);
2933
UnitTestEventsRepeater::~UnitTestEventsRepeater() {
2934
for (int i = 0; i < listeners_.size(); i++) {
2935
delete listeners_.GetElement(i);
2939
void UnitTestEventsRepeater::AddListener(
2940
UnitTestEventListenerInterface *listener) {
2941
listeners_.PushBack(listener);
2944
// Since the methods are identical, use a macro to reduce boilerplate.
2945
// This defines a member that repeats the call to all listeners.
2946
#define GTEST_REPEATER_METHOD_(Name, Type) \
2947
void UnitTestEventsRepeater::Name(const Type& parameter) { \
2948
for (int i = 0; i < listeners_.size(); i++) { \
2949
listeners_.GetElement(i)->Name(parameter); \
2953
GTEST_REPEATER_METHOD_(OnUnitTestStart, UnitTest)
2954
GTEST_REPEATER_METHOD_(OnUnitTestEnd, UnitTest)
2955
GTEST_REPEATER_METHOD_(OnGlobalSetUpStart, UnitTest)
2956
GTEST_REPEATER_METHOD_(OnGlobalSetUpEnd, UnitTest)
2957
GTEST_REPEATER_METHOD_(OnGlobalTearDownStart, UnitTest)
2958
GTEST_REPEATER_METHOD_(OnGlobalTearDownEnd, UnitTest)
2959
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2960
GTEST_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2961
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2962
GTEST_REPEATER_METHOD_(OnTestEnd, TestInfo)
2963
GTEST_REPEATER_METHOD_(OnNewTestPartResult, TestPartResult)
2965
#undef GTEST_REPEATER_METHOD_
2967
// End PrettyUnitTestResultPrinter
2969
// This class generates an XML output file.
2970
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
2972
explicit XmlUnitTestResultPrinter(const char* output_file);
2974
virtual void OnUnitTestEnd(const UnitTest& unit_test);
2977
// Is c a whitespace character that is normalized to a space character
2978
// when it appears in an XML attribute value?
2979
static bool IsNormalizableWhitespace(char c) {
2980
return c == 0x9 || c == 0xA || c == 0xD;
2983
// May c appear in a well-formed XML document?
2984
static bool IsValidXmlCharacter(char c) {
2985
return IsNormalizableWhitespace(c) || c >= 0x20;
2988
// Returns an XML-escaped copy of the input string str. If
2989
// is_attribute is true, the text is meant to appear as an attribute
2990
// value, and normalizable whitespace is preserved by replacing it
2991
// with character references.
2992
static internal::String EscapeXml(const char* str,
2995
// Convenience wrapper around EscapeXml when str is an attribute value.
2996
static internal::String EscapeXmlAttribute(const char* str) {
2997
return EscapeXml(str, true);
3000
// Convenience wrapper around EscapeXml when str is not an attribute value.
3001
static internal::String EscapeXmlText(const char* str) {
3002
return EscapeXml(str, false);
3005
// Prints an XML representation of a TestInfo object.
3006
static void PrintXmlTestInfo(FILE* out,
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 internal::String TestPropertiesAsXmlAttributes(
3021
const TestResult& result);
3024
const internal::String output_file_;
3026
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3029
// Creates a new XmlUnitTestResultPrinter.
3030
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3031
: output_file_(output_file) {
3032
if (output_file_.c_str() == NULL || output_file_.empty()) {
3033
fprintf(stderr, "XML output file may not be null\n");
3039
// Called after the unit test ends.
3040
void XmlUnitTestResultPrinter::OnUnitTestEnd(const UnitTest& unit_test) {
3041
FILE* xmlout = NULL;
3042
internal::FilePath output_file(output_file_);
3043
internal::FilePath output_dir(output_file.RemoveFileName());
3045
if (output_dir.CreateDirectoriesRecursively()) {
3046
xmlout = internal::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
internal::String XmlUnitTestResultPrinter::EscapeXml(const char* str,
3082
bool is_attribute) {
3086
for (const char* src = str; *src; ++src) {
3110
if (IsValidXmlCharacter(*src)) {
3111
if (is_attribute && IsNormalizableWhitespace(*src))
3112
m << internal::String::Format("&#x%02X;", unsigned(*src));
3121
return m.GetString();
3125
// The following routines generate an XML representation of a UnitTest
3128
// This is how Google Test concepts map to the DTD:
3130
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3131
// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3132
// <testcase name="test-name"> <-- corresponds to a TestInfo object
3133
// <failure message="...">...</failure>
3134
// <failure message="...">...</failure>
3135
// <failure message="...">...</failure>
3136
// <-- individual assertion failures
3141
namespace internal {
3143
// Formats the given time in milliseconds as seconds. The returned
3144
// C-string is owned by this function and cannot be released by the
3145
// caller. Calling the function again invalidates the previous
3147
const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3149
str = (Message() << (ms/1000.0)).GetString();
3153
} // namespace internal
3155
// Prints an XML representation of a TestInfo object.
3156
// TODO(wan): There is also value in printing properties with the plain printer.
3157
void XmlUnitTestResultPrinter::PrintXmlTestInfo(FILE* out,
3158
const char* test_case_name,
3159
const TestInfo& test_info) {
3160
const TestResult& result = *test_info.result();
3162
" <testcase name=\"%s\" status=\"%s\" time=\"%s\" "
3163
"classname=\"%s\"%s",
3164
EscapeXmlAttribute(test_info.name()).c_str(),
3165
test_info.should_run() ? "run" : "notrun",
3166
internal::FormatTimeInMillisAsSeconds(result.elapsed_time()),
3167
EscapeXmlAttribute(test_case_name).c_str(),
3168
TestPropertiesAsXmlAttributes(result).c_str());
3171
for (int i = 0; i < result.total_part_count(); ++i) {
3172
const TestPartResult& part = result.GetTestPartResult(i);
3173
if (part.failed()) {
3174
const internal::String message =
3175
internal::String::Format("%s:%d\n%s", part.file_name(),
3176
part.line_number(), part.message());
3177
if (++failures == 1)
3178
fprintf(out, ">\n");
3180
" <failure message=\"%s\" type=\"\"><![CDATA[%s]]>"
3182
EscapeXmlAttribute(part.summary()).c_str(), message.c_str());
3187
fprintf(out, " />\n");
3189
fprintf(out, " </testcase>\n");
3192
// Prints an XML representation of a TestCase object
3193
void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3194
const TestCase& test_case) {
3196
" <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3198
EscapeXmlAttribute(test_case.name()).c_str(),
3199
test_case.total_test_count(),
3200
test_case.failed_test_count(),
3201
test_case.disabled_test_count());
3203
"errors=\"0\" time=\"%s\">\n",
3204
internal::FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3205
for (int i = 0; i < test_case.total_test_count(); ++i)
3206
PrintXmlTestInfo(out, test_case.name(), *test_case.GetTestInfo(i));
3207
fprintf(out, " </testsuite>\n");
3210
// Prints an XML summary of unit_test to output stream out.
3211
void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3212
const UnitTest& unit_test) {
3213
fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3215
"<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3216
"errors=\"0\" time=\"%s\" ",
3217
unit_test.total_test_count(),
3218
unit_test.failed_test_count(),
3219
unit_test.disabled_test_count(),
3220
internal::FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3221
if (GTEST_FLAG(shuffle)) {
3222
fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3224
fprintf(out, "name=\"AllTests\">\n");
3225
for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3226
PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3227
fprintf(out, "</testsuites>\n");
3230
// Produces a string representing the test properties in a result as space
3231
// delimited XML attributes based on the property key="value" pairs.
3232
internal::String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3233
const TestResult& result) {
3235
for (int i = 0; i < result.test_property_count(); ++i) {
3236
const TestProperty& property = result.GetTestProperty(i);
3237
attributes << " " << property.key() << "="
3238
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
3240
return attributes.GetString();
3243
// End XmlUnitTestResultPrinter
3245
namespace internal {
3247
// Class ScopedTrace
3249
// Pushes the given source file location and message onto a per-thread
3250
// trace stack maintained by Google Test.
3251
// L < UnitTest::mutex_
3252
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3256
trace.message = message.GetString();
3258
UnitTest::GetInstance()->PushGTestTrace(trace);
3261
// Pops the info pushed by the c'tor.
3262
// L < UnitTest::mutex_
3263
ScopedTrace::~ScopedTrace() {
3264
UnitTest::GetInstance()->PopGTestTrace();
3268
// class OsStackTraceGetter
3270
// Returns the current OS stack trace as a String. Parameters:
3272
// max_depth - the maximum number of stack frames to be included
3274
// skip_count - the number of top frames to be skipped; doesn't count
3275
// against max_depth.
3278
// We use "L < mutex_" to denote that the function may acquire mutex_.
3279
String OsStackTraceGetter::CurrentStackTrace(int, int) {
3284
void OsStackTraceGetter::UponLeavingGTest() {
3288
OsStackTraceGetter::kElidedFramesMarker =
3289
"... " GTEST_NAME_ " internal frames ...";
3291
} // namespace internal
3295
// Gets the singleton UnitTest object. The first time this method is
3296
// called, a UnitTest object is constructed and returned. Consecutive
3297
// calls will return the same object.
3299
// We don't protect this under mutex_ as a user is not supposed to
3300
// call this before main() starts, from which point on the return
3301
// value will never change.
3302
UnitTest * UnitTest::GetInstance() {
3303
// When compiled with MSVC 7.1 in optimized mode, destroying the
3304
// UnitTest object upon exiting the program messes up the exit code,
3305
// causing successful tests to appear failed. We have to use a
3306
// different implementation in this case to bypass the compiler bug.
3307
// This implementation makes the compiler happy, at the cost of
3308
// leaking the UnitTest object.
3310
// CodeGear C++Builder insists on a public destructor for the
3311
// default implementation. Use this implementation to keep good OO
3312
// design with private destructor.
3314
#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3315
static UnitTest* const instance = new UnitTest;
3318
static UnitTest instance;
3320
#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3323
// Gets the number of successful test cases.
3324
int UnitTest::successful_test_case_count() const {
3325
return impl()->successful_test_case_count();
3328
// Gets the number of failed test cases.
3329
int UnitTest::failed_test_case_count() const {
3330
return impl()->failed_test_case_count();
3333
// Gets the number of all test cases.
3334
int UnitTest::total_test_case_count() const {
3335
return impl()->total_test_case_count();
3338
// Gets the number of all test cases that contain at least one test
3340
int UnitTest::test_case_to_run_count() const {
3341
return impl()->test_case_to_run_count();
3344
// Gets the number of successful tests.
3345
int UnitTest::successful_test_count() const {
3346
return impl()->successful_test_count();
3349
// Gets the number of failed tests.
3350
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3352
// Gets the number of disabled tests.
3353
int UnitTest::disabled_test_count() const {
3354
return impl()->disabled_test_count();
3357
// Gets the number of all tests.
3358
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3360
// Gets the number of tests that should run.
3361
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3363
// Gets the elapsed time, in milliseconds.
3364
internal::TimeInMillis UnitTest::elapsed_time() const {
3365
return impl()->elapsed_time();
3368
// Returns true iff the unit test passed (i.e. all test cases passed).
3369
bool UnitTest::Passed() const { return impl()->Passed(); }
3371
// Returns true iff the unit test failed (i.e. some test case failed
3372
// or something outside of all tests failed).
3373
bool UnitTest::Failed() const { return impl()->Failed(); }
3375
// Gets the i-th test case among all the test cases. i can range from 0 to
3376
// total_test_case_count() - 1. If i is not in that range, returns NULL.
3377
const TestCase* UnitTest::GetTestCase(int i) const {
3378
return impl()->GetTestCase(i);
3381
// Registers and returns a global test environment. When a test
3382
// program is run, all global test environments will be set-up in the
3383
// order they were registered. After all tests in the program have
3384
// finished, all global test environments will be torn-down in the
3385
// *reverse* order they were registered.
3387
// The UnitTest object takes ownership of the given environment.
3389
// We don't protect this under mutex_, as we only support calling it
3390
// from the main thread.
3391
Environment* UnitTest::AddEnvironment(Environment* env) {
3396
impl_->environments()->PushBack(env);
3397
impl_->environments_in_reverse_order()->PushFront(env);
3401
#if GTEST_HAS_EXCEPTIONS
3402
// A failed Google Test assertion will throw an exception of this type
3403
// when exceptions are enabled. We derive it from std::runtime_error,
3404
// which is for errors presumably detectable only at run time. Since
3405
// std::runtime_error inherits from std::exception, many testing
3406
// frameworks know how to extract and print the message inside it.
3407
class GoogleTestFailureException : public ::std::runtime_error {
3409
explicit GoogleTestFailureException(const TestPartResult& failure)
3410
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3414
// Adds a TestPartResult to the current TestResult object. All Google Test
3415
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3416
// this to report their results. The user code should use the
3417
// assertion macros instead of calling this directly.
3419
void UnitTest::AddTestPartResult(TestPartResultType result_type,
3420
const char* file_name,
3422
const internal::String& message,
3423
const internal::String& os_stack_trace) {
3427
internal::MutexLock lock(&mutex_);
3428
if (impl_->gtest_trace_stack()->size() > 0) {
3429
msg << "\n" << GTEST_NAME_ << " trace:";
3431
for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) {
3432
const internal::TraceInfo& trace =
3433
impl_->gtest_trace_stack()->GetElement(i);
3434
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3435
<< " " << trace.message;
3439
if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3440
msg << internal::kStackTraceMarker << os_stack_trace;
3443
const TestPartResult result =
3444
TestPartResult(result_type, file_name, line_number,
3445
msg.GetString().c_str());
3446
impl_->GetTestPartResultReporterForCurrentThread()->
3447
ReportTestPartResult(result);
3449
if (result_type != TPRT_SUCCESS) {
3450
// gtest_break_on_failure takes precedence over
3451
// gtest_throw_on_failure. This allows a user to set the latter
3452
// in the code (perhaps in order to use Google Test assertions
3453
// with another testing framework) and specify the former on the
3454
// command line for debugging.
3455
if (GTEST_FLAG(break_on_failure)) {
3456
#if GTEST_OS_WINDOWS
3457
// Using DebugBreak on Windows allows gtest to still break into a debugger
3458
// when a failure happens and both the --gtest_break_on_failure and
3459
// the --gtest_catch_exceptions flags are specified.
3462
*static_cast<int*>(NULL) = 1;
3463
#endif // GTEST_OS_WINDOWS
3464
} else if (GTEST_FLAG(throw_on_failure)) {
3465
#if GTEST_HAS_EXCEPTIONS
3466
throw GoogleTestFailureException(result);
3468
// We cannot call abort() as it generates a pop-up in debug mode
3469
// that cannot be suppressed in VC 7.1 or below.
3476
// Creates and adds a property to the current TestResult. If a property matching
3477
// the supplied value already exists, updates its value instead.
3478
void UnitTest::RecordPropertyForCurrentTest(const char* key,
3479
const char* value) {
3480
const TestProperty test_property(key, value);
3481
impl_->current_test_result()->RecordProperty(test_property);
3484
// Runs all tests in this UnitTest object and prints the result.
3485
// Returns 0 if successful, or 1 otherwise.
3487
// We don't protect this under mutex_, as we only support calling it
3488
// from the main thread.
3489
int UnitTest::Run() {
3491
// Catch SEH-style exceptions.
3493
const bool in_death_test_child_process =
3494
internal::GTEST_FLAG(internal_run_death_test).GetLength() > 0;
3496
// Either the user wants Google Test to catch exceptions thrown by the
3497
// tests or this is executing in the context of death test child
3498
// process. In either case the user does not want to see pop-up dialogs
3499
// about crashes - they are expected..
3500
if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3501
#if !defined(_WIN32_WCE)
3502
// SetErrorMode doesn't exist on CE.
3503
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3504
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3505
#endif // _WIN32_WCE
3507
#if (defined(_MSC_VER) || defined(__MINGW32__)) && !defined(_WIN32_WCE)
3508
// Death test children can be terminated with _abort(). On Windows,
3509
// _abort() can show a dialog with a warning message. This forces the
3510
// abort message to go to stderr instead.
3511
_set_error_mode(_OUT_TO_STDERR);
3514
#if _MSC_VER >= 1400 && !defined(_WIN32_WCE)
3515
// In the debug version, Visual Studio pops up a separate dialog
3516
// offering a choice to debug the aborted program. We need to suppress
3517
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3518
// executed. Google Test will notify the user of any unexpected
3519
// failure via stderr.
3521
// VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3522
// Users of prior VC versions shall suffer the agony and pain of
3523
// clicking through the countless debug dialogs.
3524
// TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3525
// debug mode when compiled with VC 7.1 or lower.
3526
if (!GTEST_FLAG(break_on_failure))
3527
_set_abort_behavior(
3528
0x0, // Clear the following flags:
3529
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
3534
return impl_->RunAllTests();
3535
} __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3536
GetExceptionCode())) {
3537
printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3542
#else // We are on a compiler or platform that doesn't support SEH.
3544
return impl_->RunAllTests();
3545
#endif // GTEST_HAS_SEH
3548
// Returns the working directory when the first TEST() or TEST_F() was
3550
const char* UnitTest::original_working_dir() const {
3551
return impl_->original_working_dir_.c_str();
3554
// Returns the TestCase object for the test that's currently running,
3555
// or NULL if no test is running.
3557
const TestCase* UnitTest::current_test_case() const {
3558
internal::MutexLock lock(&mutex_);
3559
return impl_->current_test_case();
3562
// Returns the TestInfo object for the test that's currently running,
3563
// or NULL if no test is running.
3565
const TestInfo* UnitTest::current_test_info() const {
3566
internal::MutexLock lock(&mutex_);
3567
return impl_->current_test_info();
3570
// Returns the random seed used at the start of the current test run.
3571
int UnitTest::random_seed() const { return impl_->random_seed(); }
3573
#if GTEST_HAS_PARAM_TEST
3574
// Returns ParameterizedTestCaseRegistry object used to keep track of
3575
// value-parameterized tests and instantiate and register them.
3577
internal::ParameterizedTestCaseRegistry&
3578
UnitTest::parameterized_test_registry() {
3579
return impl_->parameterized_test_registry();
3581
#endif // GTEST_HAS_PARAM_TEST
3583
// Creates an empty UnitTest.
3584
UnitTest::UnitTest() {
3585
impl_ = new internal::UnitTestImpl(this);
3588
// Destructor of UnitTest.
3589
UnitTest::~UnitTest() {
3593
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3594
// Google Test trace stack.
3596
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3597
internal::MutexLock lock(&mutex_);
3598
impl_->gtest_trace_stack()->PushFront(trace);
3601
// Pops a trace from the per-thread Google Test trace stack.
3603
void UnitTest::PopGTestTrace() {
3604
internal::MutexLock lock(&mutex_);
3605
impl_->gtest_trace_stack()->PopFront(NULL);
3608
namespace internal {
3610
UnitTestImpl::UnitTestImpl(UnitTest* parent)
3613
#pragma warning(push) // Saves the current warning state.
3614
#pragma warning(disable:4355) // Temporarily disables warning 4355
3615
// (using this in initializer).
3616
default_global_test_part_result_reporter_(this),
3617
default_per_thread_test_part_result_reporter_(this),
3618
#pragma warning(pop) // Restores the warning state again.
3620
default_global_test_part_result_reporter_(this),
3621
default_per_thread_test_part_result_reporter_(this),
3623
global_test_part_result_repoter_(
3624
&default_global_test_part_result_reporter_),
3625
per_thread_test_part_result_reporter_(
3626
&default_per_thread_test_part_result_reporter_),
3628
#if GTEST_HAS_PARAM_TEST
3629
parameterized_test_registry_(),
3630
parameterized_tests_registered_(false),
3631
#endif // GTEST_HAS_PARAM_TEST
3632
last_death_test_case_(-1),
3633
current_test_case_(NULL),
3634
current_test_info_(NULL),
3635
ad_hoc_test_result_(),
3636
result_printer_(NULL),
3637
os_stack_trace_getter_(NULL),
3639
#if GTEST_HAS_DEATH_TEST
3641
internal_run_death_test_flag_(NULL),
3642
death_test_factory_(new DefaultDeathTestFactory) {
3645
#endif // GTEST_HAS_DEATH_TEST
3648
UnitTestImpl::~UnitTestImpl() {
3649
// Deletes every TestCase.
3650
test_cases_.ForEach(internal::Delete<TestCase>);
3652
// Deletes every Environment.
3653
environments_.ForEach(internal::Delete<Environment>);
3655
// Deletes the current test result printer.
3656
delete result_printer_;
3658
delete os_stack_trace_getter_;
3661
// A predicate that checks the name of a TestCase against a known
3664
// This is used for implementation of the UnitTest class only. We put
3665
// it in the anonymous namespace to prevent polluting the outer
3668
// TestCaseNameIs is copyable.
3669
class TestCaseNameIs {
3672
explicit TestCaseNameIs(const String& name)
3675
// Returns true iff the name of test_case matches name_.
3676
bool operator()(const TestCase* test_case) const {
3677
return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3684
// Finds and returns a TestCase with the given name. If one doesn't
3685
// exist, creates one and returns it.
3689
// test_case_name: name of the test case
3690
// set_up_tc: pointer to the function that sets up the test case
3691
// tear_down_tc: pointer to the function that tears down the test case
3692
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3693
const char* comment,
3694
Test::SetUpTestCaseFunc set_up_tc,
3695
Test::TearDownTestCaseFunc tear_down_tc) {
3696
// Can we find a TestCase with the given name?
3697
TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name));
3699
if (test_case != NULL)
3702
// No. Let's create one.
3703
TestCase* const new_test_case =
3704
new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3706
// Is this a death test case?
3707
if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3708
kDeathTestCaseFilter)) {
3709
// Yes. Inserts the test case after the last death test case
3711
test_cases_.Insert(new_test_case, ++last_death_test_case_);
3713
// No. Appends to the end of the list.
3714
test_cases_.PushBack(new_test_case);
3717
return new_test_case;
3720
// Helpers for setting up / tearing down the given environment. They
3721
// are for use in the Vector::ForEach() method.
3722
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3723
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3725
// Runs all tests in this UnitTest object, prints the result, and
3726
// returns 0 if all tests are successful, or 1 otherwise. If any
3727
// exception is thrown during a test on Windows, this test is
3728
// considered to be failed, but the rest of the tests will still be
3729
// run. (We disable exceptions on Linux and Mac OS X, so the issue
3730
// doesn't apply there.)
3731
// When parameterized tests are enabled, it explands and registers
3732
// parameterized tests first in RegisterParameterizedTests().
3733
// All other functions called from RunAllTests() may safely assume that
3734
// parameterized tests are ready to be counted and run.
3735
int UnitTestImpl::RunAllTests() {
3736
// Makes sure InitGoogleTest() was called.
3737
if (!GTestIsInitialized()) {
3739
"\nThis test program did NOT call ::testing::InitGoogleTest "
3740
"before calling RUN_ALL_TESTS(). Please fix it.\n");
3744
// Do not run any test if the --help flag was specified.
3748
RegisterParameterizedTests();
3750
// Even if sharding is not on, test runners may want to use the
3751
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3753
internal::WriteToShardStatusFileIfNeeded();
3755
// True iff we are in a subprocess for running a thread-safe-style
3757
bool in_subprocess_for_death_test = false;
3759
#if GTEST_HAS_DEATH_TEST
3760
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
3761
in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3762
#endif // GTEST_HAS_DEATH_TEST
3764
UnitTestEventListenerInterface * const printer = result_printer();
3766
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3767
in_subprocess_for_death_test);
3769
// Compares the full test names with the filter to decide which
3771
const bool has_tests_to_run = FilterTests(should_shard
3772
? HONOR_SHARDING_PROTOCOL
3773
: IGNORE_SHARDING_PROTOCOL) > 0;
3775
// Lists the tests and exits if the --gtest_list_tests flag was specified.
3776
if (GTEST_FLAG(list_tests)) {
3777
// This must be called *after* FilterTests() has been called.
3778
ListTestsMatchingFilter();
3782
random_seed_ = GTEST_FLAG(shuffle) ?
3783
GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3785
// True iff at least one test has failed.
3786
bool failed = false;
3788
// How many times to repeat the tests? We don't want to repeat them
3789
// when we are inside the subprocess of a death test.
3790
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3791
// Repeats forever if the repeat count is negative.
3792
const bool forever = repeat < 0;
3793
for (int i = 0; forever || i != repeat; i++) {
3795
printf("\nRepeating all tests (iteration %d) . . .\n\n", i + 1);
3798
// Tells the unit test event listener that the tests are about to
3800
printer->OnUnitTestStart(*parent_);
3802
const TimeInMillis start = GetTimeInMillis();
3804
// Runs each test case if there is at least one test to run.
3805
if (has_tests_to_run) {
3806
// Sets up all environments beforehand.
3807
printer->OnGlobalSetUpStart(*parent_);
3808
environments_.ForEach(SetUpEnvironment);
3809
printer->OnGlobalSetUpEnd(*parent_);
3811
// Runs the tests only if there was no fatal failure during global
3813
if (!Test::HasFatalFailure()) {
3814
test_cases_.ForEach(TestCase::RunTestCase);
3817
// Tears down all environments in reverse order afterwards.
3818
printer->OnGlobalTearDownStart(*parent_);
3819
environments_in_reverse_order_.ForEach(TearDownEnvironment);
3820
printer->OnGlobalTearDownEnd(*parent_);
3823
elapsed_time_ = GetTimeInMillis() - start;
3825
// Tells the unit test event listener that the tests have just
3827
printer->OnUnitTestEnd(*parent_);
3829
// Gets the result and clears it.
3835
if (GTEST_FLAG(shuffle)) {
3836
// Picks a new random seed for each run.
3837
random_seed_ = GetNextRandomSeed(random_seed_);
3841
// Returns 0 if all tests passed, or 1 other wise.
3842
return failed ? 1 : 0;
3845
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
3846
// if the variable is present. If a file already exists at this location, this
3847
// function will write over it. If the variable is present, but the file cannot
3848
// be created, prints an error and exits.
3849
void WriteToShardStatusFileIfNeeded() {
3850
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
3851
if (test_shard_file != NULL) {
3852
FILE* const file = posix::FOpen(test_shard_file, "w");
3854
ColoredPrintf(COLOR_RED,
3855
"Could not write to the test shard status file \"%s\" "
3856
"specified by the %s environment variable.\n",
3857
test_shard_file, kTestShardStatusFile);
3865
// Checks whether sharding is enabled by examining the relevant
3866
// environment variable values. If the variables are present,
3867
// but inconsistent (i.e., shard_index >= total_shards), prints
3868
// an error and exits. If in_subprocess_for_death_test, sharding is
3869
// disabled because it must only be applied to the original test
3870
// process. Otherwise, we could filter out death tests we intended to execute.
3871
bool ShouldShard(const char* total_shards_env,
3872
const char* shard_index_env,
3873
bool in_subprocess_for_death_test) {
3874
if (in_subprocess_for_death_test) {
3878
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
3879
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
3881
if (total_shards == -1 && shard_index == -1) {
3883
} else if (total_shards == -1 && shard_index != -1) {
3884
const Message msg = Message()
3885
<< "Invalid environment variables: you have "
3886
<< kTestShardIndex << " = " << shard_index
3887
<< ", but have left " << kTestTotalShards << " unset.\n";
3888
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
3891
} else if (total_shards != -1 && shard_index == -1) {
3892
const Message msg = Message()
3893
<< "Invalid environment variables: you have "
3894
<< kTestTotalShards << " = " << total_shards
3895
<< ", but have left " << kTestShardIndex << " unset.\n";
3896
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
3899
} else if (shard_index < 0 || shard_index >= total_shards) {
3900
const Message msg = Message()
3901
<< "Invalid environment variables: we require 0 <= "
3902
<< kTestShardIndex << " < " << kTestTotalShards
3903
<< ", but you have " << kTestShardIndex << "=" << shard_index
3904
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
3905
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
3910
return total_shards > 1;
3913
// Parses the environment variable var as an Int32. If it is unset,
3914
// returns default_val. If it is not an Int32, prints an error
3916
Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
3917
const char* str_val = posix::GetEnv(var);
3918
if (str_val == NULL) {
3923
if (!ParseInt32(Message() << "The value of environment variable " << var,
3924
str_val, &result)) {
3930
// Given the total number of shards, the shard index, and the test id,
3931
// returns true iff the test should be run on this shard. The test id is
3932
// some arbitrary but unique non-negative integer assigned to each test
3933
// method. Assumes that 0 <= shard_index < total_shards.
3934
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
3935
return (test_id % total_shards) == shard_index;
3938
// Compares the name of each test with the user-specified filter to
3939
// decide whether the test should be run, then records the result in
3940
// each TestCase and TestInfo object.
3941
// If shard_tests == true, further filters tests based on sharding
3942
// variables in the environment - see
3943
// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
3944
// Returns the number of tests that should run.
3945
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
3946
const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
3947
Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
3948
const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
3949
Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
3951
// num_runnable_tests are the number of tests that will
3952
// run across all shards (i.e., match filter and are not disabled).
3953
// num_selected_tests are the number of tests to be run on
3955
int num_runnable_tests = 0;
3956
int num_selected_tests = 0;
3957
for (int i = 0; i < test_cases_.size(); i++) {
3958
TestCase* const test_case = test_cases_.GetElement(i);
3959
const String &test_case_name = test_case->name();
3960
test_case->set_should_run(false);
3962
for (int j = 0; j < test_case->test_info_list().size(); j++) {
3963
TestInfo* const test_info = test_case->test_info_list().GetElement(j);
3964
const String test_name(test_info->name());
3965
// A test is disabled if test case name or test name matches
3966
// kDisableTestFilter.
3967
const bool is_disabled =
3968
internal::UnitTestOptions::MatchesFilter(test_case_name,
3969
kDisableTestFilter) ||
3970
internal::UnitTestOptions::MatchesFilter(test_name,
3971
kDisableTestFilter);
3972
test_info->impl()->set_is_disabled(is_disabled);
3974
const bool matches_filter =
3975
internal::UnitTestOptions::FilterMatchesTest(test_case_name,
3977
test_info->impl()->set_matches_filter(matches_filter);
3979
const bool is_runnable =
3980
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
3983
const bool is_selected = is_runnable &&
3984
(shard_tests == IGNORE_SHARDING_PROTOCOL ||
3985
ShouldRunTestOnShard(total_shards, shard_index,
3986
num_runnable_tests));
3988
num_runnable_tests += is_runnable;
3989
num_selected_tests += is_selected;
3991
test_info->impl()->set_should_run(is_selected);
3992
test_case->set_should_run(test_case->should_run() || is_selected);
3995
return num_selected_tests;
3998
// Prints the names of the tests matching the user-specified filter flag.
3999
void UnitTestImpl::ListTestsMatchingFilter() {
4000
for (int i = 0; i < test_cases_.size(); i++) {
4001
const TestCase* const test_case = test_cases_.GetElement(i);
4002
bool printed_test_case_name = false;
4004
for (int j = 0; j < test_case->test_info_list().size(); j++) {
4005
const TestInfo* const test_info =
4006
test_case->test_info_list().GetElement(j);
4007
if (test_info->matches_filter()) {
4008
if (!printed_test_case_name) {
4009
printed_test_case_name = true;
4010
printf("%s.\n", test_case->name());
4012
printf(" %s\n", test_info->name());
4019
// Sets the unit test result printer.
4021
// Does nothing if the input and the current printer object are the
4022
// same; otherwise, deletes the old printer object and makes the
4023
// input the current printer.
4024
void UnitTestImpl::set_result_printer(
4025
UnitTestEventListenerInterface* result_printer) {
4026
if (result_printer_ != result_printer) {
4027
delete result_printer_;
4028
result_printer_ = result_printer;
4032
// Returns the current unit test result printer if it is not NULL;
4033
// otherwise, creates an appropriate result printer, makes it the
4034
// current printer, and returns it.
4035
UnitTestEventListenerInterface* UnitTestImpl::result_printer() {
4036
if (result_printer_ != NULL) {
4037
return result_printer_;
4040
#if GTEST_HAS_DEATH_TEST
4041
if (internal_run_death_test_flag_.get() != NULL) {
4042
result_printer_ = new NullUnitTestResultPrinter;
4043
return result_printer_;
4045
#endif // GTEST_HAS_DEATH_TEST
4047
UnitTestEventsRepeater *repeater = new UnitTestEventsRepeater;
4048
const String& output_format = internal::UnitTestOptions::GetOutputFormat();
4049
if (output_format == "xml") {
4050
repeater->AddListener(new XmlUnitTestResultPrinter(
4051
internal::UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
4052
} else if (output_format != "") {
4053
printf("WARNING: unrecognized output format \"%s\" ignored.\n",
4054
output_format.c_str());
4057
repeater->AddListener(new PrettyUnitTestResultPrinter);
4058
result_printer_ = repeater;
4059
return result_printer_;
4062
// Sets the OS stack trace getter.
4064
// Does nothing if the input and the current OS stack trace getter are
4065
// the same; otherwise, deletes the old getter and makes the input the
4067
void UnitTestImpl::set_os_stack_trace_getter(
4068
OsStackTraceGetterInterface* getter) {
4069
if (os_stack_trace_getter_ != getter) {
4070
delete os_stack_trace_getter_;
4071
os_stack_trace_getter_ = getter;
4075
// Returns the current OS stack trace getter if it is not NULL;
4076
// otherwise, creates an OsStackTraceGetter, makes it the current
4077
// getter, and returns it.
4078
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4079
if (os_stack_trace_getter_ == NULL) {
4080
os_stack_trace_getter_ = new OsStackTraceGetter;
4083
return os_stack_trace_getter_;
4086
// Returns the TestResult for the test that's currently running, or
4087
// the TestResult for the ad hoc test if no test is running.
4088
TestResult* UnitTestImpl::current_test_result() {
4089
return current_test_info_ ?
4090
current_test_info_->impl()->result() : &ad_hoc_test_result_;
4093
// TestInfoImpl constructor. The new instance assumes ownership of the test
4095
TestInfoImpl::TestInfoImpl(TestInfo* parent,
4096
const char* test_case_name,
4098
const char* test_case_comment,
4099
const char* comment,
4100
TypeId fixture_class_id,
4101
internal::TestFactoryBase* factory) :
4103
test_case_name_(String(test_case_name)),
4104
name_(String(name)),
4105
test_case_comment_(String(test_case_comment)),
4106
comment_(String(comment)),
4107
fixture_class_id_(fixture_class_id),
4109
is_disabled_(false),
4110
matches_filter_(false),
4114
// TestInfoImpl destructor.
4115
TestInfoImpl::~TestInfoImpl() {
4119
// Returns the current OS stack trace as a String.
4121
// The maximum number of stack frames to be included is specified by
4122
// the gtest_stack_trace_depth flag. The skip_count parameter
4123
// specifies the number of top frames to be skipped, which doesn't
4124
// count against the number of frames to be included.
4126
// For example, if Foo() calls Bar(), which in turn calls
4127
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4128
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4129
String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count) {
4130
// We pass skip_count + 1 to skip this wrapper function in addition
4131
// to what the user really wants to skip.
4132
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4135
// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4138
class ClassUniqueToAlwaysTrue {};
4142
#if GTEST_HAS_EXCEPTIONS
4143
// This condition is always false so AlwaysTrue() never actually throws,
4144
// but it makes the compiler think that it may throw.
4145
if (atoi("42") == 36) // NOLINT
4146
throw ClassUniqueToAlwaysTrue();
4147
#endif // GTEST_HAS_EXCEPTIONS
4151
// Parses a string as a command line flag. The string should have
4152
// the format "--flag=value". When def_optional is true, the "=value"
4153
// part can be omitted.
4155
// Returns the value of the flag, or NULL if the parsing failed.
4156
const char* ParseFlagValue(const char* str,
4158
bool def_optional) {
4159
// str and flag must not be NULL.
4160
if (str == NULL || flag == NULL) return NULL;
4162
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4163
const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
4164
const size_t flag_len = flag_str.GetLength();
4165
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4167
// Skips the flag name.
4168
const char* flag_end = str + flag_len;
4170
// When def_optional is true, it's OK to not have a "=value" part.
4171
if (def_optional && (flag_end[0] == '\0')) {
4175
// If def_optional is true and there are more characters after the
4176
// flag name, or if def_optional is false, there must be a '=' after
4178
if (flag_end[0] != '=') return NULL;
4180
// Returns the string after "=".
4181
return flag_end + 1;
4184
// Parses a string for a bool flag, in the form of either
4185
// "--flag=value" or "--flag".
4187
// In the former case, the value is taken as true as long as it does
4188
// not start with '0', 'f', or 'F'.
4190
// In the latter case, the value is taken as true.
4192
// On success, stores the value of the flag in *value, and returns
4193
// true. On failure, returns false without changing *value.
4194
bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4195
// Gets the value of the flag as a string.
4196
const char* const value_str = ParseFlagValue(str, flag, true);
4198
// Aborts if the parsing failed.
4199
if (value_str == NULL) return false;
4201
// Converts the string value to a bool.
4202
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4206
// Parses a string for an Int32 flag, in the form of
4209
// On success, stores the value of the flag in *value, and returns
4210
// true. On failure, returns false without changing *value.
4211
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4212
// Gets the value of the flag as a string.
4213
const char* const value_str = ParseFlagValue(str, flag, false);
4215
// Aborts if the parsing failed.
4216
if (value_str == NULL) return false;
4218
// Sets *value to the value of the flag.
4219
return ParseInt32(Message() << "The value of flag --" << flag,
4223
// Parses a string for a string flag, in the form of
4226
// On success, stores the value of the flag in *value, and returns
4227
// true. On failure, returns false without changing *value.
4228
bool ParseStringFlag(const char* str, const char* flag, String* value) {
4229
// Gets the value of the flag as a string.
4230
const char* const value_str = ParseFlagValue(str, flag, false);
4232
// Aborts if the parsing failed.
4233
if (value_str == NULL) return false;
4235
// Sets *value to the value of the flag.
4240
// Prints a string containing code-encoded text. The following escape
4241
// sequences can be used in the string to control the text color:
4243
// @@ prints a single '@' character.
4244
// @R changes the color to red.
4245
// @G changes the color to green.
4246
// @Y changes the color to yellow.
4247
// @D changes to the default terminal text color.
4249
// TODO(wan@google.com): Write tests for this once we add stdout
4250
// capturing to Google Test.
4251
static void PrintColorEncoded(const char* str) {
4252
GTestColor color = COLOR_DEFAULT; // The current color.
4254
// Conceptually, we split the string into segments divided by escape
4255
// sequences. Then we print one segment at a time. At the end of
4256
// each iteration, the str pointer advances to the beginning of the
4259
const char* p = strchr(str, '@');
4261
ColoredPrintf(color, "%s", str);
4265
ColoredPrintf(color, "%s", String(str, p - str).c_str());
4267
const char ch = p[1];
4270
ColoredPrintf(color, "@");
4271
} else if (ch == 'D') {
4272
color = COLOR_DEFAULT;
4273
} else if (ch == 'R') {
4275
} else if (ch == 'G') {
4276
color = COLOR_GREEN;
4277
} else if (ch == 'Y') {
4278
color = COLOR_YELLOW;
4285
static const char kColorEncodedHelpMessage[] =
4286
"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4287
"following command line flags to control its behavior:\n"
4290
" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4291
" List the names of all tests instead of running them. The name of\n"
4292
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
4293
" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4294
"[@G-@YNEGATIVE_PATTERNS]@D\n"
4295
" Run only the tests whose name matches one of the positive patterns but\n"
4296
" none of the negative patterns. '?' matches any single character; '*'\n"
4297
" matches any substring; ':' separates two patterns.\n"
4298
" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4299
" Run all disabled tests too.\n"
4302
" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4303
" Run the tests repeatedly; use a negative count to repeat forever.\n"
4304
" @G--" GTEST_FLAG_PREFIX_ "shuffle\n"
4305
" Randomize tests' orders on every run. To be implemented.\n"
4306
" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4307
" Random number seed to use for shuffling test orders (between 1 and\n"
4308
" 99999, or 0 to use a seed based on the current time).\n"
4311
" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4312
" Enable/disable colored output. The default is @Gauto@D.\n"
4313
" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4314
" Don't print the elapsed time of each test.\n"
4315
" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4316
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4317
" Generate an XML report in the given directory or with the given file\n"
4318
" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4320
"Assertion Behavior:\n"
4321
#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4322
" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4323
" Set the default death test style.\n"
4324
#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4325
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4326
" Turn assertion failures into debugger break-points.\n"
4327
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4328
" Turn assertion failures into C++ exceptions.\n"
4329
#if GTEST_OS_WINDOWS
4330
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4331
" Suppress pop-ups caused by exceptions.\n"
4332
#endif // GTEST_OS_WINDOWS
4334
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4335
"the corresponding\n"
4336
"environment variable of a flag (all letters in upper-case). For example, to\n"
4337
"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4338
"color=no@D or set\n"
4339
"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
4341
"For more information, please read the " GTEST_NAME_ " documentation at\n"
4342
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4343
"(not one in your own code or tests), please report it to\n"
4344
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4346
// Parses the command line for Google Test flags, without initializing
4347
// other parts of Google Test. The type parameter CharType can be
4348
// instantiated to either char or wchar_t.
4349
template <typename CharType>
4350
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4351
for (int i = 1; i < *argc; i++) {
4352
const String arg_string = StreamableToString(argv[i]);
4353
const char* const arg = arg_string.c_str();
4355
using internal::ParseBoolFlag;
4356
using internal::ParseInt32Flag;
4357
using internal::ParseStringFlag;
4359
// Do we see a Google Test flag?
4360
if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4361
>EST_FLAG(also_run_disabled_tests)) ||
4362
ParseBoolFlag(arg, kBreakOnFailureFlag,
4363
>EST_FLAG(break_on_failure)) ||
4364
ParseBoolFlag(arg, kCatchExceptionsFlag,
4365
>EST_FLAG(catch_exceptions)) ||
4366
ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
4367
ParseStringFlag(arg, kDeathTestStyleFlag,
4368
>EST_FLAG(death_test_style)) ||
4369
ParseBoolFlag(arg, kDeathTestUseFork,
4370
>EST_FLAG(death_test_use_fork)) ||
4371
ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
4372
ParseStringFlag(arg, kInternalRunDeathTestFlag,
4373
>EST_FLAG(internal_run_death_test)) ||
4374
ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
4375
ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
4376
ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
4377
ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
4378
ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
4379
ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
4380
ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure))
4382
// Yes. Shift the remainder of the argv list left by one. Note
4383
// that argv has (*argc + 1) elements, the last one always being
4384
// NULL. The following loop moves the trailing NULL element as
4386
for (int j = i; j != *argc; j++) {
4387
argv[j] = argv[j + 1];
4390
// Decrements the argument count.
4393
// We also need to decrement the iterator as we just removed
4396
} else if (arg_string == "--help" || arg_string == "-h" ||
4397
arg_string == "-?" || arg_string == "/?") {
4403
// We print the help here instead of in RUN_ALL_TESTS(), as the
4404
// latter may not be called at all if the user is using Google
4405
// Test with another testing framework.
4406
PrintColorEncoded(kColorEncodedHelpMessage);
4410
// Parses the command line for Google Test flags, without initializing
4411
// other parts of Google Test.
4412
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4413
ParseGoogleTestFlagsOnlyImpl(argc, argv);
4415
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4416
ParseGoogleTestFlagsOnlyImpl(argc, argv);
4419
// The internal implementation of InitGoogleTest().
4421
// The type parameter CharType can be instantiated to either char or
4423
template <typename CharType>
4424
void InitGoogleTestImpl(int* argc, CharType** argv) {
4425
g_init_gtest_count++;
4427
// We don't want to run the initialization code twice.
4428
if (g_init_gtest_count != 1) return;
4430
if (*argc <= 0) return;
4432
internal::g_executable_path = internal::StreamableToString(argv[0]);
4434
#if GTEST_HAS_DEATH_TEST
4436
for (int i = 0; i != *argc; i++) {
4437
g_argvs.push_back(StreamableToString(argv[i]));
4439
#endif // GTEST_HAS_DEATH_TEST
4441
ParseGoogleTestFlagsOnly(argc, argv);
4444
} // namespace internal
4446
// Initializes Google Test. This must be called before calling
4447
// RUN_ALL_TESTS(). In particular, it parses a command line for the
4448
// flags that Google Test recognizes. Whenever a Google Test flag is
4449
// seen, it is removed from argv, and *argc is decremented.
4451
// No value is returned. Instead, the Google Test flag variables are
4454
// Calling the function for the second time has no user-visible effect.
4455
void InitGoogleTest(int* argc, char** argv) {
4456
internal::InitGoogleTestImpl(argc, argv);
4459
// This overloaded version can be used in Windows programs compiled in
4461
void InitGoogleTest(int* argc, wchar_t** argv) {
4462
internal::InitGoogleTestImpl(argc, argv);
4465
} // namespace testing