blob: 76244974115e39bd61f2615bb2b6c36da85974b3 [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
Jay Foadb33f8e32011-07-27 09:25:14 +000034#include "gtest/gtest.h"
35#include "gtest/gtest-spi.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +000036
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>
Jay Foadb33f8e32011-07-27 09:25:14 +000046#include <ostream> // NOLINT
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().
Jay Foadb33f8e32011-07-27 09:25:14 +000054# define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +000055
Jay Foadb33f8e32011-07-27 09:25:14 +000056# include <fcntl.h> // NOLINT
57# include <limits.h> // NOLINT
58# include <sched.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000059// Declares vsnprintf(). This header is not available on Windows.
Jay Foadb33f8e32011-07-27 09:25:14 +000060# include <strings.h> // NOLINT
61# include <sys/mman.h> // NOLINT
62# include <sys/time.h> // NOLINT
63# include <unistd.h> // NOLINT
64# include <string>
Misha Brukman7ae6ff42008-12-31 17:34:06 +000065
Benjamin Kramere4b9c932010-06-02 22:01:25 +000066#elif GTEST_OS_SYMBIAN
Jay Foadb33f8e32011-07-27 09:25:14 +000067# define GTEST_HAS_GETTIMEOFDAY_ 1
68# include <sys/time.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000069
Benjamin Kramere4b9c932010-06-02 22:01:25 +000070#elif GTEST_OS_ZOS
Jay Foadb33f8e32011-07-27 09:25:14 +000071# define GTEST_HAS_GETTIMEOFDAY_ 1
72# include <sys/time.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000073
74// On z/OS we additionally need strings.h for strcasecmp.
Jay Foadb33f8e32011-07-27 09:25:14 +000075# include <strings.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000076
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000077#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000078
Jay Foadb33f8e32011-07-27 09:25:14 +000079# include <windows.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000080
Benjamin Kramere4b9c932010-06-02 22:01:25 +000081#elif GTEST_OS_WINDOWS // We are on Windows proper.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000082
Jay Foadb33f8e32011-07-27 09:25:14 +000083# include <io.h> // NOLINT
84# include <sys/timeb.h> // NOLINT
85# include <sys/types.h> // NOLINT
86# include <sys/stat.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +000087
Jay Foadb33f8e32011-07-27 09:25:14 +000088# if GTEST_OS_WINDOWS_MINGW
Misha Brukman7ae6ff42008-12-31 17:34:06 +000089// MinGW has gettimeofday() but not _ftime64().
90// TODO(kenton@google.com): Use autoconf to detect availability of
91// gettimeofday().
92// TODO(kenton@google.com): There are other ways to get the time on
93// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
94// supports these. consider using them instead.
Jay Foadb33f8e32011-07-27 09:25:14 +000095# define GTEST_HAS_GETTIMEOFDAY_ 1
96# include <sys/time.h> // NOLINT
97# endif // GTEST_OS_WINDOWS_MINGW
Misha Brukman7ae6ff42008-12-31 17:34:06 +000098
99// cpplint thinks that the header is already included, so we want to
100// silence it.
Jay Foadb33f8e32011-07-27 09:25:14 +0000101# include <windows.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000102
103#else
104
105// Assume other platforms have gettimeofday().
106// TODO(kenton@google.com): Use autoconf to detect availability of
107// gettimeofday().
Jay Foadb33f8e32011-07-27 09:25:14 +0000108# define GTEST_HAS_GETTIMEOFDAY_ 1
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000109
110// cpplint thinks that the header is already included, so we want to
111// silence it.
Jay Foadb33f8e32011-07-27 09:25:14 +0000112# include <sys/time.h> // NOLINT
113# include <unistd.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000114
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000115#endif // GTEST_OS_LINUX
116
117#if GTEST_HAS_EXCEPTIONS
Jay Foadb33f8e32011-07-27 09:25:14 +0000118# include <stdexcept>
119#endif
120
121#if GTEST_CAN_STREAM_RESULTS_
122# include <arpa/inet.h> // NOLINT
123# include <netdb.h> // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000124#endif
125
126// Indicates that this translation unit is part of Google Test's
127// implementation. It must come before gtest-internal-inl.h is
128// included, or there will be a compiler error. This trick is to
129// prevent a user from accidentally including gtest-internal-inl.h in
130// his code.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000131#define GTEST_IMPLEMENTATION_ 1
Misha Brukmane5f94712009-01-01 02:05:43 +0000132#include "gtest/internal/gtest-internal-inl.h"
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000133#undef GTEST_IMPLEMENTATION_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000134
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000135#if GTEST_OS_WINDOWS
Jay Foadb33f8e32011-07-27 09:25:14 +0000136# define vsnprintf _vsnprintf
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000137#endif // GTEST_OS_WINDOWS
138
139namespace testing {
140
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000141using internal::CountIf;
142using internal::ForEach;
143using internal::GetElementOr;
144using internal::Shuffle;
145
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000146// Constants.
147
148// A test whose test case name or test name matches this filter is
149// disabled and not run.
150static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
151
152// A test case whose name matches this filter is considered a death
153// test case and will be run before test cases whose name doesn't
154// match this filter.
155static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
156
157// A test filter that matches everything.
158static const char kUniversalFilter[] = "*";
159
160// The default output file for XML output.
161static const char kDefaultOutputFile[] = "test_detail.xml";
162
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000163// The environment variable name for the test shard index.
164static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
165// The environment variable name for the total number of test shards.
166static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
167// The environment variable name for the test shard status file.
168static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
169
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000170namespace internal {
171
172// The text used in failure messages to indicate the start of the
173// stack trace.
174const char kStackTraceMarker[] = "\nStack trace:\n";
175
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000176// g_help_flag is true iff the --help flag or an equivalent form is
177// specified on the command line.
178bool g_help_flag = false;
179
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000180} // namespace internal
181
182GTEST_DEFINE_bool_(
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000183 also_run_disabled_tests,
184 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
185 "Run disabled tests too, in addition to the tests normally being run.");
186
187GTEST_DEFINE_bool_(
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000188 break_on_failure,
189 internal::BoolFromGTestEnv("break_on_failure", false),
190 "True iff a failed assertion should be a debugger break-point.");
191
192GTEST_DEFINE_bool_(
193 catch_exceptions,
Jay Foadb33f8e32011-07-27 09:25:14 +0000194 internal::BoolFromGTestEnv("catch_exceptions", true),
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000195 "True iff " GTEST_NAME_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000196 " should catch exceptions and treat them as test failures.");
197
198GTEST_DEFINE_string_(
199 color,
200 internal::StringFromGTestEnv("color", "auto"),
201 "Whether to use colors in the output. Valid values: yes, no, "
202 "and auto. 'auto' means to use colors if the output is "
203 "being sent to a terminal and the TERM environment variable "
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000204 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000205
206GTEST_DEFINE_string_(
207 filter,
208 internal::StringFromGTestEnv("filter", kUniversalFilter),
209 "A colon-separated list of glob (not regex) patterns "
210 "for filtering the tests to run, optionally followed by a "
211 "'-' and a : separated list of negative patterns (tests to "
212 "exclude). A test is run if it matches one of the positive "
213 "patterns and does not match any of the negative patterns.");
214
215GTEST_DEFINE_bool_(list_tests, false,
216 "List all tests without running them.");
217
218GTEST_DEFINE_string_(
219 output,
220 internal::StringFromGTestEnv("output", ""),
221 "A format (currently must be \"xml\"), optionally followed "
222 "by a colon and an output file name or directory. A directory "
223 "is indicated by a trailing pathname separator. "
224 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
225 "If a directory is specified, output files will be created "
226 "within that directory, with file-names based on the test "
227 "executable's name and, if necessary, made unique by adding "
228 "digits.");
229
230GTEST_DEFINE_bool_(
231 print_time,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000232 internal::BoolFromGTestEnv("print_time", true),
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000233 "True iff " GTEST_NAME_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000234 " should display elapsed time in text output.");
235
236GTEST_DEFINE_int32_(
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000237 random_seed,
238 internal::Int32FromGTestEnv("random_seed", 0),
239 "Random number seed to use when shuffling test orders. Must be in range "
240 "[1, 99999], or 0 to use a seed based on the current time.");
241
242GTEST_DEFINE_int32_(
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000243 repeat,
244 internal::Int32FromGTestEnv("repeat", 1),
245 "How many times to repeat each test. Specify a negative number "
246 "for repeating forever. Useful for shaking out flaky tests.");
247
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000248GTEST_DEFINE_bool_(
249 show_internal_stack_frames, false,
250 "True iff " GTEST_NAME_ " should include internal stack frames when "
251 "printing test failure stack traces.");
252
253GTEST_DEFINE_bool_(
254 shuffle,
255 internal::BoolFromGTestEnv("shuffle", false),
256 "True iff " GTEST_NAME_
257 " should randomize tests' order on every run.");
258
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000259GTEST_DEFINE_int32_(
260 stack_trace_depth,
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000261 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000262 "The maximum number of stack frames to print when an "
263 "assertion fails. The valid range is 0 through 100, inclusive.");
264
Jay Foadb33f8e32011-07-27 09:25:14 +0000265GTEST_DEFINE_string_(
266 stream_result_to,
267 internal::StringFromGTestEnv("stream_result_to", ""),
268 "This flag specifies the host name and the port number on which to stream "
269 "test results. Example: \"localhost:555\". The flag is effective only on "
270 "Linux.");
271
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000272GTEST_DEFINE_bool_(
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000273 throw_on_failure,
274 internal::BoolFromGTestEnv("throw_on_failure", false),
275 "When this flag is specified, a failed assertion will throw an exception "
276 "if exceptions are enabled or exit the program with a non-zero code "
277 "otherwise.");
278
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000279namespace internal {
280
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000281// Generates a random number from [0, range), using a Linear
282// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
283// than kMaxRange.
284UInt32 Random::Generate(UInt32 range) {
285 // These constants are the same as are used in glibc's rand(3).
286 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
287
288 GTEST_CHECK_(range > 0)
289 << "Cannot generate a number in the range [0, 0).";
290 GTEST_CHECK_(range <= kMaxRange)
291 << "Generation of a number in [0, " << range << ") was requested, "
292 << "but this can only generate numbers in [0, " << kMaxRange << ").";
293
294 // Converting via modulus introduces a bit of downward bias, but
295 // it's simple, and a linear congruential generator isn't too good
296 // to begin with.
297 return state_ % range;
298}
299
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000300// GTestIsInitialized() returns true iff the user has initialized
301// Google Test. Useful for catching the user mistake of not initializing
302// Google Test before calling RUN_ALL_TESTS().
303//
304// A user must call testing::InitGoogleTest() to initialize Google
305// Test. g_init_gtest_count is set to the number of times
306// InitGoogleTest() has been called. We don't protect this variable
307// under a mutex as it is only accessed in the main thread.
308int g_init_gtest_count = 0;
309static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
310
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000311// Iterates over a vector of TestCases, keeping a running sum of the
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000312// results of calling a given int-returning method on each.
313// Returns the sum.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000314static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000315 int (TestCase::*method)() const) {
316 int sum = 0;
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000317 for (size_t i = 0; i < case_list.size(); i++) {
318 sum += (case_list[i]->*method)();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000319 }
320 return sum;
321}
322
323// Returns true iff the test case passed.
324static bool TestCasePassed(const TestCase* test_case) {
325 return test_case->should_run() && test_case->Passed();
326}
327
328// Returns true iff the test case failed.
329static bool TestCaseFailed(const TestCase* test_case) {
330 return test_case->should_run() && test_case->Failed();
331}
332
333// Returns true iff test_case contains at least one test that should
334// run.
335static bool ShouldRunTestCase(const TestCase* test_case) {
336 return test_case->should_run();
337}
338
339// AssertHelper constructor.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000340AssertHelper::AssertHelper(TestPartResult::Type type,
341 const char* file,
342 int line,
343 const char* message)
344 : data_(new AssertHelperData(type, file, line, message)) {
345}
346
347AssertHelper::~AssertHelper() {
348 delete data_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000349}
350
351// Message assignment, for assertion streaming support.
352void AssertHelper::operator=(const Message& message) const {
353 UnitTest::GetInstance()->
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000354 AddTestPartResult(data_->type, data_->file, data_->line,
355 AppendUserMessage(data_->message, message),
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000356 UnitTest::GetInstance()->impl()
357 ->CurrentOsStackTraceExceptTop(1)
358 // Skips the stack frame for this function itself.
359 ); // NOLINT
360}
361
362// Mutex for linked pointers.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000363GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000364
365// Application pathname gotten in InitGoogleTest.
366String g_executable_path;
367
368// Returns the current application's name, removing directory path if that
369// is present.
370FilePath GetCurrentExecutableName() {
371 FilePath result;
372
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000373#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000374 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
375#else
376 result.Set(FilePath(g_executable_path));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000377#endif // GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000378
379 return result.RemoveDirectoryName();
380}
381
382// Functions for processing the gtest_output flag.
383
384// Returns the output format, or "" for normal printed output.
385String UnitTestOptions::GetOutputFormat() {
386 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
387 if (gtest_output_flag == NULL) return String("");
388
389 const char* const colon = strchr(gtest_output_flag, ':');
390 return (colon == NULL) ?
391 String(gtest_output_flag) :
392 String(gtest_output_flag, colon - gtest_output_flag);
393}
394
395// Returns the name of the requested output file, or the default if none
396// was explicitly specified.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000397String UnitTestOptions::GetAbsolutePathToOutputFile() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000398 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
399 if (gtest_output_flag == NULL)
400 return String("");
401
402 const char* const colon = strchr(gtest_output_flag, ':');
403 if (colon == NULL)
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000404 return String(internal::FilePath::ConcatPaths(
405 internal::FilePath(
406 UnitTest::GetInstance()->original_working_dir()),
407 internal::FilePath(kDefaultOutputFile)).ToString() );
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000408
409 internal::FilePath output_name(colon + 1);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000410 if (!output_name.IsAbsolutePath())
411 // TODO(wan@google.com): on Windows \some\path is not an absolute
412 // path (as its meaning depends on the current drive), yet the
413 // following logic for turning it into an absolute path is wrong.
414 // Fix it.
415 output_name = internal::FilePath::ConcatPaths(
416 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
417 internal::FilePath(colon + 1));
418
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000419 if (!output_name.IsDirectory())
420 return output_name.ToString();
421
422 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
423 output_name, internal::GetCurrentExecutableName(),
424 GetOutputFormat().c_str()));
425 return result.ToString();
426}
427
428// Returns true iff the wildcard pattern matches the string. The
429// first ':' or '\0' character in pattern marks the end of it.
430//
431// This recursive algorithm isn't very efficient, but is clear and
432// works well enough for matching test names, which are short.
433bool UnitTestOptions::PatternMatchesString(const char *pattern,
434 const char *str) {
435 switch (*pattern) {
436 case '\0':
437 case ':': // Either ':' or '\0' marks the end of the pattern.
438 return *str == '\0';
439 case '?': // Matches any single character.
440 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
441 case '*': // Matches any string (possibly empty) of characters.
442 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
443 PatternMatchesString(pattern + 1, str);
444 default: // Non-special character. Matches itself.
445 return *pattern == *str &&
446 PatternMatchesString(pattern + 1, str + 1);
447 }
448}
449
450bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
451 const char *cur_pattern = filter;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000452 for (;;) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000453 if (PatternMatchesString(cur_pattern, name.c_str())) {
454 return true;
455 }
456
457 // Finds the next pattern in the filter.
458 cur_pattern = strchr(cur_pattern, ':');
459
460 // Returns if no more pattern can be found.
461 if (cur_pattern == NULL) {
462 return false;
463 }
464
465 // Skips the pattern separater (the ':' character).
466 cur_pattern++;
467 }
468}
469
470// TODO(keithray): move String function implementations to gtest-string.cc.
471
472// Returns true iff the user-specified filter matches the test case
473// name and the test name.
474bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
475 const String &test_name) {
476 const String& full_name = String::Format("%s.%s",
477 test_case_name.c_str(),
478 test_name.c_str());
479
480 // Split --gtest_filter at '-', if there is one, to separate into
481 // positive filter and negative filter portions
482 const char* const p = GTEST_FLAG(filter).c_str();
483 const char* const dash = strchr(p, '-');
484 String positive;
485 String negative;
486 if (dash == NULL) {
487 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
488 negative = String("");
489 } else {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000490 positive = String(p, dash - p); // Everything up to the dash
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000491 negative = String(dash+1); // Everything after the dash
492 if (positive.empty()) {
493 // Treat '-test1' as the same as '*-test1'
494 positive = kUniversalFilter;
495 }
496 }
497
498 // A filter is a colon-separated list of patterns. It matches a
499 // test if any pattern in it matches the test.
500 return (MatchesFilter(full_name, positive.c_str()) &&
501 !MatchesFilter(full_name, negative.c_str()));
502}
503
Jay Foadb33f8e32011-07-27 09:25:14 +0000504#if GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000505// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
506// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
507// This function is useful as an __except condition.
508int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
Jay Foadb33f8e32011-07-27 09:25:14 +0000509 // Google Test should handle a SEH exception if:
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000510 // 1. the user wants it to, AND
Jay Foadb33f8e32011-07-27 09:25:14 +0000511 // 2. this is not a breakpoint exception, AND
512 // 3. this is not a C++ exception (VC++ implements them via SEH,
513 // apparently).
514 //
515 // SEH exception code for C++ exceptions.
516 // (see http://support.microsoft.com/kb/185294 for more information).
517 const DWORD kCxxExceptionCode = 0xe06d7363;
518
519 bool should_handle = true;
520
521 if (!GTEST_FLAG(catch_exceptions))
522 should_handle = false;
523 else if (exception_code == EXCEPTION_BREAKPOINT)
524 should_handle = false;
525 else if (exception_code == kCxxExceptionCode)
526 should_handle = false;
527
528 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000529}
Jay Foadb33f8e32011-07-27 09:25:14 +0000530#endif // GTEST_HAS_SEH
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000531
532} // namespace internal
533
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000534// The c'tor sets this object as the test part result reporter used by
535// Google Test. The 'result' parameter specifies where to report the
536// results. Intercepts only failures from the current thread.
537ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
538 TestPartResultArray* result)
539 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
540 result_(result) {
541 Init();
542}
543
544// The c'tor sets this object as the test part result reporter used by
545// Google Test. The 'result' parameter specifies where to report the
546// results.
547ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
548 InterceptMode intercept_mode, TestPartResultArray* result)
549 : intercept_mode_(intercept_mode),
550 result_(result) {
551 Init();
552}
553
554void ScopedFakeTestPartResultReporter::Init() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000555 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000556 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
557 old_reporter_ = impl->GetGlobalTestPartResultReporter();
558 impl->SetGlobalTestPartResultReporter(this);
559 } else {
560 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
561 impl->SetTestPartResultReporterForCurrentThread(this);
562 }
563}
564
565// The d'tor restores the test part result reporter used by Google Test
566// before.
567ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000568 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000569 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
570 impl->SetGlobalTestPartResultReporter(old_reporter_);
571 } else {
572 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
573 }
574}
575
576// Increments the test part result count and remembers the result.
577// This method is from the TestPartResultReporterInterface interface.
578void ScopedFakeTestPartResultReporter::ReportTestPartResult(
579 const TestPartResult& result) {
580 result_->Append(result);
581}
582
583namespace internal {
584
585// Returns the type ID of ::testing::Test. We should always call this
586// instead of GetTypeId< ::testing::Test>() to get the type ID of
587// testing::Test. This is to work around a suspected linker bug when
588// using Google Test as a framework on Mac OS X. The bug causes
589// GetTypeId< ::testing::Test>() to return different values depending
590// on whether the call is from the Google Test framework itself or
591// from user test code. GetTestTypeId() is guaranteed to always
592// return the same value, as it always calls GetTypeId<>() from the
593// gtest.cc, which is within the Google Test framework.
594TypeId GetTestTypeId() {
595 return GetTypeId<Test>();
596}
597
598// The value of GetTestTypeId() as seen from within the Google Test
599// library. This is solely for testing GetTestTypeId().
Bill Wendling0a0124e2009-12-16 19:36:42 +0000600const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000601
602// This predicate-formatter checks that 'results' contains a test part
603// failure of the given type and that the failure message contains the
604// given substring.
605AssertionResult HasOneFailure(const char* /* results_expr */,
606 const char* /* type_expr */,
607 const char* /* substr_expr */,
608 const TestPartResultArray& results,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000609 TestPartResult::Type type,
Jay Foadb33f8e32011-07-27 09:25:14 +0000610 const string& substr) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000611 const String expected(type == TestPartResult::kFatalFailure ?
612 "1 fatal failure" :
613 "1 non-fatal failure");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000614 Message msg;
615 if (results.size() != 1) {
616 msg << "Expected: " << expected << "\n"
617 << " Actual: " << results.size() << " failures";
618 for (int i = 0; i < results.size(); i++) {
619 msg << "\n" << results.GetTestPartResult(i);
620 }
Jay Foadb33f8e32011-07-27 09:25:14 +0000621 return AssertionFailure() << msg;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000622 }
623
624 const TestPartResult& r = results.GetTestPartResult(0);
625 if (r.type() != type) {
Jay Foadb33f8e32011-07-27 09:25:14 +0000626 return AssertionFailure() << "Expected: " << expected << "\n"
627 << " Actual:\n"
628 << r;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000629 }
630
Jay Foadb33f8e32011-07-27 09:25:14 +0000631 if (strstr(r.message(), substr.c_str()) == NULL) {
632 return AssertionFailure() << "Expected: " << expected << " containing \""
633 << substr << "\"\n"
634 << " Actual:\n"
635 << r;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000636 }
637
638 return AssertionSuccess();
639}
640
641// The constructor of SingleFailureChecker remembers where to look up
642// test part results, what type of failure we expect, and what
643// substring the failure message should contain.
644SingleFailureChecker:: SingleFailureChecker(
645 const TestPartResultArray* results,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000646 TestPartResult::Type type,
Jay Foadb33f8e32011-07-27 09:25:14 +0000647 const string& substr)
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000648 : results_(results),
649 type_(type),
650 substr_(substr) {}
651
652// The destructor of SingleFailureChecker verifies that the given
653// TestPartResultArray contains exactly one failure that has the given
654// type and contains the given substring. If that's not the case, a
655// non-fatal failure will be generated.
656SingleFailureChecker::~SingleFailureChecker() {
Jay Foadb33f8e32011-07-27 09:25:14 +0000657 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000658}
659
660DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
661 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
662
663void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
664 const TestPartResult& result) {
665 unit_test_->current_test_result()->AddTestPartResult(result);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000666 unit_test_->listeners()->repeater()->OnTestPartResult(result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000667}
668
669DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
670 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
671
672void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
673 const TestPartResult& result) {
674 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
675}
676
677// Returns the global test part result reporter.
678TestPartResultReporterInterface*
679UnitTestImpl::GetGlobalTestPartResultReporter() {
680 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
681 return global_test_part_result_repoter_;
682}
683
684// Sets the global test part result reporter.
685void UnitTestImpl::SetGlobalTestPartResultReporter(
686 TestPartResultReporterInterface* reporter) {
687 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
688 global_test_part_result_repoter_ = reporter;
689}
690
691// Returns the test part result reporter for the current thread.
692TestPartResultReporterInterface*
693UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
694 return per_thread_test_part_result_reporter_.get();
695}
696
697// Sets the test part result reporter for the current thread.
698void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
699 TestPartResultReporterInterface* reporter) {
700 per_thread_test_part_result_reporter_.set(reporter);
701}
702
703// Gets the number of successful test cases.
704int UnitTestImpl::successful_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000705 return CountIf(test_cases_, TestCasePassed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000706}
707
708// Gets the number of failed test cases.
709int UnitTestImpl::failed_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000710 return CountIf(test_cases_, TestCaseFailed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000711}
712
713// Gets the number of all test cases.
714int UnitTestImpl::total_test_case_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000715 return static_cast<int>(test_cases_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000716}
717
718// Gets the number of all test cases that contain at least one test
719// that should run.
720int UnitTestImpl::test_case_to_run_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000721 return CountIf(test_cases_, ShouldRunTestCase);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000722}
723
724// Gets the number of successful tests.
725int UnitTestImpl::successful_test_count() const {
726 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
727}
728
729// Gets the number of failed tests.
730int UnitTestImpl::failed_test_count() const {
731 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
732}
733
734// Gets the number of disabled tests.
735int UnitTestImpl::disabled_test_count() const {
736 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
737}
738
739// Gets the number of all tests.
740int UnitTestImpl::total_test_count() const {
741 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
742}
743
744// Gets the number of tests that should run.
745int UnitTestImpl::test_to_run_count() const {
746 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
747}
748
749// Returns the current OS stack trace as a String.
750//
751// The maximum number of stack frames to be included is specified by
752// the gtest_stack_trace_depth flag. The skip_count parameter
753// specifies the number of top frames to be skipped, which doesn't
754// count against the number of frames to be included.
755//
756// For example, if Foo() calls Bar(), which in turn calls
757// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
758// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
759String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
760 (void)skip_count;
761 return String("");
762}
763
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000764// Returns the current time in milliseconds.
765TimeInMillis GetTimeInMillis() {
766#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
767 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000768 // http://analogous.blogspot.com/2005/04/epoch.html
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000769 const TimeInMillis kJavaEpochToWinFileTimeDelta =
770 static_cast<TimeInMillis>(116444736UL) * 100000UL;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000771 const DWORD kTenthMicrosInMilliSecond = 10000;
772
773 SYSTEMTIME now_systime;
774 FILETIME now_filetime;
775 ULARGE_INTEGER now_int64;
776 // TODO(kenton@google.com): Shouldn't this just use
777 // GetSystemTimeAsFileTime()?
778 GetSystemTime(&now_systime);
779 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
780 now_int64.LowPart = now_filetime.dwLowDateTime;
781 now_int64.HighPart = now_filetime.dwHighDateTime;
782 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
783 kJavaEpochToWinFileTimeDelta;
784 return now_int64.QuadPart;
785 }
786 return 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000787#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000788 __timeb64 now;
Jay Foadb33f8e32011-07-27 09:25:14 +0000789
790# ifdef _MSC_VER
791
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000792 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
793 // (deprecated function) there.
794 // TODO(kenton@google.com): Use GetTickCount()? Or use
795 // SystemTimeToFileTime()
Jay Foadb33f8e32011-07-27 09:25:14 +0000796# pragma warning(push) // Saves the current warning state.
797# pragma warning(disable:4996) // Temporarily disables warning 4996.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000798 _ftime64(&now);
Jay Foadb33f8e32011-07-27 09:25:14 +0000799# pragma warning(pop) // Restores the warning state.
800# else
801
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000802 _ftime64(&now);
Jay Foadb33f8e32011-07-27 09:25:14 +0000803
804# endif // _MSC_VER
805
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000806 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000807#elif GTEST_HAS_GETTIMEOFDAY_
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000808 struct timeval now;
809 gettimeofday(&now, NULL);
810 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
811#else
Jay Foadb33f8e32011-07-27 09:25:14 +0000812# error "Don't know how to get the current time on your system."
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000813#endif
814}
815
816// Utilities
817
818// class String
819
820// Returns the input enclosed in double quotes if it's not NULL;
821// otherwise returns "(null)". For example, "\"Hello\"" is returned
822// for input "Hello".
823//
824// This is useful for printing a C string in the syntax of a literal.
825//
826// Known issue: escape sequences are not handled yet.
827String String::ShowCStringQuoted(const char* c_str) {
828 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
829}
830
831// Copies at most length characters from str into a newly-allocated
832// piece of memory of size length+1. The memory is allocated with new[].
833// A terminating null byte is written to the memory, and a pointer to it
834// is returned. If str is NULL, NULL is returned.
835static char* CloneString(const char* str, size_t length) {
836 if (str == NULL) {
837 return NULL;
838 } else {
839 char* const clone = new char[length + 1];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000840 posix::StrNCpy(clone, str, length);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000841 clone[length] = '\0';
842 return clone;
843 }
844}
845
846// Clones a 0-terminated C string, allocating memory using new. The
847// caller is responsible for deleting[] the return value. Returns the
848// cloned string, or NULL if the input is NULL.
849const char * String::CloneCString(const char* c_str) {
850 return (c_str == NULL) ?
851 NULL : CloneString(c_str, strlen(c_str));
852}
853
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000854#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000855// Creates a UTF-16 wide string from the given ANSI string, allocating
856// memory using new. The caller is responsible for deleting the return
857// value using delete[]. Returns the wide string, or NULL if the
858// input is NULL.
859LPCWSTR String::AnsiToUtf16(const char* ansi) {
860 if (!ansi) return NULL;
861 const int length = strlen(ansi);
862 const int unicode_length =
863 MultiByteToWideChar(CP_ACP, 0, ansi, length,
864 NULL, 0);
865 WCHAR* unicode = new WCHAR[unicode_length + 1];
866 MultiByteToWideChar(CP_ACP, 0, ansi, length,
867 unicode, unicode_length);
868 unicode[unicode_length] = 0;
869 return unicode;
870}
871
872// Creates an ANSI string from the given wide string, allocating
873// memory using new. The caller is responsible for deleting the return
874// value using delete[]. Returns the ANSI string, or NULL if the
875// input is NULL.
876const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
877 if (!utf16_str) return NULL;
878 const int ansi_length =
879 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
880 NULL, 0, NULL, NULL);
881 char* ansi = new char[ansi_length + 1];
882 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
883 ansi, ansi_length, NULL, NULL);
884 ansi[ansi_length] = 0;
885 return ansi;
886}
887
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000888#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000889
890// Compares two C strings. Returns true iff they have the same content.
891//
892// Unlike strcmp(), this function can handle NULL argument(s). A NULL
893// C string is considered different to any non-NULL C string,
894// including the empty string.
895bool String::CStringEquals(const char * lhs, const char * rhs) {
896 if ( lhs == NULL ) return rhs == NULL;
897
898 if ( rhs == NULL ) return false;
899
900 return strcmp(lhs, rhs) == 0;
901}
902
903#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
904
905// Converts an array of wide chars to a narrow string using the UTF-8
906// encoding, and streams the result to the given Message object.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000907static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000908 Message* msg) {
909 // TODO(wan): consider allowing a testing::String object to
910 // contain '\0'. This will make it behave more like std::string,
911 // and will allow ToUtf8String() to return the correct encoding
912 // for '\0' s.t. we can get rid of the conditional here (and in
913 // several other places).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000914 for (size_t i = 0; i != length; ) { // NOLINT
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000915 if (wstr[i] != L'\0') {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000916 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
917 while (i != length && wstr[i] != L'\0')
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000918 i++;
919 } else {
920 *msg << '\0';
921 i++;
922 }
923 }
924}
925
926#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
927
928} // namespace internal
929
930#if GTEST_HAS_STD_WSTRING
931// Converts the given wide string to a narrow string using the UTF-8
932// encoding, and streams the result to this Message object.
933Message& Message::operator <<(const ::std::wstring& wstr) {
934 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
935 return *this;
936}
937#endif // GTEST_HAS_STD_WSTRING
938
939#if GTEST_HAS_GLOBAL_WSTRING
940// Converts the given wide string to a narrow string using the UTF-8
941// encoding, and streams the result to this Message object.
942Message& Message::operator <<(const ::wstring& wstr) {
943 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
944 return *this;
945}
946#endif // GTEST_HAS_GLOBAL_WSTRING
947
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000948// AssertionResult constructors.
949// Used in EXPECT_TRUE/FALSE(assertion_result).
950AssertionResult::AssertionResult(const AssertionResult& other)
951 : success_(other.success_),
952 message_(other.message_.get() != NULL ?
Jay Foadb33f8e32011-07-27 09:25:14 +0000953 new ::std::string(*other.message_) :
954 static_cast< ::std::string*>(NULL)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000955}
956
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000957// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
958AssertionResult AssertionResult::operator!() const {
959 AssertionResult negation(!success_);
960 if (message_.get() != NULL)
961 negation << *message_;
962 return negation;
963}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000964
965// Makes a successful assertion result.
966AssertionResult AssertionSuccess() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000967 return AssertionResult(true);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000968}
969
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000970// Makes a failed assertion result.
971AssertionResult AssertionFailure() {
972 return AssertionResult(false);
973}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000974
975// Makes a failed assertion result with the given failure message.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000976// Deprecated; use AssertionFailure() << message.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000977AssertionResult AssertionFailure(const Message& message) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000978 return AssertionFailure() << message;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000979}
980
981namespace internal {
982
983// Constructs and returns the message for an equality assertion
984// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
985//
986// The first four parameters are the expressions used in the assertion
987// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
988// where foo is 5 and bar is 6, we have:
989//
990// expected_expression: "foo"
991// actual_expression: "bar"
992// expected_value: "5"
993// actual_value: "6"
994//
995// The ignoring_case parameter is true iff the assertion is a
996// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
997// be inserted into the message.
998AssertionResult EqFailure(const char* expected_expression,
999 const char* actual_expression,
1000 const String& expected_value,
1001 const String& actual_value,
1002 bool ignoring_case) {
1003 Message msg;
1004 msg << "Value of: " << actual_expression;
1005 if (actual_value != actual_expression) {
1006 msg << "\n Actual: " << actual_value;
1007 }
1008
1009 msg << "\nExpected: " << expected_expression;
1010 if (ignoring_case) {
1011 msg << " (ignoring case)";
1012 }
1013 if (expected_value != expected_expression) {
1014 msg << "\nWhich is: " << expected_value;
1015 }
1016
Jay Foadb33f8e32011-07-27 09:25:14 +00001017 return AssertionFailure() << msg;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001018}
1019
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001020// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1021String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1022 const char* expression_text,
1023 const char* actual_predicate_value,
1024 const char* expected_predicate_value) {
1025 const char* actual_message = assertion_result.message();
1026 Message msg;
1027 msg << "Value of: " << expression_text
1028 << "\n Actual: " << actual_predicate_value;
1029 if (actual_message[0] != '\0')
1030 msg << " (" << actual_message << ")";
1031 msg << "\nExpected: " << expected_predicate_value;
1032 return msg.GetString();
1033}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001034
1035// Helper function for implementing ASSERT_NEAR.
1036AssertionResult DoubleNearPredFormat(const char* expr1,
1037 const char* expr2,
1038 const char* abs_error_expr,
1039 double val1,
1040 double val2,
1041 double abs_error) {
1042 const double diff = fabs(val1 - val2);
1043 if (diff <= abs_error) return AssertionSuccess();
1044
1045 // TODO(wan): do not print the value of an expression if it's
1046 // already a literal.
Jay Foadb33f8e32011-07-27 09:25:14 +00001047 return AssertionFailure()
1048 << "The difference between " << expr1 << " and " << expr2
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001049 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1050 << expr1 << " evaluates to " << val1 << ",\n"
1051 << expr2 << " evaluates to " << val2 << ", and\n"
1052 << abs_error_expr << " evaluates to " << abs_error << ".";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001053}
1054
1055
1056// Helper template for implementing FloatLE() and DoubleLE().
1057template <typename RawType>
1058AssertionResult FloatingPointLE(const char* expr1,
1059 const char* expr2,
1060 RawType val1,
1061 RawType val2) {
1062 // Returns success if val1 is less than val2,
1063 if (val1 < val2) {
1064 return AssertionSuccess();
1065 }
1066
1067 // or if val1 is almost equal to val2.
1068 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1069 if (lhs.AlmostEquals(rhs)) {
1070 return AssertionSuccess();
1071 }
1072
1073 // Note that the above two checks will both fail if either val1 or
1074 // val2 is NaN, as the IEEE floating-point standard requires that
1075 // any predicate involving a NaN must return false.
1076
Jay Foadb33f8e32011-07-27 09:25:14 +00001077 ::std::stringstream val1_ss;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001078 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1079 << val1;
1080
Jay Foadb33f8e32011-07-27 09:25:14 +00001081 ::std::stringstream val2_ss;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001082 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1083 << val2;
1084
Jay Foadb33f8e32011-07-27 09:25:14 +00001085 return AssertionFailure()
1086 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1087 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
1088 << StringStreamToString(&val2_ss);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001089}
1090
1091} // namespace internal
1092
1093// Asserts that val1 is less than, or almost equal to, val2. Fails
1094// otherwise. In particular, it fails if either val1 or val2 is NaN.
1095AssertionResult FloatLE(const char* expr1, const char* expr2,
1096 float val1, float val2) {
1097 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1098}
1099
1100// Asserts that val1 is less than, or almost equal to, val2. Fails
1101// otherwise. In particular, it fails if either val1 or val2 is NaN.
1102AssertionResult DoubleLE(const char* expr1, const char* expr2,
1103 double val1, double val2) {
1104 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1105}
1106
1107namespace internal {
1108
1109// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1110// arguments.
1111AssertionResult CmpHelperEQ(const char* expected_expression,
1112 const char* actual_expression,
1113 BiggestInt expected,
1114 BiggestInt actual) {
1115 if (expected == actual) {
1116 return AssertionSuccess();
1117 }
1118
1119 return EqFailure(expected_expression,
1120 actual_expression,
1121 FormatForComparisonFailureMessage(expected, actual),
1122 FormatForComparisonFailureMessage(actual, expected),
1123 false);
1124}
1125
1126// A macro for implementing the helper functions needed to implement
1127// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1128// just to avoid copy-and-paste of similar code.
1129#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1130AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1131 BiggestInt val1, BiggestInt val2) {\
1132 if (val1 op val2) {\
1133 return AssertionSuccess();\
1134 } else {\
Jay Foadb33f8e32011-07-27 09:25:14 +00001135 return AssertionFailure() \
1136 << "Expected: (" << expr1 << ") " #op " (" << expr2\
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001137 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1138 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001139 }\
1140}
1141
1142// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1143// enum arguments.
1144GTEST_IMPL_CMP_HELPER_(NE, !=)
1145// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1146// enum arguments.
1147GTEST_IMPL_CMP_HELPER_(LE, <=)
1148// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1149// enum arguments.
1150GTEST_IMPL_CMP_HELPER_(LT, < )
1151// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1152// enum arguments.
1153GTEST_IMPL_CMP_HELPER_(GE, >=)
1154// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1155// enum arguments.
1156GTEST_IMPL_CMP_HELPER_(GT, > )
1157
1158#undef GTEST_IMPL_CMP_HELPER_
1159
1160// The helper function for {ASSERT|EXPECT}_STREQ.
1161AssertionResult CmpHelperSTREQ(const char* expected_expression,
1162 const char* actual_expression,
1163 const char* expected,
1164 const char* actual) {
1165 if (String::CStringEquals(expected, actual)) {
1166 return AssertionSuccess();
1167 }
1168
1169 return EqFailure(expected_expression,
1170 actual_expression,
1171 String::ShowCStringQuoted(expected),
1172 String::ShowCStringQuoted(actual),
1173 false);
1174}
1175
1176// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1177AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1178 const char* actual_expression,
1179 const char* expected,
1180 const char* actual) {
1181 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1182 return AssertionSuccess();
1183 }
1184
1185 return EqFailure(expected_expression,
1186 actual_expression,
1187 String::ShowCStringQuoted(expected),
1188 String::ShowCStringQuoted(actual),
1189 true);
1190}
1191
1192// The helper function for {ASSERT|EXPECT}_STRNE.
1193AssertionResult CmpHelperSTRNE(const char* s1_expression,
1194 const char* s2_expression,
1195 const char* s1,
1196 const char* s2) {
1197 if (!String::CStringEquals(s1, s2)) {
1198 return AssertionSuccess();
1199 } else {
Jay Foadb33f8e32011-07-27 09:25:14 +00001200 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1201 << s2_expression << "), actual: \""
1202 << s1 << "\" vs \"" << s2 << "\"";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001203 }
1204}
1205
1206// The helper function for {ASSERT|EXPECT}_STRCASENE.
1207AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1208 const char* s2_expression,
1209 const char* s1,
1210 const char* s2) {
1211 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1212 return AssertionSuccess();
1213 } else {
Jay Foadb33f8e32011-07-27 09:25:14 +00001214 return AssertionFailure()
1215 << "Expected: (" << s1_expression << ") != ("
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001216 << s2_expression << ") (ignoring case), actual: \""
1217 << s1 << "\" vs \"" << s2 << "\"";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001218 }
1219}
1220
1221} // namespace internal
1222
1223namespace {
1224
1225// Helper functions for implementing IsSubString() and IsNotSubstring().
1226
1227// This group of overloaded functions return true iff needle is a
1228// substring of haystack. NULL is considered a substring of itself
1229// only.
1230
1231bool IsSubstringPred(const char* needle, const char* haystack) {
1232 if (needle == NULL || haystack == NULL)
1233 return needle == haystack;
1234
1235 return strstr(haystack, needle) != NULL;
1236}
1237
1238bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1239 if (needle == NULL || haystack == NULL)
1240 return needle == haystack;
1241
1242 return wcsstr(haystack, needle) != NULL;
1243}
1244
1245// StringType here can be either ::std::string or ::std::wstring.
1246template <typename StringType>
1247bool IsSubstringPred(const StringType& needle,
1248 const StringType& haystack) {
1249 return haystack.find(needle) != StringType::npos;
1250}
1251
1252// This function implements either IsSubstring() or IsNotSubstring(),
1253// depending on the value of the expected_to_be_substring parameter.
1254// StringType here can be const char*, const wchar_t*, ::std::string,
1255// or ::std::wstring.
1256template <typename StringType>
1257AssertionResult IsSubstringImpl(
1258 bool expected_to_be_substring,
1259 const char* needle_expr, const char* haystack_expr,
1260 const StringType& needle, const StringType& haystack) {
1261 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1262 return AssertionSuccess();
1263
1264 const bool is_wide_string = sizeof(needle[0]) > 1;
1265 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
Jay Foadb33f8e32011-07-27 09:25:14 +00001266 return AssertionFailure()
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001267 << "Value of: " << needle_expr << "\n"
1268 << " Actual: " << begin_string_quote << needle << "\"\n"
1269 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1270 << "a substring of " << haystack_expr << "\n"
Jay Foadb33f8e32011-07-27 09:25:14 +00001271 << "Which is: " << begin_string_quote << haystack << "\"";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001272}
1273
1274} // namespace
1275
1276// IsSubstring() and IsNotSubstring() check whether needle is a
1277// substring of haystack (NULL is considered a substring of itself
1278// only), and return an appropriate error message when they fail.
1279
1280AssertionResult IsSubstring(
1281 const char* needle_expr, const char* haystack_expr,
1282 const char* needle, const char* haystack) {
1283 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1284}
1285
1286AssertionResult IsSubstring(
1287 const char* needle_expr, const char* haystack_expr,
1288 const wchar_t* needle, const wchar_t* haystack) {
1289 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1290}
1291
1292AssertionResult IsNotSubstring(
1293 const char* needle_expr, const char* haystack_expr,
1294 const char* needle, const char* haystack) {
1295 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1296}
1297
1298AssertionResult IsNotSubstring(
1299 const char* needle_expr, const char* haystack_expr,
1300 const wchar_t* needle, const wchar_t* haystack) {
1301 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1302}
1303
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001304AssertionResult IsSubstring(
1305 const char* needle_expr, const char* haystack_expr,
1306 const ::std::string& needle, const ::std::string& haystack) {
1307 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1308}
1309
1310AssertionResult IsNotSubstring(
1311 const char* needle_expr, const char* haystack_expr,
1312 const ::std::string& needle, const ::std::string& haystack) {
1313 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1314}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001315
1316#if GTEST_HAS_STD_WSTRING
1317AssertionResult IsSubstring(
1318 const char* needle_expr, const char* haystack_expr,
1319 const ::std::wstring& needle, const ::std::wstring& haystack) {
1320 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1321}
1322
1323AssertionResult IsNotSubstring(
1324 const char* needle_expr, const char* haystack_expr,
1325 const ::std::wstring& needle, const ::std::wstring& haystack) {
1326 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1327}
1328#endif // GTEST_HAS_STD_WSTRING
1329
1330namespace internal {
1331
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001332#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001333
1334namespace {
1335
1336// Helper function for IsHRESULT{SuccessFailure} predicates
1337AssertionResult HRESULTFailureHelper(const char* expr,
1338 const char* expected,
1339 long hr) { // NOLINT
Jay Foadb33f8e32011-07-27 09:25:14 +00001340# if GTEST_OS_WINDOWS_MOBILE
1341
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001342 // Windows CE doesn't support FormatMessage.
1343 const char error_text[] = "";
Jay Foadb33f8e32011-07-27 09:25:14 +00001344
1345# else
1346
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001347 // Looks up the human-readable system message for the HRESULT code
1348 // and since we're not passing any params to FormatMessage, we don't
1349 // want inserts expanded.
1350 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1351 FORMAT_MESSAGE_IGNORE_INSERTS;
1352 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1353 // Gets the system's human readable message string for this HRESULT.
1354 char error_text[kBufSize] = { '\0' };
1355 DWORD message_length = ::FormatMessageA(kFlags,
1356 0, // no source, we're asking system
1357 hr, // the error
1358 0, // no line width restrictions
1359 error_text, // output buffer
1360 kBufSize, // buf size
1361 NULL); // no arguments for inserts
1362 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
Jay Foadb33f8e32011-07-27 09:25:14 +00001363 for (; message_length && IsSpace(error_text[message_length - 1]);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001364 --message_length) {
1365 error_text[message_length - 1] = '\0';
1366 }
Jay Foadb33f8e32011-07-27 09:25:14 +00001367
1368# endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001369
1370 const String error_hex(String::Format("0x%08X ", hr));
Jay Foadb33f8e32011-07-27 09:25:14 +00001371 return ::testing::AssertionFailure()
1372 << "Expected: " << expr << " " << expected << ".\n"
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001373 << " Actual: " << error_hex << error_text << "\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001374}
1375
1376} // namespace
1377
1378AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1379 if (SUCCEEDED(hr)) {
1380 return AssertionSuccess();
1381 }
1382 return HRESULTFailureHelper(expr, "succeeds", hr);
1383}
1384
1385AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1386 if (FAILED(hr)) {
1387 return AssertionSuccess();
1388 }
1389 return HRESULTFailureHelper(expr, "fails", hr);
1390}
1391
1392#endif // GTEST_OS_WINDOWS
1393
1394// Utility functions for encoding Unicode text (wide strings) in
1395// UTF-8.
1396
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001397// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001398// like this:
1399//
1400// Code-point length Encoding
1401// 0 - 7 bits 0xxxxxxx
1402// 8 - 11 bits 110xxxxx 10xxxxxx
1403// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1404// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1405
1406// The maximum code-point a one-byte UTF-8 sequence can represent.
1407const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1408
1409// The maximum code-point a two-byte UTF-8 sequence can represent.
1410const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1411
1412// The maximum code-point a three-byte UTF-8 sequence can represent.
1413const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1414
1415// The maximum code-point a four-byte UTF-8 sequence can represent.
1416const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1417
1418// Chops off the n lowest bits from a bit pattern. Returns the n
1419// lowest bits. As a side effect, the original bit pattern will be
1420// shifted to the right by n bits.
1421inline UInt32 ChopLowBits(UInt32* bits, int n) {
1422 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1423 *bits >>= n;
1424 return low_bits;
1425}
1426
1427// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1428// code_point parameter is of type UInt32 because wchar_t may not be
1429// wide enough to contain a code point.
1430// The output buffer str must containt at least 32 characters.
1431// The function returns the address of the output buffer.
1432// If the code_point is not a valid Unicode code point
1433// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1434// as '(Invalid Unicode 0xXXXXXXXX)'.
1435char* CodePointToUtf8(UInt32 code_point, char* str) {
1436 if (code_point <= kMaxCodePoint1) {
1437 str[1] = '\0';
1438 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1439 } else if (code_point <= kMaxCodePoint2) {
1440 str[2] = '\0';
1441 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1442 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1443 } else if (code_point <= kMaxCodePoint3) {
1444 str[3] = '\0';
1445 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1446 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1447 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1448 } else if (code_point <= kMaxCodePoint4) {
1449 str[4] = '\0';
1450 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1451 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1452 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1453 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1454 } else {
1455 // The longest string String::Format can produce when invoked
1456 // with these parameters is 28 character long (not including
1457 // the terminating nul character). We are asking for 32 character
1458 // buffer just in case. This is also enough for strncpy to
1459 // null-terminate the destination string.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001460 posix::StrNCpy(
1461 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001462 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1463 // the result unterminated.
1464 }
1465 return str;
1466}
1467
1468// The following two functions only make sense if the the system
1469// uses UTF-16 for wide string encoding. All supported systems
1470// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1471
1472// Determines if the arguments constitute UTF-16 surrogate pair
1473// and thus should be combined into a single Unicode code point
1474// using CreateCodePointFromUtf16SurrogatePair.
1475inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001476 return sizeof(wchar_t) == 2 &&
1477 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001478}
1479
1480// Creates a Unicode code point from UTF16 surrogate pair.
1481inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1482 wchar_t second) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001483 const UInt32 mask = (1 << 10) - 1;
1484 return (sizeof(wchar_t) == 2) ?
1485 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1486 // This function should not be called when the condition is
1487 // false, but we provide a sensible default in case it is.
1488 static_cast<UInt32>(first);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001489}
1490
1491// Converts a wide string to a narrow string in UTF-8 encoding.
1492// The wide string is assumed to have the following encoding:
1493// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1494// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1495// Parameter str points to a null-terminated wide string.
1496// Parameter num_chars may additionally limit the number
1497// of wchar_t characters processed. -1 is used when the entire string
1498// should be processed.
1499// If the string contains code points that are not valid Unicode code points
1500// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1501// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1502// and contains invalid UTF-16 surrogate pairs, values in those pairs
1503// will be encoded as individual Unicode characters from Basic Normal Plane.
1504String WideStringToUtf8(const wchar_t* str, int num_chars) {
1505 if (num_chars == -1)
1506 num_chars = static_cast<int>(wcslen(str));
1507
Jay Foadb33f8e32011-07-27 09:25:14 +00001508 ::std::stringstream stream;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001509 for (int i = 0; i < num_chars; ++i) {
1510 UInt32 unicode_code_point;
1511
1512 if (str[i] == L'\0') {
1513 break;
1514 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1515 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1516 str[i + 1]);
1517 i++;
1518 } else {
1519 unicode_code_point = static_cast<UInt32>(str[i]);
1520 }
1521
1522 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1523 stream << CodePointToUtf8(unicode_code_point, buffer);
1524 }
Jay Foadb33f8e32011-07-27 09:25:14 +00001525 return StringStreamToString(&stream);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001526}
1527
1528// Converts a wide C string to a String using the UTF-8 encoding.
1529// NULL will be converted to "(null)".
1530String String::ShowWideCString(const wchar_t * wide_c_str) {
1531 if (wide_c_str == NULL) return String("(null)");
1532
1533 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1534}
1535
1536// Similar to ShowWideCString(), except that this function encloses
1537// the converted string in double quotes.
1538String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1539 if (wide_c_str == NULL) return String("(null)");
1540
1541 return String::Format("L\"%s\"",
1542 String::ShowWideCString(wide_c_str).c_str());
1543}
1544
1545// Compares two wide C strings. Returns true iff they have the same
1546// content.
1547//
1548// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1549// C string is considered different to any non-NULL C string,
1550// including the empty string.
1551bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1552 if (lhs == NULL) return rhs == NULL;
1553
1554 if (rhs == NULL) return false;
1555
1556 return wcscmp(lhs, rhs) == 0;
1557}
1558
1559// Helper function for *_STREQ on wide strings.
1560AssertionResult CmpHelperSTREQ(const char* expected_expression,
1561 const char* actual_expression,
1562 const wchar_t* expected,
1563 const wchar_t* actual) {
1564 if (String::WideCStringEquals(expected, actual)) {
1565 return AssertionSuccess();
1566 }
1567
1568 return EqFailure(expected_expression,
1569 actual_expression,
1570 String::ShowWideCStringQuoted(expected),
1571 String::ShowWideCStringQuoted(actual),
1572 false);
1573}
1574
1575// Helper function for *_STRNE on wide strings.
1576AssertionResult CmpHelperSTRNE(const char* s1_expression,
1577 const char* s2_expression,
1578 const wchar_t* s1,
1579 const wchar_t* s2) {
1580 if (!String::WideCStringEquals(s1, s2)) {
1581 return AssertionSuccess();
1582 }
1583
Jay Foadb33f8e32011-07-27 09:25:14 +00001584 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1585 << s2_expression << "), actual: "
1586 << String::ShowWideCStringQuoted(s1)
1587 << " vs " << String::ShowWideCStringQuoted(s2);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001588}
1589
1590// Compares two C strings, ignoring case. Returns true iff they have
1591// the same content.
1592//
1593// Unlike strcasecmp(), this function can handle NULL argument(s). A
1594// NULL C string is considered different to any non-NULL C string,
1595// including the empty string.
1596bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001597 if (lhs == NULL)
1598 return rhs == NULL;
1599 if (rhs == NULL)
1600 return false;
1601 return posix::StrCaseCmp(lhs, rhs) == 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001602}
1603
1604 // Compares two wide C strings, ignoring case. Returns true iff they
1605 // have the same content.
1606 //
1607 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1608 // A NULL C string is considered different to any non-NULL wide C string,
1609 // including the empty string.
1610 // NB: The implementations on different platforms slightly differ.
1611 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1612 // environment variable. On GNU platform this method uses wcscasecmp
1613 // which compares according to LC_CTYPE category of the current locale.
1614 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1615 // current locale.
1616bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1617 const wchar_t* rhs) {
Jay Foadb33f8e32011-07-27 09:25:14 +00001618 if (lhs == NULL) return rhs == NULL;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001619
Jay Foadb33f8e32011-07-27 09:25:14 +00001620 if (rhs == NULL) return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001621
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001622#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001623 return _wcsicmp(lhs, rhs) == 0;
Jay Foadb33f8e32011-07-27 09:25:14 +00001624#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001625 return wcscasecmp(lhs, rhs) == 0;
1626#else
Jay Foadb33f8e32011-07-27 09:25:14 +00001627 // Android, Mac OS X and Cygwin don't define wcscasecmp.
1628 // Other unknown OSes may not define it either.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001629 wint_t left, right;
1630 do {
1631 left = towlower(*lhs++);
1632 right = towlower(*rhs++);
1633 } while (left && left == right);
1634 return left == right;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001635#endif // OS selector
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001636}
1637
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001638// Compares this with another String.
1639// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1640// if this is greater than rhs.
1641int String::Compare(const String & rhs) const {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001642 const char* const lhs_c_str = c_str();
1643 const char* const rhs_c_str = rhs.c_str();
1644
1645 if (lhs_c_str == NULL) {
1646 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1647 } else if (rhs_c_str == NULL) {
1648 return 1;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001649 }
1650
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001651 const size_t shorter_str_len =
1652 length() <= rhs.length() ? length() : rhs.length();
1653 for (size_t i = 0; i != shorter_str_len; i++) {
1654 if (lhs_c_str[i] < rhs_c_str[i]) {
1655 return -1;
1656 } else if (lhs_c_str[i] > rhs_c_str[i]) {
1657 return 1;
1658 }
1659 }
1660 return (length() < rhs.length()) ? -1 :
1661 (length() > rhs.length()) ? 1 : 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001662}
1663
1664// Returns true iff this String ends with the given suffix. *Any*
1665// String is considered to end with a NULL or empty suffix.
1666bool String::EndsWith(const char* suffix) const {
1667 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1668
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001669 if (c_str() == NULL) return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001670
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001671 const size_t this_len = strlen(c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001672 const size_t suffix_len = strlen(suffix);
1673 return (this_len >= suffix_len) &&
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001674 CStringEquals(c_str() + this_len - suffix_len, suffix);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001675}
1676
1677// Returns true iff this String ends with the given suffix, ignoring case.
1678// Any String is considered to end with a NULL or empty suffix.
1679bool String::EndsWithCaseInsensitive(const char* suffix) const {
1680 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1681
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001682 if (c_str() == NULL) return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001683
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001684 const size_t this_len = strlen(c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001685 const size_t suffix_len = strlen(suffix);
1686 return (this_len >= suffix_len) &&
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001687 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001688}
1689
1690// Formats a list of arguments to a String, using the same format
1691// spec string as for printf.
1692//
1693// We do not use the StringPrintf class as it is not universally
1694// available.
1695//
1696// The result is limited to 4096 characters (including the tailing 0).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001697// If 4096 characters are not enough to format the input, or if
1698// there's an error, "<formatting error or buffer exceeded>" is
1699// returned.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001700String String::Format(const char * format, ...) {
1701 va_list args;
1702 va_start(args, format);
1703
1704 char buffer[4096];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001705 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1706
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001707 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1708 // 4996 (deprecated function) there.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001709#ifdef _MSC_VER // We are using MSVC.
Jay Foadb33f8e32011-07-27 09:25:14 +00001710# pragma warning(push) // Saves the current warning state.
1711# pragma warning(disable:4996) // Temporarily disables warning 4996.
1712
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001713 const int size = vsnprintf(buffer, kBufferSize, format, args);
Jay Foadb33f8e32011-07-27 09:25:14 +00001714
1715# pragma warning(pop) // Restores the warning state.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001716#else // We are not using MSVC.
1717 const int size = vsnprintf(buffer, kBufferSize, format, args);
1718#endif // _MSC_VER
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001719 va_end(args);
1720
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001721 // vsnprintf()'s behavior is not portable. When the buffer is not
1722 // big enough, it returns a negative value in MSVC, and returns the
1723 // needed buffer size on Linux. When there is an output error, it
1724 // always returns a negative value. For simplicity, we lump the two
1725 // error cases together.
1726 if (size < 0 || size >= kBufferSize) {
1727 return String("<formatting error or buffer exceeded>");
1728 } else {
1729 return String(buffer, size);
1730 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001731}
1732
Jay Foadb33f8e32011-07-27 09:25:14 +00001733// Converts the buffer in a stringstream to a String, converting NUL
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001734// bytes to "\\0" along the way.
Jay Foadb33f8e32011-07-27 09:25:14 +00001735String StringStreamToString(::std::stringstream* ss) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001736 const ::std::string& str = ss->str();
1737 const char* const start = str.c_str();
1738 const char* const end = start + str.length();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001739
Jay Foadb33f8e32011-07-27 09:25:14 +00001740 // We need to use a helper stringstream to do this transformation
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001741 // because String doesn't support push_back().
Jay Foadb33f8e32011-07-27 09:25:14 +00001742 ::std::stringstream helper;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001743 for (const char* ch = start; ch != end; ++ch) {
1744 if (*ch == '\0') {
1745 helper << "\\0"; // Replaces NUL with "\\0";
1746 } else {
1747 helper.put(*ch);
1748 }
1749 }
1750
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001751 return String(helper.str().c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001752}
1753
1754// Appends the user-supplied message to the Google-Test-generated message.
1755String AppendUserMessage(const String& gtest_msg,
1756 const Message& user_msg) {
1757 // Appends the user message if it's non-empty.
1758 const String user_msg_string = user_msg.GetString();
1759 if (user_msg_string.empty()) {
1760 return gtest_msg;
1761 }
1762
1763 Message msg;
1764 msg << gtest_msg << "\n" << user_msg_string;
1765
1766 return msg.GetString();
1767}
1768
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001769} // namespace internal
1770
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001771// class TestResult
1772
1773// Creates an empty TestResult.
1774TestResult::TestResult()
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001775 : death_test_count_(0),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001776 elapsed_time_(0) {
1777}
1778
1779// D'tor.
1780TestResult::~TestResult() {
1781}
1782
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001783// Returns the i-th test part result among all the results. i can
1784// range from 0 to total_part_count() - 1. If i is not in that range,
1785// aborts the program.
1786const TestPartResult& TestResult::GetTestPartResult(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001787 if (i < 0 || i >= total_part_count())
1788 internal::posix::Abort();
1789 return test_part_results_.at(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001790}
1791
1792// Returns the i-th test property. i can range from 0 to
1793// test_property_count() - 1. If i is not in that range, aborts the
1794// program.
1795const TestProperty& TestResult::GetTestProperty(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001796 if (i < 0 || i >= test_property_count())
1797 internal::posix::Abort();
1798 return test_properties_.at(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001799}
1800
1801// Clears the test part results.
1802void TestResult::ClearTestPartResults() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001803 test_part_results_.clear();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001804}
1805
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001806// Adds a test part result to the list.
1807void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001808 test_part_results_.push_back(test_part_result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001809}
1810
1811// Adds a test property to the list. If a property with the same key as the
1812// supplied property is already represented, the value of this test_property
1813// replaces the old value for that key.
1814void TestResult::RecordProperty(const TestProperty& test_property) {
1815 if (!ValidateTestProperty(test_property)) {
1816 return;
1817 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001818 internal::MutexLock lock(&test_properites_mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001819 const std::vector<TestProperty>::iterator property_with_matching_key =
1820 std::find_if(test_properties_.begin(), test_properties_.end(),
1821 internal::TestPropertyKeyIs(test_property.key()));
1822 if (property_with_matching_key == test_properties_.end()) {
1823 test_properties_.push_back(test_property);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001824 return;
1825 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001826 property_with_matching_key->SetValue(test_property.value());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001827}
1828
1829// Adds a failure if the key is a reserved attribute of Google Test
1830// testcase tags. Returns true if the property is valid.
1831bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001832 internal::String key(test_property.key());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001833 if (key == "name" || key == "status" || key == "time" || key == "classname") {
1834 ADD_FAILURE()
1835 << "Reserved key used in RecordProperty(): "
1836 << key
1837 << " ('name', 'status', 'time', and 'classname' are reserved by "
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001838 << GTEST_NAME_ << ")";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001839 return false;
1840 }
1841 return true;
1842}
1843
1844// Clears the object.
1845void TestResult::Clear() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001846 test_part_results_.clear();
1847 test_properties_.clear();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001848 death_test_count_ = 0;
1849 elapsed_time_ = 0;
1850}
1851
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001852// Returns true iff the test failed.
1853bool TestResult::Failed() const {
1854 for (int i = 0; i < total_part_count(); ++i) {
1855 if (GetTestPartResult(i).failed())
1856 return true;
1857 }
1858 return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001859}
1860
1861// Returns true iff the test part fatally failed.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001862static bool TestPartFatallyFailed(const TestPartResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001863 return result.fatally_failed();
1864}
1865
1866// Returns true iff the test fatally failed.
1867bool TestResult::HasFatalFailure() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001868 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001869}
1870
1871// Returns true iff the test part non-fatally failed.
1872static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1873 return result.nonfatally_failed();
1874}
1875
1876// Returns true iff the test has a non-fatal failure.
1877bool TestResult::HasNonfatalFailure() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001878 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001879}
1880
1881// Gets the number of all test parts. This is the sum of the number
1882// of successful test parts and the number of failed test parts.
1883int TestResult::total_part_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001884 return static_cast<int>(test_part_results_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001885}
1886
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001887// Returns the number of the test properties.
1888int TestResult::test_property_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00001889 return static_cast<int>(test_properties_.size());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001890}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001891
1892// class Test
1893
1894// Creates a Test object.
1895
1896// The c'tor saves the values of all Google Test flags.
1897Test::Test()
1898 : gtest_flag_saver_(new internal::GTestFlagSaver) {
1899}
1900
1901// The d'tor restores the values of all Google Test flags.
1902Test::~Test() {
1903 delete gtest_flag_saver_;
1904}
1905
1906// Sets up the test fixture.
1907//
1908// A sub-class may override this.
1909void Test::SetUp() {
1910}
1911
1912// Tears down the test fixture.
1913//
1914// A sub-class may override this.
1915void Test::TearDown() {
1916}
1917
1918// Allows user supplied key value pairs to be recorded for later output.
1919void Test::RecordProperty(const char* key, const char* value) {
1920 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1921}
1922
1923// Allows user supplied key value pairs to be recorded for later output.
1924void Test::RecordProperty(const char* key, int value) {
1925 Message value_message;
1926 value_message << value;
1927 RecordProperty(key, value_message.GetString().c_str());
1928}
1929
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001930namespace internal {
1931
1932void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1933 const String& message) {
1934 // This function is a friend of UnitTest and as such has access to
1935 // AddTestPartResult.
1936 UnitTest::GetInstance()->AddTestPartResult(
1937 result_type,
1938 NULL, // No info about the source file where the exception occurred.
1939 -1, // We have no info on which line caused the exception.
1940 message,
1941 String()); // No stack trace, either.
1942}
1943
1944} // namespace internal
1945
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001946// Google Test requires all tests in the same test case to use the same test
1947// fixture class. This function checks if the current test has the
1948// same fixture class as the first test in the current test case. If
1949// yes, it returns true; otherwise it generates a Google Test failure and
1950// returns false.
1951bool Test::HasSameFixtureClass() {
1952 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1953 const TestCase* const test_case = impl->current_test_case();
1954
1955 // Info about the first test in the current test case.
Jay Foadb33f8e32011-07-27 09:25:14 +00001956 const TestInfo* const first_test_info = test_case->test_info_list()[0];
1957 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001958 const char* const first_test_name = first_test_info->name();
1959
1960 // Info about the current test.
Jay Foadb33f8e32011-07-27 09:25:14 +00001961 const TestInfo* const this_test_info = impl->current_test_info();
1962 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001963 const char* const this_test_name = this_test_info->name();
1964
1965 if (this_fixture_id != first_fixture_id) {
1966 // Is the first test defined using TEST?
1967 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
1968 // Is this test defined using TEST?
1969 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
1970
1971 if (first_is_TEST || this_is_TEST) {
1972 // The user mixed TEST and TEST_F in this test case - we'll tell
1973 // him/her how to fix it.
1974
1975 // Gets the name of the TEST and the name of the TEST_F. Note
1976 // that first_is_TEST and this_is_TEST cannot both be true, as
1977 // the fixture IDs are different for the two tests.
1978 const char* const TEST_name =
1979 first_is_TEST ? first_test_name : this_test_name;
1980 const char* const TEST_F_name =
1981 first_is_TEST ? this_test_name : first_test_name;
1982
1983 ADD_FAILURE()
1984 << "All tests in the same test case must use the same test fixture\n"
1985 << "class, so mixing TEST_F and TEST in the same test case is\n"
1986 << "illegal. In test case " << this_test_info->test_case_name()
1987 << ",\n"
1988 << "test " << TEST_F_name << " is defined using TEST_F but\n"
1989 << "test " << TEST_name << " is defined using TEST. You probably\n"
1990 << "want to change the TEST to TEST_F or move it to another test\n"
1991 << "case.";
1992 } else {
1993 // The user defined two fixture classes with the same name in
1994 // two namespaces - we'll tell him/her how to fix it.
1995 ADD_FAILURE()
1996 << "All tests in the same test case must use the same test fixture\n"
1997 << "class. However, in test case "
1998 << this_test_info->test_case_name() << ",\n"
1999 << "you defined test " << first_test_name
2000 << " and test " << this_test_name << "\n"
2001 << "using two different test fixture classes. This can happen if\n"
2002 << "the two classes are from different namespaces or translation\n"
2003 << "units and have the same name. You should probably rename one\n"
2004 << "of the classes to put the tests into different test cases.";
2005 }
2006 return false;
2007 }
2008
2009 return true;
2010}
2011
Jay Foadb33f8e32011-07-27 09:25:14 +00002012#if GTEST_HAS_SEH
2013
2014// Adds an "exception thrown" fatal failure to the current test. This
2015// function returns its result via an output parameter pointer because VC++
2016// prohibits creation of objects with destructors on stack in functions
2017// using __try (see error C2712).
2018static internal::String* FormatSehExceptionMessage(DWORD exception_code,
2019 const char* location) {
2020 Message message;
2021 message << "SEH exception with code 0x" << std::setbase(16) <<
2022 exception_code << std::setbase(10) << " thrown in " << location << ".";
2023
2024 return new internal::String(message.GetString());
2025}
2026
2027#endif // GTEST_HAS_SEH
2028
2029#if GTEST_HAS_EXCEPTIONS
2030
2031// Adds an "exception thrown" fatal failure to the current test.
2032static internal::String FormatCxxExceptionMessage(const char* description,
2033 const char* location) {
2034 Message message;
2035 if (description != NULL) {
2036 message << "C++ exception with description \"" << description << "\"";
2037 } else {
2038 message << "Unknown C++ exception";
2039 }
2040 message << " thrown in " << location << ".";
2041
2042 return message.GetString();
2043}
2044
2045static internal::String PrintTestPartResultToString(
2046 const TestPartResult& test_part_result);
2047
2048// A failed Google Test assertion will throw an exception of this type when
2049// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
2050// derive it from std::runtime_error, which is for errors presumably
2051// detectable only at run time. Since std::runtime_error inherits from
2052// std::exception, many testing frameworks know how to extract and print the
2053// message inside it.
2054class GoogleTestFailureException : public ::std::runtime_error {
2055 public:
2056 explicit GoogleTestFailureException(const TestPartResult& failure)
2057 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2058};
2059#endif // GTEST_HAS_EXCEPTIONS
2060
2061namespace internal {
2062// We put these helper functions in the internal namespace as IBM's xlC
2063// compiler rejects the code if they were declared static.
2064
2065// Runs the given method and handles SEH exceptions it throws, when
2066// SEH is supported; returns the 0-value for type Result in case of an
2067// SEH exception. (Microsoft compilers cannot handle SEH and C++
2068// exceptions in the same function. Therefore, we provide a separate
2069// wrapper function for handling SEH exceptions.)
2070template <class T, typename Result>
2071Result HandleSehExceptionsInMethodIfSupported(
2072 T* object, Result (T::*method)(), const char* location) {
2073#if GTEST_HAS_SEH
2074 __try {
2075 return (object->*method)();
2076 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
2077 GetExceptionCode())) {
2078 // We create the exception message on the heap because VC++ prohibits
2079 // creation of objects with destructors on stack in functions using __try
2080 // (see error C2712).
2081 internal::String* exception_message = FormatSehExceptionMessage(
2082 GetExceptionCode(), location);
2083 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2084 *exception_message);
2085 delete exception_message;
2086 return static_cast<Result>(0);
2087 }
2088#else
2089 (void)location;
2090 return (object->*method)();
2091#endif // GTEST_HAS_SEH
2092}
2093
2094// Runs the given method and catches and reports C++ and/or SEH-style
2095// exceptions, if they are supported; returns the 0-value for type
2096// Result in case of an SEH exception.
2097template <class T, typename Result>
2098Result HandleExceptionsInMethodIfSupported(
2099 T* object, Result (T::*method)(), const char* location) {
2100 // NOTE: The user code can affect the way in which Google Test handles
2101 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2102 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2103 // after the exception is caught and either report or re-throw the
2104 // exception based on the flag's value:
2105 //
2106 // try {
2107 // // Perform the test method.
2108 // } catch (...) {
2109 // if (GTEST_FLAG(catch_exceptions))
2110 // // Report the exception as failure.
2111 // else
2112 // throw; // Re-throws the original exception.
2113 // }
2114 //
2115 // However, the purpose of this flag is to allow the program to drop into
2116 // the debugger when the exception is thrown. On most platforms, once the
2117 // control enters the catch block, the exception origin information is
2118 // lost and the debugger will stop the program at the point of the
2119 // re-throw in this function -- instead of at the point of the original
2120 // throw statement in the code under test. For this reason, we perform
2121 // the check early, sacrificing the ability to affect Google Test's
2122 // exception handling in the method where the exception is thrown.
2123 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2124#if GTEST_HAS_EXCEPTIONS
2125 try {
2126 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2127 } catch (const GoogleTestFailureException&) { // NOLINT
2128 // This exception doesn't originate in code under test. It makes no
2129 // sense to report it as a test failure.
2130 throw;
2131 } catch (const std::exception& e) { // NOLINT
2132 internal::ReportFailureInUnknownLocation(
2133 TestPartResult::kFatalFailure,
2134 FormatCxxExceptionMessage(e.what(), location));
2135 } catch (...) { // NOLINT
2136 internal::ReportFailureInUnknownLocation(
2137 TestPartResult::kFatalFailure,
2138 FormatCxxExceptionMessage(NULL, location));
2139 }
2140 return static_cast<Result>(0);
2141#else
2142 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2143#endif // GTEST_HAS_EXCEPTIONS
2144 } else {
2145 return (object->*method)();
2146 }
2147}
2148
2149} // namespace internal
2150
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002151// Runs the test and updates the test result.
2152void Test::Run() {
2153 if (!HasSameFixtureClass()) return;
2154
2155 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002156 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002157 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002158 // We will run the test only if SetUp() was successful.
2159 if (!HasFatalFailure()) {
2160 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002161 internal::HandleExceptionsInMethodIfSupported(
2162 this, &Test::TestBody, "the test body");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002163 }
2164
2165 // However, we want to clean up as much as possible. Hence we will
2166 // always call TearDown(), even if SetUp() or the test body has
2167 // failed.
2168 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002169 internal::HandleExceptionsInMethodIfSupported(
2170 this, &Test::TearDown, "TearDown()");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002171}
2172
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002173// Returns true iff the current test has a fatal failure.
2174bool Test::HasFatalFailure() {
2175 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2176}
2177
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002178// Returns true iff the current test has a non-fatal failure.
2179bool Test::HasNonfatalFailure() {
2180 return internal::GetUnitTestImpl()->current_test_result()->
2181 HasNonfatalFailure();
2182}
2183
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002184// class TestInfo
2185
2186// Constructs a TestInfo object. It assumes ownership of the test factory
Jay Foadb33f8e32011-07-27 09:25:14 +00002187// object.
2188// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
2189// to signify they cannot be NULLs.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002190TestInfo::TestInfo(const char* a_test_case_name,
2191 const char* a_name,
Jay Foadb33f8e32011-07-27 09:25:14 +00002192 const char* a_type_param,
2193 const char* a_value_param,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002194 internal::TypeId fixture_class_id,
Jay Foadb33f8e32011-07-27 09:25:14 +00002195 internal::TestFactoryBase* factory)
2196 : test_case_name_(a_test_case_name),
2197 name_(a_name),
2198 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2199 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2200 fixture_class_id_(fixture_class_id),
2201 should_run_(false),
2202 is_disabled_(false),
2203 matches_filter_(false),
2204 factory_(factory),
2205 result_() {}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002206
2207// Destructs a TestInfo object.
Jay Foadb33f8e32011-07-27 09:25:14 +00002208TestInfo::~TestInfo() { delete factory_; }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002209
2210namespace internal {
2211
2212// Creates a new TestInfo object and registers it with Google Test;
2213// returns the created object.
2214//
2215// Arguments:
2216//
2217// test_case_name: name of the test case
2218// name: name of the test
Jay Foadb33f8e32011-07-27 09:25:14 +00002219// type_param: the name of the test's type parameter, or NULL if
2220// this is not a typed or a type-parameterized test.
2221// value_param: text representation of the test's value parameter,
2222// or NULL if this is not a value-parameterized test.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002223// fixture_class_id: ID of the test fixture class
2224// set_up_tc: pointer to the function that sets up the test case
2225// tear_down_tc: pointer to the function that tears down the test case
2226// factory: pointer to the factory that creates a test object.
2227// The newly created TestInfo instance will assume
2228// ownership of the factory object.
2229TestInfo* MakeAndRegisterTestInfo(
2230 const char* test_case_name, const char* name,
Jay Foadb33f8e32011-07-27 09:25:14 +00002231 const char* type_param,
2232 const char* value_param,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002233 TypeId fixture_class_id,
2234 SetUpTestCaseFunc set_up_tc,
2235 TearDownTestCaseFunc tear_down_tc,
2236 TestFactoryBase* factory) {
2237 TestInfo* const test_info =
Jay Foadb33f8e32011-07-27 09:25:14 +00002238 new TestInfo(test_case_name, name, type_param, value_param,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002239 fixture_class_id, factory);
2240 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2241 return test_info;
2242}
2243
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002244#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002245void ReportInvalidTestCaseType(const char* test_case_name,
2246 const char* file, int line) {
2247 Message errors;
2248 errors
2249 << "Attempted redefinition of test case " << test_case_name << ".\n"
2250 << "All tests in the same test case must use the same test fixture\n"
2251 << "class. However, in test case " << test_case_name << ", you tried\n"
2252 << "to define a test using a fixture class different from the one\n"
2253 << "used earlier. This can happen if the two fixture classes are\n"
2254 << "from different namespaces and have the same name. You should\n"
2255 << "probably rename one of the classes to put the tests into different\n"
2256 << "test cases.";
2257
2258 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2259 errors.GetString().c_str());
2260}
2261#endif // GTEST_HAS_PARAM_TEST
2262
2263} // namespace internal
2264
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002265namespace internal {
2266
2267// This method expands all parameterized tests registered with macros TEST_P
2268// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2269// This will be done just once during the program runtime.
2270void UnitTestImpl::RegisterParameterizedTests() {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002271#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002272 if (!parameterized_tests_registered_) {
2273 parameterized_test_registry_.RegisterTests();
2274 parameterized_tests_registered_ = true;
2275 }
2276#endif
2277}
2278
Jay Foadb33f8e32011-07-27 09:25:14 +00002279} // namespace internal
2280
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002281// Creates the test object, runs it, records its result, and then
2282// deletes it.
Jay Foadb33f8e32011-07-27 09:25:14 +00002283void TestInfo::Run() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002284 if (!should_run_) return;
2285
2286 // Tells UnitTest where to store test result.
Jay Foadb33f8e32011-07-27 09:25:14 +00002287 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2288 impl->set_current_test_info(this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002289
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002290 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2291
2292 // Notifies the unit test event listeners that a test is about to start.
Jay Foadb33f8e32011-07-27 09:25:14 +00002293 repeater->OnTestStart(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002294
Jay Foadb33f8e32011-07-27 09:25:14 +00002295 const TimeInMillis start = internal::GetTimeInMillis();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002296
2297 impl->os_stack_trace_getter()->UponLeavingGTest();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002298
2299 // Creates the test object.
Jay Foadb33f8e32011-07-27 09:25:14 +00002300 Test* const test = internal::HandleExceptionsInMethodIfSupported(
2301 factory_, &internal::TestFactoryBase::CreateTest,
2302 "the test fixture's constructor");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002303
Jay Foadb33f8e32011-07-27 09:25:14 +00002304 // Runs the test only if the test object was created and its
2305 // constructor didn't generate a fatal failure.
2306 if ((test != NULL) && !Test::HasFatalFailure()) {
2307 // This doesn't throw as all user code that can throw are wrapped into
2308 // exception handling code.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002309 test->Run();
2310 }
2311
2312 // Deletes the test object.
2313 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002314 internal::HandleExceptionsInMethodIfSupported(
2315 test, &Test::DeleteSelf_, "the test fixture's destructor");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002316
Jay Foadb33f8e32011-07-27 09:25:14 +00002317 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002318
2319 // Notifies the unit test event listener that a test has just finished.
Jay Foadb33f8e32011-07-27 09:25:14 +00002320 repeater->OnTestEnd(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002321
2322 // Tells UnitTest to stop associating assertion results to this
2323 // test.
2324 impl->set_current_test_info(NULL);
2325}
2326
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002327// class TestCase
2328
2329// Gets the number of successful tests in this test case.
2330int TestCase::successful_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002331 return CountIf(test_info_list_, TestPassed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002332}
2333
2334// Gets the number of failed tests in this test case.
2335int TestCase::failed_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002336 return CountIf(test_info_list_, TestFailed);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002337}
2338
2339int TestCase::disabled_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002340 return CountIf(test_info_list_, TestDisabled);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002341}
2342
2343// Get the number of tests in this test case that should run.
2344int TestCase::test_to_run_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002345 return CountIf(test_info_list_, ShouldRunTest);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002346}
2347
2348// Gets the number of all tests.
2349int TestCase::total_test_count() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002350 return static_cast<int>(test_info_list_.size());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002351}
2352
2353// Creates a TestCase with the given name.
2354//
2355// Arguments:
2356//
2357// name: name of the test case
Jay Foadb33f8e32011-07-27 09:25:14 +00002358// a_type_param: the name of the test case's type parameter, or NULL if
2359// this is not a typed or a type-parameterized test case.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002360// set_up_tc: pointer to the function that sets up the test case
2361// tear_down_tc: pointer to the function that tears down the test case
Jay Foadb33f8e32011-07-27 09:25:14 +00002362TestCase::TestCase(const char* a_name, const char* a_type_param,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002363 Test::SetUpTestCaseFunc set_up_tc,
2364 Test::TearDownTestCaseFunc tear_down_tc)
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002365 : name_(a_name),
Jay Foadb33f8e32011-07-27 09:25:14 +00002366 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002367 set_up_tc_(set_up_tc),
2368 tear_down_tc_(tear_down_tc),
2369 should_run_(false),
2370 elapsed_time_(0) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002371}
2372
2373// Destructor of TestCase.
2374TestCase::~TestCase() {
2375 // Deletes every Test in the collection.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002376 ForEach(test_info_list_, internal::Delete<TestInfo>);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002377}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002378
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002379// Returns the i-th test among all the tests. i can range from 0 to
2380// total_test_count() - 1. If i is not in that range, returns NULL.
2381const TestInfo* TestCase::GetTestInfo(int i) const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002382 const int index = GetElementOr(test_indices_, i, -1);
2383 return index < 0 ? NULL : test_info_list_[index];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002384}
2385
2386// Returns the i-th test among all the tests. i can range from 0 to
2387// total_test_count() - 1. If i is not in that range, returns NULL.
2388TestInfo* TestCase::GetMutableTestInfo(int i) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002389 const int index = GetElementOr(test_indices_, i, -1);
2390 return index < 0 ? NULL : test_info_list_[index];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002391}
2392
2393// Adds a test to this test case. Will delete the test upon
2394// destruction of the TestCase object.
2395void TestCase::AddTestInfo(TestInfo * test_info) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002396 test_info_list_.push_back(test_info);
2397 test_indices_.push_back(static_cast<int>(test_indices_.size()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002398}
2399
2400// Runs every test in this TestCase.
2401void TestCase::Run() {
2402 if (!should_run_) return;
2403
2404 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2405 impl->set_current_test_case(this);
2406
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002407 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002408
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002409 repeater->OnTestCaseStart(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002410 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002411 internal::HandleExceptionsInMethodIfSupported(
2412 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002413
2414 const internal::TimeInMillis start = internal::GetTimeInMillis();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002415 for (int i = 0; i < total_test_count(); i++) {
Jay Foadb33f8e32011-07-27 09:25:14 +00002416 GetMutableTestInfo(i)->Run();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002417 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002418 elapsed_time_ = internal::GetTimeInMillis() - start;
2419
2420 impl->os_stack_trace_getter()->UponLeavingGTest();
Jay Foadb33f8e32011-07-27 09:25:14 +00002421 internal::HandleExceptionsInMethodIfSupported(
2422 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2423
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002424 repeater->OnTestCaseEnd(*this);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002425 impl->set_current_test_case(NULL);
2426}
2427
2428// Clears the results of all tests in this test case.
2429void TestCase::ClearResult() {
Jay Foadb33f8e32011-07-27 09:25:14 +00002430 ForEach(test_info_list_, TestInfo::ClearTestResult);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002431}
2432
2433// Shuffles the tests in this test case.
2434void TestCase::ShuffleTests(internal::Random* random) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002435 Shuffle(random, &test_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002436}
2437
2438// Restores the test order to before the first shuffle.
2439void TestCase::UnshuffleTests() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002440 for (size_t i = 0; i < test_indices_.size(); i++) {
2441 test_indices_[i] = static_cast<int>(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002442 }
2443}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002444
2445// Formats a countable noun. Depending on its quantity, either the
2446// singular form or the plural form is used. e.g.
2447//
2448// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2449// FormatCountableNoun(5, "book", "books") returns "5 books".
2450static internal::String FormatCountableNoun(int count,
2451 const char * singular_form,
2452 const char * plural_form) {
2453 return internal::String::Format("%d %s", count,
2454 count == 1 ? singular_form : plural_form);
2455}
2456
2457// Formats the count of tests.
2458static internal::String FormatTestCount(int test_count) {
2459 return FormatCountableNoun(test_count, "test", "tests");
2460}
2461
2462// Formats the count of test cases.
2463static internal::String FormatTestCaseCount(int test_case_count) {
2464 return FormatCountableNoun(test_case_count, "test case", "test cases");
2465}
2466
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002467// Converts a TestPartResult::Type enum to human-friendly string
2468// representation. Both kNonFatalFailure and kFatalFailure are translated
2469// to "Failure", as the user usually doesn't care about the difference
2470// between the two when viewing the test result.
2471static const char * TestPartResultTypeToString(TestPartResult::Type type) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002472 switch (type) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002473 case TestPartResult::kSuccess:
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002474 return "Success";
2475
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002476 case TestPartResult::kNonFatalFailure:
2477 case TestPartResult::kFatalFailure:
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002478#ifdef _MSC_VER
2479 return "error: ";
2480#else
2481 return "Failure\n";
2482#endif
Jay Foadb33f8e32011-07-27 09:25:14 +00002483 default:
2484 return "Unknown result type";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002485 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002486}
2487
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002488// Prints a TestPartResult to a String.
2489static internal::String PrintTestPartResultToString(
2490 const TestPartResult& test_part_result) {
2491 return (Message()
2492 << internal::FormatFileLocation(test_part_result.file_name(),
2493 test_part_result.line_number())
2494 << " " << TestPartResultTypeToString(test_part_result.type())
2495 << test_part_result.message()).GetString();
2496}
2497
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002498// Prints a TestPartResult.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002499static void PrintTestPartResult(const TestPartResult& test_part_result) {
2500 const internal::String& result =
2501 PrintTestPartResultToString(test_part_result);
2502 printf("%s\n", result.c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002503 fflush(stdout);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002504 // If the test program runs in Visual Studio or a debugger, the
2505 // following statements add the test part result message to the Output
2506 // window such that the user can double-click on it to jump to the
2507 // corresponding source code location; otherwise they do nothing.
2508#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2509 // We don't call OutputDebugString*() on Windows Mobile, as printing
2510 // to stdout is done by OutputDebugString() there already - we don't
2511 // want the same message printed twice.
2512 ::OutputDebugStringA(result.c_str());
2513 ::OutputDebugStringA("\n");
2514#endif
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002515}
2516
2517// class PrettyUnitTestResultPrinter
2518
2519namespace internal {
2520
2521enum GTestColor {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002522 COLOR_DEFAULT,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002523 COLOR_RED,
2524 COLOR_GREEN,
2525 COLOR_YELLOW
2526};
2527
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002528#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002529
2530// Returns the character attribute for the given color.
2531WORD GetColorAttribute(GTestColor color) {
2532 switch (color) {
2533 case COLOR_RED: return FOREGROUND_RED;
2534 case COLOR_GREEN: return FOREGROUND_GREEN;
2535 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002536 default: return 0;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002537 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002538}
2539
2540#else
2541
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002542// Returns the ANSI color code for the given color. COLOR_DEFAULT is
2543// an invalid input.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002544const char* GetAnsiColorCode(GTestColor color) {
2545 switch (color) {
2546 case COLOR_RED: return "1";
2547 case COLOR_GREEN: return "2";
2548 case COLOR_YELLOW: return "3";
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002549 default: return NULL;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002550 };
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002551}
2552
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002553#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002554
2555// Returns true iff Google Test should use colors in the output.
2556bool ShouldUseColor(bool stdout_is_tty) {
2557 const char* const gtest_color = GTEST_FLAG(color).c_str();
2558
2559 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002560#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002561 // On Windows the TERM variable is usually not set, but the
2562 // console there does support colors.
2563 return stdout_is_tty;
2564#else
2565 // On non-Windows platforms, we rely on the TERM variable.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002566 const char* const term = posix::GetEnv("TERM");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002567 const bool term_supports_color =
2568 String::CStringEquals(term, "xterm") ||
2569 String::CStringEquals(term, "xterm-color") ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002570 String::CStringEquals(term, "xterm-256color") ||
Jay Foadb33f8e32011-07-27 09:25:14 +00002571 String::CStringEquals(term, "screen") ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002572 String::CStringEquals(term, "linux") ||
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002573 String::CStringEquals(term, "cygwin");
2574 return stdout_is_tty && term_supports_color;
2575#endif // GTEST_OS_WINDOWS
2576 }
2577
2578 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2579 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2580 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2581 String::CStringEquals(gtest_color, "1");
2582 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2583 // value is neither one of these nor "auto", we treat it as "no" to
2584 // be conservative.
2585}
2586
2587// Helpers for printing colored strings to stdout. Note that on Windows, we
2588// cannot simply emit special characters and have the terminal change colors.
2589// This routine must actually emit the characters rather than return a string
2590// that would be colored when printed, as can be done on Linux.
2591void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2592 va_list args;
2593 va_start(args, fmt);
2594
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002595#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002596 const bool use_color = false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002597#else
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002598 static const bool in_color_mode =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002599 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002600 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002601#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002602 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2603
2604 if (!use_color) {
2605 vprintf(fmt, args);
2606 va_end(args);
2607 return;
2608 }
2609
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002610#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002611 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2612
2613 // Gets the current text color.
2614 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2615 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2616 const WORD old_color_attrs = buffer_info.wAttributes;
2617
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002618 // We need to flush the stream buffers into the console before each
2619 // SetConsoleTextAttribute call lest it affect the text that is already
2620 // printed but has not yet reached the console.
2621 fflush(stdout);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002622 SetConsoleTextAttribute(stdout_handle,
2623 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2624 vprintf(fmt, args);
2625
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002626 fflush(stdout);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002627 // Restores the text color.
2628 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2629#else
2630 printf("\033[0;3%sm", GetAnsiColorCode(color));
2631 vprintf(fmt, args);
2632 printf("\033[m"); // Resets the terminal to default.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002633#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002634 va_end(args);
2635}
2636
Jay Foadb33f8e32011-07-27 09:25:14 +00002637void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
2638 const char* const type_param = test_info.type_param();
2639 const char* const value_param = test_info.value_param();
2640
2641 if (type_param != NULL || value_param != NULL) {
2642 printf(", where ");
2643 if (type_param != NULL) {
2644 printf("TypeParam = %s", type_param);
2645 if (value_param != NULL)
2646 printf(" and ");
2647 }
2648 if (value_param != NULL) {
2649 printf("GetParam() = %s", value_param);
2650 }
2651 }
2652}
2653
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002654// This class implements the TestEventListener interface.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002655//
2656// Class PrettyUnitTestResultPrinter is copyable.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002657class PrettyUnitTestResultPrinter : public TestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002658 public:
2659 PrettyUnitTestResultPrinter() {}
2660 static void PrintTestName(const char * test_case, const char * test) {
2661 printf("%s.%s", test_case, test);
2662 }
2663
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002664 // The following methods override what's in the TestEventListener class.
2665 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2666 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2667 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2668 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2669 virtual void OnTestCaseStart(const TestCase& test_case);
2670 virtual void OnTestStart(const TestInfo& test_info);
2671 virtual void OnTestPartResult(const TestPartResult& result);
2672 virtual void OnTestEnd(const TestInfo& test_info);
2673 virtual void OnTestCaseEnd(const TestCase& test_case);
2674 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2675 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2676 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2677 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002678
2679 private:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002680 static void PrintFailedTests(const UnitTest& unit_test);
2681
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002682 internal::String test_case_name_;
2683};
2684
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002685 // Fired before each iteration of tests starts.
2686void PrettyUnitTestResultPrinter::OnTestIterationStart(
2687 const UnitTest& unit_test, int iteration) {
2688 if (GTEST_FLAG(repeat) != 1)
2689 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2690
2691 const char* const filter = GTEST_FLAG(filter).c_str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002692
2693 // Prints the filter if it's not *. This reminds the user that some
2694 // tests may be skipped.
2695 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2696 ColoredPrintf(COLOR_YELLOW,
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002697 "Note: %s filter = %s\n", GTEST_NAME_, filter);
2698 }
2699
2700 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
Jay Foadb33f8e32011-07-27 09:25:14 +00002701 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002702 ColoredPrintf(COLOR_YELLOW,
Jay Foadb33f8e32011-07-27 09:25:14 +00002703 "Note: This is test shard %d of %s.\n",
2704 static_cast<int>(shard_index) + 1,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002705 internal::posix::GetEnv(kTestTotalShards));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002706 }
2707
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002708 if (GTEST_FLAG(shuffle)) {
2709 ColoredPrintf(COLOR_YELLOW,
2710 "Note: Randomizing tests' orders with a seed of %d .\n",
2711 unit_test.random_seed());
2712 }
2713
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002714 ColoredPrintf(COLOR_GREEN, "[==========] ");
2715 printf("Running %s from %s.\n",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002716 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2717 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002718 fflush(stdout);
2719}
2720
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002721void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2722 const UnitTest& /*unit_test*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002723 ColoredPrintf(COLOR_GREEN, "[----------] ");
2724 printf("Global test environment set-up.\n");
2725 fflush(stdout);
2726}
2727
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002728void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2729 test_case_name_ = test_case.name();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002730 const internal::String counts =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002731 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002732 ColoredPrintf(COLOR_GREEN, "[----------] ");
2733 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
Jay Foadb33f8e32011-07-27 09:25:14 +00002734 if (test_case.type_param() == NULL) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002735 printf("\n");
2736 } else {
Jay Foadb33f8e32011-07-27 09:25:14 +00002737 printf(", where TypeParam = %s\n", test_case.type_param());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002738 }
2739 fflush(stdout);
2740}
2741
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002742void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002743 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002744 PrintTestName(test_case_name_.c_str(), test_info.name());
Jay Foadb33f8e32011-07-27 09:25:14 +00002745 printf("\n");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002746 fflush(stdout);
2747}
2748
2749// Called after an assertion failure.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002750void PrettyUnitTestResultPrinter::OnTestPartResult(
2751 const TestPartResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002752 // If the test part succeeded, we don't need to do anything.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002753 if (result.type() == TestPartResult::kSuccess)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002754 return;
2755
2756 // Print failure message from the assertion (e.g. expected this and got that).
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002757 PrintTestPartResult(result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002758 fflush(stdout);
2759}
2760
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002761void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2762 if (test_info.result()->Passed()) {
2763 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2764 } else {
2765 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2766 }
2767 PrintTestName(test_case_name_.c_str(), test_info.name());
Jay Foadb33f8e32011-07-27 09:25:14 +00002768 if (test_info.result()->Failed())
2769 PrintFullTestCommentIfPresent(test_info);
2770
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002771 if (GTEST_FLAG(print_time)) {
2772 printf(" (%s ms)\n", internal::StreamableToString(
2773 test_info.result()->elapsed_time()).c_str());
2774 } else {
2775 printf("\n");
2776 }
2777 fflush(stdout);
2778}
2779
2780void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2781 if (!GTEST_FLAG(print_time)) return;
2782
2783 test_case_name_ = test_case.name();
2784 const internal::String counts =
2785 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2786 ColoredPrintf(COLOR_GREEN, "[----------] ");
2787 printf("%s from %s (%s ms total)\n\n",
2788 counts.c_str(), test_case_name_.c_str(),
2789 internal::StreamableToString(test_case.elapsed_time()).c_str());
2790 fflush(stdout);
2791}
2792
2793void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2794 const UnitTest& /*unit_test*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002795 ColoredPrintf(COLOR_GREEN, "[----------] ");
2796 printf("Global test environment tear-down\n");
2797 fflush(stdout);
2798}
2799
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002800// Internal helper for printing the list of failed tests.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002801void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2802 const int failed_test_count = unit_test.failed_test_count();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002803 if (failed_test_count == 0) {
2804 return;
2805 }
2806
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002807 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2808 const TestCase& test_case = *unit_test.GetTestCase(i);
2809 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002810 continue;
2811 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002812 for (int j = 0; j < test_case.total_test_count(); ++j) {
2813 const TestInfo& test_info = *test_case.GetTestInfo(j);
2814 if (!test_info.should_run() || test_info.result()->Passed()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002815 continue;
2816 }
2817 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002818 printf("%s.%s", test_case.name(), test_info.name());
Jay Foadb33f8e32011-07-27 09:25:14 +00002819 PrintFullTestCommentIfPresent(test_info);
2820 printf("\n");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002821 }
2822 }
2823}
2824
Jay Foadb33f8e32011-07-27 09:25:14 +00002825void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2826 int /*iteration*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002827 ColoredPrintf(COLOR_GREEN, "[==========] ");
2828 printf("%s from %s ran.",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002829 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2830 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002831 if (GTEST_FLAG(print_time)) {
2832 printf(" (%s ms total)",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002833 internal::StreamableToString(unit_test.elapsed_time()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002834 }
2835 printf("\n");
2836 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002837 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002838
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002839 int num_failures = unit_test.failed_test_count();
2840 if (!unit_test.Passed()) {
2841 const int failed_test_count = unit_test.failed_test_count();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002842 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2843 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002844 PrintFailedTests(unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002845 printf("\n%2d FAILED %s\n", num_failures,
2846 num_failures == 1 ? "TEST" : "TESTS");
2847 }
2848
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002849 int num_disabled = unit_test.disabled_test_count();
Benjamin Kramere4b9c932010-06-02 22:01:25 +00002850 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002851 if (!num_failures) {
2852 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2853 }
2854 ColoredPrintf(COLOR_YELLOW,
2855 " YOU HAVE %d DISABLED %s\n\n",
2856 num_disabled,
2857 num_disabled == 1 ? "TEST" : "TESTS");
2858 }
2859 // Ensure that Google Test output is printed before, e.g., heapchecker output.
2860 fflush(stdout);
2861}
2862
2863// End PrettyUnitTestResultPrinter
2864
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002865// class TestEventRepeater
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002866//
2867// This class forwards events to other event listeners.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002868class TestEventRepeater : public TestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002869 public:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002870 TestEventRepeater() : forwarding_enabled_(true) {}
2871 virtual ~TestEventRepeater();
2872 void Append(TestEventListener *listener);
2873 TestEventListener* Release(TestEventListener* listener);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002874
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002875 // Controls whether events will be forwarded to listeners_. Set to false
2876 // in death test child processes.
2877 bool forwarding_enabled() const { return forwarding_enabled_; }
2878 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2879
2880 virtual void OnTestProgramStart(const UnitTest& unit_test);
2881 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2882 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2883 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2884 virtual void OnTestCaseStart(const TestCase& test_case);
2885 virtual void OnTestStart(const TestInfo& test_info);
2886 virtual void OnTestPartResult(const TestPartResult& result);
2887 virtual void OnTestEnd(const TestInfo& test_info);
2888 virtual void OnTestCaseEnd(const TestCase& test_case);
2889 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2890 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2891 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2892 virtual void OnTestProgramEnd(const UnitTest& unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002893
2894 private:
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002895 // Controls whether events will be forwarded to listeners_. Set to false
2896 // in death test child processes.
2897 bool forwarding_enabled_;
2898 // The list of listeners that receive events.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002899 std::vector<TestEventListener*> listeners_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002900
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002901 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002902};
2903
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002904TestEventRepeater::~TestEventRepeater() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002905 ForEach(listeners_, Delete<TestEventListener>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002906}
2907
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002908void TestEventRepeater::Append(TestEventListener *listener) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002909 listeners_.push_back(listener);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002910}
2911
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002912// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2913TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002914 for (size_t i = 0; i < listeners_.size(); ++i) {
2915 if (listeners_[i] == listener) {
2916 listeners_.erase(listeners_.begin() + i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002917 return listener;
2918 }
2919 }
2920
2921 return NULL;
2922}
2923
2924// Since most methods are very similar, use macros to reduce boilerplate.
2925// This defines a member that forwards the call to all listeners.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002926#define GTEST_REPEATER_METHOD_(Name, Type) \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002927void TestEventRepeater::Name(const Type& parameter) { \
2928 if (forwarding_enabled_) { \
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002929 for (size_t i = 0; i < listeners_.size(); i++) { \
2930 listeners_[i]->Name(parameter); \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002931 } \
2932 } \
2933}
2934// This defines a member that forwards the call to all listeners in reverse
2935// order.
2936#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2937void TestEventRepeater::Name(const Type& parameter) { \
2938 if (forwarding_enabled_) { \
2939 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002940 listeners_[i]->Name(parameter); \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002941 } \
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002942 } \
2943}
2944
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002945GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2946GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002947GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002948GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002949GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2950GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2951GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2952GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2953GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2954GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2955GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002956
2957#undef GTEST_REPEATER_METHOD_
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002958#undef GTEST_REVERSE_REPEATER_METHOD_
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002959
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002960void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2961 int iteration) {
2962 if (forwarding_enabled_) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002963 for (size_t i = 0; i < listeners_.size(); i++) {
2964 listeners_[i]->OnTestIterationStart(unit_test, iteration);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002965 }
2966 }
2967}
2968
2969void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2970 int iteration) {
2971 if (forwarding_enabled_) {
2972 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00002973 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002974 }
2975 }
2976}
2977
2978// End TestEventRepeater
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002979
2980// This class generates an XML output file.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002981class XmlUnitTestResultPrinter : public EmptyTestEventListener {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002982 public:
2983 explicit XmlUnitTestResultPrinter(const char* output_file);
2984
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00002985 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00002986
2987 private:
2988 // Is c a whitespace character that is normalized to a space character
2989 // when it appears in an XML attribute value?
2990 static bool IsNormalizableWhitespace(char c) {
2991 return c == 0x9 || c == 0xA || c == 0xD;
2992 }
2993
2994 // May c appear in a well-formed XML document?
2995 static bool IsValidXmlCharacter(char c) {
2996 return IsNormalizableWhitespace(c) || c >= 0x20;
2997 }
2998
2999 // Returns an XML-escaped copy of the input string str. If
3000 // is_attribute is true, the text is meant to appear as an attribute
3001 // value, and normalizable whitespace is preserved by replacing it
3002 // with character references.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003003 static String EscapeXml(const char* str, bool is_attribute);
3004
3005 // Returns the given string with all characters invalid in XML removed.
Jay Foadb33f8e32011-07-27 09:25:14 +00003006 static string RemoveInvalidXmlCharacters(const string& str);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003007
3008 // Convenience wrapper around EscapeXml when str is an attribute value.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003009 static String EscapeXmlAttribute(const char* str) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003010 return EscapeXml(str, true);
3011 }
3012
3013 // Convenience wrapper around EscapeXml when str is not an attribute value.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003014 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003015
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003016 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3017 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3018
3019 // Streams an XML representation of a TestInfo object.
3020 static void OutputXmlTestInfo(::std::ostream* stream,
3021 const char* test_case_name,
3022 const TestInfo& test_info);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003023
3024 // Prints an XML representation of a TestCase object
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003025 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003026
3027 // Prints an XML summary of unit_test to output stream out.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003028 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003029
3030 // Produces a string representing the test properties in a result as space
3031 // delimited XML attributes based on the property key="value" pairs.
3032 // When the String is not empty, it includes a space at the beginning,
3033 // to delimit this attribute from prior attributes.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003034 static String TestPropertiesAsXmlAttributes(const TestResult& result);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003035
3036 // The output file.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003037 const String output_file_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003038
3039 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3040};
3041
3042// Creates a new XmlUnitTestResultPrinter.
3043XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3044 : output_file_(output_file) {
3045 if (output_file_.c_str() == NULL || output_file_.empty()) {
3046 fprintf(stderr, "XML output file may not be null\n");
3047 fflush(stderr);
3048 exit(EXIT_FAILURE);
3049 }
3050}
3051
3052// Called after the unit test ends.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003053void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3054 int /*iteration*/) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003055 FILE* xmlout = NULL;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003056 FilePath output_file(output_file_);
3057 FilePath output_dir(output_file.RemoveFileName());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003058
3059 if (output_dir.CreateDirectoriesRecursively()) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003060 xmlout = posix::FOpen(output_file_.c_str(), "w");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003061 }
3062 if (xmlout == NULL) {
3063 // TODO(wan): report the reason of the failure.
3064 //
3065 // We don't do it for now as:
3066 //
3067 // 1. There is no urgent need for it.
3068 // 2. It's a bit involved to make the errno variable thread-safe on
3069 // all three operating systems (Linux, Windows, and Mac OS).
3070 // 3. To interpret the meaning of errno in a thread-safe way,
3071 // we need the strerror_r() function, which is not available on
3072 // Windows.
3073 fprintf(stderr,
3074 "Unable to open file \"%s\"\n",
3075 output_file_.c_str());
3076 fflush(stderr);
3077 exit(EXIT_FAILURE);
3078 }
3079 PrintXmlUnitTest(xmlout, unit_test);
3080 fclose(xmlout);
3081}
3082
3083// Returns an XML-escaped copy of the input string str. If is_attribute
3084// is true, the text is meant to appear as an attribute value, and
3085// normalizable whitespace is preserved by replacing it with character
3086// references.
3087//
3088// Invalid XML characters in str, if any, are stripped from the output.
3089// It is expected that most, if not all, of the text processed by this
3090// module will consist of ordinary English text.
3091// If this module is ever modified to produce version 1.1 XML output,
3092// most invalid characters can be retained using character references.
3093// TODO(wan): It might be nice to have a minimally invasive, human-readable
3094// escaping scheme for invalid characters, rather than dropping them.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003095String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003096 Message m;
3097
3098 if (str != NULL) {
3099 for (const char* src = str; *src; ++src) {
3100 switch (*src) {
3101 case '<':
3102 m << "&lt;";
3103 break;
3104 case '>':
3105 m << "&gt;";
3106 break;
3107 case '&':
3108 m << "&amp;";
3109 break;
3110 case '\'':
3111 if (is_attribute)
3112 m << "&apos;";
3113 else
3114 m << '\'';
3115 break;
3116 case '"':
3117 if (is_attribute)
3118 m << "&quot;";
3119 else
3120 m << '"';
3121 break;
3122 default:
3123 if (IsValidXmlCharacter(*src)) {
3124 if (is_attribute && IsNormalizableWhitespace(*src))
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003125 m << String::Format("&#x%02X;", unsigned(*src));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003126 else
3127 m << *src;
3128 }
3129 break;
3130 }
3131 }
3132 }
3133
3134 return m.GetString();
3135}
3136
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003137// Returns the given string with all characters invalid in XML removed.
3138// Currently invalid characters are dropped from the string. An
3139// alternative is to replace them with certain characters such as . or ?.
Jay Foadb33f8e32011-07-27 09:25:14 +00003140string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
3141 string output;
3142 output.reserve(str.size());
3143 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
3144 if (IsValidXmlCharacter(*it))
3145 output.push_back(*it);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003146
Jay Foadb33f8e32011-07-27 09:25:14 +00003147 return output;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003148}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003149
3150// The following routines generate an XML representation of a UnitTest
3151// object.
3152//
3153// This is how Google Test concepts map to the DTD:
3154//
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003155// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003156// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3157// <testcase name="test-name"> <-- corresponds to a TestInfo object
3158// <failure message="...">...</failure>
3159// <failure message="...">...</failure>
3160// <failure message="...">...</failure>
3161// <-- individual assertion failures
3162// </testcase>
3163// </testsuite>
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003164// </testsuites>
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003165
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003166// Formats the given time in milliseconds as seconds.
3167std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3168 ::std::stringstream ss;
3169 ss << ms/1000.0;
3170 return ss.str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003171}
3172
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003173// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3174void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3175 const char* data) {
3176 const char* segment = data;
3177 *stream << "<![CDATA[";
3178 for (;;) {
3179 const char* const next_segment = strstr(segment, "]]>");
3180 if (next_segment != NULL) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003181 stream->write(
3182 segment, static_cast<std::streamsize>(next_segment - segment));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003183 *stream << "]]>]]&gt;<![CDATA[";
3184 segment = next_segment + strlen("]]>");
3185 } else {
3186 *stream << segment;
3187 break;
3188 }
3189 }
3190 *stream << "]]>";
3191}
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003192
3193// Prints an XML representation of a TestInfo object.
3194// TODO(wan): There is also value in printing properties with the plain printer.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003195void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3196 const char* test_case_name,
3197 const TestInfo& test_info) {
3198 const TestResult& result = *test_info.result();
3199 *stream << " <testcase name=\""
Jay Foadb33f8e32011-07-27 09:25:14 +00003200 << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
3201
3202 if (test_info.value_param() != NULL) {
3203 *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
3204 << "\"";
3205 }
3206 if (test_info.type_param() != NULL) {
3207 *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
3208 << "\"";
3209 }
3210
3211 *stream << " status=\""
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003212 << (test_info.should_run() ? "run" : "notrun")
3213 << "\" time=\""
3214 << FormatTimeInMillisAsSeconds(result.elapsed_time())
3215 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3216 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003217
3218 int failures = 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003219 for (int i = 0; i < result.total_part_count(); ++i) {
3220 const TestPartResult& part = result.GetTestPartResult(i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003221 if (part.failed()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003222 if (++failures == 1)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003223 *stream << ">\n";
3224 *stream << " <failure message=\""
3225 << EscapeXmlAttribute(part.summary()).c_str()
3226 << "\" type=\"\">";
Jay Foadb33f8e32011-07-27 09:25:14 +00003227 const string location = internal::FormatCompilerIndependentFileLocation(
3228 part.file_name(), part.line_number());
3229 const string message = location + "\n" + part.message();
3230 OutputXmlCDataSection(stream,
3231 RemoveInvalidXmlCharacters(message).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003232 *stream << "</failure>\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003233 }
3234 }
3235
3236 if (failures == 0)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003237 *stream << " />\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003238 else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003239 *stream << " </testcase>\n";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003240}
3241
3242// Prints an XML representation of a TestCase object
3243void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003244 const TestCase& test_case) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003245 fprintf(out,
3246 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3247 "disabled=\"%d\" ",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003248 EscapeXmlAttribute(test_case.name()).c_str(),
3249 test_case.total_test_count(),
3250 test_case.failed_test_count(),
3251 test_case.disabled_test_count());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003252 fprintf(out,
3253 "errors=\"0\" time=\"%s\">\n",
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003254 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003255 for (int i = 0; i < test_case.total_test_count(); ++i) {
Jay Foadb33f8e32011-07-27 09:25:14 +00003256 ::std::stringstream stream;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003257 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
Jay Foadb33f8e32011-07-27 09:25:14 +00003258 fprintf(out, "%s", StringStreamToString(&stream).c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003259 }
3260 fprintf(out, " </testsuite>\n");
3261}
3262
3263// Prints an XML summary of unit_test to output stream out.
3264void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003265 const UnitTest& unit_test) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003266 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3267 fprintf(out,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003268 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003269 "errors=\"0\" time=\"%s\" ",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003270 unit_test.total_test_count(),
3271 unit_test.failed_test_count(),
3272 unit_test.disabled_test_count(),
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003273 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003274 if (GTEST_FLAG(shuffle)) {
3275 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003276 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003277 fprintf(out, "name=\"AllTests\">\n");
3278 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3279 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3280 fprintf(out, "</testsuites>\n");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003281}
3282
3283// Produces a string representing the test properties in a result as space
3284// delimited XML attributes based on the property key="value" pairs.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003285String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3286 const TestResult& result) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003287 Message attributes;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003288 for (int i = 0; i < result.test_property_count(); ++i) {
3289 const TestProperty& property = result.GetTestProperty(i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003290 attributes << " " << property.key() << "="
3291 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3292 }
3293 return attributes.GetString();
3294}
3295
3296// End XmlUnitTestResultPrinter
3297
Jay Foadb33f8e32011-07-27 09:25:14 +00003298#if GTEST_CAN_STREAM_RESULTS_
3299
3300// Streams test results to the given port on the given host machine.
3301class StreamingListener : public EmptyTestEventListener {
3302 public:
3303 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
3304 static string UrlEncode(const char* str);
3305
3306 StreamingListener(const string& host, const string& port)
3307 : sockfd_(-1), host_name_(host), port_num_(port) {
3308 MakeConnection();
3309 Send("gtest_streaming_protocol_version=1.0\n");
3310 }
3311
3312 virtual ~StreamingListener() {
3313 if (sockfd_ != -1)
3314 CloseConnection();
3315 }
3316
3317 void OnTestProgramStart(const UnitTest& /* unit_test */) {
3318 Send("event=TestProgramStart\n");
3319 }
3320
3321 void OnTestProgramEnd(const UnitTest& unit_test) {
3322 // Note that Google Test current only report elapsed time for each
3323 // test iteration, not for the entire test program.
3324 Send(String::Format("event=TestProgramEnd&passed=%d\n",
3325 unit_test.Passed()));
3326
3327 // Notify the streaming server to stop.
3328 CloseConnection();
3329 }
3330
3331 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
3332 Send(String::Format("event=TestIterationStart&iteration=%d\n",
3333 iteration));
3334 }
3335
3336 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
3337 Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
3338 unit_test.Passed(),
3339 StreamableToString(unit_test.elapsed_time()).c_str()));
3340 }
3341
3342 void OnTestCaseStart(const TestCase& test_case) {
3343 Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
3344 }
3345
3346 void OnTestCaseEnd(const TestCase& test_case) {
3347 Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
3348 test_case.Passed(),
3349 StreamableToString(test_case.elapsed_time()).c_str()));
3350 }
3351
3352 void OnTestStart(const TestInfo& test_info) {
3353 Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
3354 }
3355
3356 void OnTestEnd(const TestInfo& test_info) {
3357 Send(String::Format(
3358 "event=TestEnd&passed=%d&elapsed_time=%sms\n",
3359 (test_info.result())->Passed(),
3360 StreamableToString((test_info.result())->elapsed_time()).c_str()));
3361 }
3362
3363 void OnTestPartResult(const TestPartResult& test_part_result) {
3364 const char* file_name = test_part_result.file_name();
3365 if (file_name == NULL)
3366 file_name = "";
3367 Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
3368 UrlEncode(file_name).c_str(),
3369 test_part_result.line_number()));
3370 Send(UrlEncode(test_part_result.message()) + "\n");
3371 }
3372
3373 private:
3374 // Creates a client socket and connects to the server.
3375 void MakeConnection();
3376
3377 // Closes the socket.
3378 void CloseConnection() {
3379 GTEST_CHECK_(sockfd_ != -1)
3380 << "CloseConnection() can be called only when there is a connection.";
3381
3382 close(sockfd_);
3383 sockfd_ = -1;
3384 }
3385
3386 // Sends a string to the socket.
3387 void Send(const string& message) {
3388 GTEST_CHECK_(sockfd_ != -1)
3389 << "Send() can be called only when there is a connection.";
3390
3391 const int len = static_cast<int>(message.length());
3392 if (write(sockfd_, message.c_str(), len) != len) {
3393 GTEST_LOG_(WARNING)
3394 << "stream_result_to: failed to stream to "
3395 << host_name_ << ":" << port_num_;
3396 }
3397 }
3398
3399 int sockfd_; // socket file descriptor
3400 const string host_name_;
3401 const string port_num_;
3402
3403 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
3404}; // class StreamingListener
3405
3406// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
3407// replaces them by "%xx" where xx is their hexadecimal value. For
3408// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
3409// in both time and space -- important as the input str may contain an
3410// arbitrarily long test failure message and stack trace.
3411string StreamingListener::UrlEncode(const char* str) {
3412 string result;
3413 result.reserve(strlen(str) + 1);
3414 for (char ch = *str; ch != '\0'; ch = *++str) {
3415 switch (ch) {
3416 case '%':
3417 case '=':
3418 case '&':
3419 case '\n':
3420 result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
3421 break;
3422 default:
3423 result.push_back(ch);
3424 break;
3425 }
3426 }
3427 return result;
3428}
3429
3430void StreamingListener::MakeConnection() {
3431 GTEST_CHECK_(sockfd_ == -1)
3432 << "MakeConnection() can't be called when there is already a connection.";
3433
3434 addrinfo hints;
3435 memset(&hints, 0, sizeof(hints));
3436 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
3437 hints.ai_socktype = SOCK_STREAM;
3438 addrinfo* servinfo = NULL;
3439
3440 // Use the getaddrinfo() to get a linked list of IP addresses for
3441 // the given host name.
3442 const int error_num = getaddrinfo(
3443 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
3444 if (error_num != 0) {
3445 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
3446 << gai_strerror(error_num);
3447 }
3448
3449 // Loop through all the results and connect to the first we can.
3450 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
3451 cur_addr = cur_addr->ai_next) {
3452 sockfd_ = socket(
3453 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
3454 if (sockfd_ != -1) {
3455 // Connect the client socket to the server socket.
3456 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
3457 close(sockfd_);
3458 sockfd_ = -1;
3459 }
3460 }
3461 }
3462
3463 freeaddrinfo(servinfo); // all done with this structure
3464
3465 if (sockfd_ == -1) {
3466 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
3467 << host_name_ << ":" << port_num_;
3468 }
3469}
3470
3471// End of class Streaming Listener
3472#endif // GTEST_CAN_STREAM_RESULTS__
3473
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003474// Class ScopedTrace
3475
3476// Pushes the given source file location and message onto a per-thread
3477// trace stack maintained by Google Test.
3478// L < UnitTest::mutex_
3479ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3480 TraceInfo trace;
3481 trace.file = file;
3482 trace.line = line;
3483 trace.message = message.GetString();
3484
3485 UnitTest::GetInstance()->PushGTestTrace(trace);
3486}
3487
3488// Pops the info pushed by the c'tor.
3489// L < UnitTest::mutex_
3490ScopedTrace::~ScopedTrace() {
3491 UnitTest::GetInstance()->PopGTestTrace();
3492}
3493
3494
3495// class OsStackTraceGetter
3496
3497// Returns the current OS stack trace as a String. Parameters:
3498//
3499// max_depth - the maximum number of stack frames to be included
3500// in the trace.
3501// skip_count - the number of top frames to be skipped; doesn't count
3502// against max_depth.
3503//
3504// L < mutex_
3505// We use "L < mutex_" to denote that the function may acquire mutex_.
3506String OsStackTraceGetter::CurrentStackTrace(int, int) {
3507 return String("");
3508}
3509
3510// L < mutex_
3511void OsStackTraceGetter::UponLeavingGTest() {
3512}
3513
3514const char* const
3515OsStackTraceGetter::kElidedFramesMarker =
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003516 "... " GTEST_NAME_ " internal frames ...";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003517
3518} // namespace internal
3519
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003520// class TestEventListeners
3521
3522TestEventListeners::TestEventListeners()
3523 : repeater_(new internal::TestEventRepeater()),
3524 default_result_printer_(NULL),
3525 default_xml_generator_(NULL) {
3526}
3527
3528TestEventListeners::~TestEventListeners() { delete repeater_; }
3529
3530// Returns the standard listener responsible for the default console
3531// output. Can be removed from the listeners list to shut down default
3532// console output. Note that removing this object from the listener list
3533// with Release transfers its ownership to the user.
3534void TestEventListeners::Append(TestEventListener* listener) {
3535 repeater_->Append(listener);
3536}
3537
3538// Removes the given event listener from the list and returns it. It then
3539// becomes the caller's responsibility to delete the listener. Returns
3540// NULL if the listener is not found in the list.
3541TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3542 if (listener == default_result_printer_)
3543 default_result_printer_ = NULL;
3544 else if (listener == default_xml_generator_)
3545 default_xml_generator_ = NULL;
3546 return repeater_->Release(listener);
3547}
3548
3549// Returns repeater that broadcasts the TestEventListener events to all
3550// subscribers.
3551TestEventListener* TestEventListeners::repeater() { return repeater_; }
3552
3553// Sets the default_result_printer attribute to the provided listener.
3554// The listener is also added to the listener list and previous
3555// default_result_printer is removed from it and deleted. The listener can
3556// also be NULL in which case it will not be added to the list. Does
3557// nothing if the previous and the current listener objects are the same.
3558void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3559 if (default_result_printer_ != listener) {
3560 // It is an error to pass this method a listener that is already in the
3561 // list.
3562 delete Release(default_result_printer_);
3563 default_result_printer_ = listener;
3564 if (listener != NULL)
3565 Append(listener);
3566 }
3567}
3568
3569// Sets the default_xml_generator attribute to the provided listener. The
3570// listener is also added to the listener list and previous
3571// default_xml_generator is removed from it and deleted. The listener can
3572// also be NULL in which case it will not be added to the list. Does
3573// nothing if the previous and the current listener objects are the same.
3574void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3575 if (default_xml_generator_ != listener) {
3576 // It is an error to pass this method a listener that is already in the
3577 // list.
3578 delete Release(default_xml_generator_);
3579 default_xml_generator_ = listener;
3580 if (listener != NULL)
3581 Append(listener);
3582 }
3583}
3584
3585// Controls whether events will be forwarded by the repeater to the
3586// listeners in the list.
3587bool TestEventListeners::EventForwardingEnabled() const {
3588 return repeater_->forwarding_enabled();
3589}
3590
3591void TestEventListeners::SuppressEventForwarding() {
3592 repeater_->set_forwarding_enabled(false);
3593}
3594
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003595// class UnitTest
3596
3597// Gets the singleton UnitTest object. The first time this method is
3598// called, a UnitTest object is constructed and returned. Consecutive
3599// calls will return the same object.
3600//
3601// We don't protect this under mutex_ as a user is not supposed to
3602// call this before main() starts, from which point on the return
3603// value will never change.
3604UnitTest * UnitTest::GetInstance() {
3605 // When compiled with MSVC 7.1 in optimized mode, destroying the
3606 // UnitTest object upon exiting the program messes up the exit code,
3607 // causing successful tests to appear failed. We have to use a
3608 // different implementation in this case to bypass the compiler bug.
3609 // This implementation makes the compiler happy, at the cost of
3610 // leaking the UnitTest object.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003611
3612 // CodeGear C++Builder insists on a public destructor for the
3613 // default implementation. Use this implementation to keep good OO
3614 // design with private destructor.
3615
3616#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003617 static UnitTest* const instance = new UnitTest;
3618 return instance;
3619#else
3620 static UnitTest instance;
3621 return &instance;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003622#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3623}
3624
3625// Gets the number of successful test cases.
3626int UnitTest::successful_test_case_count() const {
3627 return impl()->successful_test_case_count();
3628}
3629
3630// Gets the number of failed test cases.
3631int UnitTest::failed_test_case_count() const {
3632 return impl()->failed_test_case_count();
3633}
3634
3635// Gets the number of all test cases.
3636int UnitTest::total_test_case_count() const {
3637 return impl()->total_test_case_count();
3638}
3639
3640// Gets the number of all test cases that contain at least one test
3641// that should run.
3642int UnitTest::test_case_to_run_count() const {
3643 return impl()->test_case_to_run_count();
3644}
3645
3646// Gets the number of successful tests.
3647int UnitTest::successful_test_count() const {
3648 return impl()->successful_test_count();
3649}
3650
3651// Gets the number of failed tests.
3652int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3653
3654// Gets the number of disabled tests.
3655int UnitTest::disabled_test_count() const {
3656 return impl()->disabled_test_count();
3657}
3658
3659// Gets the number of all tests.
3660int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3661
3662// Gets the number of tests that should run.
3663int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3664
3665// Gets the elapsed time, in milliseconds.
3666internal::TimeInMillis UnitTest::elapsed_time() const {
3667 return impl()->elapsed_time();
3668}
3669
3670// Returns true iff the unit test passed (i.e. all test cases passed).
3671bool UnitTest::Passed() const { return impl()->Passed(); }
3672
3673// Returns true iff the unit test failed (i.e. some test case failed
3674// or something outside of all tests failed).
3675bool UnitTest::Failed() const { return impl()->Failed(); }
3676
3677// Gets the i-th test case among all the test cases. i can range from 0 to
3678// total_test_case_count() - 1. If i is not in that range, returns NULL.
3679const TestCase* UnitTest::GetTestCase(int i) const {
3680 return impl()->GetTestCase(i);
3681}
3682
3683// Gets the i-th test case among all the test cases. i can range from 0 to
3684// total_test_case_count() - 1. If i is not in that range, returns NULL.
3685TestCase* UnitTest::GetMutableTestCase(int i) {
3686 return impl()->GetMutableTestCase(i);
3687}
3688
3689// Returns the list of event listeners that can be used to track events
3690// inside Google Test.
3691TestEventListeners& UnitTest::listeners() {
3692 return *impl()->listeners();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003693}
3694
3695// Registers and returns a global test environment. When a test
3696// program is run, all global test environments will be set-up in the
3697// order they were registered. After all tests in the program have
3698// finished, all global test environments will be torn-down in the
3699// *reverse* order they were registered.
3700//
3701// The UnitTest object takes ownership of the given environment.
3702//
3703// We don't protect this under mutex_, as we only support calling it
3704// from the main thread.
3705Environment* UnitTest::AddEnvironment(Environment* env) {
3706 if (env == NULL) {
3707 return NULL;
3708 }
3709
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003710 impl_->environments().push_back(env);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003711 return env;
3712}
3713
3714// Adds a TestPartResult to the current TestResult object. All Google Test
3715// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3716// this to report their results. The user code should use the
3717// assertion macros instead of calling this directly.
3718// L < mutex_
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003719void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003720 const char* file_name,
3721 int line_number,
3722 const internal::String& message,
3723 const internal::String& os_stack_trace) {
3724 Message msg;
3725 msg << message;
3726
3727 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003728 if (impl_->gtest_trace_stack().size() > 0) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003729 msg << "\n" << GTEST_NAME_ << " trace:";
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003730
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003731 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
3732 i > 0; --i) {
3733 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003734 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3735 << " " << trace.message;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003736 }
3737 }
3738
3739 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3740 msg << internal::kStackTraceMarker << os_stack_trace;
3741 }
3742
3743 const TestPartResult result =
3744 TestPartResult(result_type, file_name, line_number,
3745 msg.GetString().c_str());
3746 impl_->GetTestPartResultReporterForCurrentThread()->
3747 ReportTestPartResult(result);
3748
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003749 if (result_type != TestPartResult::kSuccess) {
3750 // gtest_break_on_failure takes precedence over
3751 // gtest_throw_on_failure. This allows a user to set the latter
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003752 // in the code (perhaps in order to use Google Test assertions
3753 // with another testing framework) and specify the former on the
3754 // command line for debugging.
3755 if (GTEST_FLAG(break_on_failure)) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003756#if GTEST_OS_WINDOWS
3757 // Using DebugBreak on Windows allows gtest to still break into a debugger
3758 // when a failure happens and both the --gtest_break_on_failure and
3759 // the --gtest_catch_exceptions flags are specified.
3760 DebugBreak();
3761#else
Jakob Stoklund Olesena70282d2010-07-12 18:17:47 +00003762 abort();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003763#endif // GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003764 } else if (GTEST_FLAG(throw_on_failure)) {
3765#if GTEST_HAS_EXCEPTIONS
3766 throw GoogleTestFailureException(result);
3767#else
3768 // We cannot call abort() as it generates a pop-up in debug mode
3769 // that cannot be suppressed in VC 7.1 or below.
3770 exit(1);
3771#endif
3772 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003773 }
3774}
3775
3776// Creates and adds a property to the current TestResult. If a property matching
3777// the supplied value already exists, updates its value instead.
3778void UnitTest::RecordPropertyForCurrentTest(const char* key,
3779 const char* value) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003780 const TestProperty test_property(key, value);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003781 impl_->current_test_result()->RecordProperty(test_property);
3782}
3783
3784// Runs all tests in this UnitTest object and prints the result.
3785// Returns 0 if successful, or 1 otherwise.
3786//
3787// We don't protect this under mutex_, as we only support calling it
3788// from the main thread.
3789int UnitTest::Run() {
Jay Foadb33f8e32011-07-27 09:25:14 +00003790 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
3791 // used for the duration of the program.
3792 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003793
Jay Foadb33f8e32011-07-27 09:25:14 +00003794#if GTEST_HAS_SEH
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003795 const bool in_death_test_child_process =
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003796 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003797
3798 // Either the user wants Google Test to catch exceptions thrown by the
3799 // tests or this is executing in the context of death test child
3800 // process. In either case the user does not want to see pop-up dialogs
Jay Foadb33f8e32011-07-27 09:25:14 +00003801 // about crashes - they are expected.
3802 if (impl()->catch_exceptions() || in_death_test_child_process) {
3803
3804# if !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003805 // SetErrorMode doesn't exist on CE.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003806 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3807 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
Jay Foadb33f8e32011-07-27 09:25:14 +00003808# endif // !GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003809
Jay Foadb33f8e32011-07-27 09:25:14 +00003810# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003811 // Death test children can be terminated with _abort(). On Windows,
3812 // _abort() can show a dialog with a warning message. This forces the
3813 // abort message to go to stderr instead.
3814 _set_error_mode(_OUT_TO_STDERR);
Jay Foadb33f8e32011-07-27 09:25:14 +00003815# endif
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003816
Jay Foadb33f8e32011-07-27 09:25:14 +00003817# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003818 // In the debug version, Visual Studio pops up a separate dialog
3819 // offering a choice to debug the aborted program. We need to suppress
3820 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3821 // executed. Google Test will notify the user of any unexpected
3822 // failure via stderr.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003823 //
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003824 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3825 // Users of prior VC versions shall suffer the agony and pain of
3826 // clicking through the countless debug dialogs.
3827 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3828 // debug mode when compiled with VC 7.1 or lower.
3829 if (!GTEST_FLAG(break_on_failure))
3830 _set_abort_behavior(
3831 0x0, // Clear the following flags:
3832 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
Jay Foadb33f8e32011-07-27 09:25:14 +00003833# endif
3834
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003835 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003836#endif // GTEST_HAS_SEH
Jay Foadb33f8e32011-07-27 09:25:14 +00003837
3838 return internal::HandleExceptionsInMethodIfSupported(
3839 impl(),
3840 &internal::UnitTestImpl::RunAllTests,
3841 "auxiliary test code (environments or event listeners)") ? 0 : 1;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003842}
3843
3844// Returns the working directory when the first TEST() or TEST_F() was
3845// executed.
3846const char* UnitTest::original_working_dir() const {
3847 return impl_->original_working_dir_.c_str();
3848}
3849
3850// Returns the TestCase object for the test that's currently running,
3851// or NULL if no test is running.
3852// L < mutex_
3853const TestCase* UnitTest::current_test_case() const {
3854 internal::MutexLock lock(&mutex_);
3855 return impl_->current_test_case();
3856}
3857
3858// Returns the TestInfo object for the test that's currently running,
3859// or NULL if no test is running.
3860// L < mutex_
3861const TestInfo* UnitTest::current_test_info() const {
3862 internal::MutexLock lock(&mutex_);
3863 return impl_->current_test_info();
3864}
3865
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003866// Returns the random seed used at the start of the current test run.
3867int UnitTest::random_seed() const { return impl_->random_seed(); }
3868
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003869#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003870// Returns ParameterizedTestCaseRegistry object used to keep track of
3871// value-parameterized tests and instantiate and register them.
3872// L < mutex_
3873internal::ParameterizedTestCaseRegistry&
3874 UnitTest::parameterized_test_registry() {
3875 return impl_->parameterized_test_registry();
3876}
3877#endif // GTEST_HAS_PARAM_TEST
3878
3879// Creates an empty UnitTest.
3880UnitTest::UnitTest() {
3881 impl_ = new internal::UnitTestImpl(this);
3882}
3883
3884// Destructor of UnitTest.
3885UnitTest::~UnitTest() {
3886 delete impl_;
3887}
3888
3889// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3890// Google Test trace stack.
3891// L < mutex_
3892void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3893 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003894 impl_->gtest_trace_stack().push_back(trace);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003895}
3896
3897// Pops a trace from the per-thread Google Test trace stack.
3898// L < mutex_
3899void UnitTest::PopGTestTrace() {
3900 internal::MutexLock lock(&mutex_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003901 impl_->gtest_trace_stack().pop_back();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003902}
3903
3904namespace internal {
3905
3906UnitTestImpl::UnitTestImpl(UnitTest* parent)
3907 : parent_(parent),
3908#ifdef _MSC_VER
Jay Foadb33f8e32011-07-27 09:25:14 +00003909# pragma warning(push) // Saves the current warning state.
3910# pragma warning(disable:4355) // Temporarily disables warning 4355
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003911 // (using this in initializer).
3912 default_global_test_part_result_reporter_(this),
3913 default_per_thread_test_part_result_reporter_(this),
Jay Foadb33f8e32011-07-27 09:25:14 +00003914# pragma warning(pop) // Restores the warning state again.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003915#else
3916 default_global_test_part_result_reporter_(this),
3917 default_per_thread_test_part_result_reporter_(this),
3918#endif // _MSC_VER
3919 global_test_part_result_repoter_(
3920 &default_global_test_part_result_reporter_),
3921 per_thread_test_part_result_reporter_(
3922 &default_per_thread_test_part_result_reporter_),
Benjamin Kramere4b9c932010-06-02 22:01:25 +00003923#if GTEST_HAS_PARAM_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003924 parameterized_test_registry_(),
3925 parameterized_tests_registered_(false),
3926#endif // GTEST_HAS_PARAM_TEST
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003927 last_death_test_case_(-1),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003928 current_test_case_(NULL),
3929 current_test_info_(NULL),
3930 ad_hoc_test_result_(),
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003931 os_stack_trace_getter_(NULL),
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003932 post_flag_parse_init_performed_(false),
3933 random_seed_(0), // Will be overridden by the flag before first use.
3934 random_(0), // Will be reseeded before first use.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003935 elapsed_time_(0),
Jay Foadb33f8e32011-07-27 09:25:14 +00003936#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003937 internal_run_death_test_flag_(NULL),
Jay Foadb33f8e32011-07-27 09:25:14 +00003938 death_test_factory_(new DefaultDeathTestFactory),
3939#endif
3940 // Will be overridden by the flag before first use.
3941 catch_exceptions_(false) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003942 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003943}
3944
3945UnitTestImpl::~UnitTestImpl() {
3946 // Deletes every TestCase.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003947 ForEach(test_cases_, internal::Delete<TestCase>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003948
3949 // Deletes every Environment.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00003950 ForEach(environments_, internal::Delete<Environment>);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003951
Misha Brukman7ae6ff42008-12-31 17:34:06 +00003952 delete os_stack_trace_getter_;
3953}
3954
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003955#if GTEST_HAS_DEATH_TEST
3956// Disables event forwarding if the control is currently in a death test
3957// subprocess. Must not be called before InitGoogleTest.
3958void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3959 if (internal_run_death_test_flag_.get() != NULL)
3960 listeners()->SuppressEventForwarding();
3961}
3962#endif // GTEST_HAS_DEATH_TEST
3963
3964// Initializes event listeners performing XML output as specified by
3965// UnitTestOptions. Must not be called before InitGoogleTest.
3966void UnitTestImpl::ConfigureXmlOutput() {
3967 const String& output_format = UnitTestOptions::GetOutputFormat();
3968 if (output_format == "xml") {
3969 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3970 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3971 } else if (output_format != "") {
3972 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3973 output_format.c_str());
3974 fflush(stdout);
3975 }
3976}
3977
Jay Foadb33f8e32011-07-27 09:25:14 +00003978#if GTEST_CAN_STREAM_RESULTS_
3979// Initializes event listeners for streaming test results in String form.
3980// Must not be called before InitGoogleTest.
3981void UnitTestImpl::ConfigureStreamingOutput() {
3982 const string& target = GTEST_FLAG(stream_result_to);
3983 if (!target.empty()) {
3984 const size_t pos = target.find(':');
3985 if (pos != string::npos) {
3986 listeners()->Append(new StreamingListener(target.substr(0, pos),
3987 target.substr(pos+1)));
3988 } else {
3989 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
3990 target.c_str());
3991 fflush(stdout);
3992 }
3993 }
3994}
3995#endif // GTEST_CAN_STREAM_RESULTS_
3996
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00003997// Performs initialization dependent upon flag values obtained in
3998// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
3999// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
4000// this function is also called from RunAllTests. Since this function can be
4001// called more than once, it has to be idempotent.
4002void UnitTestImpl::PostFlagParsingInit() {
4003 // Ensures that this function does not execute more than once.
4004 if (!post_flag_parse_init_performed_) {
4005 post_flag_parse_init_performed_ = true;
4006
4007#if GTEST_HAS_DEATH_TEST
4008 InitDeathTestSubprocessControlInfo();
4009 SuppressTestEventsIfInSubprocess();
4010#endif // GTEST_HAS_DEATH_TEST
4011
4012 // Registers parameterized tests. This makes parameterized tests
4013 // available to the UnitTest reflection API without running
4014 // RUN_ALL_TESTS.
4015 RegisterParameterizedTests();
4016
4017 // Configures listeners for XML output. This makes it possible for users
4018 // to shut down the default XML output before invoking RUN_ALL_TESTS.
4019 ConfigureXmlOutput();
Jay Foadb33f8e32011-07-27 09:25:14 +00004020
4021#if GTEST_CAN_STREAM_RESULTS_
4022 // Configures listeners for streaming test results to the specified server.
4023 ConfigureStreamingOutput();
4024#endif // GTEST_CAN_STREAM_RESULTS_
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004025 }
4026}
4027
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004028// A predicate that checks the name of a TestCase against a known
4029// value.
4030//
4031// This is used for implementation of the UnitTest class only. We put
4032// it in the anonymous namespace to prevent polluting the outer
4033// namespace.
4034//
4035// TestCaseNameIs is copyable.
4036class TestCaseNameIs {
4037 public:
4038 // Constructor.
4039 explicit TestCaseNameIs(const String& name)
4040 : name_(name) {}
4041
4042 // Returns true iff the name of test_case matches name_.
4043 bool operator()(const TestCase* test_case) const {
4044 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
4045 }
4046
4047 private:
4048 String name_;
4049};
4050
4051// Finds and returns a TestCase with the given name. If one doesn't
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004052// exist, creates one and returns it. It's the CALLER'S
4053// RESPONSIBILITY to ensure that this function is only called WHEN THE
4054// TESTS ARE NOT SHUFFLED.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004055//
4056// Arguments:
4057//
4058// test_case_name: name of the test case
Jay Foadb33f8e32011-07-27 09:25:14 +00004059// type_param: the name of the test case's type parameter, or NULL if
4060// this is not a typed or a type-parameterized test case.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004061// set_up_tc: pointer to the function that sets up the test case
4062// tear_down_tc: pointer to the function that tears down the test case
4063TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
Jay Foadb33f8e32011-07-27 09:25:14 +00004064 const char* type_param,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004065 Test::SetUpTestCaseFunc set_up_tc,
4066 Test::TearDownTestCaseFunc tear_down_tc) {
4067 // Can we find a TestCase with the given name?
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004068 const std::vector<TestCase*>::const_iterator test_case =
4069 std::find_if(test_cases_.begin(), test_cases_.end(),
4070 TestCaseNameIs(test_case_name));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004071
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004072 if (test_case != test_cases_.end())
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004073 return *test_case;
4074
4075 // No. Let's create one.
4076 TestCase* const new_test_case =
Jay Foadb33f8e32011-07-27 09:25:14 +00004077 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004078
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004079 // Is this a death test case?
4080 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
4081 kDeathTestCaseFilter)) {
4082 // Yes. Inserts the test case after the last death test case
4083 // defined so far. This only works when the test cases haven't
4084 // been shuffled. Otherwise we may end up running a death test
4085 // after a non-death test.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004086 ++last_death_test_case_;
4087 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
4088 new_test_case);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004089 } else {
4090 // No. Appends to the end of the list.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004091 test_cases_.push_back(new_test_case);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004092 }
4093
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004094 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004095 return new_test_case;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004096}
4097
4098// Helpers for setting up / tearing down the given environment. They
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004099// are for use in the ForEach() function.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004100static void SetUpEnvironment(Environment* env) { env->SetUp(); }
4101static void TearDownEnvironment(Environment* env) { env->TearDown(); }
4102
4103// Runs all tests in this UnitTest object, prints the result, and
Jay Foadb33f8e32011-07-27 09:25:14 +00004104// returns true if all tests are successful. If any exception is
4105// thrown during a test, the test is considered to be failed, but the
4106// rest of the tests will still be run.
4107//
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004108// When parameterized tests are enabled, it expands and registers
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004109// parameterized tests first in RegisterParameterizedTests().
4110// All other functions called from RunAllTests() may safely assume that
4111// parameterized tests are ready to be counted and run.
Jay Foadb33f8e32011-07-27 09:25:14 +00004112bool UnitTestImpl::RunAllTests() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004113 // Makes sure InitGoogleTest() was called.
4114 if (!GTestIsInitialized()) {
4115 printf("%s",
4116 "\nThis test program did NOT call ::testing::InitGoogleTest "
4117 "before calling RUN_ALL_TESTS(). Please fix it.\n");
Jay Foadb33f8e32011-07-27 09:25:14 +00004118 return false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004119 }
4120
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004121 // Do not run any test if the --help flag was specified.
4122 if (g_help_flag)
Jay Foadb33f8e32011-07-27 09:25:14 +00004123 return true;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004124
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004125 // Repeats the call to the post-flag parsing initialization in case the
4126 // user didn't call InitGoogleTest.
4127 PostFlagParsingInit();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004128
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004129 // Even if sharding is not on, test runners may want to use the
4130 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
4131 // protocol.
4132 internal::WriteToShardStatusFileIfNeeded();
4133
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004134 // True iff we are in a subprocess for running a thread-safe-style
4135 // death test.
4136 bool in_subprocess_for_death_test = false;
4137
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004138#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004139 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
4140#endif // GTEST_HAS_DEATH_TEST
4141
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004142 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
4143 in_subprocess_for_death_test);
4144
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004145 // Compares the full test names with the filter to decide which
4146 // tests to run.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004147 const bool has_tests_to_run = FilterTests(should_shard
4148 ? HONOR_SHARDING_PROTOCOL
4149 : IGNORE_SHARDING_PROTOCOL) > 0;
4150
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004151 // Lists the tests and exits if the --gtest_list_tests flag was specified.
4152 if (GTEST_FLAG(list_tests)) {
4153 // This must be called *after* FilterTests() has been called.
4154 ListTestsMatchingFilter();
Jay Foadb33f8e32011-07-27 09:25:14 +00004155 return true;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004156 }
4157
4158 random_seed_ = GTEST_FLAG(shuffle) ?
4159 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
4160
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004161 // True iff at least one test has failed.
4162 bool failed = false;
4163
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004164 TestEventListener* repeater = listeners()->repeater();
4165
4166 repeater->OnTestProgramStart(*parent_);
4167
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004168 // How many times to repeat the tests? We don't want to repeat them
4169 // when we are inside the subprocess of a death test.
4170 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
4171 // Repeats forever if the repeat count is negative.
4172 const bool forever = repeat < 0;
4173 for (int i = 0; forever || i != repeat; i++) {
Jay Foadb33f8e32011-07-27 09:25:14 +00004174 // We want to preserve failures generated by ad-hoc test
4175 // assertions executed before RUN_ALL_TESTS().
4176 ClearNonAdHocTestResult();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004177
4178 const TimeInMillis start = GetTimeInMillis();
4179
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004180 // Shuffles test cases and tests if requested.
4181 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
4182 random()->Reseed(random_seed_);
4183 // This should be done before calling OnTestIterationStart(),
4184 // such that a test event listener can see the actual test order
4185 // in the event.
4186 ShuffleTests();
4187 }
4188
4189 // Tells the unit test event listeners that the tests are about to start.
4190 repeater->OnTestIterationStart(*parent_, i);
4191
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004192 // Runs each test case if there is at least one test to run.
4193 if (has_tests_to_run) {
4194 // Sets up all environments beforehand.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004195 repeater->OnEnvironmentsSetUpStart(*parent_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004196 ForEach(environments_, SetUpEnvironment);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004197 repeater->OnEnvironmentsSetUpEnd(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004198
4199 // Runs the tests only if there was no fatal failure during global
4200 // set-up.
4201 if (!Test::HasFatalFailure()) {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004202 for (int test_index = 0; test_index < total_test_case_count();
4203 test_index++) {
4204 GetMutableTestCase(test_index)->Run();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004205 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004206 }
4207
4208 // Tears down all environments in reverse order afterwards.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004209 repeater->OnEnvironmentsTearDownStart(*parent_);
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004210 std::for_each(environments_.rbegin(), environments_.rend(),
4211 TearDownEnvironment);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004212 repeater->OnEnvironmentsTearDownEnd(*parent_);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004213 }
4214
4215 elapsed_time_ = GetTimeInMillis() - start;
4216
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004217 // Tells the unit test event listener that the tests have just finished.
4218 repeater->OnTestIterationEnd(*parent_, i);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004219
4220 // Gets the result and clears it.
4221 if (!Passed()) {
4222 failed = true;
4223 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004224
4225 // Restores the original test order after the iteration. This
4226 // allows the user to quickly repro a failure that happens in the
4227 // N-th iteration without repeating the first (N - 1) iterations.
4228 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4229 // case the user somehow changes the value of the flag somewhere
4230 // (it's always safe to unshuffle the tests).
4231 UnshuffleTests();
4232
4233 if (GTEST_FLAG(shuffle)) {
4234 // Picks a new random seed for each iteration.
4235 random_seed_ = GetNextRandomSeed(random_seed_);
4236 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004237 }
4238
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004239 repeater->OnTestProgramEnd(*parent_);
4240
Jay Foadb33f8e32011-07-27 09:25:14 +00004241 return !failed;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004242}
4243
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004244// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4245// if the variable is present. If a file already exists at this location, this
4246// function will write over it. If the variable is present, but the file cannot
4247// be created, prints an error and exits.
4248void WriteToShardStatusFileIfNeeded() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004249 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004250 if (test_shard_file != NULL) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004251 FILE* const file = posix::FOpen(test_shard_file, "w");
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004252 if (file == NULL) {
4253 ColoredPrintf(COLOR_RED,
4254 "Could not write to the test shard status file \"%s\" "
4255 "specified by the %s environment variable.\n",
4256 test_shard_file, kTestShardStatusFile);
4257 fflush(stdout);
4258 exit(EXIT_FAILURE);
4259 }
4260 fclose(file);
4261 }
4262}
4263
4264// Checks whether sharding is enabled by examining the relevant
4265// environment variable values. If the variables are present,
4266// but inconsistent (i.e., shard_index >= total_shards), prints
4267// an error and exits. If in_subprocess_for_death_test, sharding is
4268// disabled because it must only be applied to the original test
4269// process. Otherwise, we could filter out death tests we intended to execute.
4270bool ShouldShard(const char* total_shards_env,
4271 const char* shard_index_env,
4272 bool in_subprocess_for_death_test) {
4273 if (in_subprocess_for_death_test) {
4274 return false;
4275 }
4276
4277 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4278 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4279
4280 if (total_shards == -1 && shard_index == -1) {
4281 return false;
4282 } else if (total_shards == -1 && shard_index != -1) {
4283 const Message msg = Message()
4284 << "Invalid environment variables: you have "
4285 << kTestShardIndex << " = " << shard_index
4286 << ", but have left " << kTestTotalShards << " unset.\n";
4287 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4288 fflush(stdout);
4289 exit(EXIT_FAILURE);
4290 } else if (total_shards != -1 && shard_index == -1) {
4291 const Message msg = Message()
4292 << "Invalid environment variables: you have "
4293 << kTestTotalShards << " = " << total_shards
4294 << ", but have left " << kTestShardIndex << " unset.\n";
4295 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4296 fflush(stdout);
4297 exit(EXIT_FAILURE);
4298 } else if (shard_index < 0 || shard_index >= total_shards) {
4299 const Message msg = Message()
4300 << "Invalid environment variables: we require 0 <= "
4301 << kTestShardIndex << " < " << kTestTotalShards
4302 << ", but you have " << kTestShardIndex << "=" << shard_index
4303 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4304 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4305 fflush(stdout);
4306 exit(EXIT_FAILURE);
4307 }
4308
4309 return total_shards > 1;
4310}
4311
4312// Parses the environment variable var as an Int32. If it is unset,
4313// returns default_val. If it is not an Int32, prints an error
4314// and aborts.
Jay Foadb33f8e32011-07-27 09:25:14 +00004315Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004316 const char* str_val = posix::GetEnv(var);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004317 if (str_val == NULL) {
4318 return default_val;
4319 }
4320
4321 Int32 result;
4322 if (!ParseInt32(Message() << "The value of environment variable " << var,
4323 str_val, &result)) {
4324 exit(EXIT_FAILURE);
4325 }
4326 return result;
4327}
4328
4329// Given the total number of shards, the shard index, and the test id,
4330// returns true iff the test should be run on this shard. The test id is
4331// some arbitrary but unique non-negative integer assigned to each test
4332// method. Assumes that 0 <= shard_index < total_shards.
4333bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4334 return (test_id % total_shards) == shard_index;
4335}
4336
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004337// Compares the name of each test with the user-specified filter to
4338// decide whether the test should be run, then records the result in
4339// each TestCase and TestInfo object.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004340// If shard_tests == true, further filters tests based on sharding
4341// variables in the environment - see
4342// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004343// Returns the number of tests that should run.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004344int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4345 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4346 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4347 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4348 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4349
4350 // num_runnable_tests are the number of tests that will
4351 // run across all shards (i.e., match filter and are not disabled).
4352 // num_selected_tests are the number of tests to be run on
4353 // this shard.
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004354 int num_runnable_tests = 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004355 int num_selected_tests = 0;
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004356 for (size_t i = 0; i < test_cases_.size(); i++) {
4357 TestCase* const test_case = test_cases_[i];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004358 const String &test_case_name = test_case->name();
4359 test_case->set_should_run(false);
4360
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004361 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4362 TestInfo* const test_info = test_case->test_info_list()[j];
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004363 const String test_name(test_info->name());
4364 // A test is disabled if test case name or test name matches
4365 // kDisableTestFilter.
4366 const bool is_disabled =
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004367 internal::UnitTestOptions::MatchesFilter(test_case_name,
4368 kDisableTestFilter) ||
4369 internal::UnitTestOptions::MatchesFilter(test_name,
4370 kDisableTestFilter);
Jay Foadb33f8e32011-07-27 09:25:14 +00004371 test_info->is_disabled_ = is_disabled;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004372
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004373 const bool matches_filter =
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004374 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4375 test_name);
Jay Foadb33f8e32011-07-27 09:25:14 +00004376 test_info->matches_filter_ = matches_filter;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004377
4378 const bool is_runnable =
4379 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4380 matches_filter;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004381
4382 const bool is_selected = is_runnable &&
4383 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4384 ShouldRunTestOnShard(total_shards, shard_index,
4385 num_runnable_tests));
4386
4387 num_runnable_tests += is_runnable;
4388 num_selected_tests += is_selected;
4389
Jay Foadb33f8e32011-07-27 09:25:14 +00004390 test_info->should_run_ = is_selected;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004391 test_case->set_should_run(test_case->should_run() || is_selected);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004392 }
4393 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004394 return num_selected_tests;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004395}
4396
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004397// Prints the names of the tests matching the user-specified filter flag.
4398void UnitTestImpl::ListTestsMatchingFilter() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004399 for (size_t i = 0; i < test_cases_.size(); i++) {
4400 const TestCase* const test_case = test_cases_[i];
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004401 bool printed_test_case_name = false;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004402
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004403 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004404 const TestInfo* const test_info =
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004405 test_case->test_info_list()[j];
Jay Foadb33f8e32011-07-27 09:25:14 +00004406 if (test_info->matches_filter_) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004407 if (!printed_test_case_name) {
4408 printed_test_case_name = true;
4409 printf("%s.\n", test_case->name());
4410 }
4411 printf(" %s\n", test_info->name());
4412 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004413 }
4414 }
4415 fflush(stdout);
4416}
4417
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004418// Sets the OS stack trace getter.
4419//
4420// Does nothing if the input and the current OS stack trace getter are
4421// the same; otherwise, deletes the old getter and makes the input the
4422// current getter.
4423void UnitTestImpl::set_os_stack_trace_getter(
4424 OsStackTraceGetterInterface* getter) {
4425 if (os_stack_trace_getter_ != getter) {
4426 delete os_stack_trace_getter_;
4427 os_stack_trace_getter_ = getter;
4428 }
4429}
4430
4431// Returns the current OS stack trace getter if it is not NULL;
4432// otherwise, creates an OsStackTraceGetter, makes it the current
4433// getter, and returns it.
4434OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4435 if (os_stack_trace_getter_ == NULL) {
4436 os_stack_trace_getter_ = new OsStackTraceGetter;
4437 }
4438
4439 return os_stack_trace_getter_;
4440}
4441
4442// Returns the TestResult for the test that's currently running, or
4443// the TestResult for the ad hoc test if no test is running.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004444TestResult* UnitTestImpl::current_test_result() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004445 return current_test_info_ ?
Jay Foadb33f8e32011-07-27 09:25:14 +00004446 &(current_test_info_->result_) : &ad_hoc_test_result_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004447}
4448
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004449// Shuffles all test cases, and the tests within each test case,
4450// making sure that death tests are still run first.
4451void UnitTestImpl::ShuffleTests() {
4452 // Shuffles the death test cases.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004453 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004454
4455 // Shuffles the non-death test cases.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004456 ShuffleRange(random(), last_death_test_case_ + 1,
4457 static_cast<int>(test_cases_.size()), &test_case_indices_);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004458
4459 // Shuffles the tests inside each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004460 for (size_t i = 0; i < test_cases_.size(); i++) {
4461 test_cases_[i]->ShuffleTests(random());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004462 }
4463}
4464
4465// Restores the test cases and tests to their order before the first shuffle.
4466void UnitTestImpl::UnshuffleTests() {
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004467 for (size_t i = 0; i < test_cases_.size(); i++) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004468 // Unshuffles the tests in each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004469 test_cases_[i]->UnshuffleTests();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004470 // Resets the index of each test case.
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004471 test_case_indices_[i] = static_cast<int>(i);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004472 }
4473}
4474
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004475// Returns the current OS stack trace as a String.
4476//
4477// The maximum number of stack frames to be included is specified by
4478// the gtest_stack_trace_depth flag. The skip_count parameter
4479// specifies the number of top frames to be skipped, which doesn't
4480// count against the number of frames to be included.
4481//
4482// For example, if Foo() calls Bar(), which in turn calls
4483// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4484// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004485String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4486 int skip_count) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004487 // We pass skip_count + 1 to skip this wrapper function in addition
4488 // to what the user really wants to skip.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004489 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004490}
4491
Jay Foadb33f8e32011-07-27 09:25:14 +00004492// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
4493// suppress unreachable code warnings.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004494namespace {
4495class ClassUniqueToAlwaysTrue {};
4496}
4497
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004498bool IsTrue(bool condition) { return condition; }
4499
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004500bool AlwaysTrue() {
4501#if GTEST_HAS_EXCEPTIONS
4502 // This condition is always false so AlwaysTrue() never actually throws,
4503 // but it makes the compiler think that it may throw.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004504 if (IsTrue(false))
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004505 throw ClassUniqueToAlwaysTrue();
4506#endif // GTEST_HAS_EXCEPTIONS
4507 return true;
4508}
4509
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004510// If *pstr starts with the given prefix, modifies *pstr to be right
4511// past the prefix and returns true; otherwise leaves *pstr unchanged
4512// and returns false. None of pstr, *pstr, and prefix can be NULL.
4513bool SkipPrefix(const char* prefix, const char** pstr) {
4514 const size_t prefix_len = strlen(prefix);
4515 if (strncmp(*pstr, prefix, prefix_len) == 0) {
4516 *pstr += prefix_len;
4517 return true;
4518 }
4519 return false;
4520}
4521
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004522// Parses a string as a command line flag. The string should have
4523// the format "--flag=value". When def_optional is true, the "=value"
4524// part can be omitted.
4525//
4526// Returns the value of the flag, or NULL if the parsing failed.
4527const char* ParseFlagValue(const char* str,
4528 const char* flag,
4529 bool def_optional) {
4530 // str and flag must not be NULL.
4531 if (str == NULL || flag == NULL) return NULL;
4532
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004533 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4534 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004535 const size_t flag_len = flag_str.length();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004536 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4537
4538 // Skips the flag name.
4539 const char* flag_end = str + flag_len;
4540
4541 // When def_optional is true, it's OK to not have a "=value" part.
4542 if (def_optional && (flag_end[0] == '\0')) {
4543 return flag_end;
4544 }
4545
4546 // If def_optional is true and there are more characters after the
4547 // flag name, or if def_optional is false, there must be a '=' after
4548 // the flag name.
4549 if (flag_end[0] != '=') return NULL;
4550
4551 // Returns the string after "=".
4552 return flag_end + 1;
4553}
4554
4555// Parses a string for a bool flag, in the form of either
4556// "--flag=value" or "--flag".
4557//
4558// In the former case, the value is taken as true as long as it does
4559// not start with '0', 'f', or 'F'.
4560//
4561// In the latter case, the value is taken as true.
4562//
4563// On success, stores the value of the flag in *value, and returns
4564// true. On failure, returns false without changing *value.
4565bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4566 // Gets the value of the flag as a string.
4567 const char* const value_str = ParseFlagValue(str, flag, true);
4568
4569 // Aborts if the parsing failed.
4570 if (value_str == NULL) return false;
4571
4572 // Converts the string value to a bool.
4573 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4574 return true;
4575}
4576
4577// Parses a string for an Int32 flag, in the form of
4578// "--flag=value".
4579//
4580// On success, stores the value of the flag in *value, and returns
4581// true. On failure, returns false without changing *value.
4582bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4583 // Gets the value of the flag as a string.
4584 const char* const value_str = ParseFlagValue(str, flag, false);
4585
4586 // Aborts if the parsing failed.
4587 if (value_str == NULL) return false;
4588
4589 // Sets *value to the value of the flag.
4590 return ParseInt32(Message() << "The value of flag --" << flag,
4591 value_str, value);
4592}
4593
4594// Parses a string for a string flag, in the form of
4595// "--flag=value".
4596//
4597// On success, stores the value of the flag in *value, and returns
4598// true. On failure, returns false without changing *value.
4599bool ParseStringFlag(const char* str, const char* flag, String* value) {
4600 // Gets the value of the flag as a string.
4601 const char* const value_str = ParseFlagValue(str, flag, false);
4602
4603 // Aborts if the parsing failed.
4604 if (value_str == NULL) return false;
4605
4606 // Sets *value to the value of the flag.
4607 *value = value_str;
4608 return true;
4609}
4610
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004611// Determines whether a string has a prefix that Google Test uses for its
4612// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
4613// If Google Test detects that a command line flag has its prefix but is not
4614// recognized, it will print its help message. Flags starting with
4615// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
4616// internal flags and do not trigger the help message.
4617static bool HasGoogleTestFlagPrefix(const char* str) {
4618 return (SkipPrefix("--", &str) ||
4619 SkipPrefix("-", &str) ||
4620 SkipPrefix("/", &str)) &&
4621 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
4622 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
4623 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
4624}
4625
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004626// Prints a string containing code-encoded text. The following escape
4627// sequences can be used in the string to control the text color:
4628//
4629// @@ prints a single '@' character.
4630// @R changes the color to red.
4631// @G changes the color to green.
4632// @Y changes the color to yellow.
4633// @D changes to the default terminal text color.
4634//
4635// TODO(wan@google.com): Write tests for this once we add stdout
4636// capturing to Google Test.
4637static void PrintColorEncoded(const char* str) {
4638 GTestColor color = COLOR_DEFAULT; // The current color.
4639
4640 // Conceptually, we split the string into segments divided by escape
4641 // sequences. Then we print one segment at a time. At the end of
4642 // each iteration, the str pointer advances to the beginning of the
4643 // next segment.
4644 for (;;) {
4645 const char* p = strchr(str, '@');
4646 if (p == NULL) {
4647 ColoredPrintf(color, "%s", str);
4648 return;
4649 }
4650
4651 ColoredPrintf(color, "%s", String(str, p - str).c_str());
4652
4653 const char ch = p[1];
4654 str = p + 2;
4655 if (ch == '@') {
4656 ColoredPrintf(color, "@");
4657 } else if (ch == 'D') {
4658 color = COLOR_DEFAULT;
4659 } else if (ch == 'R') {
4660 color = COLOR_RED;
4661 } else if (ch == 'G') {
4662 color = COLOR_GREEN;
4663 } else if (ch == 'Y') {
4664 color = COLOR_YELLOW;
4665 } else {
4666 --str;
4667 }
4668 }
4669}
4670
4671static const char kColorEncodedHelpMessage[] =
4672"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4673"following command line flags to control its behavior:\n"
4674"\n"
4675"Test Selection:\n"
4676" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4677" List the names of all tests instead of running them. The name of\n"
4678" TEST(Foo, Bar) is \"Foo.Bar\".\n"
4679" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4680 "[@G-@YNEGATIVE_PATTERNS]@D\n"
4681" Run only the tests whose name matches one of the positive patterns but\n"
4682" none of the negative patterns. '?' matches any single character; '*'\n"
4683" matches any substring; ':' separates two patterns.\n"
4684" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4685" Run all disabled tests too.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004686"\n"
4687"Test Execution:\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004688" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4689" Run the tests repeatedly; use a negative count to repeat forever.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004690" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4691" Randomize tests' orders on every iteration.\n"
4692" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4693" Random number seed to use for shuffling test orders (between 1 and\n"
4694" 99999, or 0 to use a seed based on the current time).\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004695"\n"
4696"Test Output:\n"
4697" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4698" Enable/disable colored output. The default is @Gauto@D.\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004699" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4700" Don't print the elapsed time of each test.\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004701" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4702 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4703" Generate an XML report in the given directory or with the given file\n"
4704" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
Jay Foadb33f8e32011-07-27 09:25:14 +00004705#if GTEST_CAN_STREAM_RESULTS_
4706" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
4707" Stream test results to the given server.\n"
4708#endif // GTEST_CAN_STREAM_RESULTS_
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004709"\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004710"Assertion Behavior:\n"
4711#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4712" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4713" Set the default death test style.\n"
4714#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004715" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4716" Turn assertion failures into debugger break-points.\n"
4717" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4718" Turn assertion failures into C++ exceptions.\n"
Jay Foadb33f8e32011-07-27 09:25:14 +00004719" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
4720" Do not report exceptions as test failures. Instead, allow them\n"
4721" to crash the program or throw a pop-up (on Windows).\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004722"\n"
4723"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4724 "the corresponding\n"
4725"environment variable of a flag (all letters in upper-case). For example, to\n"
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004726"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4727 "color=no@D or set\n"
4728"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004729"\n"
4730"For more information, please read the " GTEST_NAME_ " documentation at\n"
4731"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4732"(not one in your own code or tests), please report it to\n"
4733"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4734
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004735// Parses the command line for Google Test flags, without initializing
4736// other parts of Google Test. The type parameter CharType can be
4737// instantiated to either char or wchar_t.
4738template <typename CharType>
4739void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4740 for (int i = 1; i < *argc; i++) {
4741 const String arg_string = StreamableToString(argv[i]);
4742 const char* const arg = arg_string.c_str();
4743
4744 using internal::ParseBoolFlag;
4745 using internal::ParseInt32Flag;
4746 using internal::ParseStringFlag;
4747
4748 // Do we see a Google Test flag?
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004749 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4750 &GTEST_FLAG(also_run_disabled_tests)) ||
4751 ParseBoolFlag(arg, kBreakOnFailureFlag,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004752 &GTEST_FLAG(break_on_failure)) ||
4753 ParseBoolFlag(arg, kCatchExceptionsFlag,
4754 &GTEST_FLAG(catch_exceptions)) ||
4755 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
4756 ParseStringFlag(arg, kDeathTestStyleFlag,
4757 &GTEST_FLAG(death_test_style)) ||
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004758 ParseBoolFlag(arg, kDeathTestUseFork,
4759 &GTEST_FLAG(death_test_use_fork)) ||
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004760 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
4761 ParseStringFlag(arg, kInternalRunDeathTestFlag,
4762 &GTEST_FLAG(internal_run_death_test)) ||
4763 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
4764 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
4765 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004766 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004767 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004768 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004769 ParseInt32Flag(arg, kStackTraceDepthFlag,
4770 &GTEST_FLAG(stack_trace_depth)) ||
Jay Foadb33f8e32011-07-27 09:25:14 +00004771 ParseStringFlag(arg, kStreamResultToFlag,
4772 &GTEST_FLAG(stream_result_to)) ||
4773 ParseBoolFlag(arg, kThrowOnFailureFlag,
4774 &GTEST_FLAG(throw_on_failure))
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004775 ) {
4776 // Yes. Shift the remainder of the argv list left by one. Note
4777 // that argv has (*argc + 1) elements, the last one always being
4778 // NULL. The following loop moves the trailing NULL element as
4779 // well.
4780 for (int j = i; j != *argc; j++) {
4781 argv[j] = argv[j + 1];
4782 }
4783
4784 // Decrements the argument count.
4785 (*argc)--;
4786
4787 // We also need to decrement the iterator as we just removed
4788 // an element.
4789 i--;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004790 } else if (arg_string == "--help" || arg_string == "-h" ||
Benjamin Kramer57240ff2010-06-02 22:02:30 +00004791 arg_string == "-?" || arg_string == "/?" ||
4792 HasGoogleTestFlagPrefix(arg)) {
4793 // Both help flag and unrecognized Google Test flags (excluding
4794 // internal ones) trigger help display.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004795 g_help_flag = true;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004796 }
4797 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004798
4799 if (g_help_flag) {
4800 // We print the help here instead of in RUN_ALL_TESTS(), as the
4801 // latter may not be called at all if the user is using Google
4802 // Test with another testing framework.
4803 PrintColorEncoded(kColorEncodedHelpMessage);
4804 }
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004805}
4806
4807// Parses the command line for Google Test flags, without initializing
4808// other parts of Google Test.
4809void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4810 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4811}
4812void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4813 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4814}
4815
4816// The internal implementation of InitGoogleTest().
4817//
4818// The type parameter CharType can be instantiated to either char or
4819// wchar_t.
4820template <typename CharType>
4821void InitGoogleTestImpl(int* argc, CharType** argv) {
4822 g_init_gtest_count++;
4823
4824 // We don't want to run the initialization code twice.
4825 if (g_init_gtest_count != 1) return;
4826
4827 if (*argc <= 0) return;
4828
4829 internal::g_executable_path = internal::StreamableToString(argv[0]);
4830
Benjamin Kramere4b9c932010-06-02 22:01:25 +00004831#if GTEST_HAS_DEATH_TEST
Jay Foadb33f8e32011-07-27 09:25:14 +00004832
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004833 g_argvs.clear();
4834 for (int i = 0; i != *argc; i++) {
4835 g_argvs.push_back(StreamableToString(argv[i]));
4836 }
Jay Foadb33f8e32011-07-27 09:25:14 +00004837
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004838#endif // GTEST_HAS_DEATH_TEST
4839
4840 ParseGoogleTestFlagsOnly(argc, argv);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00004841 GetUnitTestImpl()->PostFlagParsingInit();
Misha Brukman7ae6ff42008-12-31 17:34:06 +00004842}
4843
4844} // namespace internal
4845
4846// Initializes Google Test. This must be called before calling
4847// RUN_ALL_TESTS(). In particular, it parses a command line for the
4848// flags that Google Test recognizes. Whenever a Google Test flag is
4849// seen, it is removed from argv, and *argc is decremented.
4850//
4851// No value is returned. Instead, the Google Test flag variables are
4852// updated.
4853//
4854// Calling the function for the second time has no user-visible effect.
4855void InitGoogleTest(int* argc, char** argv) {
4856 internal::InitGoogleTestImpl(argc, argv);
4857}
4858
4859// This overloaded version can be used in Windows programs compiled in
4860// UNICODE mode.
4861void InitGoogleTest(int* argc, wchar_t** argv) {
4862 internal::InitGoogleTestImpl(argc, argv);
4863}
4864
4865} // namespace testing