source: gtest-1.7.0/src/gtest.cc@ 12758

Last change on this file since 12758 was 12746, checked in by hock@…, 11 years ago

integrated the Google Testing Framework (gtest)

and wrote an Hello World test, to ensure the framework is working..

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