blob: 9aa54411497a0a39918952728b5c50447629b584 [file] [log] [blame]
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33
34#include <gtest/gtest.h>
35#include <gtest/gtest-spi.h>
36
37#include <ctype.h>
38#include <math.h>
39#include <stdarg.h>
40#include <stdio.h>
41#include <stdlib.h>
Misha Brukman7ae6ff42008-12-31 17:34:06 +000042#include <wchar.h>
43#include <wctype.h>
44
Benjamin Kramer57240ff2010-06-02 22:02:30 +000045#include <algorithm>
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000046#include <ostream>
Benjamin Kramer57240ff2010-06-02 22:02:30 +000047#include <sstream>
48#include <vector>
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000049
Benjamin Kramere4b9c932010-06-02 22:01:25 +000050#if GTEST_OS_LINUX
Misha Brukman7ae6ff42008-12-31 17:34:06 +000051
52// TODO(kenton@google.com): Use autoconf to detect availability of
53// gettimeofday().
Benjamin Kramere4b9c932010-06-02 22:01:25 +000054#define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +000055
56#include <fcntl.h>
57#include <limits.h>
58#include <sched.h>
59// Declares vsnprintf(). This header is not available on Windows.
60#include <strings.h>
61#include <sys/mman.h>
62#include <sys/time.h>
63#include <unistd.h>
64#include <string>
65#include <vector>
66
Benjamin Kramere4b9c932010-06-02 22:01:25 +000067#elif GTEST_OS_SYMBIAN
68#define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +000069#include <sys/time.h> // NOLINT
70
Benjamin Kramere4b9c932010-06-02 22:01:25 +000071#elif GTEST_OS_ZOS
72#define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +000073#include <sys/time.h> // NOLINT
74
75// On z/OS we additionally need strings.h for strcasecmp.
Benjamin Kramere4b9c932010-06-02 22:01:25 +000076#include <strings.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000077
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000078#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000079
80#include <windows.h> // NOLINT
81
Benjamin Kramere4b9c932010-06-02 22:01:25 +000082#elif GTEST_OS_WINDOWS // We are on Windows proper.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000083
84#include <io.h> // NOLINT
85#include <sys/timeb.h> // NOLINT
86#include <sys/types.h> // NOLINT
87#include <sys/stat.h> // NOLINT
88
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000089#if GTEST_OS_WINDOWS_MINGW
Misha Brukman7ae6ff42008-12-31 17:34:06 +000090// MinGW has gettimeofday() but not _ftime64().
91// TODO(kenton@google.com): Use autoconf to detect availability of
92// gettimeofday().
93// TODO(kenton@google.com): There are other ways to get the time on
94// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
95// supports these. consider using them instead.
Benjamin Kramere4b9c932010-06-02 22:01:25 +000096#define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +000097#include <sys/time.h> // NOLINT
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000098#endif // GTEST_OS_WINDOWS_MINGW
Misha Brukman7ae6ff42008-12-31 17:34:06 +000099
100// cpplint thinks that the header is already included, so we want to
101// silence it.
102#include <windows.h> // NOLINT
103
104#else
105
106// Assume other platforms have gettimeofday().
107// TODO(kenton@google.com): Use autoconf to detect availability of
108// gettimeofday().
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000109#define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000110
111// cpplint thinks that the header is already included, so we want to
112// silence it.
113#include <sys/time.h> // NOLINT
114#include <unistd.h> // NOLINT
115
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000116#endif // GTEST_OS_LINUX
117
118#if GTEST_HAS_EXCEPTIONS
119#include <stdexcept>
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000120#endif
121
122// Indicates that this translation unit is part of Google Test's
123// implementation. It must come before gtest-internal-inl.h is
124// included, or there will be a compiler error. This trick is to
125// prevent a user from accidentally including gtest-internal-inl.h in
126// his code.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000127#define GTEST_IMPLEMENTATION_ 1
Misha Brukmane5f94712009-01-01 02:05:43 +0000128#include "gtest/internal/gtest-internal-inl.h"
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000129#undef GTEST_IMPLEMENTATION_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000130
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000131#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000132#define vsnprintf _vsnprintf
133#endif // GTEST_OS_WINDOWS
134
135namespace testing {
136
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000137using internal::CountIf;
138using internal::ForEach;
139using internal::GetElementOr;
140using internal::Shuffle;
141
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000142// Constants.
143
144// A test whose test case name or test name matches this filter is
145// disabled and not run.
146static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
147
148// A test case whose name matches this filter is considered a death
149// test case and will be run before test cases whose name doesn't
150// match this filter.
151static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
152
153// A test filter that matches everything.
154static const char kUniversalFilter[] = "*";
155
156// The default output file for XML output.
157static const char kDefaultOutputFile[] = "test_detail.xml";
158
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000159// The environment variable name for the test shard index.
160static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
161// The environment variable name for the total number of test shards.
162static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
163// The environment variable name for the test shard status file.
164static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
165
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000166namespace internal {
167
168// The text used in failure messages to indicate the start of the
169// stack trace.
170const char kStackTraceMarker[] = "\nStack trace:\n";
171
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000172// g_help_flag is true iff the --help flag or an equivalent form is
173// specified on the command line.
174bool g_help_flag = false;
175
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000176} // namespace internal
177
178GTEST_DEFINE_bool_(
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000179 also_run_disabled_tests,
180 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
181 "Run disabled tests too, in addition to the tests normally being run.");
182
183GTEST_DEFINE_bool_(
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000184 break_on_failure,
185 internal::BoolFromGTestEnv("break_on_failure", false),
186 "True iff a failed assertion should be a debugger break-point.");
187
188GTEST_DEFINE_bool_(
189 catch_exceptions,
190 internal::BoolFromGTestEnv("catch_exceptions", false),
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000191 "True iff " GTEST_NAME_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000192 " should catch exceptions and treat them as test failures.");
193
194GTEST_DEFINE_string_(
195 color,
196 internal::StringFromGTestEnv("color", "auto"),
197 "Whether to use colors in the output. Valid values: yes, no, "
198 "and auto. 'auto' means to use colors if the output is "
199 "being sent to a terminal and the TERM environment variable "
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000200 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000201
202GTEST_DEFINE_string_(
203 filter,
204 internal::StringFromGTestEnv("filter", kUniversalFilter),
205 "A colon-separated list of glob (not regex) patterns "
206 "for filtering the tests to run, optionally followed by a "
207 "'-' and a : separated list of negative patterns (tests to "
208 "exclude). A test is run if it matches one of the positive "
209 "patterns and does not match any of the negative patterns.");
210
211GTEST_DEFINE_bool_(list_tests, false,
212 "List all tests without running them.");
213
214GTEST_DEFINE_string_(
215 output,
216 internal::StringFromGTestEnv("output", ""),
217 "A format (currently must be \"xml\"), optionally followed "
218 "by a colon and an output file name or directory. A directory "
219 "is indicated by a trailing pathname separator. "
220 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
221 "If a directory is specified, output files will be created "
222 "within that directory, with file-names based on the test "
223 "executable's name and, if necessary, made unique by adding "
224 "digits.");
225
226GTEST_DEFINE_bool_(
227 print_time,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000228 internal::BoolFromGTestEnv("print_time", true),
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000229 "True iff " GTEST_NAME_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000230 " should display elapsed time in text output.");
231
232GTEST_DEFINE_int32_(
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000233 random_seed,
234 internal::Int32FromGTestEnv("random_seed", 0),
235 "Random number seed to use when shuffling test orders. Must be in range "
236 "[1, 99999], or 0 to use a seed based on the current time.");
237
238GTEST_DEFINE_int32_(
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000239 repeat,
240 internal::Int32FromGTestEnv("repeat", 1),
241 "How many times to repeat each test. Specify a negative number "
242 "for repeating forever. Useful for shaking out flaky tests.");
243
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000244GTEST_DEFINE_bool_(
245 show_internal_stack_frames, false,
246 "True iff " GTEST_NAME_ " should include internal stack frames when "
247 "printing test failure stack traces.");
248
249GTEST_DEFINE_bool_(
250 shuffle,
251 internal::BoolFromGTestEnv("shuffle", false),
252 "True iff " GTEST_NAME_
253 " should randomize tests' order on every run.");
254
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000255GTEST_DEFINE_int32_(
256 stack_trace_depth,
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000257 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000258 "The maximum number of stack frames to print when an "
259 "assertion fails. The valid range is 0 through 100, inclusive.");
260
261GTEST_DEFINE_bool_(
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000262 throw_on_failure,
263 internal::BoolFromGTestEnv("throw_on_failure", false),
264 "When this flag is specified, a failed assertion will throw an exception "
265 "if exceptions are enabled or exit the program with a non-zero code "
266 "otherwise.");
267
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000268namespace internal {
269
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000270// Generates a random number from [0, range), using a Linear
271// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
272// than kMaxRange.
273UInt32 Random::Generate(UInt32 range) {
274 // These constants are the same as are used in glibc's rand(3).
275 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
276
277 GTEST_CHECK_(range > 0)
278 << "Cannot generate a number in the range [0, 0).";
279 GTEST_CHECK_(range <= kMaxRange)
280 << "Generation of a number in [0, " << range << ") was requested, "
281 << "but this can only generate numbers in [0, " << kMaxRange << ").";
282
283 // Converting via modulus introduces a bit of downward bias, but
284 // it's simple, and a linear congruential generator isn't too good
285 // to begin with.
286 return state_ % range;
287}
288
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000289// GTestIsInitialized() returns true iff the user has initialized
290// Google Test. Useful for catching the user mistake of not initializing
291// Google Test before calling RUN_ALL_TESTS().
292//
293// A user must call testing::InitGoogleTest() to initialize Google
294// Test. g_init_gtest_count is set to the number of times
295// InitGoogleTest() has been called. We don't protect this variable
296// under a mutex as it is only accessed in the main thread.
297int g_init_gtest_count = 0;
298static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
299
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000300// Iterates over a vector of TestCases, keeping a running sum of the
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000301// results of calling a given int-returning method on each.
302// Returns the sum.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000303static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000304 int (TestCase::*method)() const) {
305 int sum = 0;
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000306 for (size_t i = 0; i < case_list.size(); i++) {
307 sum += (case_list[i]->*method)();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000308 }
309 return sum;
310}
311
312// Returns true iff the test case passed.
313static bool TestCasePassed(const TestCase* test_case) {
314 return test_case->should_run() && test_case->Passed();
315}
316
317// Returns true iff the test case failed.
318static bool TestCaseFailed(const TestCase* test_case) {
319 return test_case->should_run() && test_case->Failed();
320}
321
322// Returns true iff test_case contains at least one test that should
323// run.
324static bool ShouldRunTestCase(const TestCase* test_case) {
325 return test_case->should_run();
326}
327
328// AssertHelper constructor.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000329AssertHelper::AssertHelper(TestPartResult::Type type,
330 const char* file,
331 int line,
332 const char* message)
333 : data_(new AssertHelperData(type, file, line, message)) {
334}
335
336AssertHelper::~AssertHelper() {
337 delete data_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000338}
339
340// Message assignment, for assertion streaming support.
341void AssertHelper::operator=(const Message& message) const {
342 UnitTest::GetInstance()->
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000343 AddTestPartResult(data_->type, data_->file, data_->line,
344 AppendUserMessage(data_->message, message),
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000345 UnitTest::GetInstance()->impl()
346 ->CurrentOsStackTraceExceptTop(1)
347 // Skips the stack frame for this function itself.
348 ); // NOLINT
349}
350
351// Mutex for linked pointers.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000352GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000353
354// Application pathname gotten in InitGoogleTest.
355String g_executable_path;
356
357// Returns the current application's name, removing directory path if that
358// is present.
359FilePath GetCurrentExecutableName() {
360 FilePath result;
361
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000362#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000363 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
364#else
365 result.Set(FilePath(g_executable_path));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000366#endif // GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000367
368 return result.RemoveDirectoryName();
369}
370
371// Functions for processing the gtest_output flag.
372
373// Returns the output format, or "" for normal printed output.
374String UnitTestOptions::GetOutputFormat() {
375 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
376 if (gtest_output_flag == NULL) return String("");
377
378 const char* const colon = strchr(gtest_output_flag, ':');
379 return (colon == NULL) ?
380 String(gtest_output_flag) :
381 String(gtest_output_flag, colon - gtest_output_flag);
382}
383
384// Returns the name of the requested output file, or the default if none
385// was explicitly specified.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000386String UnitTestOptions::GetAbsolutePathToOutputFile() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000387 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
388 if (gtest_output_flag == NULL)
389 return String("");
390
391 const char* const colon = strchr(gtest_output_flag, ':');
392 if (colon == NULL)
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000393 return String(internal::FilePath::ConcatPaths(
394 internal::FilePath(
395 UnitTest::GetInstance()->original_working_dir()),
396 internal::FilePath(kDefaultOutputFile)).ToString() );
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000397
398 internal::FilePath output_name(colon + 1);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000399 if (!output_name.IsAbsolutePath())
400 // TODO(wan@google.com): on Windows \some\path is not an absolute
401 // path (as its meaning depends on the current drive), yet the
402 // following logic for turning it into an absolute path is wrong.
403 // Fix it.
404 output_name = internal::FilePath::ConcatPaths(
405 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
406 internal::FilePath(colon + 1));
407
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000408 if (!output_name.IsDirectory())
409 return output_name.ToString();
410
411 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
412 output_name, internal::GetCurrentExecutableName(),
413 GetOutputFormat().c_str()));
414 return result.ToString();
415}
416
417// Returns true iff the wildcard pattern matches the string. The
418// first ':' or '\0' character in pattern marks the end of it.
419//
420// This recursive algorithm isn't very efficient, but is clear and
421// works well enough for matching test names, which are short.
422bool UnitTestOptions::PatternMatchesString(const char *pattern,
423 const char *str) {
424 switch (*pattern) {
425 case '\0':
426 case ':': // Either ':' or '\0' marks the end of the pattern.
427 return *str == '\0';
428 case '?': // Matches any single character.
429 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
430 case '*': // Matches any string (possibly empty) of characters.
431 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
432 PatternMatchesString(pattern + 1, str);
433 default: // Non-special character. Matches itself.
434 return *pattern == *str &&
435 PatternMatchesString(pattern + 1, str + 1);
436 }
437}
438
439bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
440 const char *cur_pattern = filter;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000441 for (;;) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000442 if (PatternMatchesString(cur_pattern, name.c_str())) {
443 return true;
444 }
445
446 // Finds the next pattern in the filter.
447 cur_pattern = strchr(cur_pattern, ':');
448
449 // Returns if no more pattern can be found.
450 if (cur_pattern == NULL) {
451 return false;
452 }
453
454 // Skips the pattern separater (the ':' character).
455 cur_pattern++;
456 }
457}
458
459// TODO(keithray): move String function implementations to gtest-string.cc.
460
461// Returns true iff the user-specified filter matches the test case
462// name and the test name.
463bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
464 const String &test_name) {
465 const String& full_name = String::Format("%s.%s",
466 test_case_name.c_str(),
467 test_name.c_str());
468
469 // Split --gtest_filter at '-', if there is one, to separate into
470 // positive filter and negative filter portions
471 const char* const p = GTEST_FLAG(filter).c_str();
472 const char* const dash = strchr(p, '-');
473 String positive;
474 String negative;
475 if (dash == NULL) {
476 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
477 negative = String("");
478 } else {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000479 positive = String(p, dash - p); // Everything up to the dash
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000480 negative = String(dash+1); // Everything after the dash
481 if (positive.empty()) {
482 // Treat '-test1' as the same as '*-test1'
483 positive = kUniversalFilter;
484 }
485 }
486
487 // A filter is a colon-separated list of patterns. It matches a
488 // test if any pattern in it matches the test.
489 return (MatchesFilter(full_name, positive.c_str()) &&
490 !MatchesFilter(full_name, negative.c_str()));
491}
492
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000493#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000494// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
495// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
496// This function is useful as an __except condition.
497int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
498 // Google Test should handle an exception if:
499 // 1. the user wants it to, AND
500 // 2. this is not a breakpoint exception.
501 return (GTEST_FLAG(catch_exceptions) &&
502 exception_code != EXCEPTION_BREAKPOINT) ?
503 EXCEPTION_EXECUTE_HANDLER :
504 EXCEPTION_CONTINUE_SEARCH;
505}
506#endif // GTEST_OS_WINDOWS
507
508} // namespace internal
509
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000510// The c'tor sets this object as the test part result reporter used by
511// Google Test. The 'result' parameter specifies where to report the
512// results. Intercepts only failures from the current thread.
513ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
514 TestPartResultArray* result)
515 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
516 result_(result) {
517 Init();
518}
519
520// The c'tor sets this object as the test part result reporter used by
521// Google Test. The 'result' parameter specifies where to report the
522// results.
523ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
524 InterceptMode intercept_mode, TestPartResultArray* result)
525 : intercept_mode_(intercept_mode),
526 result_(result) {
527 Init();
528}
529
530void ScopedFakeTestPartResultReporter::Init() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000531 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000532 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
533 old_reporter_ = impl->GetGlobalTestPartResultReporter();
534 impl->SetGlobalTestPartResultReporter(this);
535 } else {
536 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
537 impl->SetTestPartResultReporterForCurrentThread(this);
538 }
539}
540
541// The d'tor restores the test part result reporter used by Google Test
542// before.
543ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000544 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000545 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
546 impl->SetGlobalTestPartResultReporter(old_reporter_);
547 } else {
548 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
549 }
550}
551
552// Increments the test part result count and remembers the result.
553// This method is from the TestPartResultReporterInterface interface.
554void ScopedFakeTestPartResultReporter::ReportTestPartResult(
555 const TestPartResult& result) {
556 result_->Append(result);
557}
558
559namespace internal {
560
561// Returns the type ID of ::testing::Test. We should always call this
562// instead of GetTypeId< ::testing::Test>() to get the type ID of
563// testing::Test. This is to work around a suspected linker bug when
564// using Google Test as a framework on Mac OS X. The bug causes
565// GetTypeId< ::testing::Test>() to return different values depending
566// on whether the call is from the Google Test framework itself or
567// from user test code. GetTestTypeId() is guaranteed to always
568// return the same value, as it always calls GetTypeId<>() from the
569// gtest.cc, which is within the Google Test framework.
570TypeId GetTestTypeId() {
571 return GetTypeId<Test>();
572}
573
574// The value of GetTestTypeId() as seen from within the Google Test
575// library. This is solely for testing GetTestTypeId().
Bill Wendling0a0124e2009-12-16 19:36:42 +0000576const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000577
578// This predicate-formatter checks that 'results' contains a test part
579// failure of the given type and that the failure message contains the
580// given substring.
581AssertionResult HasOneFailure(const char* /* results_expr */,
582 const char* /* type_expr */,
583 const char* /* substr_expr */,
584 const TestPartResultArray& results,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000585 TestPartResult::Type type,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000586 const char* substr) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000587 const String expected(type == TestPartResult::kFatalFailure ?
588 "1 fatal failure" :
589 "1 non-fatal failure");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000590 Message msg;
591 if (results.size() != 1) {
592 msg << "Expected: " << expected << "\n"
593 << " Actual: " << results.size() << " failures";
594 for (int i = 0; i < results.size(); i++) {
595 msg << "\n" << results.GetTestPartResult(i);
596 }
597 return AssertionFailure(msg);
598 }
599
600 const TestPartResult& r = results.GetTestPartResult(0);
601 if (r.type() != type) {
602 msg << "Expected: " << expected << "\n"
603 << " Actual:\n"
604 << r;
605 return AssertionFailure(msg);
606 }
607
608 if (strstr(r.message(), substr) == NULL) {
609 msg << "Expected: " << expected << " containing \""
610 << substr << "\"\n"
611 << " Actual:\n"
612 << r;
613 return AssertionFailure(msg);
614 }
615
616 return AssertionSuccess();
617}
618
619// The constructor of SingleFailureChecker remembers where to look up
620// test part results, what type of failure we expect, and what
621// substring the failure message should contain.
622SingleFailureChecker:: SingleFailureChecker(
623 const TestPartResultArray* results,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000624 TestPartResult::Type type,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000625 const char* substr)
626 : results_(results),
627 type_(type),
628 substr_(substr) {}
629
630// The destructor of SingleFailureChecker verifies that the given
631// TestPartResultArray contains exactly one failure that has the given
632// type and contains the given substring. If that's not the case, a
633// non-fatal failure will be generated.
634SingleFailureChecker::~SingleFailureChecker() {
635 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
636}
637
638DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
639 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
640
641void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
642 const TestPartResult& result) {
643 unit_test_->current_test_result()->AddTestPartResult(result);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000644 unit_test_->listeners()->repeater()->OnTestPartResult(result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000645}
646
647DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
648 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
649
650void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
651 const TestPartResult& result) {
652 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
653}
654
655// Returns the global test part result reporter.
656TestPartResultReporterInterface*
657UnitTestImpl::GetGlobalTestPartResultReporter() {
658 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
659 return global_test_part_result_repoter_;
660}
661
662// Sets the global test part result reporter.
663void UnitTestImpl::SetGlobalTestPartResultReporter(
664 TestPartResultReporterInterface* reporter) {
665 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
666 global_test_part_result_repoter_ = reporter;
667}
668
669// Returns the test part result reporter for the current thread.
670TestPartResultReporterInterface*
671UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
672 return per_thread_test_part_result_reporter_.get();
673}
674
675// Sets the test part result reporter for the current thread.
676void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
677 TestPartResultReporterInterface* reporter) {
678 per_thread_test_part_result_reporter_.set(reporter);
679}
680
681// Gets the number of successful test cases.
682int UnitTestImpl::successful_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000683 return CountIf(test_cases_, TestCasePassed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000684}
685
686// Gets the number of failed test cases.
687int UnitTestImpl::failed_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000688 return CountIf(test_cases_, TestCaseFailed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000689}
690
691// Gets the number of all test cases.
692int UnitTestImpl::total_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000693 return static_cast<int>(test_cases_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000694}
695
696// Gets the number of all test cases that contain at least one test
697// that should run.
698int UnitTestImpl::test_case_to_run_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000699 return CountIf(test_cases_, ShouldRunTestCase);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000700}
701
702// Gets the number of successful tests.
703int UnitTestImpl::successful_test_count() const {
704 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
705}
706
707// Gets the number of failed tests.
708int UnitTestImpl::failed_test_count() const {
709 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
710}
711
712// Gets the number of disabled tests.
713int UnitTestImpl::disabled_test_count() const {
714 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
715}
716
717// Gets the number of all tests.
718int UnitTestImpl::total_test_count() const {
719 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
720}
721
722// Gets the number of tests that should run.
723int UnitTestImpl::test_to_run_count() const {
724 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
725}
726
727// Returns the current OS stack trace as a String.
728//
729// The maximum number of stack frames to be included is specified by
730// the gtest_stack_trace_depth flag. The skip_count parameter
731// specifies the number of top frames to be skipped, which doesn't
732// count against the number of frames to be included.
733//
734// For example, if Foo() calls Bar(), which in turn calls
735// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
736// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
737String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
738 (void)skip_count;
739 return String("");
740}
741
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000742// Returns the current time in milliseconds.
743TimeInMillis GetTimeInMillis() {
744#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
745 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000746 // http://analogous.blogspot.com/2005/04/epoch.html
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000747 const TimeInMillis kJavaEpochToWinFileTimeDelta =
748 static_cast<TimeInMillis>(116444736UL) * 100000UL;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000749 const DWORD kTenthMicrosInMilliSecond = 10000;
750
751 SYSTEMTIME now_systime;
752 FILETIME now_filetime;
753 ULARGE_INTEGER now_int64;
754 // TODO(kenton@google.com): Shouldn't this just use
755 // GetSystemTimeAsFileTime()?
756 GetSystemTime(&now_systime);
757 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
758 now_int64.LowPart = now_filetime.dwLowDateTime;
759 now_int64.HighPart = now_filetime.dwHighDateTime;
760 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
761 kJavaEpochToWinFileTimeDelta;
762 return now_int64.QuadPart;
763 }
764 return 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000765#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000766 __timeb64 now;
767#ifdef _MSC_VER
768 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
769 // (deprecated function) there.
770 // TODO(kenton@google.com): Use GetTickCount()? Or use
771 // SystemTimeToFileTime()
772#pragma warning(push) // Saves the current warning state.
773#pragma warning(disable:4996) // Temporarily disables warning 4996.
774 _ftime64(&now);
775#pragma warning(pop) // Restores the warning state.
776#else
777 _ftime64(&now);
778#endif // _MSC_VER
779 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000780#elif GTEST_HAS_GETTIMEOFDAY_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000781 struct timeval now;
782 gettimeofday(&now, NULL);
783 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
784#else
785#error "Don't know how to get the current time on your system."
786#endif
787}
788
789// Utilities
790
791// class String
792
793// Returns the input enclosed in double quotes if it's not NULL;
794// otherwise returns "(null)". For example, "\"Hello\"" is returned
795// for input "Hello".
796//
797// This is useful for printing a C string in the syntax of a literal.
798//
799// Known issue: escape sequences are not handled yet.
800String String::ShowCStringQuoted(const char* c_str) {
801 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
802}
803
804// Copies at most length characters from str into a newly-allocated
805// piece of memory of size length+1. The memory is allocated with new[].
806// A terminating null byte is written to the memory, and a pointer to it
807// is returned. If str is NULL, NULL is returned.
808static char* CloneString(const char* str, size_t length) {
809 if (str == NULL) {
810 return NULL;
811 } else {
812 char* const clone = new char[length + 1];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000813 posix::StrNCpy(clone, str, length);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000814 clone[length] = '\0';
815 return clone;
816 }
817}
818
819// Clones a 0-terminated C string, allocating memory using new. The
820// caller is responsible for deleting[] the return value. Returns the
821// cloned string, or NULL if the input is NULL.
822const char * String::CloneCString(const char* c_str) {
823 return (c_str == NULL) ?
824 NULL : CloneString(c_str, strlen(c_str));
825}
826
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000827#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000828// Creates a UTF-16 wide string from the given ANSI string, allocating
829// memory using new. The caller is responsible for deleting the return
830// value using delete[]. Returns the wide string, or NULL if the
831// input is NULL.
832LPCWSTR String::AnsiToUtf16(const char* ansi) {
833 if (!ansi) return NULL;
834 const int length = strlen(ansi);
835 const int unicode_length =
836 MultiByteToWideChar(CP_ACP, 0, ansi, length,
837 NULL, 0);
838 WCHAR* unicode = new WCHAR[unicode_length + 1];
839 MultiByteToWideChar(CP_ACP, 0, ansi, length,
840 unicode, unicode_length);
841 unicode[unicode_length] = 0;
842 return unicode;
843}
844
845// Creates an ANSI string from the given wide string, allocating
846// memory using new. The caller is responsible for deleting the return
847// value using delete[]. Returns the ANSI string, or NULL if the
848// input is NULL.
849const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
850 if (!utf16_str) return NULL;
851 const int ansi_length =
852 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
853 NULL, 0, NULL, NULL);
854 char* ansi = new char[ansi_length + 1];
855 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
856 ansi, ansi_length, NULL, NULL);
857 ansi[ansi_length] = 0;
858 return ansi;
859}
860
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000861#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000862
863// Compares two C strings. Returns true iff they have the same content.
864//
865// Unlike strcmp(), this function can handle NULL argument(s). A NULL
866// C string is considered different to any non-NULL C string,
867// including the empty string.
868bool String::CStringEquals(const char * lhs, const char * rhs) {
869 if ( lhs == NULL ) return rhs == NULL;
870
871 if ( rhs == NULL ) return false;
872
873 return strcmp(lhs, rhs) == 0;
874}
875
876#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
877
878// Converts an array of wide chars to a narrow string using the UTF-8
879// encoding, and streams the result to the given Message object.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000880static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000881 Message* msg) {
882 // TODO(wan): consider allowing a testing::String object to
883 // contain '\0'. This will make it behave more like std::string,
884 // and will allow ToUtf8String() to return the correct encoding
885 // for '\0' s.t. we can get rid of the conditional here (and in
886 // several other places).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000887 for (size_t i = 0; i != length; ) { // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000888 if (wstr[i] != L'\0') {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000889 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
890 while (i != length && wstr[i] != L'\0')
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000891 i++;
892 } else {
893 *msg << '\0';
894 i++;
895 }
896 }
897}
898
899#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
900
901} // namespace internal
902
903#if GTEST_HAS_STD_WSTRING
904// Converts the given wide string to a narrow string using the UTF-8
905// encoding, and streams the result to this Message object.
906Message& Message::operator <<(const ::std::wstring& wstr) {
907 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
908 return *this;
909}
910#endif // GTEST_HAS_STD_WSTRING
911
912#if GTEST_HAS_GLOBAL_WSTRING
913// Converts the given wide string to a narrow string using the UTF-8
914// encoding, and streams the result to this Message object.
915Message& Message::operator <<(const ::wstring& wstr) {
916 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
917 return *this;
918}
919#endif // GTEST_HAS_GLOBAL_WSTRING
920
921namespace internal {
922
923// Formats a value to be used in a failure message.
924
925// For a char value, we print it as a C++ char literal and as an
926// unsigned integer (both in decimal and in hexadecimal).
927String FormatForFailureMessage(char ch) {
928 const unsigned int ch_as_uint = ch;
929 // A String object cannot contain '\0', so we print "\\0" when ch is
930 // '\0'.
931 return String::Format("'%s' (%u, 0x%X)",
932 ch ? String::Format("%c", ch).c_str() : "\\0",
933 ch_as_uint, ch_as_uint);
934}
935
936// For a wchar_t value, we print it as a C++ wchar_t literal and as an
937// unsigned integer (both in decimal and in hexidecimal).
938String FormatForFailureMessage(wchar_t wchar) {
939 // The C++ standard doesn't specify the exact size of the wchar_t
940 // type. It just says that it shall have the same size as another
941 // integral type, called its underlying type.
942 //
943 // Therefore, in order to print a wchar_t value in the numeric form,
944 // we first convert it to the largest integral type (UInt64) and
945 // then print the converted value.
946 //
947 // We use streaming to print the value as "%llu" doesn't work
948 // correctly with MSVC 7.1.
949 const UInt64 wchar_as_uint64 = wchar;
950 Message msg;
951 // A String object cannot contain '\0', so we print "\\0" when wchar is
952 // L'\0'.
953 char buffer[32]; // CodePointToUtf8 requires a buffer that big.
954 msg << "L'"
955 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
956 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
957 << wchar_as_uint64 << ")";
958 return msg.GetString();
959}
960
961} // namespace internal
962
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000963// AssertionResult constructors.
964// Used in EXPECT_TRUE/FALSE(assertion_result).
965AssertionResult::AssertionResult(const AssertionResult& other)
966 : success_(other.success_),
967 message_(other.message_.get() != NULL ?
968 new internal::String(*other.message_) :
969 static_cast<internal::String*>(NULL)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000970}
971
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000972// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
973AssertionResult AssertionResult::operator!() const {
974 AssertionResult negation(!success_);
975 if (message_.get() != NULL)
976 negation << *message_;
977 return negation;
978}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000979
980// Makes a successful assertion result.
981AssertionResult AssertionSuccess() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000982 return AssertionResult(true);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000983}
984
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000985// Makes a failed assertion result.
986AssertionResult AssertionFailure() {
987 return AssertionResult(false);
988}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000989
990// Makes a failed assertion result with the given failure message.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000991// Deprecated; use AssertionFailure() << message.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000992AssertionResult AssertionFailure(const Message& message) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000993 return AssertionFailure() << message;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000994}
995
996namespace internal {
997
998// Constructs and returns the message for an equality assertion
999// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1000//
1001// The first four parameters are the expressions used in the assertion
1002// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1003// where foo is 5 and bar is 6, we have:
1004//
1005// expected_expression: "foo"
1006// actual_expression: "bar"
1007// expected_value: "5"
1008// actual_value: "6"
1009//
1010// The ignoring_case parameter is true iff the assertion is a
1011// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
1012// be inserted into the message.
1013AssertionResult EqFailure(const char* expected_expression,
1014 const char* actual_expression,
1015 const String& expected_value,
1016 const String& actual_value,
1017 bool ignoring_case) {
1018 Message msg;
1019 msg << "Value of: " << actual_expression;
1020 if (actual_value != actual_expression) {
1021 msg << "\n Actual: " << actual_value;
1022 }
1023
1024 msg << "\nExpected: " << expected_expression;
1025 if (ignoring_case) {
1026 msg << " (ignoring case)";
1027 }
1028 if (expected_value != expected_expression) {
1029 msg << "\nWhich is: " << expected_value;
1030 }
1031
1032 return AssertionFailure(msg);
1033}
1034
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001035// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1036String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1037 const char* expression_text,
1038 const char* actual_predicate_value,
1039 const char* expected_predicate_value) {
1040 const char* actual_message = assertion_result.message();
1041 Message msg;
1042 msg << "Value of: " << expression_text
1043 << "\n Actual: " << actual_predicate_value;
1044 if (actual_message[0] != '\0')
1045 msg << " (" << actual_message << ")";
1046 msg << "\nExpected: " << expected_predicate_value;
1047 return msg.GetString();
1048}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001049
1050// Helper function for implementing ASSERT_NEAR.
1051AssertionResult DoubleNearPredFormat(const char* expr1,
1052 const char* expr2,
1053 const char* abs_error_expr,
1054 double val1,
1055 double val2,
1056 double abs_error) {
1057 const double diff = fabs(val1 - val2);
1058 if (diff <= abs_error) return AssertionSuccess();
1059
1060 // TODO(wan): do not print the value of an expression if it's
1061 // already a literal.
1062 Message msg;
1063 msg << "The difference between " << expr1 << " and " << expr2
1064 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1065 << expr1 << " evaluates to " << val1 << ",\n"
1066 << expr2 << " evaluates to " << val2 << ", and\n"
1067 << abs_error_expr << " evaluates to " << abs_error << ".";
1068 return AssertionFailure(msg);
1069}
1070
1071
1072// Helper template for implementing FloatLE() and DoubleLE().
1073template <typename RawType>
1074AssertionResult FloatingPointLE(const char* expr1,
1075 const char* expr2,
1076 RawType val1,
1077 RawType val2) {
1078 // Returns success if val1 is less than val2,
1079 if (val1 < val2) {
1080 return AssertionSuccess();
1081 }
1082
1083 // or if val1 is almost equal to val2.
1084 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1085 if (lhs.AlmostEquals(rhs)) {
1086 return AssertionSuccess();
1087 }
1088
1089 // Note that the above two checks will both fail if either val1 or
1090 // val2 is NaN, as the IEEE floating-point standard requires that
1091 // any predicate involving a NaN must return false.
1092
1093 StrStream val1_ss;
1094 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1095 << val1;
1096
1097 StrStream val2_ss;
1098 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1099 << val2;
1100
1101 Message msg;
1102 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1103 << " Actual: " << StrStreamToString(&val1_ss) << " vs "
1104 << StrStreamToString(&val2_ss);
1105
1106 return AssertionFailure(msg);
1107}
1108
1109} // namespace internal
1110
1111// Asserts that val1 is less than, or almost equal to, val2. Fails
1112// otherwise. In particular, it fails if either val1 or val2 is NaN.
1113AssertionResult FloatLE(const char* expr1, const char* expr2,
1114 float val1, float val2) {
1115 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1116}
1117
1118// Asserts that val1 is less than, or almost equal to, val2. Fails
1119// otherwise. In particular, it fails if either val1 or val2 is NaN.
1120AssertionResult DoubleLE(const char* expr1, const char* expr2,
1121 double val1, double val2) {
1122 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1123}
1124
1125namespace internal {
1126
1127// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1128// arguments.
1129AssertionResult CmpHelperEQ(const char* expected_expression,
1130 const char* actual_expression,
1131 BiggestInt expected,
1132 BiggestInt actual) {
1133 if (expected == actual) {
1134 return AssertionSuccess();
1135 }
1136
1137 return EqFailure(expected_expression,
1138 actual_expression,
1139 FormatForComparisonFailureMessage(expected, actual),
1140 FormatForComparisonFailureMessage(actual, expected),
1141 false);
1142}
1143
1144// A macro for implementing the helper functions needed to implement
1145// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1146// just to avoid copy-and-paste of similar code.
1147#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1148AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1149 BiggestInt val1, BiggestInt val2) {\
1150 if (val1 op val2) {\
1151 return AssertionSuccess();\
1152 } else {\
1153 Message msg;\
1154 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1155 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1156 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1157 return AssertionFailure(msg);\
1158 }\
1159}
1160
1161// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1162// enum arguments.
1163GTEST_IMPL_CMP_HELPER_(NE, !=)
1164// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1165// enum arguments.
1166GTEST_IMPL_CMP_HELPER_(LE, <=)
1167// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1168// enum arguments.
1169GTEST_IMPL_CMP_HELPER_(LT, < )
1170// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1171// enum arguments.
1172GTEST_IMPL_CMP_HELPER_(GE, >=)
1173// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1174// enum arguments.
1175GTEST_IMPL_CMP_HELPER_(GT, > )
1176
1177#undef GTEST_IMPL_CMP_HELPER_
1178
1179// The helper function for {ASSERT|EXPECT}_STREQ.
1180AssertionResult CmpHelperSTREQ(const char* expected_expression,
1181 const char* actual_expression,
1182 const char* expected,
1183 const char* actual) {
1184 if (String::CStringEquals(expected, actual)) {
1185 return AssertionSuccess();
1186 }
1187
1188 return EqFailure(expected_expression,
1189 actual_expression,
1190 String::ShowCStringQuoted(expected),
1191 String::ShowCStringQuoted(actual),
1192 false);
1193}
1194
1195// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1196AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1197 const char* actual_expression,
1198 const char* expected,
1199 const char* actual) {
1200 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1201 return AssertionSuccess();
1202 }
1203
1204 return EqFailure(expected_expression,
1205 actual_expression,
1206 String::ShowCStringQuoted(expected),
1207 String::ShowCStringQuoted(actual),
1208 true);
1209}
1210
1211// The helper function for {ASSERT|EXPECT}_STRNE.
1212AssertionResult CmpHelperSTRNE(const char* s1_expression,
1213 const char* s2_expression,
1214 const char* s1,
1215 const char* s2) {
1216 if (!String::CStringEquals(s1, s2)) {
1217 return AssertionSuccess();
1218 } else {
1219 Message msg;
1220 msg << "Expected: (" << s1_expression << ") != ("
1221 << s2_expression << "), actual: \""
1222 << s1 << "\" vs \"" << s2 << "\"";
1223 return AssertionFailure(msg);
1224 }
1225}
1226
1227// The helper function for {ASSERT|EXPECT}_STRCASENE.
1228AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1229 const char* s2_expression,
1230 const char* s1,
1231 const char* s2) {
1232 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1233 return AssertionSuccess();
1234 } else {
1235 Message msg;
1236 msg << "Expected: (" << s1_expression << ") != ("
1237 << s2_expression << ") (ignoring case), actual: \""
1238 << s1 << "\" vs \"" << s2 << "\"";
1239 return AssertionFailure(msg);
1240 }
1241}
1242
1243} // namespace internal
1244
1245namespace {
1246
1247// Helper functions for implementing IsSubString() and IsNotSubstring().
1248
1249// This group of overloaded functions return true iff needle is a
1250// substring of haystack. NULL is considered a substring of itself
1251// only.
1252
1253bool IsSubstringPred(const char* needle, const char* haystack) {
1254 if (needle == NULL || haystack == NULL)
1255 return needle == haystack;
1256
1257 return strstr(haystack, needle) != NULL;
1258}
1259
1260bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1261 if (needle == NULL || haystack == NULL)
1262 return needle == haystack;
1263
1264 return wcsstr(haystack, needle) != NULL;
1265}
1266
1267// StringType here can be either ::std::string or ::std::wstring.
1268template <typename StringType>
1269bool IsSubstringPred(const StringType& needle,
1270 const StringType& haystack) {
1271 return haystack.find(needle) != StringType::npos;
1272}
1273
1274// This function implements either IsSubstring() or IsNotSubstring(),
1275// depending on the value of the expected_to_be_substring parameter.
1276// StringType here can be const char*, const wchar_t*, ::std::string,
1277// or ::std::wstring.
1278template <typename StringType>
1279AssertionResult IsSubstringImpl(
1280 bool expected_to_be_substring,
1281 const char* needle_expr, const char* haystack_expr,
1282 const StringType& needle, const StringType& haystack) {
1283 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1284 return AssertionSuccess();
1285
1286 const bool is_wide_string = sizeof(needle[0]) > 1;
1287 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1288 return AssertionFailure(
1289 Message()
1290 << "Value of: " << needle_expr << "\n"
1291 << " Actual: " << begin_string_quote << needle << "\"\n"
1292 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1293 << "a substring of " << haystack_expr << "\n"
1294 << "Which is: " << begin_string_quote << haystack << "\"");
1295}
1296
1297} // namespace
1298
1299// IsSubstring() and IsNotSubstring() check whether needle is a
1300// substring of haystack (NULL is considered a substring of itself
1301// only), and return an appropriate error message when they fail.
1302
1303AssertionResult IsSubstring(
1304 const char* needle_expr, const char* haystack_expr,
1305 const char* needle, const char* haystack) {
1306 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1307}
1308
1309AssertionResult IsSubstring(
1310 const char* needle_expr, const char* haystack_expr,
1311 const wchar_t* needle, const wchar_t* haystack) {
1312 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1313}
1314
1315AssertionResult IsNotSubstring(
1316 const char* needle_expr, const char* haystack_expr,
1317 const char* needle, const char* haystack) {
1318 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1319}
1320
1321AssertionResult IsNotSubstring(
1322 const char* needle_expr, const char* haystack_expr,
1323 const wchar_t* needle, const wchar_t* haystack) {
1324 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1325}
1326
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001327AssertionResult IsSubstring(
1328 const char* needle_expr, const char* haystack_expr,
1329 const ::std::string& needle, const ::std::string& haystack) {
1330 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1331}
1332
1333AssertionResult IsNotSubstring(
1334 const char* needle_expr, const char* haystack_expr,
1335 const ::std::string& needle, const ::std::string& haystack) {
1336 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1337}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001338
1339#if GTEST_HAS_STD_WSTRING
1340AssertionResult IsSubstring(
1341 const char* needle_expr, const char* haystack_expr,
1342 const ::std::wstring& needle, const ::std::wstring& haystack) {
1343 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1344}
1345
1346AssertionResult IsNotSubstring(
1347 const char* needle_expr, const char* haystack_expr,
1348 const ::std::wstring& needle, const ::std::wstring& haystack) {
1349 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1350}
1351#endif // GTEST_HAS_STD_WSTRING
1352
1353namespace internal {
1354
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001355#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001356
1357namespace {
1358
1359// Helper function for IsHRESULT{SuccessFailure} predicates
1360AssertionResult HRESULTFailureHelper(const char* expr,
1361 const char* expected,
1362 long hr) { // NOLINT
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001363#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001364 // Windows CE doesn't support FormatMessage.
1365 const char error_text[] = "";
1366#else
1367 // Looks up the human-readable system message for the HRESULT code
1368 // and since we're not passing any params to FormatMessage, we don't
1369 // want inserts expanded.
1370 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1371 FORMAT_MESSAGE_IGNORE_INSERTS;
1372 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1373 // Gets the system's human readable message string for this HRESULT.
1374 char error_text[kBufSize] = { '\0' };
1375 DWORD message_length = ::FormatMessageA(kFlags,
1376 0, // no source, we're asking system
1377 hr, // the error
1378 0, // no line width restrictions
1379 error_text, // output buffer
1380 kBufSize, // buf size
1381 NULL); // no arguments for inserts
1382 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1383 for (; message_length && isspace(error_text[message_length - 1]);
1384 --message_length) {
1385 error_text[message_length - 1] = '\0';
1386 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001387#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001388
1389 const String error_hex(String::Format("0x%08X ", hr));
1390 Message msg;
1391 msg << "Expected: " << expr << " " << expected << ".\n"
1392 << " Actual: " << error_hex << error_text << "\n";
1393
1394 return ::testing::AssertionFailure(msg);
1395}
1396
1397} // namespace
1398
1399AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1400 if (SUCCEEDED(hr)) {
1401 return AssertionSuccess();
1402 }
1403 return HRESULTFailureHelper(expr, "succeeds", hr);
1404}
1405
1406AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1407 if (FAILED(hr)) {
1408 return AssertionSuccess();
1409 }
1410 return HRESULTFailureHelper(expr, "fails", hr);
1411}
1412
1413#endif // GTEST_OS_WINDOWS
1414
1415// Utility functions for encoding Unicode text (wide strings) in
1416// UTF-8.
1417
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001418// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001419// like this:
1420//
1421// Code-point length Encoding
1422// 0 - 7 bits 0xxxxxxx
1423// 8 - 11 bits 110xxxxx 10xxxxxx
1424// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1425// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1426
1427// The maximum code-point a one-byte UTF-8 sequence can represent.
1428const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1429
1430// The maximum code-point a two-byte UTF-8 sequence can represent.
1431const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1432
1433// The maximum code-point a three-byte UTF-8 sequence can represent.
1434const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1435
1436// The maximum code-point a four-byte UTF-8 sequence can represent.
1437const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1438
1439// Chops off the n lowest bits from a bit pattern. Returns the n
1440// lowest bits. As a side effect, the original bit pattern will be
1441// shifted to the right by n bits.
1442inline UInt32 ChopLowBits(UInt32* bits, int n) {
1443 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1444 *bits >>= n;
1445 return low_bits;
1446}
1447
1448// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1449// code_point parameter is of type UInt32 because wchar_t may not be
1450// wide enough to contain a code point.
1451// The output buffer str must containt at least 32 characters.
1452// The function returns the address of the output buffer.
1453// If the code_point is not a valid Unicode code point
1454// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1455// as '(Invalid Unicode 0xXXXXXXXX)'.
1456char* CodePointToUtf8(UInt32 code_point, char* str) {
1457 if (code_point <= kMaxCodePoint1) {
1458 str[1] = '\0';
1459 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1460 } else if (code_point <= kMaxCodePoint2) {
1461 str[2] = '\0';
1462 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1463 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1464 } else if (code_point <= kMaxCodePoint3) {
1465 str[3] = '\0';
1466 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1467 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1468 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1469 } else if (code_point <= kMaxCodePoint4) {
1470 str[4] = '\0';
1471 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1472 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1473 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1474 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1475 } else {
1476 // The longest string String::Format can produce when invoked
1477 // with these parameters is 28 character long (not including
1478 // the terminating nul character). We are asking for 32 character
1479 // buffer just in case. This is also enough for strncpy to
1480 // null-terminate the destination string.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001481 posix::StrNCpy(
1482 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001483 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1484 // the result unterminated.
1485 }
1486 return str;
1487}
1488
1489// The following two functions only make sense if the the system
1490// uses UTF-16 for wide string encoding. All supported systems
1491// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1492
1493// Determines if the arguments constitute UTF-16 surrogate pair
1494// and thus should be combined into a single Unicode code point
1495// using CreateCodePointFromUtf16SurrogatePair.
1496inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001497 return sizeof(wchar_t) == 2 &&
1498 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001499}
1500
1501// Creates a Unicode code point from UTF16 surrogate pair.
1502inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1503 wchar_t second) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001504 const UInt32 mask = (1 << 10) - 1;
1505 return (sizeof(wchar_t) == 2) ?
1506 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1507 // This function should not be called when the condition is
1508 // false, but we provide a sensible default in case it is.
1509 static_cast<UInt32>(first);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001510}
1511
1512// Converts a wide string to a narrow string in UTF-8 encoding.
1513// The wide string is assumed to have the following encoding:
1514// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1515// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1516// Parameter str points to a null-terminated wide string.
1517// Parameter num_chars may additionally limit the number
1518// of wchar_t characters processed. -1 is used when the entire string
1519// should be processed.
1520// If the string contains code points that are not valid Unicode code points
1521// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1522// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1523// and contains invalid UTF-16 surrogate pairs, values in those pairs
1524// will be encoded as individual Unicode characters from Basic Normal Plane.
1525String WideStringToUtf8(const wchar_t* str, int num_chars) {
1526 if (num_chars == -1)
1527 num_chars = static_cast<int>(wcslen(str));
1528
1529 StrStream stream;
1530 for (int i = 0; i < num_chars; ++i) {
1531 UInt32 unicode_code_point;
1532
1533 if (str[i] == L'\0') {
1534 break;
1535 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1536 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1537 str[i + 1]);
1538 i++;
1539 } else {
1540 unicode_code_point = static_cast<UInt32>(str[i]);
1541 }
1542
1543 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1544 stream << CodePointToUtf8(unicode_code_point, buffer);
1545 }
1546 return StrStreamToString(&stream);
1547}
1548
1549// Converts a wide C string to a String using the UTF-8 encoding.
1550// NULL will be converted to "(null)".
1551String String::ShowWideCString(const wchar_t * wide_c_str) {
1552 if (wide_c_str == NULL) return String("(null)");
1553
1554 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1555}
1556
1557// Similar to ShowWideCString(), except that this function encloses
1558// the converted string in double quotes.
1559String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1560 if (wide_c_str == NULL) return String("(null)");
1561
1562 return String::Format("L\"%s\"",
1563 String::ShowWideCString(wide_c_str).c_str());
1564}
1565
1566// Compares two wide C strings. Returns true iff they have the same
1567// content.
1568//
1569// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1570// C string is considered different to any non-NULL C string,
1571// including the empty string.
1572bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1573 if (lhs == NULL) return rhs == NULL;
1574
1575 if (rhs == NULL) return false;
1576
1577 return wcscmp(lhs, rhs) == 0;
1578}
1579
1580// Helper function for *_STREQ on wide strings.
1581AssertionResult CmpHelperSTREQ(const char* expected_expression,
1582 const char* actual_expression,
1583 const wchar_t* expected,
1584 const wchar_t* actual) {
1585 if (String::WideCStringEquals(expected, actual)) {
1586 return AssertionSuccess();
1587 }
1588
1589 return EqFailure(expected_expression,
1590 actual_expression,
1591 String::ShowWideCStringQuoted(expected),
1592 String::ShowWideCStringQuoted(actual),
1593 false);
1594}
1595
1596// Helper function for *_STRNE on wide strings.
1597AssertionResult CmpHelperSTRNE(const char* s1_expression,
1598 const char* s2_expression,
1599 const wchar_t* s1,
1600 const wchar_t* s2) {
1601 if (!String::WideCStringEquals(s1, s2)) {
1602 return AssertionSuccess();
1603 }
1604
1605 Message msg;
1606 msg << "Expected: (" << s1_expression << ") != ("
1607 << s2_expression << "), actual: "
1608 << String::ShowWideCStringQuoted(s1)
1609 << " vs " << String::ShowWideCStringQuoted(s2);
1610 return AssertionFailure(msg);
1611}
1612
1613// Compares two C strings, ignoring case. Returns true iff they have
1614// the same content.
1615//
1616// Unlike strcasecmp(), this function can handle NULL argument(s). A
1617// NULL C string is considered different to any non-NULL C string,
1618// including the empty string.
1619bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001620 if (lhs == NULL)
1621 return rhs == NULL;
1622 if (rhs == NULL)
1623 return false;
1624 return posix::StrCaseCmp(lhs, rhs) == 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001625}
1626
1627 // Compares two wide C strings, ignoring case. Returns true iff they
1628 // have the same content.
1629 //
1630 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1631 // A NULL C string is considered different to any non-NULL wide C string,
1632 // including the empty string.
1633 // NB: The implementations on different platforms slightly differ.
1634 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1635 // environment variable. On GNU platform this method uses wcscasecmp
1636 // which compares according to LC_CTYPE category of the current locale.
1637 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1638 // current locale.
1639bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1640 const wchar_t* rhs) {
1641 if ( lhs == NULL ) return rhs == NULL;
1642
1643 if ( rhs == NULL ) return false;
1644
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001645#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001646 return _wcsicmp(lhs, rhs) == 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001647#elif GTEST_OS_LINUX
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001648 return wcscasecmp(lhs, rhs) == 0;
1649#else
1650 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1651 // may not define it either.
1652 wint_t left, right;
1653 do {
1654 left = towlower(*lhs++);
1655 right = towlower(*rhs++);
1656 } while (left && left == right);
1657 return left == right;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001658#endif // OS selector
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001659}
1660
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001661// Compares this with another String.
1662// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1663// if this is greater than rhs.
1664int String::Compare(const String & rhs) const {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001665 const char* const lhs_c_str = c_str();
1666 const char* const rhs_c_str = rhs.c_str();
1667
1668 if (lhs_c_str == NULL) {
1669 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1670 } else if (rhs_c_str == NULL) {
1671 return 1;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001672 }
1673
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001674 const size_t shorter_str_len =
1675 length() <= rhs.length() ? length() : rhs.length();
1676 for (size_t i = 0; i != shorter_str_len; i++) {
1677 if (lhs_c_str[i] < rhs_c_str[i]) {
1678 return -1;
1679 } else if (lhs_c_str[i] > rhs_c_str[i]) {
1680 return 1;
1681 }
1682 }
1683 return (length() < rhs.length()) ? -1 :
1684 (length() > rhs.length()) ? 1 : 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001685}
1686
1687// Returns true iff this String ends with the given suffix. *Any*
1688// String is considered to end with a NULL or empty suffix.
1689bool String::EndsWith(const char* suffix) const {
1690 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1691
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001692 if (c_str() == NULL) return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001693
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001694 const size_t this_len = strlen(c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001695 const size_t suffix_len = strlen(suffix);
1696 return (this_len >= suffix_len) &&
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001697 CStringEquals(c_str() + this_len - suffix_len, suffix);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001698}
1699
1700// Returns true iff this String ends with the given suffix, ignoring case.
1701// Any String is considered to end with a NULL or empty suffix.
1702bool String::EndsWithCaseInsensitive(const char* suffix) const {
1703 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1704
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001705 if (c_str() == NULL) return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001706
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001707 const size_t this_len = strlen(c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001708 const size_t suffix_len = strlen(suffix);
1709 return (this_len >= suffix_len) &&
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001710 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001711}
1712
1713// Formats a list of arguments to a String, using the same format
1714// spec string as for printf.
1715//
1716// We do not use the StringPrintf class as it is not universally
1717// available.
1718//
1719// The result is limited to 4096 characters (including the tailing 0).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001720// If 4096 characters are not enough to format the input, or if
1721// there's an error, "<formatting error or buffer exceeded>" is
1722// returned.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001723String String::Format(const char * format, ...) {
1724 va_list args;
1725 va_start(args, format);
1726
1727 char buffer[4096];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001728 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1729
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001730 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1731 // 4996 (deprecated function) there.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001732#ifdef _MSC_VER // We are using MSVC.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001733#pragma warning(push) // Saves the current warning state.
1734#pragma warning(disable:4996) // Temporarily disables warning 4996.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001735 const int size = vsnprintf(buffer, kBufferSize, format, args);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001736#pragma warning(pop) // Restores the warning state.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001737#else // We are not using MSVC.
1738 const int size = vsnprintf(buffer, kBufferSize, format, args);
1739#endif // _MSC_VER
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001740 va_end(args);
1741
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001742 // vsnprintf()'s behavior is not portable. When the buffer is not
1743 // big enough, it returns a negative value in MSVC, and returns the
1744 // needed buffer size on Linux. When there is an output error, it
1745 // always returns a negative value. For simplicity, we lump the two
1746 // error cases together.
1747 if (size < 0 || size >= kBufferSize) {
1748 return String("<formatting error or buffer exceeded>");
1749 } else {
1750 return String(buffer, size);
1751 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001752}
1753
1754// Converts the buffer in a StrStream to a String, converting NUL
1755// bytes to "\\0" along the way.
1756String StrStreamToString(StrStream* ss) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001757 const ::std::string& str = ss->str();
1758 const char* const start = str.c_str();
1759 const char* const end = start + str.length();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001760
1761 // We need to use a helper StrStream to do this transformation
1762 // because String doesn't support push_back().
1763 StrStream helper;
1764 for (const char* ch = start; ch != end; ++ch) {
1765 if (*ch == '\0') {
1766 helper << "\\0"; // Replaces NUL with "\\0";
1767 } else {
1768 helper.put(*ch);
1769 }
1770 }
1771
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001772 return String(helper.str().c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001773}
1774
1775// Appends the user-supplied message to the Google-Test-generated message.
1776String AppendUserMessage(const String& gtest_msg,
1777 const Message& user_msg) {
1778 // Appends the user message if it's non-empty.
1779 const String user_msg_string = user_msg.GetString();
1780 if (user_msg_string.empty()) {
1781 return gtest_msg;
1782 }
1783
1784 Message msg;
1785 msg << gtest_msg << "\n" << user_msg_string;
1786
1787 return msg.GetString();
1788}
1789
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001790} // namespace internal
1791
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001792// class TestResult
1793
1794// Creates an empty TestResult.
1795TestResult::TestResult()
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001796 : death_test_count_(0),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001797 elapsed_time_(0) {
1798}
1799
1800// D'tor.
1801TestResult::~TestResult() {
1802}
1803
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001804// Returns the i-th test part result among all the results. i can
1805// range from 0 to total_part_count() - 1. If i is not in that range,
1806// aborts the program.
1807const TestPartResult& TestResult::GetTestPartResult(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001808 if (i < 0 || i >= total_part_count())
1809 internal::posix::Abort();
1810 return test_part_results_.at(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001811}
1812
1813// Returns the i-th test property. i can range from 0 to
1814// test_property_count() - 1. If i is not in that range, aborts the
1815// program.
1816const TestProperty& TestResult::GetTestProperty(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001817 if (i < 0 || i >= test_property_count())
1818 internal::posix::Abort();
1819 return test_properties_.at(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001820}
1821
1822// Clears the test part results.
1823void TestResult::ClearTestPartResults() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001824 test_part_results_.clear();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001825}
1826
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001827// Adds a test part result to the list.
1828void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001829 test_part_results_.push_back(test_part_result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001830}
1831
1832// Adds a test property to the list. If a property with the same key as the
1833// supplied property is already represented, the value of this test_property
1834// replaces the old value for that key.
1835void TestResult::RecordProperty(const TestProperty& test_property) {
1836 if (!ValidateTestProperty(test_property)) {
1837 return;
1838 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001839 internal::MutexLock lock(&test_properites_mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001840 const std::vector<TestProperty>::iterator property_with_matching_key =
1841 std::find_if(test_properties_.begin(), test_properties_.end(),
1842 internal::TestPropertyKeyIs(test_property.key()));
1843 if (property_with_matching_key == test_properties_.end()) {
1844 test_properties_.push_back(test_property);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001845 return;
1846 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001847 property_with_matching_key->SetValue(test_property.value());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001848}
1849
1850// Adds a failure if the key is a reserved attribute of Google Test
1851// testcase tags. Returns true if the property is valid.
1852bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001853 internal::String key(test_property.key());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001854 if (key == "name" || key == "status" || key == "time" || key == "classname") {
1855 ADD_FAILURE()
1856 << "Reserved key used in RecordProperty(): "
1857 << key
1858 << " ('name', 'status', 'time', and 'classname' are reserved by "
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001859 << GTEST_NAME_ << ")";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001860 return false;
1861 }
1862 return true;
1863}
1864
1865// Clears the object.
1866void TestResult::Clear() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001867 test_part_results_.clear();
1868 test_properties_.clear();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001869 death_test_count_ = 0;
1870 elapsed_time_ = 0;
1871}
1872
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001873// Returns true iff the test failed.
1874bool TestResult::Failed() const {
1875 for (int i = 0; i < total_part_count(); ++i) {
1876 if (GetTestPartResult(i).failed())
1877 return true;
1878 }
1879 return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001880}
1881
1882// Returns true iff the test part fatally failed.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001883static bool TestPartFatallyFailed(const TestPartResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001884 return result.fatally_failed();
1885}
1886
1887// Returns true iff the test fatally failed.
1888bool TestResult::HasFatalFailure() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001889 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001890}
1891
1892// Returns true iff the test part non-fatally failed.
1893static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1894 return result.nonfatally_failed();
1895}
1896
1897// Returns true iff the test has a non-fatal failure.
1898bool TestResult::HasNonfatalFailure() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001899 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001900}
1901
1902// Gets the number of all test parts. This is the sum of the number
1903// of successful test parts and the number of failed test parts.
1904int TestResult::total_part_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001905 return static_cast<int>(test_part_results_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001906}
1907
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001908// Returns the number of the test properties.
1909int TestResult::test_property_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001910 return static_cast<int>(test_properties_.size());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001911}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001912
1913// class Test
1914
1915// Creates a Test object.
1916
1917// The c'tor saves the values of all Google Test flags.
1918Test::Test()
1919 : gtest_flag_saver_(new internal::GTestFlagSaver) {
1920}
1921
1922// The d'tor restores the values of all Google Test flags.
1923Test::~Test() {
1924 delete gtest_flag_saver_;
1925}
1926
1927// Sets up the test fixture.
1928//
1929// A sub-class may override this.
1930void Test::SetUp() {
1931}
1932
1933// Tears down the test fixture.
1934//
1935// A sub-class may override this.
1936void Test::TearDown() {
1937}
1938
1939// Allows user supplied key value pairs to be recorded for later output.
1940void Test::RecordProperty(const char* key, const char* value) {
1941 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1942}
1943
1944// Allows user supplied key value pairs to be recorded for later output.
1945void Test::RecordProperty(const char* key, int value) {
1946 Message value_message;
1947 value_message << value;
1948 RecordProperty(key, value_message.GetString().c_str());
1949}
1950
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001951namespace internal {
1952
1953void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1954 const String& message) {
1955 // This function is a friend of UnitTest and as such has access to
1956 // AddTestPartResult.
1957 UnitTest::GetInstance()->AddTestPartResult(
1958 result_type,
1959 NULL, // No info about the source file where the exception occurred.
1960 -1, // We have no info on which line caused the exception.
1961 message,
1962 String()); // No stack trace, either.
1963}
1964
1965} // namespace internal
1966
Michael J. Spencer6b178302010-10-07 18:29:44 +00001967#if GTEST_HAS_SEH
1968// We are on Windows with SEH.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001969
1970// Adds an "exception thrown" fatal failure to the current test.
1971static void AddExceptionThrownFailure(DWORD exception_code,
1972 const char* location) {
1973 Message message;
1974 message << "Exception thrown with code 0x" << std::setbase(16) <<
1975 exception_code << std::setbase(10) << " in " << location << ".";
1976
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001977 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1978 message.GetString());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001979}
1980
Michael J. Spencer6b178302010-10-07 18:29:44 +00001981#endif // GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001982
1983// Google Test requires all tests in the same test case to use the same test
1984// fixture class. This function checks if the current test has the
1985// same fixture class as the first test in the current test case. If
1986// yes, it returns true; otherwise it generates a Google Test failure and
1987// returns false.
1988bool Test::HasSameFixtureClass() {
1989 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1990 const TestCase* const test_case = impl->current_test_case();
1991
1992 // Info about the first test in the current test case.
1993 const internal::TestInfoImpl* const first_test_info =
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001994 test_case->test_info_list()[0]->impl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001995 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1996 const char* const first_test_name = first_test_info->name();
1997
1998 // Info about the current test.
1999 const internal::TestInfoImpl* const this_test_info =
2000 impl->current_test_info()->impl();
2001 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
2002 const char* const this_test_name = this_test_info->name();
2003
2004 if (this_fixture_id != first_fixture_id) {
2005 // Is the first test defined using TEST?
2006 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2007 // Is this test defined using TEST?
2008 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2009
2010 if (first_is_TEST || this_is_TEST) {
2011 // The user mixed TEST and TEST_F in this test case - we'll tell
2012 // him/her how to fix it.
2013
2014 // Gets the name of the TEST and the name of the TEST_F. Note
2015 // that first_is_TEST and this_is_TEST cannot both be true, as
2016 // the fixture IDs are different for the two tests.
2017 const char* const TEST_name =
2018 first_is_TEST ? first_test_name : this_test_name;
2019 const char* const TEST_F_name =
2020 first_is_TEST ? this_test_name : first_test_name;
2021
2022 ADD_FAILURE()
2023 << "All tests in the same test case must use the same test fixture\n"
2024 << "class, so mixing TEST_F and TEST in the same test case is\n"
2025 << "illegal. In test case " << this_test_info->test_case_name()
2026 << ",\n"
2027 << "test " << TEST_F_name << " is defined using TEST_F but\n"
2028 << "test " << TEST_name << " is defined using TEST. You probably\n"
2029 << "want to change the TEST to TEST_F or move it to another test\n"
2030 << "case.";
2031 } else {
2032 // The user defined two fixture classes with the same name in
2033 // two namespaces - we'll tell him/her how to fix it.
2034 ADD_FAILURE()
2035 << "All tests in the same test case must use the same test fixture\n"
2036 << "class. However, in test case "
2037 << this_test_info->test_case_name() << ",\n"
2038 << "you defined test " << first_test_name
2039 << " and test " << this_test_name << "\n"
2040 << "using two different test fixture classes. This can happen if\n"
2041 << "the two classes are from different namespaces or translation\n"
2042 << "units and have the same name. You should probably rename one\n"
2043 << "of the classes to put the tests into different test cases.";
2044 }
2045 return false;
2046 }
2047
2048 return true;
2049}
2050
2051// Runs the test and updates the test result.
2052void Test::Run() {
2053 if (!HasSameFixtureClass()) return;
2054
2055 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002056#if GTEST_HAS_SEH
2057 // Catch SEH-style exceptions.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002058 impl->os_stack_trace_getter()->UponLeavingGTest();
2059 __try {
2060 SetUp();
2061 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2062 GetExceptionCode())) {
2063 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2064 }
2065
2066 // We will run the test only if SetUp() had no fatal failure.
2067 if (!HasFatalFailure()) {
2068 impl->os_stack_trace_getter()->UponLeavingGTest();
2069 __try {
2070 TestBody();
2071 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2072 GetExceptionCode())) {
2073 AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2074 }
2075 }
2076
2077 // However, we want to clean up as much as possible. Hence we will
2078 // always call TearDown(), even if SetUp() or the test body has
2079 // failed.
2080 impl->os_stack_trace_getter()->UponLeavingGTest();
2081 __try {
2082 TearDown();
2083 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2084 GetExceptionCode())) {
2085 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2086 }
2087
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002088#else // We are on a compiler or platform that doesn't support SEH.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002089 impl->os_stack_trace_getter()->UponLeavingGTest();
2090 SetUp();
2091
2092 // We will run the test only if SetUp() was successful.
2093 if (!HasFatalFailure()) {
2094 impl->os_stack_trace_getter()->UponLeavingGTest();
2095 TestBody();
2096 }
2097
2098 // However, we want to clean up as much as possible. Hence we will
2099 // always call TearDown(), even if SetUp() or the test body has
2100 // failed.
2101 impl->os_stack_trace_getter()->UponLeavingGTest();
2102 TearDown();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002103#endif // GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002104}
2105
2106
2107// Returns true iff the current test has a fatal failure.
2108bool Test::HasFatalFailure() {
2109 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2110}
2111
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002112// Returns true iff the current test has a non-fatal failure.
2113bool Test::HasNonfatalFailure() {
2114 return internal::GetUnitTestImpl()->current_test_result()->
2115 HasNonfatalFailure();
2116}
2117
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002118// class TestInfo
2119
2120// Constructs a TestInfo object. It assumes ownership of the test factory
2121// object via impl_.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002122TestInfo::TestInfo(const char* a_test_case_name,
2123 const char* a_name,
2124 const char* a_test_case_comment,
2125 const char* a_comment,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002126 internal::TypeId fixture_class_id,
2127 internal::TestFactoryBase* factory) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002128 impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name,
2129 a_test_case_comment, a_comment,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002130 fixture_class_id, factory);
2131}
2132
2133// Destructs a TestInfo object.
2134TestInfo::~TestInfo() {
2135 delete impl_;
2136}
2137
2138namespace internal {
2139
2140// Creates a new TestInfo object and registers it with Google Test;
2141// returns the created object.
2142//
2143// Arguments:
2144//
2145// test_case_name: name of the test case
2146// name: name of the test
2147// test_case_comment: a comment on the test case that will be included in
2148// the test output
2149// comment: a comment on the test that will be included in the
2150// test output
2151// fixture_class_id: ID of the test fixture class
2152// set_up_tc: pointer to the function that sets up the test case
2153// tear_down_tc: pointer to the function that tears down the test case
2154// factory: pointer to the factory that creates a test object.
2155// The newly created TestInfo instance will assume
2156// ownership of the factory object.
2157TestInfo* MakeAndRegisterTestInfo(
2158 const char* test_case_name, const char* name,
2159 const char* test_case_comment, const char* comment,
2160 TypeId fixture_class_id,
2161 SetUpTestCaseFunc set_up_tc,
2162 TearDownTestCaseFunc tear_down_tc,
2163 TestFactoryBase* factory) {
2164 TestInfo* const test_info =
2165 new TestInfo(test_case_name, name, test_case_comment, comment,
2166 fixture_class_id, factory);
2167 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2168 return test_info;
2169}
2170
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002171#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002172void ReportInvalidTestCaseType(const char* test_case_name,
2173 const char* file, int line) {
2174 Message errors;
2175 errors
2176 << "Attempted redefinition of test case " << test_case_name << ".\n"
2177 << "All tests in the same test case must use the same test fixture\n"
2178 << "class. However, in test case " << test_case_name << ", you tried\n"
2179 << "to define a test using a fixture class different from the one\n"
2180 << "used earlier. This can happen if the two fixture classes are\n"
2181 << "from different namespaces and have the same name. You should\n"
2182 << "probably rename one of the classes to put the tests into different\n"
2183 << "test cases.";
2184
2185 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2186 errors.GetString().c_str());
2187}
2188#endif // GTEST_HAS_PARAM_TEST
2189
2190} // namespace internal
2191
2192// Returns the test case name.
2193const char* TestInfo::test_case_name() const {
2194 return impl_->test_case_name();
2195}
2196
2197// Returns the test name.
2198const char* TestInfo::name() const {
2199 return impl_->name();
2200}
2201
2202// Returns the test case comment.
2203const char* TestInfo::test_case_comment() const {
2204 return impl_->test_case_comment();
2205}
2206
2207// Returns the test comment.
2208const char* TestInfo::comment() const {
2209 return impl_->comment();
2210}
2211
2212// Returns true if this test should run.
2213bool TestInfo::should_run() const { return impl_->should_run(); }
2214
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002215// Returns true if this test matches the user-specified filter.
2216bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2217
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002218// Returns the result of the test.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002219const TestResult* TestInfo::result() const { return impl_->result(); }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002220
2221// Increments the number of death tests encountered in this test so
2222// far.
2223int TestInfo::increment_death_test_count() {
2224 return impl_->result()->increment_death_test_count();
2225}
2226
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002227namespace internal {
2228
2229// This method expands all parameterized tests registered with macros TEST_P
2230// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2231// This will be done just once during the program runtime.
2232void UnitTestImpl::RegisterParameterizedTests() {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002233#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002234 if (!parameterized_tests_registered_) {
2235 parameterized_test_registry_.RegisterTests();
2236 parameterized_tests_registered_ = true;
2237 }
2238#endif
2239}
2240
2241// Creates the test object, runs it, records its result, and then
2242// deletes it.
2243void TestInfoImpl::Run() {
2244 if (!should_run_) return;
2245
2246 // Tells UnitTest where to store test result.
2247 UnitTestImpl* const impl = internal::GetUnitTestImpl();
2248 impl->set_current_test_info(parent_);
2249
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002250 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2251
2252 // Notifies the unit test event listeners that a test is about to start.
2253 repeater->OnTestStart(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002254
2255 const TimeInMillis start = GetTimeInMillis();
2256
2257 impl->os_stack_trace_getter()->UponLeavingGTest();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002258#if GTEST_HAS_SEH
2259 // Catch SEH-style exceptions.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002260 Test* test = NULL;
2261
2262 __try {
2263 // Creates the test object.
2264 test = factory_->CreateTest();
2265 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2266 GetExceptionCode())) {
2267 AddExceptionThrownFailure(GetExceptionCode(),
2268 "the test fixture's constructor");
2269 return;
2270 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002271#else // We are on a compiler or platform that doesn't support SEH.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002272
2273 // TODO(wan): If test->Run() throws, test won't be deleted. This is
2274 // not a problem now as we don't use exceptions. If we were to
2275 // enable exceptions, we should revise the following to be
2276 // exception-safe.
2277
2278 // Creates the test object.
2279 Test* test = factory_->CreateTest();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002280#endif // GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002281
2282 // Runs the test only if the constructor of the test fixture didn't
2283 // generate a fatal failure.
2284 if (!Test::HasFatalFailure()) {
2285 test->Run();
2286 }
2287
2288 // Deletes the test object.
2289 impl->os_stack_trace_getter()->UponLeavingGTest();
2290 delete test;
2291 test = NULL;
2292
2293 result_.set_elapsed_time(GetTimeInMillis() - start);
2294
2295 // Notifies the unit test event listener that a test has just finished.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002296 repeater->OnTestEnd(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002297
2298 // Tells UnitTest to stop associating assertion results to this
2299 // test.
2300 impl->set_current_test_info(NULL);
2301}
2302
2303} // namespace internal
2304
2305// class TestCase
2306
2307// Gets the number of successful tests in this test case.
2308int TestCase::successful_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002309 return CountIf(test_info_list_, TestPassed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002310}
2311
2312// Gets the number of failed tests in this test case.
2313int TestCase::failed_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002314 return CountIf(test_info_list_, TestFailed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002315}
2316
2317int TestCase::disabled_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002318 return CountIf(test_info_list_, TestDisabled);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002319}
2320
2321// Get the number of tests in this test case that should run.
2322int TestCase::test_to_run_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002323 return CountIf(test_info_list_, ShouldRunTest);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002324}
2325
2326// Gets the number of all tests.
2327int TestCase::total_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002328 return static_cast<int>(test_info_list_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002329}
2330
2331// Creates a TestCase with the given name.
2332//
2333// Arguments:
2334//
2335// name: name of the test case
2336// set_up_tc: pointer to the function that sets up the test case
2337// tear_down_tc: pointer to the function that tears down the test case
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002338TestCase::TestCase(const char* a_name, const char* a_comment,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002339 Test::SetUpTestCaseFunc set_up_tc,
2340 Test::TearDownTestCaseFunc tear_down_tc)
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002341 : name_(a_name),
2342 comment_(a_comment),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002343 set_up_tc_(set_up_tc),
2344 tear_down_tc_(tear_down_tc),
2345 should_run_(false),
2346 elapsed_time_(0) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002347}
2348
2349// Destructor of TestCase.
2350TestCase::~TestCase() {
2351 // Deletes every Test in the collection.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002352 ForEach(test_info_list_, internal::Delete<TestInfo>);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002353}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002354
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002355// Returns the i-th test among all the tests. i can range from 0 to
2356// total_test_count() - 1. If i is not in that range, returns NULL.
2357const TestInfo* TestCase::GetTestInfo(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002358 const int index = GetElementOr(test_indices_, i, -1);
2359 return index < 0 ? NULL : test_info_list_[index];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002360}
2361
2362// Returns the i-th test among all the tests. i can range from 0 to
2363// total_test_count() - 1. If i is not in that range, returns NULL.
2364TestInfo* TestCase::GetMutableTestInfo(int i) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002365 const int index = GetElementOr(test_indices_, i, -1);
2366 return index < 0 ? NULL : test_info_list_[index];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002367}
2368
2369// Adds a test to this test case. Will delete the test upon
2370// destruction of the TestCase object.
2371void TestCase::AddTestInfo(TestInfo * test_info) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002372 test_info_list_.push_back(test_info);
2373 test_indices_.push_back(static_cast<int>(test_indices_.size()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002374}
2375
2376// Runs every test in this TestCase.
2377void TestCase::Run() {
2378 if (!should_run_) return;
2379
2380 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2381 impl->set_current_test_case(this);
2382
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002383 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002384
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002385 repeater->OnTestCaseStart(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002386 impl->os_stack_trace_getter()->UponLeavingGTest();
2387 set_up_tc_();
2388
2389 const internal::TimeInMillis start = internal::GetTimeInMillis();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002390 for (int i = 0; i < total_test_count(); i++) {
2391 GetMutableTestInfo(i)->impl()->Run();
2392 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002393 elapsed_time_ = internal::GetTimeInMillis() - start;
2394
2395 impl->os_stack_trace_getter()->UponLeavingGTest();
2396 tear_down_tc_();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002397 repeater->OnTestCaseEnd(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002398 impl->set_current_test_case(NULL);
2399}
2400
2401// Clears the results of all tests in this test case.
2402void TestCase::ClearResult() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002403 ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002404}
2405
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002406// Returns true iff test passed.
2407bool TestCase::TestPassed(const TestInfo * test_info) {
2408 const internal::TestInfoImpl* const impl = test_info->impl();
2409 return impl->should_run() && impl->result()->Passed();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002410}
2411
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002412// Returns true iff test failed.
2413bool TestCase::TestFailed(const TestInfo * test_info) {
2414 const internal::TestInfoImpl* const impl = test_info->impl();
2415 return impl->should_run() && impl->result()->Failed();
2416}
2417
2418// Returns true iff test is disabled.
2419bool TestCase::TestDisabled(const TestInfo * test_info) {
2420 return test_info->impl()->is_disabled();
2421}
2422
2423// Returns true if the given test should run.
2424bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2425 return test_info->impl()->should_run();
2426}
2427
2428// Shuffles the tests in this test case.
2429void TestCase::ShuffleTests(internal::Random* random) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002430 Shuffle(random, &test_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002431}
2432
2433// Restores the test order to before the first shuffle.
2434void TestCase::UnshuffleTests() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002435 for (size_t i = 0; i < test_indices_.size(); i++) {
2436 test_indices_[i] = static_cast<int>(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002437 }
2438}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002439
2440// Formats a countable noun. Depending on its quantity, either the
2441// singular form or the plural form is used. e.g.
2442//
2443// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2444// FormatCountableNoun(5, "book", "books") returns "5 books".
2445static internal::String FormatCountableNoun(int count,
2446 const char * singular_form,
2447 const char * plural_form) {
2448 return internal::String::Format("%d %s", count,
2449 count == 1 ? singular_form : plural_form);
2450}
2451
2452// Formats the count of tests.
2453static internal::String FormatTestCount(int test_count) {
2454 return FormatCountableNoun(test_count, "test", "tests");
2455}
2456
2457// Formats the count of test cases.
2458static internal::String FormatTestCaseCount(int test_case_count) {
2459 return FormatCountableNoun(test_case_count, "test case", "test cases");
2460}
2461
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002462// Converts a TestPartResult::Type enum to human-friendly string
2463// representation. Both kNonFatalFailure and kFatalFailure are translated
2464// to "Failure", as the user usually doesn't care about the difference
2465// between the two when viewing the test result.
2466static const char * TestPartResultTypeToString(TestPartResult::Type type) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002467 switch (type) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002468 case TestPartResult::kSuccess:
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002469 return "Success";
2470
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002471 case TestPartResult::kNonFatalFailure:
2472 case TestPartResult::kFatalFailure:
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002473#ifdef _MSC_VER
2474 return "error: ";
2475#else
2476 return "Failure\n";
2477#endif
2478 }
2479
2480 return "Unknown result type";
2481}
2482
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002483// Prints a TestPartResult to a String.
2484static internal::String PrintTestPartResultToString(
2485 const TestPartResult& test_part_result) {
2486 return (Message()
2487 << internal::FormatFileLocation(test_part_result.file_name(),
2488 test_part_result.line_number())
2489 << " " << TestPartResultTypeToString(test_part_result.type())
2490 << test_part_result.message()).GetString();
2491}
2492
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002493// Prints a TestPartResult.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002494static void PrintTestPartResult(const TestPartResult& test_part_result) {
2495 const internal::String& result =
2496 PrintTestPartResultToString(test_part_result);
2497 printf("%s\n", result.c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002498 fflush(stdout);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002499 // If the test program runs in Visual Studio or a debugger, the
2500 // following statements add the test part result message to the Output
2501 // window such that the user can double-click on it to jump to the
2502 // corresponding source code location; otherwise they do nothing.
2503#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2504 // We don't call OutputDebugString*() on Windows Mobile, as printing
2505 // to stdout is done by OutputDebugString() there already - we don't
2506 // want the same message printed twice.
2507 ::OutputDebugStringA(result.c_str());
2508 ::OutputDebugStringA("\n");
2509#endif
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002510}
2511
2512// class PrettyUnitTestResultPrinter
2513
2514namespace internal {
2515
2516enum GTestColor {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002517 COLOR_DEFAULT,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002518 COLOR_RED,
2519 COLOR_GREEN,
2520 COLOR_YELLOW
2521};
2522
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002523#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002524
2525// Returns the character attribute for the given color.
2526WORD GetColorAttribute(GTestColor color) {
2527 switch (color) {
2528 case COLOR_RED: return FOREGROUND_RED;
2529 case COLOR_GREEN: return FOREGROUND_GREEN;
2530 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002531 default: return 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002532 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002533}
2534
2535#else
2536
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002537// Returns the ANSI color code for the given color. COLOR_DEFAULT is
2538// an invalid input.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002539const char* GetAnsiColorCode(GTestColor color) {
2540 switch (color) {
2541 case COLOR_RED: return "1";
2542 case COLOR_GREEN: return "2";
2543 case COLOR_YELLOW: return "3";
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002544 default: return NULL;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002545 };
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002546}
2547
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002548#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002549
2550// Returns true iff Google Test should use colors in the output.
2551bool ShouldUseColor(bool stdout_is_tty) {
2552 const char* const gtest_color = GTEST_FLAG(color).c_str();
2553
2554 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002555#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002556 // On Windows the TERM variable is usually not set, but the
2557 // console there does support colors.
2558 return stdout_is_tty;
2559#else
2560 // On non-Windows platforms, we rely on the TERM variable.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002561 const char* const term = posix::GetEnv("TERM");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002562 const bool term_supports_color =
2563 String::CStringEquals(term, "xterm") ||
2564 String::CStringEquals(term, "xterm-color") ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002565 String::CStringEquals(term, "xterm-256color") ||
2566 String::CStringEquals(term, "linux") ||
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002567 String::CStringEquals(term, "cygwin");
2568 return stdout_is_tty && term_supports_color;
2569#endif // GTEST_OS_WINDOWS
2570 }
2571
2572 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2573 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2574 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2575 String::CStringEquals(gtest_color, "1");
2576 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2577 // value is neither one of these nor "auto", we treat it as "no" to
2578 // be conservative.
2579}
2580
2581// Helpers for printing colored strings to stdout. Note that on Windows, we
2582// cannot simply emit special characters and have the terminal change colors.
2583// This routine must actually emit the characters rather than return a string
2584// that would be colored when printed, as can be done on Linux.
2585void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2586 va_list args;
2587 va_start(args, fmt);
2588
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002589#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002590 const bool use_color = false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002591#else
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002592 static const bool in_color_mode =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002593 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002594 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002595#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002596 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2597
2598 if (!use_color) {
2599 vprintf(fmt, args);
2600 va_end(args);
2601 return;
2602 }
2603
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002604#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002605 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2606
2607 // Gets the current text color.
2608 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2609 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2610 const WORD old_color_attrs = buffer_info.wAttributes;
2611
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002612 // We need to flush the stream buffers into the console before each
2613 // SetConsoleTextAttribute call lest it affect the text that is already
2614 // printed but has not yet reached the console.
2615 fflush(stdout);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002616 SetConsoleTextAttribute(stdout_handle,
2617 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2618 vprintf(fmt, args);
2619
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002620 fflush(stdout);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002621 // Restores the text color.
2622 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2623#else
2624 printf("\033[0;3%sm", GetAnsiColorCode(color));
2625 vprintf(fmt, args);
2626 printf("\033[m"); // Resets the terminal to default.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002627#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002628 va_end(args);
2629}
2630
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002631// This class implements the TestEventListener interface.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002632//
2633// Class PrettyUnitTestResultPrinter is copyable.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002634class PrettyUnitTestResultPrinter : public TestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002635 public:
2636 PrettyUnitTestResultPrinter() {}
2637 static void PrintTestName(const char * test_case, const char * test) {
2638 printf("%s.%s", test_case, test);
2639 }
2640
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002641 // The following methods override what's in the TestEventListener class.
2642 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2643 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2644 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2645 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2646 virtual void OnTestCaseStart(const TestCase& test_case);
2647 virtual void OnTestStart(const TestInfo& test_info);
2648 virtual void OnTestPartResult(const TestPartResult& result);
2649 virtual void OnTestEnd(const TestInfo& test_info);
2650 virtual void OnTestCaseEnd(const TestCase& test_case);
2651 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2652 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2653 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2654 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002655
2656 private:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002657 static void PrintFailedTests(const UnitTest& unit_test);
2658
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002659 internal::String test_case_name_;
2660};
2661
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002662 // Fired before each iteration of tests starts.
2663void PrettyUnitTestResultPrinter::OnTestIterationStart(
2664 const UnitTest& unit_test, int iteration) {
2665 if (GTEST_FLAG(repeat) != 1)
2666 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2667
2668 const char* const filter = GTEST_FLAG(filter).c_str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002669
2670 // Prints the filter if it's not *. This reminds the user that some
2671 // tests may be skipped.
2672 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2673 ColoredPrintf(COLOR_YELLOW,
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002674 "Note: %s filter = %s\n", GTEST_NAME_, filter);
2675 }
2676
2677 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2678 ColoredPrintf(COLOR_YELLOW,
2679 "Note: This is test shard %s of %s.\n",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002680 internal::posix::GetEnv(kTestShardIndex),
2681 internal::posix::GetEnv(kTestTotalShards));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002682 }
2683
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002684 if (GTEST_FLAG(shuffle)) {
2685 ColoredPrintf(COLOR_YELLOW,
2686 "Note: Randomizing tests' orders with a seed of %d .\n",
2687 unit_test.random_seed());
2688 }
2689
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002690 ColoredPrintf(COLOR_GREEN, "[==========] ");
2691 printf("Running %s from %s.\n",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002692 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2693 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002694 fflush(stdout);
2695}
2696
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002697void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2698 const UnitTest& /*unit_test*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002699 ColoredPrintf(COLOR_GREEN, "[----------] ");
2700 printf("Global test environment set-up.\n");
2701 fflush(stdout);
2702}
2703
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002704void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2705 test_case_name_ = test_case.name();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002706 const internal::String counts =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002707 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002708 ColoredPrintf(COLOR_GREEN, "[----------] ");
2709 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002710 if (test_case.comment()[0] == '\0') {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002711 printf("\n");
2712 } else {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002713 printf(", where %s\n", test_case.comment());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002714 }
2715 fflush(stdout);
2716}
2717
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002718void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002719 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002720 PrintTestName(test_case_name_.c_str(), test_info.name());
2721 if (test_info.comment()[0] == '\0') {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002722 printf("\n");
2723 } else {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002724 printf(", where %s\n", test_info.comment());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002725 }
2726 fflush(stdout);
2727}
2728
2729// Called after an assertion failure.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002730void PrettyUnitTestResultPrinter::OnTestPartResult(
2731 const TestPartResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002732 // If the test part succeeded, we don't need to do anything.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002733 if (result.type() == TestPartResult::kSuccess)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002734 return;
2735
2736 // Print failure message from the assertion (e.g. expected this and got that).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002737 PrintTestPartResult(result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002738 fflush(stdout);
2739}
2740
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002741void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2742 if (test_info.result()->Passed()) {
2743 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2744 } else {
2745 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2746 }
2747 PrintTestName(test_case_name_.c_str(), test_info.name());
2748 if (GTEST_FLAG(print_time)) {
2749 printf(" (%s ms)\n", internal::StreamableToString(
2750 test_info.result()->elapsed_time()).c_str());
2751 } else {
2752 printf("\n");
2753 }
2754 fflush(stdout);
2755}
2756
2757void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2758 if (!GTEST_FLAG(print_time)) return;
2759
2760 test_case_name_ = test_case.name();
2761 const internal::String counts =
2762 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2763 ColoredPrintf(COLOR_GREEN, "[----------] ");
2764 printf("%s from %s (%s ms total)\n\n",
2765 counts.c_str(), test_case_name_.c_str(),
2766 internal::StreamableToString(test_case.elapsed_time()).c_str());
2767 fflush(stdout);
2768}
2769
2770void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2771 const UnitTest& /*unit_test*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002772 ColoredPrintf(COLOR_GREEN, "[----------] ");
2773 printf("Global test environment tear-down\n");
2774 fflush(stdout);
2775}
2776
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002777// Internal helper for printing the list of failed tests.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002778void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2779 const int failed_test_count = unit_test.failed_test_count();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002780 if (failed_test_count == 0) {
2781 return;
2782 }
2783
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002784 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2785 const TestCase& test_case = *unit_test.GetTestCase(i);
2786 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002787 continue;
2788 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002789 for (int j = 0; j < test_case.total_test_count(); ++j) {
2790 const TestInfo& test_info = *test_case.GetTestInfo(j);
2791 if (!test_info.should_run() || test_info.result()->Passed()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002792 continue;
2793 }
2794 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002795 printf("%s.%s", test_case.name(), test_info.name());
2796 if (test_case.comment()[0] != '\0' ||
2797 test_info.comment()[0] != '\0') {
2798 printf(", where %s", test_case.comment());
2799 if (test_case.comment()[0] != '\0' &&
2800 test_info.comment()[0] != '\0') {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002801 printf(" and ");
2802 }
2803 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002804 printf("%s\n", test_info.comment());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002805 }
2806 }
2807}
2808
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002809 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2810 int /*iteration*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002811 ColoredPrintf(COLOR_GREEN, "[==========] ");
2812 printf("%s from %s ran.",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002813 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2814 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002815 if (GTEST_FLAG(print_time)) {
2816 printf(" (%s ms total)",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002817 internal::StreamableToString(unit_test.elapsed_time()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002818 }
2819 printf("\n");
2820 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002821 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002822
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002823 int num_failures = unit_test.failed_test_count();
2824 if (!unit_test.Passed()) {
2825 const int failed_test_count = unit_test.failed_test_count();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002826 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2827 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002828 PrintFailedTests(unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002829 printf("\n%2d FAILED %s\n", num_failures,
2830 num_failures == 1 ? "TEST" : "TESTS");
2831 }
2832
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002833 int num_disabled = unit_test.disabled_test_count();
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002834 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002835 if (!num_failures) {
2836 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2837 }
2838 ColoredPrintf(COLOR_YELLOW,
2839 " YOU HAVE %d DISABLED %s\n\n",
2840 num_disabled,
2841 num_disabled == 1 ? "TEST" : "TESTS");
2842 }
2843 // Ensure that Google Test output is printed before, e.g., heapchecker output.
2844 fflush(stdout);
2845}
2846
2847// End PrettyUnitTestResultPrinter
2848
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002849// class TestEventRepeater
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002850//
2851// This class forwards events to other event listeners.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002852class TestEventRepeater : public TestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002853 public:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002854 TestEventRepeater() : forwarding_enabled_(true) {}
2855 virtual ~TestEventRepeater();
2856 void Append(TestEventListener *listener);
2857 TestEventListener* Release(TestEventListener* listener);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002858
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002859 // Controls whether events will be forwarded to listeners_. Set to false
2860 // in death test child processes.
2861 bool forwarding_enabled() const { return forwarding_enabled_; }
2862 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2863
2864 virtual void OnTestProgramStart(const UnitTest& unit_test);
2865 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2866 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2867 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2868 virtual void OnTestCaseStart(const TestCase& test_case);
2869 virtual void OnTestStart(const TestInfo& test_info);
2870 virtual void OnTestPartResult(const TestPartResult& result);
2871 virtual void OnTestEnd(const TestInfo& test_info);
2872 virtual void OnTestCaseEnd(const TestCase& test_case);
2873 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2874 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2875 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2876 virtual void OnTestProgramEnd(const UnitTest& unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002877
2878 private:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002879 // Controls whether events will be forwarded to listeners_. Set to false
2880 // in death test child processes.
2881 bool forwarding_enabled_;
2882 // The list of listeners that receive events.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002883 std::vector<TestEventListener*> listeners_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002884
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002885 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002886};
2887
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002888TestEventRepeater::~TestEventRepeater() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002889 ForEach(listeners_, Delete<TestEventListener>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002890}
2891
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002892void TestEventRepeater::Append(TestEventListener *listener) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002893 listeners_.push_back(listener);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002894}
2895
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002896// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2897TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002898 for (size_t i = 0; i < listeners_.size(); ++i) {
2899 if (listeners_[i] == listener) {
2900 listeners_.erase(listeners_.begin() + i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002901 return listener;
2902 }
2903 }
2904
2905 return NULL;
2906}
2907
2908// Since most methods are very similar, use macros to reduce boilerplate.
2909// This defines a member that forwards the call to all listeners.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002910#define GTEST_REPEATER_METHOD_(Name, Type) \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002911void TestEventRepeater::Name(const Type& parameter) { \
2912 if (forwarding_enabled_) { \
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002913 for (size_t i = 0; i < listeners_.size(); i++) { \
2914 listeners_[i]->Name(parameter); \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002915 } \
2916 } \
2917}
2918// This defines a member that forwards the call to all listeners in reverse
2919// order.
2920#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2921void TestEventRepeater::Name(const Type& parameter) { \
2922 if (forwarding_enabled_) { \
2923 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002924 listeners_[i]->Name(parameter); \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002925 } \
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002926 } \
2927}
2928
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002929GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2930GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002931GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002932GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002933GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2934GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2935GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2936GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2937GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2938GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2939GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002940
2941#undef GTEST_REPEATER_METHOD_
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002942#undef GTEST_REVERSE_REPEATER_METHOD_
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002943
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002944void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2945 int iteration) {
2946 if (forwarding_enabled_) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002947 for (size_t i = 0; i < listeners_.size(); i++) {
2948 listeners_[i]->OnTestIterationStart(unit_test, iteration);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002949 }
2950 }
2951}
2952
2953void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2954 int iteration) {
2955 if (forwarding_enabled_) {
2956 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002957 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002958 }
2959 }
2960}
2961
2962// End TestEventRepeater
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002963
2964// This class generates an XML output file.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002965class XmlUnitTestResultPrinter : public EmptyTestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002966 public:
2967 explicit XmlUnitTestResultPrinter(const char* output_file);
2968
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002969 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002970
2971 private:
2972 // Is c a whitespace character that is normalized to a space character
2973 // when it appears in an XML attribute value?
2974 static bool IsNormalizableWhitespace(char c) {
2975 return c == 0x9 || c == 0xA || c == 0xD;
2976 }
2977
2978 // May c appear in a well-formed XML document?
2979 static bool IsValidXmlCharacter(char c) {
2980 return IsNormalizableWhitespace(c) || c >= 0x20;
2981 }
2982
2983 // Returns an XML-escaped copy of the input string str. If
2984 // is_attribute is true, the text is meant to appear as an attribute
2985 // value, and normalizable whitespace is preserved by replacing it
2986 // with character references.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002987 static String EscapeXml(const char* str, bool is_attribute);
2988
2989 // Returns the given string with all characters invalid in XML removed.
2990 static String RemoveInvalidXmlCharacters(const char* str);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002991
2992 // Convenience wrapper around EscapeXml when str is an attribute value.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002993 static String EscapeXmlAttribute(const char* str) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002994 return EscapeXml(str, true);
2995 }
2996
2997 // Convenience wrapper around EscapeXml when str is not an attribute value.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002998 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002999
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003000 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3001 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3002
3003 // Streams an XML representation of a TestInfo object.
3004 static void OutputXmlTestInfo(::std::ostream* stream,
3005 const char* test_case_name,
3006 const TestInfo& test_info);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003007
3008 // Prints an XML representation of a TestCase object
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003009 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003010
3011 // Prints an XML summary of unit_test to output stream out.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003012 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003013
3014 // Produces a string representing the test properties in a result as space
3015 // delimited XML attributes based on the property key="value" pairs.
3016 // When the String is not empty, it includes a space at the beginning,
3017 // to delimit this attribute from prior attributes.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003018 static String TestPropertiesAsXmlAttributes(const TestResult& result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003019
3020 // The output file.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003021 const String output_file_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003022
3023 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3024};
3025
3026// Creates a new XmlUnitTestResultPrinter.
3027XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3028 : output_file_(output_file) {
3029 if (output_file_.c_str() == NULL || output_file_.empty()) {
3030 fprintf(stderr, "XML output file may not be null\n");
3031 fflush(stderr);
3032 exit(EXIT_FAILURE);
3033 }
3034}
3035
3036// Called after the unit test ends.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003037void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3038 int /*iteration*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003039 FILE* xmlout = NULL;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003040 FilePath output_file(output_file_);
3041 FilePath output_dir(output_file.RemoveFileName());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003042
3043 if (output_dir.CreateDirectoriesRecursively()) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003044 xmlout = posix::FOpen(output_file_.c_str(), "w");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003045 }
3046 if (xmlout == NULL) {
3047 // TODO(wan): report the reason of the failure.
3048 //
3049 // We don't do it for now as:
3050 //
3051 // 1. There is no urgent need for it.
3052 // 2. It's a bit involved to make the errno variable thread-safe on
3053 // all three operating systems (Linux, Windows, and Mac OS).
3054 // 3. To interpret the meaning of errno in a thread-safe way,
3055 // we need the strerror_r() function, which is not available on
3056 // Windows.
3057 fprintf(stderr,
3058 "Unable to open file \"%s\"\n",
3059 output_file_.c_str());
3060 fflush(stderr);
3061 exit(EXIT_FAILURE);
3062 }
3063 PrintXmlUnitTest(xmlout, unit_test);
3064 fclose(xmlout);
3065}
3066
3067// Returns an XML-escaped copy of the input string str. If is_attribute
3068// is true, the text is meant to appear as an attribute value, and
3069// normalizable whitespace is preserved by replacing it with character
3070// references.
3071//
3072// Invalid XML characters in str, if any, are stripped from the output.
3073// It is expected that most, if not all, of the text processed by this
3074// module will consist of ordinary English text.
3075// If this module is ever modified to produce version 1.1 XML output,
3076// most invalid characters can be retained using character references.
3077// TODO(wan): It might be nice to have a minimally invasive, human-readable
3078// escaping scheme for invalid characters, rather than dropping them.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003079String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003080 Message m;
3081
3082 if (str != NULL) {
3083 for (const char* src = str; *src; ++src) {
3084 switch (*src) {
3085 case '<':
3086 m << "&lt;";
3087 break;
3088 case '>':
3089 m << "&gt;";
3090 break;
3091 case '&':
3092 m << "&amp;";
3093 break;
3094 case '\'':
3095 if (is_attribute)
3096 m << "&apos;";
3097 else
3098 m << '\'';
3099 break;
3100 case '"':
3101 if (is_attribute)
3102 m << "&quot;";
3103 else
3104 m << '"';
3105 break;
3106 default:
3107 if (IsValidXmlCharacter(*src)) {
3108 if (is_attribute && IsNormalizableWhitespace(*src))
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003109 m << String::Format("&#x%02X;", unsigned(*src));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003110 else
3111 m << *src;
3112 }
3113 break;
3114 }
3115 }
3116 }
3117
3118 return m.GetString();
3119}
3120
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003121// Returns the given string with all characters invalid in XML removed.
3122// Currently invalid characters are dropped from the string. An
3123// alternative is to replace them with certain characters such as . or ?.
3124String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3125 char* const output = new char[strlen(str) + 1];
3126 char* appender = output;
3127 for (char ch = *str; ch != '\0'; ch = *++str)
3128 if (IsValidXmlCharacter(ch))
3129 *appender++ = ch;
3130 *appender = '\0';
3131
3132 String ret_value(output);
3133 delete[] output;
3134 return ret_value;
3135}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003136
3137// The following routines generate an XML representation of a UnitTest
3138// object.
3139//
3140// This is how Google Test concepts map to the DTD:
3141//
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003142// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003143// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3144// <testcase name="test-name"> <-- corresponds to a TestInfo object
3145// <failure message="...">...</failure>
3146// <failure message="...">...</failure>
3147// <failure message="...">...</failure>
3148// <-- individual assertion failures
3149// </testcase>
3150// </testsuite>
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003151// </testsuites>
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003152
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003153// Formats the given time in milliseconds as seconds.
3154std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3155 ::std::stringstream ss;
3156 ss << ms/1000.0;
3157 return ss.str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003158}
3159
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003160// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3161void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3162 const char* data) {
3163 const char* segment = data;
3164 *stream << "<![CDATA[";
3165 for (;;) {
3166 const char* const next_segment = strstr(segment, "]]>");
3167 if (next_segment != NULL) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003168 stream->write(
3169 segment, static_cast<std::streamsize>(next_segment - segment));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003170 *stream << "]]>]]&gt;<![CDATA[";
3171 segment = next_segment + strlen("]]>");
3172 } else {
3173 *stream << segment;
3174 break;
3175 }
3176 }
3177 *stream << "]]>";
3178}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003179
3180// Prints an XML representation of a TestInfo object.
3181// TODO(wan): There is also value in printing properties with the plain printer.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003182void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3183 const char* test_case_name,
3184 const TestInfo& test_info) {
3185 const TestResult& result = *test_info.result();
3186 *stream << " <testcase name=\""
3187 << EscapeXmlAttribute(test_info.name()).c_str()
3188 << "\" status=\""
3189 << (test_info.should_run() ? "run" : "notrun")
3190 << "\" time=\""
3191 << FormatTimeInMillisAsSeconds(result.elapsed_time())
3192 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3193 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003194
3195 int failures = 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003196 for (int i = 0; i < result.total_part_count(); ++i) {
3197 const TestPartResult& part = result.GetTestPartResult(i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003198 if (part.failed()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003199 if (++failures == 1)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003200 *stream << ">\n";
3201 *stream << " <failure message=\""
3202 << EscapeXmlAttribute(part.summary()).c_str()
3203 << "\" type=\"\">";
3204 const String message = RemoveInvalidXmlCharacters(String::Format(
3205 "%s:%d\n%s",
3206 part.file_name(), part.line_number(),
3207 part.message()).c_str());
3208 OutputXmlCDataSection(stream, message.c_str());
3209 *stream << "</failure>\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003210 }
3211 }
3212
3213 if (failures == 0)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003214 *stream << " />\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003215 else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003216 *stream << " </testcase>\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003217}
3218
3219// Prints an XML representation of a TestCase object
3220void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003221 const TestCase& test_case) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003222 fprintf(out,
3223 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3224 "disabled=\"%d\" ",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003225 EscapeXmlAttribute(test_case.name()).c_str(),
3226 test_case.total_test_count(),
3227 test_case.failed_test_count(),
3228 test_case.disabled_test_count());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003229 fprintf(out,
3230 "errors=\"0\" time=\"%s\">\n",
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003231 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003232 for (int i = 0; i < test_case.total_test_count(); ++i) {
3233 StrStream stream;
3234 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3235 fprintf(out, "%s", StrStreamToString(&stream).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003236 }
3237 fprintf(out, " </testsuite>\n");
3238}
3239
3240// Prints an XML summary of unit_test to output stream out.
3241void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003242 const UnitTest& unit_test) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003243 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3244 fprintf(out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003245 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003246 "errors=\"0\" time=\"%s\" ",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003247 unit_test.total_test_count(),
3248 unit_test.failed_test_count(),
3249 unit_test.disabled_test_count(),
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003250 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003251 if (GTEST_FLAG(shuffle)) {
3252 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003253 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003254 fprintf(out, "name=\"AllTests\">\n");
3255 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3256 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3257 fprintf(out, "</testsuites>\n");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003258}
3259
3260// Produces a string representing the test properties in a result as space
3261// delimited XML attributes based on the property key="value" pairs.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003262String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3263 const TestResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003264 Message attributes;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003265 for (int i = 0; i < result.test_property_count(); ++i) {
3266 const TestProperty& property = result.GetTestProperty(i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003267 attributes << " " << property.key() << "="
3268 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3269 }
3270 return attributes.GetString();
3271}
3272
3273// End XmlUnitTestResultPrinter
3274
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003275// Class ScopedTrace
3276
3277// Pushes the given source file location and message onto a per-thread
3278// trace stack maintained by Google Test.
3279// L < UnitTest::mutex_
3280ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3281 TraceInfo trace;
3282 trace.file = file;
3283 trace.line = line;
3284 trace.message = message.GetString();
3285
3286 UnitTest::GetInstance()->PushGTestTrace(trace);
3287}
3288
3289// Pops the info pushed by the c'tor.
3290// L < UnitTest::mutex_
3291ScopedTrace::~ScopedTrace() {
3292 UnitTest::GetInstance()->PopGTestTrace();
3293}
3294
3295
3296// class OsStackTraceGetter
3297
3298// Returns the current OS stack trace as a String. Parameters:
3299//
3300// max_depth - the maximum number of stack frames to be included
3301// in the trace.
3302// skip_count - the number of top frames to be skipped; doesn't count
3303// against max_depth.
3304//
3305// L < mutex_
3306// We use "L < mutex_" to denote that the function may acquire mutex_.
3307String OsStackTraceGetter::CurrentStackTrace(int, int) {
3308 return String("");
3309}
3310
3311// L < mutex_
3312void OsStackTraceGetter::UponLeavingGTest() {
3313}
3314
3315const char* const
3316OsStackTraceGetter::kElidedFramesMarker =
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003317 "... " GTEST_NAME_ " internal frames ...";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003318
3319} // namespace internal
3320
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003321// class TestEventListeners
3322
3323TestEventListeners::TestEventListeners()
3324 : repeater_(new internal::TestEventRepeater()),
3325 default_result_printer_(NULL),
3326 default_xml_generator_(NULL) {
3327}
3328
3329TestEventListeners::~TestEventListeners() { delete repeater_; }
3330
3331// Returns the standard listener responsible for the default console
3332// output. Can be removed from the listeners list to shut down default
3333// console output. Note that removing this object from the listener list
3334// with Release transfers its ownership to the user.
3335void TestEventListeners::Append(TestEventListener* listener) {
3336 repeater_->Append(listener);
3337}
3338
3339// Removes the given event listener from the list and returns it. It then
3340// becomes the caller's responsibility to delete the listener. Returns
3341// NULL if the listener is not found in the list.
3342TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3343 if (listener == default_result_printer_)
3344 default_result_printer_ = NULL;
3345 else if (listener == default_xml_generator_)
3346 default_xml_generator_ = NULL;
3347 return repeater_->Release(listener);
3348}
3349
3350// Returns repeater that broadcasts the TestEventListener events to all
3351// subscribers.
3352TestEventListener* TestEventListeners::repeater() { return repeater_; }
3353
3354// Sets the default_result_printer attribute to the provided listener.
3355// The listener is also added to the listener list and previous
3356// default_result_printer is removed from it and deleted. The listener can
3357// also be NULL in which case it will not be added to the list. Does
3358// nothing if the previous and the current listener objects are the same.
3359void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3360 if (default_result_printer_ != listener) {
3361 // It is an error to pass this method a listener that is already in the
3362 // list.
3363 delete Release(default_result_printer_);
3364 default_result_printer_ = listener;
3365 if (listener != NULL)
3366 Append(listener);
3367 }
3368}
3369
3370// Sets the default_xml_generator attribute to the provided listener. The
3371// listener is also added to the listener list and previous
3372// default_xml_generator is removed from it and deleted. The listener can
3373// also be NULL in which case it will not be added to the list. Does
3374// nothing if the previous and the current listener objects are the same.
3375void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3376 if (default_xml_generator_ != listener) {
3377 // It is an error to pass this method a listener that is already in the
3378 // list.
3379 delete Release(default_xml_generator_);
3380 default_xml_generator_ = listener;
3381 if (listener != NULL)
3382 Append(listener);
3383 }
3384}
3385
3386// Controls whether events will be forwarded by the repeater to the
3387// listeners in the list.
3388bool TestEventListeners::EventForwardingEnabled() const {
3389 return repeater_->forwarding_enabled();
3390}
3391
3392void TestEventListeners::SuppressEventForwarding() {
3393 repeater_->set_forwarding_enabled(false);
3394}
3395
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003396// class UnitTest
3397
3398// Gets the singleton UnitTest object. The first time this method is
3399// called, a UnitTest object is constructed and returned. Consecutive
3400// calls will return the same object.
3401//
3402// We don't protect this under mutex_ as a user is not supposed to
3403// call this before main() starts, from which point on the return
3404// value will never change.
3405UnitTest * UnitTest::GetInstance() {
3406 // When compiled with MSVC 7.1 in optimized mode, destroying the
3407 // UnitTest object upon exiting the program messes up the exit code,
3408 // causing successful tests to appear failed. We have to use a
3409 // different implementation in this case to bypass the compiler bug.
3410 // This implementation makes the compiler happy, at the cost of
3411 // leaking the UnitTest object.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003412
3413 // CodeGear C++Builder insists on a public destructor for the
3414 // default implementation. Use this implementation to keep good OO
3415 // design with private destructor.
3416
3417#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003418 static UnitTest* const instance = new UnitTest;
3419 return instance;
3420#else
3421 static UnitTest instance;
3422 return &instance;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003423#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3424}
3425
3426// Gets the number of successful test cases.
3427int UnitTest::successful_test_case_count() const {
3428 return impl()->successful_test_case_count();
3429}
3430
3431// Gets the number of failed test cases.
3432int UnitTest::failed_test_case_count() const {
3433 return impl()->failed_test_case_count();
3434}
3435
3436// Gets the number of all test cases.
3437int UnitTest::total_test_case_count() const {
3438 return impl()->total_test_case_count();
3439}
3440
3441// Gets the number of all test cases that contain at least one test
3442// that should run.
3443int UnitTest::test_case_to_run_count() const {
3444 return impl()->test_case_to_run_count();
3445}
3446
3447// Gets the number of successful tests.
3448int UnitTest::successful_test_count() const {
3449 return impl()->successful_test_count();
3450}
3451
3452// Gets the number of failed tests.
3453int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3454
3455// Gets the number of disabled tests.
3456int UnitTest::disabled_test_count() const {
3457 return impl()->disabled_test_count();
3458}
3459
3460// Gets the number of all tests.
3461int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3462
3463// Gets the number of tests that should run.
3464int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3465
3466// Gets the elapsed time, in milliseconds.
3467internal::TimeInMillis UnitTest::elapsed_time() const {
3468 return impl()->elapsed_time();
3469}
3470
3471// Returns true iff the unit test passed (i.e. all test cases passed).
3472bool UnitTest::Passed() const { return impl()->Passed(); }
3473
3474// Returns true iff the unit test failed (i.e. some test case failed
3475// or something outside of all tests failed).
3476bool UnitTest::Failed() const { return impl()->Failed(); }
3477
3478// Gets the i-th test case among all the test cases. i can range from 0 to
3479// total_test_case_count() - 1. If i is not in that range, returns NULL.
3480const TestCase* UnitTest::GetTestCase(int i) const {
3481 return impl()->GetTestCase(i);
3482}
3483
3484// Gets the i-th test case among all the test cases. i can range from 0 to
3485// total_test_case_count() - 1. If i is not in that range, returns NULL.
3486TestCase* UnitTest::GetMutableTestCase(int i) {
3487 return impl()->GetMutableTestCase(i);
3488}
3489
3490// Returns the list of event listeners that can be used to track events
3491// inside Google Test.
3492TestEventListeners& UnitTest::listeners() {
3493 return *impl()->listeners();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003494}
3495
3496// Registers and returns a global test environment. When a test
3497// program is run, all global test environments will be set-up in the
3498// order they were registered. After all tests in the program have
3499// finished, all global test environments will be torn-down in the
3500// *reverse* order they were registered.
3501//
3502// The UnitTest object takes ownership of the given environment.
3503//
3504// We don't protect this under mutex_, as we only support calling it
3505// from the main thread.
3506Environment* UnitTest::AddEnvironment(Environment* env) {
3507 if (env == NULL) {
3508 return NULL;
3509 }
3510
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003511 impl_->environments().push_back(env);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003512 return env;
3513}
3514
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003515#if GTEST_HAS_EXCEPTIONS
3516// A failed Google Test assertion will throw an exception of this type
3517// when exceptions are enabled. We derive it from std::runtime_error,
3518// which is for errors presumably detectable only at run time. Since
3519// std::runtime_error inherits from std::exception, many testing
3520// frameworks know how to extract and print the message inside it.
3521class GoogleTestFailureException : public ::std::runtime_error {
3522 public:
3523 explicit GoogleTestFailureException(const TestPartResult& failure)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003524 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003525};
3526#endif
3527
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003528// Adds a TestPartResult to the current TestResult object. All Google Test
3529// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3530// this to report their results. The user code should use the
3531// assertion macros instead of calling this directly.
3532// L < mutex_
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003533void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003534 const char* file_name,
3535 int line_number,
3536 const internal::String& message,
3537 const internal::String& os_stack_trace) {
3538 Message msg;
3539 msg << message;
3540
3541 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003542 if (impl_->gtest_trace_stack().size() > 0) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003543 msg << "\n" << GTEST_NAME_ << " trace:";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003544
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003545 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
3546 i > 0; --i) {
3547 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003548 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3549 << " " << trace.message;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003550 }
3551 }
3552
3553 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3554 msg << internal::kStackTraceMarker << os_stack_trace;
3555 }
3556
3557 const TestPartResult result =
3558 TestPartResult(result_type, file_name, line_number,
3559 msg.GetString().c_str());
3560 impl_->GetTestPartResultReporterForCurrentThread()->
3561 ReportTestPartResult(result);
3562
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003563 if (result_type != TestPartResult::kSuccess) {
3564 // gtest_break_on_failure takes precedence over
3565 // gtest_throw_on_failure. This allows a user to set the latter
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003566 // in the code (perhaps in order to use Google Test assertions
3567 // with another testing framework) and specify the former on the
3568 // command line for debugging.
3569 if (GTEST_FLAG(break_on_failure)) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003570#if GTEST_OS_WINDOWS
3571 // Using DebugBreak on Windows allows gtest to still break into a debugger
3572 // when a failure happens and both the --gtest_break_on_failure and
3573 // the --gtest_catch_exceptions flags are specified.
3574 DebugBreak();
3575#else
Jakob Stoklund Olesena70282d2010-07-12 18:17:47 +00003576 abort();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003577#endif // GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003578 } else if (GTEST_FLAG(throw_on_failure)) {
3579#if GTEST_HAS_EXCEPTIONS
3580 throw GoogleTestFailureException(result);
3581#else
3582 // We cannot call abort() as it generates a pop-up in debug mode
3583 // that cannot be suppressed in VC 7.1 or below.
3584 exit(1);
3585#endif
3586 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003587 }
3588}
3589
3590// Creates and adds a property to the current TestResult. If a property matching
3591// the supplied value already exists, updates its value instead.
3592void UnitTest::RecordPropertyForCurrentTest(const char* key,
3593 const char* value) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003594 const TestProperty test_property(key, value);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003595 impl_->current_test_result()->RecordProperty(test_property);
3596}
3597
3598// Runs all tests in this UnitTest object and prints the result.
3599// Returns 0 if successful, or 1 otherwise.
3600//
3601// We don't protect this under mutex_, as we only support calling it
3602// from the main thread.
3603int UnitTest::Run() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003604#if GTEST_HAS_SEH
3605 // Catch SEH-style exceptions.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003606
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003607 const bool in_death_test_child_process =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003608 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003609
3610 // Either the user wants Google Test to catch exceptions thrown by the
3611 // tests or this is executing in the context of death test child
3612 // process. In either case the user does not want to see pop-up dialogs
3613 // about crashes - they are expected..
3614 if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003615#if !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003616 // SetErrorMode doesn't exist on CE.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003617 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3618 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003619#endif // !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003620
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003621#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003622 // Death test children can be terminated with _abort(). On Windows,
3623 // _abort() can show a dialog with a warning message. This forces the
3624 // abort message to go to stderr instead.
3625 _set_error_mode(_OUT_TO_STDERR);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003626#endif
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003627
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003628#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003629 // In the debug version, Visual Studio pops up a separate dialog
3630 // offering a choice to debug the aborted program. We need to suppress
3631 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3632 // executed. Google Test will notify the user of any unexpected
3633 // failure via stderr.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003634 //
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003635 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3636 // Users of prior VC versions shall suffer the agony and pain of
3637 // clicking through the countless debug dialogs.
3638 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3639 // debug mode when compiled with VC 7.1 or lower.
3640 if (!GTEST_FLAG(break_on_failure))
3641 _set_abort_behavior(
3642 0x0, // Clear the following flags:
3643 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003644#endif
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003645 }
3646
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003647 __try {
3648 return impl_->RunAllTests();
3649 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3650 GetExceptionCode())) {
3651 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3652 fflush(stdout);
3653 return 1;
3654 }
3655
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003656#else // We are on a compiler or platform that doesn't support SEH.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003657
3658 return impl_->RunAllTests();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003659#endif // GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003660}
3661
3662// Returns the working directory when the first TEST() or TEST_F() was
3663// executed.
3664const char* UnitTest::original_working_dir() const {
3665 return impl_->original_working_dir_.c_str();
3666}
3667
3668// Returns the TestCase object for the test that's currently running,
3669// or NULL if no test is running.
3670// L < mutex_
3671const TestCase* UnitTest::current_test_case() const {
3672 internal::MutexLock lock(&mutex_);
3673 return impl_->current_test_case();
3674}
3675
3676// Returns the TestInfo object for the test that's currently running,
3677// or NULL if no test is running.
3678// L < mutex_
3679const TestInfo* UnitTest::current_test_info() const {
3680 internal::MutexLock lock(&mutex_);
3681 return impl_->current_test_info();
3682}
3683
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003684// Returns the random seed used at the start of the current test run.
3685int UnitTest::random_seed() const { return impl_->random_seed(); }
3686
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003687#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003688// Returns ParameterizedTestCaseRegistry object used to keep track of
3689// value-parameterized tests and instantiate and register them.
3690// L < mutex_
3691internal::ParameterizedTestCaseRegistry&
3692 UnitTest::parameterized_test_registry() {
3693 return impl_->parameterized_test_registry();
3694}
3695#endif // GTEST_HAS_PARAM_TEST
3696
3697// Creates an empty UnitTest.
3698UnitTest::UnitTest() {
3699 impl_ = new internal::UnitTestImpl(this);
3700}
3701
3702// Destructor of UnitTest.
3703UnitTest::~UnitTest() {
3704 delete impl_;
3705}
3706
3707// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3708// Google Test trace stack.
3709// L < mutex_
3710void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3711 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003712 impl_->gtest_trace_stack().push_back(trace);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003713}
3714
3715// Pops a trace from the per-thread Google Test trace stack.
3716// L < mutex_
3717void UnitTest::PopGTestTrace() {
3718 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003719 impl_->gtest_trace_stack().pop_back();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003720}
3721
3722namespace internal {
3723
3724UnitTestImpl::UnitTestImpl(UnitTest* parent)
3725 : parent_(parent),
3726#ifdef _MSC_VER
3727#pragma warning(push) // Saves the current warning state.
3728#pragma warning(disable:4355) // Temporarily disables warning 4355
3729 // (using this in initializer).
3730 default_global_test_part_result_reporter_(this),
3731 default_per_thread_test_part_result_reporter_(this),
3732#pragma warning(pop) // Restores the warning state again.
3733#else
3734 default_global_test_part_result_reporter_(this),
3735 default_per_thread_test_part_result_reporter_(this),
3736#endif // _MSC_VER
3737 global_test_part_result_repoter_(
3738 &default_global_test_part_result_reporter_),
3739 per_thread_test_part_result_reporter_(
3740 &default_per_thread_test_part_result_reporter_),
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003741#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003742 parameterized_test_registry_(),
3743 parameterized_tests_registered_(false),
3744#endif // GTEST_HAS_PARAM_TEST
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003745 last_death_test_case_(-1),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003746 current_test_case_(NULL),
3747 current_test_info_(NULL),
3748 ad_hoc_test_result_(),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003749 os_stack_trace_getter_(NULL),
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003750 post_flag_parse_init_performed_(false),
3751 random_seed_(0), // Will be overridden by the flag before first use.
3752 random_(0), // Will be reseeded before first use.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003753#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003754 elapsed_time_(0),
3755 internal_run_death_test_flag_(NULL),
3756 death_test_factory_(new DefaultDeathTestFactory) {
3757#else
3758 elapsed_time_(0) {
3759#endif // GTEST_HAS_DEATH_TEST
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003760 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003761}
3762
3763UnitTestImpl::~UnitTestImpl() {
3764 // Deletes every TestCase.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003765 ForEach(test_cases_, internal::Delete<TestCase>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003766
3767 // Deletes every Environment.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003768 ForEach(environments_, internal::Delete<Environment>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003769
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003770 delete os_stack_trace_getter_;
3771}
3772
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003773#if GTEST_HAS_DEATH_TEST
3774// Disables event forwarding if the control is currently in a death test
3775// subprocess. Must not be called before InitGoogleTest.
3776void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3777 if (internal_run_death_test_flag_.get() != NULL)
3778 listeners()->SuppressEventForwarding();
3779}
3780#endif // GTEST_HAS_DEATH_TEST
3781
3782// Initializes event listeners performing XML output as specified by
3783// UnitTestOptions. Must not be called before InitGoogleTest.
3784void UnitTestImpl::ConfigureXmlOutput() {
3785 const String& output_format = UnitTestOptions::GetOutputFormat();
3786 if (output_format == "xml") {
3787 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3788 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3789 } else if (output_format != "") {
3790 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3791 output_format.c_str());
3792 fflush(stdout);
3793 }
3794}
3795
3796// Performs initialization dependent upon flag values obtained in
3797// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
3798// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
3799// this function is also called from RunAllTests. Since this function can be
3800// called more than once, it has to be idempotent.
3801void UnitTestImpl::PostFlagParsingInit() {
3802 // Ensures that this function does not execute more than once.
3803 if (!post_flag_parse_init_performed_) {
3804 post_flag_parse_init_performed_ = true;
3805
3806#if GTEST_HAS_DEATH_TEST
3807 InitDeathTestSubprocessControlInfo();
3808 SuppressTestEventsIfInSubprocess();
3809#endif // GTEST_HAS_DEATH_TEST
3810
3811 // Registers parameterized tests. This makes parameterized tests
3812 // available to the UnitTest reflection API without running
3813 // RUN_ALL_TESTS.
3814 RegisterParameterizedTests();
3815
3816 // Configures listeners for XML output. This makes it possible for users
3817 // to shut down the default XML output before invoking RUN_ALL_TESTS.
3818 ConfigureXmlOutput();
3819 }
3820}
3821
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003822// A predicate that checks the name of a TestCase against a known
3823// value.
3824//
3825// This is used for implementation of the UnitTest class only. We put
3826// it in the anonymous namespace to prevent polluting the outer
3827// namespace.
3828//
3829// TestCaseNameIs is copyable.
3830class TestCaseNameIs {
3831 public:
3832 // Constructor.
3833 explicit TestCaseNameIs(const String& name)
3834 : name_(name) {}
3835
3836 // Returns true iff the name of test_case matches name_.
3837 bool operator()(const TestCase* test_case) const {
3838 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3839 }
3840
3841 private:
3842 String name_;
3843};
3844
3845// Finds and returns a TestCase with the given name. If one doesn't
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003846// exist, creates one and returns it. It's the CALLER'S
3847// RESPONSIBILITY to ensure that this function is only called WHEN THE
3848// TESTS ARE NOT SHUFFLED.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003849//
3850// Arguments:
3851//
3852// test_case_name: name of the test case
3853// set_up_tc: pointer to the function that sets up the test case
3854// tear_down_tc: pointer to the function that tears down the test case
3855TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3856 const char* comment,
3857 Test::SetUpTestCaseFunc set_up_tc,
3858 Test::TearDownTestCaseFunc tear_down_tc) {
3859 // Can we find a TestCase with the given name?
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003860 const std::vector<TestCase*>::const_iterator test_case =
3861 std::find_if(test_cases_.begin(), test_cases_.end(),
3862 TestCaseNameIs(test_case_name));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003863
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003864 if (test_case != test_cases_.end())
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003865 return *test_case;
3866
3867 // No. Let's create one.
3868 TestCase* const new_test_case =
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003869 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3870
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003871 // Is this a death test case?
3872 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3873 kDeathTestCaseFilter)) {
3874 // Yes. Inserts the test case after the last death test case
3875 // defined so far. This only works when the test cases haven't
3876 // been shuffled. Otherwise we may end up running a death test
3877 // after a non-death test.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003878 ++last_death_test_case_;
3879 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
3880 new_test_case);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003881 } else {
3882 // No. Appends to the end of the list.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003883 test_cases_.push_back(new_test_case);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003884 }
3885
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003886 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003887 return new_test_case;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003888}
3889
3890// Helpers for setting up / tearing down the given environment. They
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003891// are for use in the ForEach() function.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003892static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3893static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3894
3895// Runs all tests in this UnitTest object, prints the result, and
3896// returns 0 if all tests are successful, or 1 otherwise. If any
3897// exception is thrown during a test on Windows, this test is
3898// considered to be failed, but the rest of the tests will still be
3899// run. (We disable exceptions on Linux and Mac OS X, so the issue
3900// doesn't apply there.)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003901// When parameterized tests are enabled, it expands and registers
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003902// parameterized tests first in RegisterParameterizedTests().
3903// All other functions called from RunAllTests() may safely assume that
3904// parameterized tests are ready to be counted and run.
3905int UnitTestImpl::RunAllTests() {
3906 // Makes sure InitGoogleTest() was called.
3907 if (!GTestIsInitialized()) {
3908 printf("%s",
3909 "\nThis test program did NOT call ::testing::InitGoogleTest "
3910 "before calling RUN_ALL_TESTS(). Please fix it.\n");
3911 return 1;
3912 }
3913
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003914 // Do not run any test if the --help flag was specified.
3915 if (g_help_flag)
3916 return 0;
3917
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003918 // Repeats the call to the post-flag parsing initialization in case the
3919 // user didn't call InitGoogleTest.
3920 PostFlagParsingInit();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003921
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003922 // Even if sharding is not on, test runners may want to use the
3923 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3924 // protocol.
3925 internal::WriteToShardStatusFileIfNeeded();
3926
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003927 // True iff we are in a subprocess for running a thread-safe-style
3928 // death test.
3929 bool in_subprocess_for_death_test = false;
3930
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003931#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003932 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3933#endif // GTEST_HAS_DEATH_TEST
3934
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003935 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3936 in_subprocess_for_death_test);
3937
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003938 // Compares the full test names with the filter to decide which
3939 // tests to run.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003940 const bool has_tests_to_run = FilterTests(should_shard
3941 ? HONOR_SHARDING_PROTOCOL
3942 : IGNORE_SHARDING_PROTOCOL) > 0;
3943
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003944 // Lists the tests and exits if the --gtest_list_tests flag was specified.
3945 if (GTEST_FLAG(list_tests)) {
3946 // This must be called *after* FilterTests() has been called.
3947 ListTestsMatchingFilter();
3948 return 0;
3949 }
3950
3951 random_seed_ = GTEST_FLAG(shuffle) ?
3952 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3953
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003954 // True iff at least one test has failed.
3955 bool failed = false;
3956
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003957 TestEventListener* repeater = listeners()->repeater();
3958
3959 repeater->OnTestProgramStart(*parent_);
3960
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003961 // How many times to repeat the tests? We don't want to repeat them
3962 // when we are inside the subprocess of a death test.
3963 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3964 // Repeats forever if the repeat count is negative.
3965 const bool forever = repeat < 0;
3966 for (int i = 0; forever || i != repeat; i++) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003967 ClearResult();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003968
3969 const TimeInMillis start = GetTimeInMillis();
3970
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003971 // Shuffles test cases and tests if requested.
3972 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
3973 random()->Reseed(random_seed_);
3974 // This should be done before calling OnTestIterationStart(),
3975 // such that a test event listener can see the actual test order
3976 // in the event.
3977 ShuffleTests();
3978 }
3979
3980 // Tells the unit test event listeners that the tests are about to start.
3981 repeater->OnTestIterationStart(*parent_, i);
3982
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003983 // Runs each test case if there is at least one test to run.
3984 if (has_tests_to_run) {
3985 // Sets up all environments beforehand.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003986 repeater->OnEnvironmentsSetUpStart(*parent_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003987 ForEach(environments_, SetUpEnvironment);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003988 repeater->OnEnvironmentsSetUpEnd(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003989
3990 // Runs the tests only if there was no fatal failure during global
3991 // set-up.
3992 if (!Test::HasFatalFailure()) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003993 for (int test_index = 0; test_index < total_test_case_count();
3994 test_index++) {
3995 GetMutableTestCase(test_index)->Run();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003996 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003997 }
3998
3999 // Tears down all environments in reverse order afterwards.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004000 repeater->OnEnvironmentsTearDownStart(*parent_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004001 std::for_each(environments_.rbegin(), environments_.rend(),
4002 TearDownEnvironment);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004003 repeater->OnEnvironmentsTearDownEnd(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004004 }
4005
4006 elapsed_time_ = GetTimeInMillis() - start;
4007
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004008 // Tells the unit test event listener that the tests have just finished.
4009 repeater->OnTestIterationEnd(*parent_, i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004010
4011 // Gets the result and clears it.
4012 if (!Passed()) {
4013 failed = true;
4014 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004015
4016 // Restores the original test order after the iteration. This
4017 // allows the user to quickly repro a failure that happens in the
4018 // N-th iteration without repeating the first (N - 1) iterations.
4019 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4020 // case the user somehow changes the value of the flag somewhere
4021 // (it's always safe to unshuffle the tests).
4022 UnshuffleTests();
4023
4024 if (GTEST_FLAG(shuffle)) {
4025 // Picks a new random seed for each iteration.
4026 random_seed_ = GetNextRandomSeed(random_seed_);
4027 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004028 }
4029
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004030 repeater->OnTestProgramEnd(*parent_);
4031
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004032 // Returns 0 if all tests passed, or 1 other wise.
4033 return failed ? 1 : 0;
4034}
4035
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004036// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4037// if the variable is present. If a file already exists at this location, this
4038// function will write over it. If the variable is present, but the file cannot
4039// be created, prints an error and exits.
4040void WriteToShardStatusFileIfNeeded() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004041 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004042 if (test_shard_file != NULL) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004043 FILE* const file = posix::FOpen(test_shard_file, "w");
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004044 if (file == NULL) {
4045 ColoredPrintf(COLOR_RED,
4046 "Could not write to the test shard status file \"%s\" "
4047 "specified by the %s environment variable.\n",
4048 test_shard_file, kTestShardStatusFile);
4049 fflush(stdout);
4050 exit(EXIT_FAILURE);
4051 }
4052 fclose(file);
4053 }
4054}
4055
4056// Checks whether sharding is enabled by examining the relevant
4057// environment variable values. If the variables are present,
4058// but inconsistent (i.e., shard_index >= total_shards), prints
4059// an error and exits. If in_subprocess_for_death_test, sharding is
4060// disabled because it must only be applied to the original test
4061// process. Otherwise, we could filter out death tests we intended to execute.
4062bool ShouldShard(const char* total_shards_env,
4063 const char* shard_index_env,
4064 bool in_subprocess_for_death_test) {
4065 if (in_subprocess_for_death_test) {
4066 return false;
4067 }
4068
4069 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4070 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4071
4072 if (total_shards == -1 && shard_index == -1) {
4073 return false;
4074 } else if (total_shards == -1 && shard_index != -1) {
4075 const Message msg = Message()
4076 << "Invalid environment variables: you have "
4077 << kTestShardIndex << " = " << shard_index
4078 << ", but have left " << kTestTotalShards << " unset.\n";
4079 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4080 fflush(stdout);
4081 exit(EXIT_FAILURE);
4082 } else if (total_shards != -1 && shard_index == -1) {
4083 const Message msg = Message()
4084 << "Invalid environment variables: you have "
4085 << kTestTotalShards << " = " << total_shards
4086 << ", but have left " << kTestShardIndex << " unset.\n";
4087 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4088 fflush(stdout);
4089 exit(EXIT_FAILURE);
4090 } else if (shard_index < 0 || shard_index >= total_shards) {
4091 const Message msg = Message()
4092 << "Invalid environment variables: we require 0 <= "
4093 << kTestShardIndex << " < " << kTestTotalShards
4094 << ", but you have " << kTestShardIndex << "=" << shard_index
4095 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4096 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4097 fflush(stdout);
4098 exit(EXIT_FAILURE);
4099 }
4100
4101 return total_shards > 1;
4102}
4103
4104// Parses the environment variable var as an Int32. If it is unset,
4105// returns default_val. If it is not an Int32, prints an error
4106// and aborts.
4107Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004108 const char* str_val = posix::GetEnv(var);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004109 if (str_val == NULL) {
4110 return default_val;
4111 }
4112
4113 Int32 result;
4114 if (!ParseInt32(Message() << "The value of environment variable " << var,
4115 str_val, &result)) {
4116 exit(EXIT_FAILURE);
4117 }
4118 return result;
4119}
4120
4121// Given the total number of shards, the shard index, and the test id,
4122// returns true iff the test should be run on this shard. The test id is
4123// some arbitrary but unique non-negative integer assigned to each test
4124// method. Assumes that 0 <= shard_index < total_shards.
4125bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4126 return (test_id % total_shards) == shard_index;
4127}
4128
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004129// Compares the name of each test with the user-specified filter to
4130// decide whether the test should be run, then records the result in
4131// each TestCase and TestInfo object.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004132// If shard_tests == true, further filters tests based on sharding
4133// variables in the environment - see
4134// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004135// Returns the number of tests that should run.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004136int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4137 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4138 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4139 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4140 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4141
4142 // num_runnable_tests are the number of tests that will
4143 // run across all shards (i.e., match filter and are not disabled).
4144 // num_selected_tests are the number of tests to be run on
4145 // this shard.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004146 int num_runnable_tests = 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004147 int num_selected_tests = 0;
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004148 for (size_t i = 0; i < test_cases_.size(); i++) {
4149 TestCase* const test_case = test_cases_[i];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004150 const String &test_case_name = test_case->name();
4151 test_case->set_should_run(false);
4152
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004153 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4154 TestInfo* const test_info = test_case->test_info_list()[j];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004155 const String test_name(test_info->name());
4156 // A test is disabled if test case name or test name matches
4157 // kDisableTestFilter.
4158 const bool is_disabled =
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004159 internal::UnitTestOptions::MatchesFilter(test_case_name,
4160 kDisableTestFilter) ||
4161 internal::UnitTestOptions::MatchesFilter(test_name,
4162 kDisableTestFilter);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004163 test_info->impl()->set_is_disabled(is_disabled);
4164
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004165 const bool matches_filter =
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004166 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4167 test_name);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004168 test_info->impl()->set_matches_filter(matches_filter);
4169
4170 const bool is_runnable =
4171 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4172 matches_filter;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004173
4174 const bool is_selected = is_runnable &&
4175 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4176 ShouldRunTestOnShard(total_shards, shard_index,
4177 num_runnable_tests));
4178
4179 num_runnable_tests += is_runnable;
4180 num_selected_tests += is_selected;
4181
4182 test_info->impl()->set_should_run(is_selected);
4183 test_case->set_should_run(test_case->should_run() || is_selected);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004184 }
4185 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004186 return num_selected_tests;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004187}
4188
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004189// Prints the names of the tests matching the user-specified filter flag.
4190void UnitTestImpl::ListTestsMatchingFilter() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004191 for (size_t i = 0; i < test_cases_.size(); i++) {
4192 const TestCase* const test_case = test_cases_[i];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004193 bool printed_test_case_name = false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004194
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004195 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004196 const TestInfo* const test_info =
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004197 test_case->test_info_list()[j];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004198 if (test_info->matches_filter()) {
4199 if (!printed_test_case_name) {
4200 printed_test_case_name = true;
4201 printf("%s.\n", test_case->name());
4202 }
4203 printf(" %s\n", test_info->name());
4204 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004205 }
4206 }
4207 fflush(stdout);
4208}
4209
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004210// Sets the OS stack trace getter.
4211//
4212// Does nothing if the input and the current OS stack trace getter are
4213// the same; otherwise, deletes the old getter and makes the input the
4214// current getter.
4215void UnitTestImpl::set_os_stack_trace_getter(
4216 OsStackTraceGetterInterface* getter) {
4217 if (os_stack_trace_getter_ != getter) {
4218 delete os_stack_trace_getter_;
4219 os_stack_trace_getter_ = getter;
4220 }
4221}
4222
4223// Returns the current OS stack trace getter if it is not NULL;
4224// otherwise, creates an OsStackTraceGetter, makes it the current
4225// getter, and returns it.
4226OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4227 if (os_stack_trace_getter_ == NULL) {
4228 os_stack_trace_getter_ = new OsStackTraceGetter;
4229 }
4230
4231 return os_stack_trace_getter_;
4232}
4233
4234// Returns the TestResult for the test that's currently running, or
4235// the TestResult for the ad hoc test if no test is running.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004236TestResult* UnitTestImpl::current_test_result() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004237 return current_test_info_ ?
4238 current_test_info_->impl()->result() : &ad_hoc_test_result_;
4239}
4240
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004241// Shuffles all test cases, and the tests within each test case,
4242// making sure that death tests are still run first.
4243void UnitTestImpl::ShuffleTests() {
4244 // Shuffles the death test cases.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004245 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004246
4247 // Shuffles the non-death test cases.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004248 ShuffleRange(random(), last_death_test_case_ + 1,
4249 static_cast<int>(test_cases_.size()), &test_case_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004250
4251 // Shuffles the tests inside each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004252 for (size_t i = 0; i < test_cases_.size(); i++) {
4253 test_cases_[i]->ShuffleTests(random());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004254 }
4255}
4256
4257// Restores the test cases and tests to their order before the first shuffle.
4258void UnitTestImpl::UnshuffleTests() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004259 for (size_t i = 0; i < test_cases_.size(); i++) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004260 // Unshuffles the tests in each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004261 test_cases_[i]->UnshuffleTests();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004262 // Resets the index of each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004263 test_case_indices_[i] = static_cast<int>(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004264 }
4265}
4266
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004267// TestInfoImpl constructor. The new instance assumes ownership of the test
4268// factory object.
4269TestInfoImpl::TestInfoImpl(TestInfo* parent,
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004270 const char* a_test_case_name,
4271 const char* a_name,
4272 const char* a_test_case_comment,
4273 const char* a_comment,
4274 TypeId a_fixture_class_id,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004275 internal::TestFactoryBase* factory) :
4276 parent_(parent),
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004277 test_case_name_(String(a_test_case_name)),
4278 name_(String(a_name)),
4279 test_case_comment_(String(a_test_case_comment)),
4280 comment_(String(a_comment)),
4281 fixture_class_id_(a_fixture_class_id),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004282 should_run_(false),
4283 is_disabled_(false),
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004284 matches_filter_(false),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004285 factory_(factory) {
4286}
4287
4288// TestInfoImpl destructor.
4289TestInfoImpl::~TestInfoImpl() {
4290 delete factory_;
4291}
4292
4293// Returns the current OS stack trace as a String.
4294//
4295// The maximum number of stack frames to be included is specified by
4296// the gtest_stack_trace_depth flag. The skip_count parameter
4297// specifies the number of top frames to be skipped, which doesn't
4298// count against the number of frames to be included.
4299//
4300// For example, if Foo() calls Bar(), which in turn calls
4301// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4302// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004303String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4304 int skip_count) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004305 // We pass skip_count + 1 to skip this wrapper function in addition
4306 // to what the user really wants to skip.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004307 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004308}
4309
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004310// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4311// code warnings.
4312namespace {
4313class ClassUniqueToAlwaysTrue {};
4314}
4315
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004316bool IsTrue(bool condition) { return condition; }
4317
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004318bool AlwaysTrue() {
4319#if GTEST_HAS_EXCEPTIONS
4320 // This condition is always false so AlwaysTrue() never actually throws,
4321 // but it makes the compiler think that it may throw.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004322 if (IsTrue(false))
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004323 throw ClassUniqueToAlwaysTrue();
4324#endif // GTEST_HAS_EXCEPTIONS
4325 return true;
4326}
4327
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004328// If *pstr starts with the given prefix, modifies *pstr to be right
4329// past the prefix and returns true; otherwise leaves *pstr unchanged
4330// and returns false. None of pstr, *pstr, and prefix can be NULL.
4331bool SkipPrefix(const char* prefix, const char** pstr) {
4332 const size_t prefix_len = strlen(prefix);
4333 if (strncmp(*pstr, prefix, prefix_len) == 0) {
4334 *pstr += prefix_len;
4335 return true;
4336 }
4337 return false;
4338}
4339
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004340// Parses a string as a command line flag. The string should have
4341// the format "--flag=value". When def_optional is true, the "=value"
4342// part can be omitted.
4343//
4344// Returns the value of the flag, or NULL if the parsing failed.
4345const char* ParseFlagValue(const char* str,
4346 const char* flag,
4347 bool def_optional) {
4348 // str and flag must not be NULL.
4349 if (str == NULL || flag == NULL) return NULL;
4350
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004351 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4352 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004353 const size_t flag_len = flag_str.length();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004354 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4355
4356 // Skips the flag name.
4357 const char* flag_end = str + flag_len;
4358
4359 // When def_optional is true, it's OK to not have a "=value" part.
4360 if (def_optional && (flag_end[0] == '\0')) {
4361 return flag_end;
4362 }
4363
4364 // If def_optional is true and there are more characters after the
4365 // flag name, or if def_optional is false, there must be a '=' after
4366 // the flag name.
4367 if (flag_end[0] != '=') return NULL;
4368
4369 // Returns the string after "=".
4370 return flag_end + 1;
4371}
4372
4373// Parses a string for a bool flag, in the form of either
4374// "--flag=value" or "--flag".
4375//
4376// In the former case, the value is taken as true as long as it does
4377// not start with '0', 'f', or 'F'.
4378//
4379// In the latter case, the value is taken as true.
4380//
4381// On success, stores the value of the flag in *value, and returns
4382// true. On failure, returns false without changing *value.
4383bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4384 // Gets the value of the flag as a string.
4385 const char* const value_str = ParseFlagValue(str, flag, true);
4386
4387 // Aborts if the parsing failed.
4388 if (value_str == NULL) return false;
4389
4390 // Converts the string value to a bool.
4391 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4392 return true;
4393}
4394
4395// Parses a string for an Int32 flag, in the form of
4396// "--flag=value".
4397//
4398// On success, stores the value of the flag in *value, and returns
4399// true. On failure, returns false without changing *value.
4400bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4401 // Gets the value of the flag as a string.
4402 const char* const value_str = ParseFlagValue(str, flag, false);
4403
4404 // Aborts if the parsing failed.
4405 if (value_str == NULL) return false;
4406
4407 // Sets *value to the value of the flag.
4408 return ParseInt32(Message() << "The value of flag --" << flag,
4409 value_str, value);
4410}
4411
4412// Parses a string for a string flag, in the form of
4413// "--flag=value".
4414//
4415// On success, stores the value of the flag in *value, and returns
4416// true. On failure, returns false without changing *value.
4417bool ParseStringFlag(const char* str, const char* flag, String* value) {
4418 // Gets the value of the flag as a string.
4419 const char* const value_str = ParseFlagValue(str, flag, false);
4420
4421 // Aborts if the parsing failed.
4422 if (value_str == NULL) return false;
4423
4424 // Sets *value to the value of the flag.
4425 *value = value_str;
4426 return true;
4427}
4428
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004429// Determines whether a string has a prefix that Google Test uses for its
4430// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
4431// If Google Test detects that a command line flag has its prefix but is not
4432// recognized, it will print its help message. Flags starting with
4433// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
4434// internal flags and do not trigger the help message.
4435static bool HasGoogleTestFlagPrefix(const char* str) {
4436 return (SkipPrefix("--", &str) ||
4437 SkipPrefix("-", &str) ||
4438 SkipPrefix("/", &str)) &&
4439 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
4440 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
4441 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
4442}
4443
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004444// Prints a string containing code-encoded text. The following escape
4445// sequences can be used in the string to control the text color:
4446//
4447// @@ prints a single '@' character.
4448// @R changes the color to red.
4449// @G changes the color to green.
4450// @Y changes the color to yellow.
4451// @D changes to the default terminal text color.
4452//
4453// TODO(wan@google.com): Write tests for this once we add stdout
4454// capturing to Google Test.
4455static void PrintColorEncoded(const char* str) {
4456 GTestColor color = COLOR_DEFAULT; // The current color.
4457
4458 // Conceptually, we split the string into segments divided by escape
4459 // sequences. Then we print one segment at a time. At the end of
4460 // each iteration, the str pointer advances to the beginning of the
4461 // next segment.
4462 for (;;) {
4463 const char* p = strchr(str, '@');
4464 if (p == NULL) {
4465 ColoredPrintf(color, "%s", str);
4466 return;
4467 }
4468
4469 ColoredPrintf(color, "%s", String(str, p - str).c_str());
4470
4471 const char ch = p[1];
4472 str = p + 2;
4473 if (ch == '@') {
4474 ColoredPrintf(color, "@");
4475 } else if (ch == 'D') {
4476 color = COLOR_DEFAULT;
4477 } else if (ch == 'R') {
4478 color = COLOR_RED;
4479 } else if (ch == 'G') {
4480 color = COLOR_GREEN;
4481 } else if (ch == 'Y') {
4482 color = COLOR_YELLOW;
4483 } else {
4484 --str;
4485 }
4486 }
4487}
4488
4489static const char kColorEncodedHelpMessage[] =
4490"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4491"following command line flags to control its behavior:\n"
4492"\n"
4493"Test Selection:\n"
4494" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4495" List the names of all tests instead of running them. The name of\n"
4496" TEST(Foo, Bar) is \"Foo.Bar\".\n"
4497" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4498 "[@G-@YNEGATIVE_PATTERNS]@D\n"
4499" Run only the tests whose name matches one of the positive patterns but\n"
4500" none of the negative patterns. '?' matches any single character; '*'\n"
4501" matches any substring; ':' separates two patterns.\n"
4502" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4503" Run all disabled tests too.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004504"\n"
4505"Test Execution:\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004506" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4507" Run the tests repeatedly; use a negative count to repeat forever.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004508" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4509" Randomize tests' orders on every iteration.\n"
4510" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4511" Random number seed to use for shuffling test orders (between 1 and\n"
4512" 99999, or 0 to use a seed based on the current time).\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004513"\n"
4514"Test Output:\n"
4515" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4516" Enable/disable colored output. The default is @Gauto@D.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004517" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4518" Don't print the elapsed time of each test.\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004519" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4520 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4521" Generate an XML report in the given directory or with the given file\n"
4522" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4523"\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004524"Assertion Behavior:\n"
4525#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4526" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4527" Set the default death test style.\n"
4528#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004529" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4530" Turn assertion failures into debugger break-points.\n"
4531" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4532" Turn assertion failures into C++ exceptions.\n"
4533#if GTEST_OS_WINDOWS
4534" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4535" Suppress pop-ups caused by exceptions.\n"
4536#endif // GTEST_OS_WINDOWS
4537"\n"
4538"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4539 "the corresponding\n"
4540"environment variable of a flag (all letters in upper-case). For example, to\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004541"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4542 "color=no@D or set\n"
4543"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004544"\n"
4545"For more information, please read the " GTEST_NAME_ " documentation at\n"
4546"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4547"(not one in your own code or tests), please report it to\n"
4548"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4549
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004550// Parses the command line for Google Test flags, without initializing
4551// other parts of Google Test. The type parameter CharType can be
4552// instantiated to either char or wchar_t.
4553template <typename CharType>
4554void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4555 for (int i = 1; i < *argc; i++) {
4556 const String arg_string = StreamableToString(argv[i]);
4557 const char* const arg = arg_string.c_str();
4558
4559 using internal::ParseBoolFlag;
4560 using internal::ParseInt32Flag;
4561 using internal::ParseStringFlag;
4562
4563 // Do we see a Google Test flag?
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004564 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4565 &GTEST_FLAG(also_run_disabled_tests)) ||
4566 ParseBoolFlag(arg, kBreakOnFailureFlag,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004567 &GTEST_FLAG(break_on_failure)) ||
4568 ParseBoolFlag(arg, kCatchExceptionsFlag,
4569 &GTEST_FLAG(catch_exceptions)) ||
4570 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
4571 ParseStringFlag(arg, kDeathTestStyleFlag,
4572 &GTEST_FLAG(death_test_style)) ||
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004573 ParseBoolFlag(arg, kDeathTestUseFork,
4574 &GTEST_FLAG(death_test_use_fork)) ||
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004575 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
4576 ParseStringFlag(arg, kInternalRunDeathTestFlag,
4577 &GTEST_FLAG(internal_run_death_test)) ||
4578 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
4579 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
4580 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004581 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004582 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004583 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004584 ParseInt32Flag(arg, kStackTraceDepthFlag,
4585 &GTEST_FLAG(stack_trace_depth)) ||
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004586 ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure))
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004587 ) {
4588 // Yes. Shift the remainder of the argv list left by one. Note
4589 // that argv has (*argc + 1) elements, the last one always being
4590 // NULL. The following loop moves the trailing NULL element as
4591 // well.
4592 for (int j = i; j != *argc; j++) {
4593 argv[j] = argv[j + 1];
4594 }
4595
4596 // Decrements the argument count.
4597 (*argc)--;
4598
4599 // We also need to decrement the iterator as we just removed
4600 // an element.
4601 i--;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004602 } else if (arg_string == "--help" || arg_string == "-h" ||
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004603 arg_string == "-?" || arg_string == "/?" ||
4604 HasGoogleTestFlagPrefix(arg)) {
4605 // Both help flag and unrecognized Google Test flags (excluding
4606 // internal ones) trigger help display.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004607 g_help_flag = true;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004608 }
4609 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004610
4611 if (g_help_flag) {
4612 // We print the help here instead of in RUN_ALL_TESTS(), as the
4613 // latter may not be called at all if the user is using Google
4614 // Test with another testing framework.
4615 PrintColorEncoded(kColorEncodedHelpMessage);
4616 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004617}
4618
4619// Parses the command line for Google Test flags, without initializing
4620// other parts of Google Test.
4621void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4622 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4623}
4624void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4625 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4626}
4627
4628// The internal implementation of InitGoogleTest().
4629//
4630// The type parameter CharType can be instantiated to either char or
4631// wchar_t.
4632template <typename CharType>
4633void InitGoogleTestImpl(int* argc, CharType** argv) {
4634 g_init_gtest_count++;
4635
4636 // We don't want to run the initialization code twice.
4637 if (g_init_gtest_count != 1) return;
4638
4639 if (*argc <= 0) return;
4640
4641 internal::g_executable_path = internal::StreamableToString(argv[0]);
4642
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004643#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004644 g_argvs.clear();
4645 for (int i = 0; i != *argc; i++) {
4646 g_argvs.push_back(StreamableToString(argv[i]));
4647 }
4648#endif // GTEST_HAS_DEATH_TEST
4649
4650 ParseGoogleTestFlagsOnly(argc, argv);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004651 GetUnitTestImpl()->PostFlagParsingInit();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004652}
4653
4654} // namespace internal
4655
4656// Initializes Google Test. This must be called before calling
4657// RUN_ALL_TESTS(). In particular, it parses a command line for the
4658// flags that Google Test recognizes. Whenever a Google Test flag is
4659// seen, it is removed from argv, and *argc is decremented.
4660//
4661// No value is returned. Instead, the Google Test flag variables are
4662// updated.
4663//
4664// Calling the function for the second time has no user-visible effect.
4665void InitGoogleTest(int* argc, char** argv) {
4666 internal::InitGoogleTestImpl(argc, argv);
4667}
4668
4669// This overloaded version can be used in Windows programs compiled in
4670// UNICODE mode.
4671void InitGoogleTest(int* argc, wchar_t** argv) {
4672 internal::InitGoogleTestImpl(argc, argv);
4673}
4674
4675} // namespace testing