blob: 15ae355508e783370501f2df5dcc0be603838f12 [file] [log] [blame]
Keir Mierle8ebb0732012-04-30 23:09:08 -07001// Copyright 2008, 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: mheule@google.com (Markus Heule)
31//
32// Google C++ Testing Framework (Google Test)
33//
34// Sometimes it's desirable to build Google Test by compiling a single file.
35// This file serves this purpose.
36
37// This line ensures that gtest.h can be compiled on its own, even
38// when it's fused.
39#include "gtest/gtest.h"
40
41// The following lines pull in the real gtest *.cc files.
42// Copyright 2005, Google Inc.
43// All rights reserved.
44//
45// Redistribution and use in source and binary forms, with or without
46// modification, are permitted provided that the following conditions are
47// met:
48//
49// * Redistributions of source code must retain the above copyright
50// notice, this list of conditions and the following disclaimer.
51// * Redistributions in binary form must reproduce the above
52// copyright notice, this list of conditions and the following disclaimer
53// in the documentation and/or other materials provided with the
54// distribution.
55// * Neither the name of Google Inc. nor the names of its
56// contributors may be used to endorse or promote products derived from
57// this software without specific prior written permission.
58//
59// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70//
71// Author: wan@google.com (Zhanyong Wan)
72//
73// The Google C++ Testing Framework (Google Test)
74
75// Copyright 2007, Google Inc.
76// All rights reserved.
77//
78// Redistribution and use in source and binary forms, with or without
79// modification, are permitted provided that the following conditions are
80// met:
81//
82// * Redistributions of source code must retain the above copyright
83// notice, this list of conditions and the following disclaimer.
84// * Redistributions in binary form must reproduce the above
85// copyright notice, this list of conditions and the following disclaimer
86// in the documentation and/or other materials provided with the
87// distribution.
88// * Neither the name of Google Inc. nor the names of its
89// contributors may be used to endorse or promote products derived from
90// this software without specific prior written permission.
91//
92// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
103//
104// Author: wan@google.com (Zhanyong Wan)
105//
106// Utilities for testing Google Test itself and code that uses Google Test
107// (e.g. frameworks built on top of Google Test).
108
109#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
111
112
113namespace testing {
114
115// This helper class can be used to mock out Google Test failure reporting
116// so that we can test Google Test or code that builds on Google Test.
117//
118// An object of this class appends a TestPartResult object to the
119// TestPartResultArray object given in the constructor whenever a Google Test
120// failure is reported. It can either intercept only failures that are
121// generated in the same thread that created this object or it can intercept
122// all generated failures. The scope of this mock object can be controlled with
123// the second argument to the two arguments constructor.
124class GTEST_API_ ScopedFakeTestPartResultReporter
125 : public TestPartResultReporterInterface {
126 public:
127 // The two possible mocking modes of this object.
128 enum InterceptMode {
129 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
130 INTERCEPT_ALL_THREADS // Intercepts all failures.
131 };
132
133 // The c'tor sets this object as the test part result reporter used
134 // by Google Test. The 'result' parameter specifies where to report the
135 // results. This reporter will only catch failures generated in the current
136 // thread. DEPRECATED
137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
138
139 // Same as above, but you can choose the interception scope of this object.
140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
141 TestPartResultArray* result);
142
143 // The d'tor restores the previous test part result reporter.
144 virtual ~ScopedFakeTestPartResultReporter();
145
146 // Appends the TestPartResult object to the TestPartResultArray
147 // received in the constructor.
148 //
149 // This method is from the TestPartResultReporterInterface
150 // interface.
151 virtual void ReportTestPartResult(const TestPartResult& result);
152 private:
153 void Init();
154
155 const InterceptMode intercept_mode_;
156 TestPartResultReporterInterface* old_reporter_;
157 TestPartResultArray* const result_;
158
159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
160};
161
162namespace internal {
163
164// A helper class for implementing EXPECT_FATAL_FAILURE() and
165// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
166// TestPartResultArray contains exactly one failure that has the given
167// type and contains the given substring. If that's not the case, a
168// non-fatal failure will be generated.
169class GTEST_API_ SingleFailureChecker {
170 public:
171 // The constructor remembers the arguments.
172 SingleFailureChecker(const TestPartResultArray* results,
173 TestPartResult::Type type,
174 const string& substr);
175 ~SingleFailureChecker();
176 private:
177 const TestPartResultArray* const results_;
178 const TestPartResult::Type type_;
179 const string substr_;
180
181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
182};
183
184} // namespace internal
185
186} // namespace testing
187
188// A set of macros for testing Google Test assertions or code that's expected
189// to generate Google Test fatal failures. It verifies that the given
190// statement will cause exactly one fatal Google Test failure with 'substr'
191// being part of the failure message.
192//
193// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194// affects and considers failures generated in the current thread and
195// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
196//
197// The verification of the assertion is done correctly even when the statement
198// throws an exception or aborts the current function.
199//
200// Known restrictions:
201// - 'statement' cannot reference local non-static variables or
202// non-static members of the current object.
203// - 'statement' cannot return a value.
204// - You cannot stream a failure message to this macro.
205//
206// Note that even though the implementations of the following two
207// macros are much alike, we cannot refactor them to use a common
208// helper macro, due to some peculiarity in how the preprocessor
209// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
210// gtest_unittest.cc will fail to compile if we do that.
211#define EXPECT_FATAL_FAILURE(statement, substr) \
212 do { \
213 class GTestExpectFatalFailureHelper {\
214 public:\
215 static void Execute() { statement; }\
216 };\
217 ::testing::TestPartResultArray gtest_failures;\
218 ::testing::internal::SingleFailureChecker gtest_checker(\
219 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
220 {\
221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222 ::testing::ScopedFakeTestPartResultReporter:: \
223 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
224 GTestExpectFatalFailureHelper::Execute();\
225 }\
226 } while (::testing::internal::AlwaysFalse())
227
228#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
229 do { \
230 class GTestExpectFatalFailureHelper {\
231 public:\
232 static void Execute() { statement; }\
233 };\
234 ::testing::TestPartResultArray gtest_failures;\
235 ::testing::internal::SingleFailureChecker gtest_checker(\
236 &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
237 {\
238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239 ::testing::ScopedFakeTestPartResultReporter:: \
240 INTERCEPT_ALL_THREADS, &gtest_failures);\
241 GTestExpectFatalFailureHelper::Execute();\
242 }\
243 } while (::testing::internal::AlwaysFalse())
244
245// A macro for testing Google Test assertions or code that's expected to
246// generate Google Test non-fatal failures. It asserts that the given
247// statement will cause exactly one non-fatal Google Test failure with 'substr'
248// being part of the failure message.
249//
250// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251// affects and considers failures generated in the current thread and
252// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
253//
254// 'statement' is allowed to reference local variables and members of
255// the current object.
256//
257// The verification of the assertion is done correctly even when the statement
258// throws an exception or aborts the current function.
259//
260// Known restrictions:
261// - You cannot stream a failure message to this macro.
262//
263// Note that even though the implementations of the following two
264// macros are much alike, we cannot refactor them to use a common
265// helper macro, due to some peculiarity in how the preprocessor
266// works. If we do that, the code won't compile when the user gives
267// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268// expands to code containing an unprotected comma. The
269// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
270// catches that.
271//
272// For the same reason, we have to write
273// if (::testing::internal::AlwaysTrue()) { statement; }
274// instead of
275// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276// to avoid an MSVC warning on unreachable code.
277#define EXPECT_NONFATAL_FAILURE(statement, substr) \
278 do {\
279 ::testing::TestPartResultArray gtest_failures;\
280 ::testing::internal::SingleFailureChecker gtest_checker(\
281 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
282 (substr));\
283 {\
284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285 ::testing::ScopedFakeTestPartResultReporter:: \
286 INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
287 if (::testing::internal::AlwaysTrue()) { statement; }\
288 }\
289 } while (::testing::internal::AlwaysFalse())
290
291#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
292 do {\
293 ::testing::TestPartResultArray gtest_failures;\
294 ::testing::internal::SingleFailureChecker gtest_checker(\
295 &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
296 (substr));\
297 {\
298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
300 &gtest_failures);\
301 if (::testing::internal::AlwaysTrue()) { statement; }\
302 }\
303 } while (::testing::internal::AlwaysFalse())
304
305#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
306
307#include <ctype.h>
308#include <math.h>
309#include <stdarg.h>
310#include <stdio.h>
311#include <stdlib.h>
312#include <wchar.h>
313#include <wctype.h>
314
315#include <algorithm>
316#include <ostream> // NOLINT
317#include <sstream>
318#include <vector>
319
320#if GTEST_OS_LINUX
321
322// TODO(kenton@google.com): Use autoconf to detect availability of
323// gettimeofday().
324# define GTEST_HAS_GETTIMEOFDAY_ 1
325
326# include <fcntl.h> // NOLINT
327# include <limits.h> // NOLINT
328# include <sched.h> // NOLINT
329// Declares vsnprintf(). This header is not available on Windows.
330# include <strings.h> // NOLINT
331# include <sys/mman.h> // NOLINT
332# include <sys/time.h> // NOLINT
333# include <unistd.h> // NOLINT
334# include <string>
335
336#elif GTEST_OS_SYMBIAN
337# define GTEST_HAS_GETTIMEOFDAY_ 1
338# include <sys/time.h> // NOLINT
339
340#elif GTEST_OS_ZOS
341# define GTEST_HAS_GETTIMEOFDAY_ 1
342# include <sys/time.h> // NOLINT
343
344// On z/OS we additionally need strings.h for strcasecmp.
345# include <strings.h> // NOLINT
346
347#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
348
349# include <windows.h> // NOLINT
350
351#elif GTEST_OS_WINDOWS // We are on Windows proper.
352
353# include <io.h> // NOLINT
354# include <sys/timeb.h> // NOLINT
355# include <sys/types.h> // NOLINT
356# include <sys/stat.h> // NOLINT
357
358# if GTEST_OS_WINDOWS_MINGW
359// MinGW has gettimeofday() but not _ftime64().
360// TODO(kenton@google.com): Use autoconf to detect availability of
361// gettimeofday().
362// TODO(kenton@google.com): There are other ways to get the time on
363// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
364// supports these. consider using them instead.
365# define GTEST_HAS_GETTIMEOFDAY_ 1
366# include <sys/time.h> // NOLINT
367# endif // GTEST_OS_WINDOWS_MINGW
368
369// cpplint thinks that the header is already included, so we want to
370// silence it.
371# include <windows.h> // NOLINT
372
373#else
374
375// Assume other platforms have gettimeofday().
376// TODO(kenton@google.com): Use autoconf to detect availability of
377// gettimeofday().
378# define GTEST_HAS_GETTIMEOFDAY_ 1
379
380// cpplint thinks that the header is already included, so we want to
381// silence it.
382# include <sys/time.h> // NOLINT
383# include <unistd.h> // NOLINT
384
385#endif // GTEST_OS_LINUX
386
387#if GTEST_HAS_EXCEPTIONS
388# include <stdexcept>
389#endif
390
391#if GTEST_CAN_STREAM_RESULTS_
392# include <arpa/inet.h> // NOLINT
393# include <netdb.h> // NOLINT
394#endif
395
396// Indicates that this translation unit is part of Google Test's
397// implementation. It must come before gtest-internal-inl.h is
398// included, or there will be a compiler error. This trick is to
399// prevent a user from accidentally including gtest-internal-inl.h in
400// his code.
401#define GTEST_IMPLEMENTATION_ 1
402// Copyright 2005, Google Inc.
403// All rights reserved.
404//
405// Redistribution and use in source and binary forms, with or without
406// modification, are permitted provided that the following conditions are
407// met:
408//
409// * Redistributions of source code must retain the above copyright
410// notice, this list of conditions and the following disclaimer.
411// * Redistributions in binary form must reproduce the above
412// copyright notice, this list of conditions and the following disclaimer
413// in the documentation and/or other materials provided with the
414// distribution.
415// * Neither the name of Google Inc. nor the names of its
416// contributors may be used to endorse or promote products derived from
417// this software without specific prior written permission.
418//
419// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
420// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
421// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
422// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
423// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
424// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
425// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
426// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
427// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
428// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
429// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
430
431// Utility functions and classes used by the Google C++ testing framework.
432//
433// Author: wan@google.com (Zhanyong Wan)
434//
435// This file contains purely Google Test's internal implementation. Please
436// DO NOT #INCLUDE IT IN A USER PROGRAM.
437
438#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
439#define GTEST_SRC_GTEST_INTERNAL_INL_H_
440
441// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
442// part of Google Test's implementation; otherwise it's undefined.
443#if !GTEST_IMPLEMENTATION_
444// A user is trying to include this from his code - just say no.
445# error "gtest-internal-inl.h is part of Google Test's internal implementation."
446# error "It must not be included except by Google Test itself."
447#endif // GTEST_IMPLEMENTATION_
448
449#ifndef _WIN32_WCE
450# include <errno.h>
451#endif // !_WIN32_WCE
452#include <stddef.h>
453#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
454#include <string.h> // For memmove.
455
456#include <algorithm>
457#include <string>
458#include <vector>
459
460
461#if GTEST_OS_WINDOWS
462# include <windows.h> // NOLINT
463#endif // GTEST_OS_WINDOWS
464
465
466namespace testing {
467
468// Declares the flags.
469//
470// We don't want the users to modify this flag in the code, but want
471// Google Test's own unit tests to be able to access it. Therefore we
472// declare it here as opposed to in gtest.h.
473GTEST_DECLARE_bool_(death_test_use_fork);
474
475namespace internal {
476
477// The value of GetTestTypeId() as seen from within the Google Test
478// library. This is solely for testing GetTestTypeId().
479GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
480
481// Names of the flags (needed for parsing Google Test flags).
482const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
483const char kBreakOnFailureFlag[] = "break_on_failure";
484const char kCatchExceptionsFlag[] = "catch_exceptions";
485const char kColorFlag[] = "color";
486const char kFilterFlag[] = "filter";
487const char kListTestsFlag[] = "list_tests";
488const char kOutputFlag[] = "output";
489const char kPrintTimeFlag[] = "print_time";
490const char kRandomSeedFlag[] = "random_seed";
491const char kRepeatFlag[] = "repeat";
492const char kShuffleFlag[] = "shuffle";
493const char kStackTraceDepthFlag[] = "stack_trace_depth";
494const char kStreamResultToFlag[] = "stream_result_to";
495const char kThrowOnFailureFlag[] = "throw_on_failure";
496
497// A valid random seed must be in [1, kMaxRandomSeed].
498const int kMaxRandomSeed = 99999;
499
500// g_help_flag is true iff the --help flag or an equivalent form is
501// specified on the command line.
502GTEST_API_ extern bool g_help_flag;
503
504// Returns the current time in milliseconds.
505GTEST_API_ TimeInMillis GetTimeInMillis();
506
507// Returns true iff Google Test should use colors in the output.
508GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
509
510// Formats the given time in milliseconds as seconds.
511GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
512
513// Parses a string for an Int32 flag, in the form of "--flag=value".
514//
515// On success, stores the value of the flag in *value, and returns
516// true. On failure, returns false without changing *value.
517GTEST_API_ bool ParseInt32Flag(
518 const char* str, const char* flag, Int32* value);
519
520// Returns a random seed in range [1, kMaxRandomSeed] based on the
521// given --gtest_random_seed flag value.
522inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
523 const unsigned int raw_seed = (random_seed_flag == 0) ?
524 static_cast<unsigned int>(GetTimeInMillis()) :
525 static_cast<unsigned int>(random_seed_flag);
526
527 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
528 // it's easy to type.
529 const int normalized_seed =
530 static_cast<int>((raw_seed - 1U) %
531 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
532 return normalized_seed;
533}
534
535// Returns the first valid random seed after 'seed'. The behavior is
536// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
537// considered to be 1.
538inline int GetNextRandomSeed(int seed) {
539 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
540 << "Invalid random seed " << seed << " - must be in [1, "
541 << kMaxRandomSeed << "].";
542 const int next_seed = seed + 1;
543 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
544}
545
546// This class saves the values of all Google Test flags in its c'tor, and
547// restores them in its d'tor.
548class GTestFlagSaver {
549 public:
550 // The c'tor.
551 GTestFlagSaver() {
552 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
553 break_on_failure_ = GTEST_FLAG(break_on_failure);
554 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
555 color_ = GTEST_FLAG(color);
556 death_test_style_ = GTEST_FLAG(death_test_style);
557 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
558 filter_ = GTEST_FLAG(filter);
559 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
560 list_tests_ = GTEST_FLAG(list_tests);
561 output_ = GTEST_FLAG(output);
562 print_time_ = GTEST_FLAG(print_time);
563 random_seed_ = GTEST_FLAG(random_seed);
564 repeat_ = GTEST_FLAG(repeat);
565 shuffle_ = GTEST_FLAG(shuffle);
566 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
567 stream_result_to_ = GTEST_FLAG(stream_result_to);
568 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
569 }
570
571 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
572 ~GTestFlagSaver() {
573 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
574 GTEST_FLAG(break_on_failure) = break_on_failure_;
575 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
576 GTEST_FLAG(color) = color_;
577 GTEST_FLAG(death_test_style) = death_test_style_;
578 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
579 GTEST_FLAG(filter) = filter_;
580 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
581 GTEST_FLAG(list_tests) = list_tests_;
582 GTEST_FLAG(output) = output_;
583 GTEST_FLAG(print_time) = print_time_;
584 GTEST_FLAG(random_seed) = random_seed_;
585 GTEST_FLAG(repeat) = repeat_;
586 GTEST_FLAG(shuffle) = shuffle_;
587 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
588 GTEST_FLAG(stream_result_to) = stream_result_to_;
589 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
590 }
591 private:
592 // Fields for saving the original values of flags.
593 bool also_run_disabled_tests_;
594 bool break_on_failure_;
595 bool catch_exceptions_;
596 String color_;
597 String death_test_style_;
598 bool death_test_use_fork_;
599 String filter_;
600 String internal_run_death_test_;
601 bool list_tests_;
602 String output_;
603 bool print_time_;
Alex Stewartfef82b32013-02-27 10:44:12 +0000604 // TODO(keir): We removed this to fix the unused private variable issue;
605 // remove this when/if upstream has the patch.
606 //bool pretty_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700607 internal::Int32 random_seed_;
608 internal::Int32 repeat_;
609 bool shuffle_;
610 internal::Int32 stack_trace_depth_;
611 String stream_result_to_;
612 bool throw_on_failure_;
613} GTEST_ATTRIBUTE_UNUSED_;
614
615// Converts a Unicode code point to a narrow string in UTF-8 encoding.
616// code_point parameter is of type UInt32 because wchar_t may not be
617// wide enough to contain a code point.
618// The output buffer str must containt at least 32 characters.
619// The function returns the address of the output buffer.
620// If the code_point is not a valid Unicode code point
621// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
622// as '(Invalid Unicode 0xXXXXXXXX)'.
623GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
624
625// Converts a wide string to a narrow string in UTF-8 encoding.
626// The wide string is assumed to have the following encoding:
627// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
628// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
629// Parameter str points to a null-terminated wide string.
630// Parameter num_chars may additionally limit the number
631// of wchar_t characters processed. -1 is used when the entire string
632// should be processed.
633// If the string contains code points that are not valid Unicode code points
634// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
635// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
636// and contains invalid UTF-16 surrogate pairs, values in those pairs
637// will be encoded as individual Unicode characters from Basic Normal Plane.
638GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
639
640// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
641// if the variable is present. If a file already exists at this location, this
642// function will write over it. If the variable is present, but the file cannot
643// be created, prints an error and exits.
644void WriteToShardStatusFileIfNeeded();
645
646// Checks whether sharding is enabled by examining the relevant
647// environment variable values. If the variables are present,
648// but inconsistent (e.g., shard_index >= total_shards), prints
649// an error and exits. If in_subprocess_for_death_test, sharding is
650// disabled because it must only be applied to the original test
651// process. Otherwise, we could filter out death tests we intended to execute.
652GTEST_API_ bool ShouldShard(const char* total_shards_str,
653 const char* shard_index_str,
654 bool in_subprocess_for_death_test);
655
656// Parses the environment variable var as an Int32. If it is unset,
657// returns default_val. If it is not an Int32, prints an error and
658// and aborts.
659GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
660
661// Given the total number of shards, the shard index, and the test id,
662// returns true iff the test should be run on this shard. The test id is
663// some arbitrary but unique non-negative integer assigned to each test
664// method. Assumes that 0 <= shard_index < total_shards.
665GTEST_API_ bool ShouldRunTestOnShard(
666 int total_shards, int shard_index, int test_id);
667
668// STL container utilities.
669
670// Returns the number of elements in the given container that satisfy
671// the given predicate.
672template <class Container, typename Predicate>
673inline int CountIf(const Container& c, Predicate predicate) {
674 // Implemented as an explicit loop since std::count_if() in libCstd on
675 // Solaris has a non-standard signature.
676 int count = 0;
677 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
678 if (predicate(*it))
679 ++count;
680 }
681 return count;
682}
683
684// Applies a function/functor to each element in the container.
685template <class Container, typename Functor>
686void ForEach(const Container& c, Functor functor) {
687 std::for_each(c.begin(), c.end(), functor);
688}
689
690// Returns the i-th element of the vector, or default_value if i is not
691// in range [0, v.size()).
692template <typename E>
693inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
694 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
695}
696
697// Performs an in-place shuffle of a range of the vector's elements.
698// 'begin' and 'end' are element indices as an STL-style range;
699// i.e. [begin, end) are shuffled, where 'end' == size() means to
700// shuffle to the end of the vector.
701template <typename E>
702void ShuffleRange(internal::Random* random, int begin, int end,
703 std::vector<E>* v) {
704 const int size = static_cast<int>(v->size());
705 GTEST_CHECK_(0 <= begin && begin <= size)
706 << "Invalid shuffle range start " << begin << ": must be in range [0, "
707 << size << "].";
708 GTEST_CHECK_(begin <= end && end <= size)
709 << "Invalid shuffle range finish " << end << ": must be in range ["
710 << begin << ", " << size << "].";
711
712 // Fisher-Yates shuffle, from
713 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
714 for (int range_width = end - begin; range_width >= 2; range_width--) {
715 const int last_in_range = begin + range_width - 1;
716 const int selected = begin + random->Generate(range_width);
717 std::swap((*v)[selected], (*v)[last_in_range]);
718 }
719}
720
721// Performs an in-place shuffle of the vector's elements.
722template <typename E>
723inline void Shuffle(internal::Random* random, std::vector<E>* v) {
724 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
725}
726
727// A function for deleting an object. Handy for being used as a
728// functor.
729template <typename T>
730static void Delete(T* x) {
731 delete x;
732}
733
734// A predicate that checks the key of a TestProperty against a known key.
735//
736// TestPropertyKeyIs is copyable.
737class TestPropertyKeyIs {
738 public:
739 // Constructor.
740 //
741 // TestPropertyKeyIs has NO default constructor.
742 explicit TestPropertyKeyIs(const char* key)
743 : key_(key) {}
744
745 // Returns true iff the test name of test property matches on key_.
746 bool operator()(const TestProperty& test_property) const {
747 return String(test_property.key()).Compare(key_) == 0;
748 }
749
750 private:
751 String key_;
752};
753
754// Class UnitTestOptions.
755//
756// This class contains functions for processing options the user
757// specifies when running the tests. It has only static members.
758//
759// In most cases, the user can specify an option using either an
760// environment variable or a command line flag. E.g. you can set the
761// test filter using either GTEST_FILTER or --gtest_filter. If both
762// the variable and the flag are present, the latter overrides the
763// former.
764class GTEST_API_ UnitTestOptions {
765 public:
766 // Functions for processing the gtest_output flag.
767
768 // Returns the output format, or "" for normal printed output.
769 static String GetOutputFormat();
770
771 // Returns the absolute path of the requested output file, or the
772 // default (test_detail.xml in the original working directory) if
773 // none was explicitly specified.
774 static String GetAbsolutePathToOutputFile();
775
776 // Functions for processing the gtest_filter flag.
777
778 // Returns true iff the wildcard pattern matches the string. The
779 // first ':' or '\0' character in pattern marks the end of it.
780 //
781 // This recursive algorithm isn't very efficient, but is clear and
782 // works well enough for matching test names, which are short.
783 static bool PatternMatchesString(const char *pattern, const char *str);
784
785 // Returns true iff the user-specified filter matches the test case
786 // name and the test name.
787 static bool FilterMatchesTest(const String &test_case_name,
788 const String &test_name);
789
790#if GTEST_OS_WINDOWS
791 // Function for supporting the gtest_catch_exception flag.
792
793 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
794 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
795 // This function is useful as an __except condition.
796 static int GTestShouldProcessSEH(DWORD exception_code);
797#endif // GTEST_OS_WINDOWS
798
799 // Returns true if "name" matches the ':' separated list of glob-style
800 // filters in "filter".
801 static bool MatchesFilter(const String& name, const char* filter);
802};
803
804// Returns the current application's name, removing directory path if that
805// is present. Used by UnitTestOptions::GetOutputFile.
806GTEST_API_ FilePath GetCurrentExecutableName();
807
808// The role interface for getting the OS stack trace as a string.
809class OsStackTraceGetterInterface {
810 public:
811 OsStackTraceGetterInterface() {}
812 virtual ~OsStackTraceGetterInterface() {}
813
814 // Returns the current OS stack trace as a String. Parameters:
815 //
816 // max_depth - the maximum number of stack frames to be included
817 // in the trace.
818 // skip_count - the number of top frames to be skipped; doesn't count
819 // against max_depth.
820 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
821
822 // UponLeavingGTest() should be called immediately before Google Test calls
823 // user code. It saves some information about the current stack that
824 // CurrentStackTrace() will use to find and hide Google Test stack frames.
825 virtual void UponLeavingGTest() = 0;
826
827 private:
828 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
829};
830
831// A working implementation of the OsStackTraceGetterInterface interface.
832class OsStackTraceGetter : public OsStackTraceGetterInterface {
833 public:
834 OsStackTraceGetter() : caller_frame_(NULL) {}
835 virtual String CurrentStackTrace(int max_depth, int skip_count);
836 virtual void UponLeavingGTest();
837
838 // This string is inserted in place of stack frames that are part of
839 // Google Test's implementation.
840 static const char* const kElidedFramesMarker;
841
842 private:
843 Mutex mutex_; // protects all internal state
844
845 // We save the stack frame below the frame that calls user code.
846 // We do this because the address of the frame immediately below
847 // the user code changes between the call to UponLeavingGTest()
848 // and any calls to CurrentStackTrace() from within the user code.
849 void* caller_frame_;
850
851 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
852};
853
854// Information about a Google Test trace point.
855struct TraceInfo {
856 const char* file;
857 int line;
858 String message;
859};
860
861// This is the default global test part result reporter used in UnitTestImpl.
862// This class should only be used by UnitTestImpl.
863class DefaultGlobalTestPartResultReporter
864 : public TestPartResultReporterInterface {
865 public:
866 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
867 // Implements the TestPartResultReporterInterface. Reports the test part
868 // result in the current test.
869 virtual void ReportTestPartResult(const TestPartResult& result);
870
871 private:
872 UnitTestImpl* const unit_test_;
873
874 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
875};
876
877// This is the default per thread test part result reporter used in
878// UnitTestImpl. This class should only be used by UnitTestImpl.
879class DefaultPerThreadTestPartResultReporter
880 : public TestPartResultReporterInterface {
881 public:
882 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
883 // Implements the TestPartResultReporterInterface. The implementation just
884 // delegates to the current global test part result reporter of *unit_test_.
885 virtual void ReportTestPartResult(const TestPartResult& result);
886
887 private:
888 UnitTestImpl* const unit_test_;
889
890 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
891};
892
893// The private implementation of the UnitTest class. We don't protect
894// the methods under a mutex, as this class is not accessible by a
895// user and the UnitTest class that delegates work to this class does
896// proper locking.
897class GTEST_API_ UnitTestImpl {
898 public:
899 explicit UnitTestImpl(UnitTest* parent);
900 virtual ~UnitTestImpl();
901
902 // There are two different ways to register your own TestPartResultReporter.
903 // You can register your own repoter to listen either only for test results
904 // from the current thread or for results from all threads.
905 // By default, each per-thread test result repoter just passes a new
906 // TestPartResult to the global test result reporter, which registers the
907 // test part result for the currently running test.
908
909 // Returns the global test part result reporter.
910 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
911
912 // Sets the global test part result reporter.
913 void SetGlobalTestPartResultReporter(
914 TestPartResultReporterInterface* reporter);
915
916 // Returns the test part result reporter for the current thread.
917 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
918
919 // Sets the test part result reporter for the current thread.
920 void SetTestPartResultReporterForCurrentThread(
921 TestPartResultReporterInterface* reporter);
922
923 // Gets the number of successful test cases.
924 int successful_test_case_count() const;
925
926 // Gets the number of failed test cases.
927 int failed_test_case_count() const;
928
929 // Gets the number of all test cases.
930 int total_test_case_count() const;
931
932 // Gets the number of all test cases that contain at least one test
933 // that should run.
934 int test_case_to_run_count() const;
935
936 // Gets the number of successful tests.
937 int successful_test_count() const;
938
939 // Gets the number of failed tests.
940 int failed_test_count() const;
941
942 // Gets the number of disabled tests.
943 int disabled_test_count() const;
944
945 // Gets the number of all tests.
946 int total_test_count() const;
947
948 // Gets the number of tests that should run.
949 int test_to_run_count() const;
950
951 // Gets the elapsed time, in milliseconds.
952 TimeInMillis elapsed_time() const { return elapsed_time_; }
953
954 // Returns true iff the unit test passed (i.e. all test cases passed).
955 bool Passed() const { return !Failed(); }
956
957 // Returns true iff the unit test failed (i.e. some test case failed
958 // or something outside of all tests failed).
959 bool Failed() const {
960 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
961 }
962
963 // Gets the i-th test case among all the test cases. i can range from 0 to
964 // total_test_case_count() - 1. If i is not in that range, returns NULL.
965 const TestCase* GetTestCase(int i) const {
966 const int index = GetElementOr(test_case_indices_, i, -1);
967 return index < 0 ? NULL : test_cases_[i];
968 }
969
970 // Gets the i-th test case among all the test cases. i can range from 0 to
971 // total_test_case_count() - 1. If i is not in that range, returns NULL.
972 TestCase* GetMutableTestCase(int i) {
973 const int index = GetElementOr(test_case_indices_, i, -1);
974 return index < 0 ? NULL : test_cases_[index];
975 }
976
977 // Provides access to the event listener list.
978 TestEventListeners* listeners() { return &listeners_; }
979
980 // Returns the TestResult for the test that's currently running, or
981 // the TestResult for the ad hoc test if no test is running.
982 TestResult* current_test_result();
983
984 // Returns the TestResult for the ad hoc test.
985 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
986
987 // Sets the OS stack trace getter.
988 //
989 // Does nothing if the input and the current OS stack trace getter
990 // are the same; otherwise, deletes the old getter and makes the
991 // input the current getter.
992 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
993
994 // Returns the current OS stack trace getter if it is not NULL;
995 // otherwise, creates an OsStackTraceGetter, makes it the current
996 // getter, and returns it.
997 OsStackTraceGetterInterface* os_stack_trace_getter();
998
999 // Returns the current OS stack trace as a String.
1000 //
1001 // The maximum number of stack frames to be included is specified by
1002 // the gtest_stack_trace_depth flag. The skip_count parameter
1003 // specifies the number of top frames to be skipped, which doesn't
1004 // count against the number of frames to be included.
1005 //
1006 // For example, if Foo() calls Bar(), which in turn calls
1007 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1008 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1009 String CurrentOsStackTraceExceptTop(int skip_count);
1010
1011 // Finds and returns a TestCase with the given name. If one doesn't
1012 // exist, creates one and returns it.
1013 //
1014 // Arguments:
1015 //
1016 // test_case_name: name of the test case
1017 // type_param: the name of the test's type parameter, or NULL if
1018 // this is not a typed or a type-parameterized test.
1019 // set_up_tc: pointer to the function that sets up the test case
1020 // tear_down_tc: pointer to the function that tears down the test case
1021 TestCase* GetTestCase(const char* test_case_name,
1022 const char* type_param,
1023 Test::SetUpTestCaseFunc set_up_tc,
1024 Test::TearDownTestCaseFunc tear_down_tc);
1025
1026 // Adds a TestInfo to the unit test.
1027 //
1028 // Arguments:
1029 //
1030 // set_up_tc: pointer to the function that sets up the test case
1031 // tear_down_tc: pointer to the function that tears down the test case
1032 // test_info: the TestInfo object
1033 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1034 Test::TearDownTestCaseFunc tear_down_tc,
1035 TestInfo* test_info) {
1036 // In order to support thread-safe death tests, we need to
1037 // remember the original working directory when the test program
1038 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1039 // the user may have changed the current directory before calling
1040 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1041 // AddTestInfo(), which is called to register a TEST or TEST_F
1042 // before main() is reached.
1043 if (original_working_dir_.IsEmpty()) {
1044 original_working_dir_.Set(FilePath::GetCurrentDir());
1045 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1046 << "Failed to get the current working directory.";
1047 }
1048
1049 GetTestCase(test_info->test_case_name(),
1050 test_info->type_param(),
1051 set_up_tc,
1052 tear_down_tc)->AddTestInfo(test_info);
1053 }
1054
1055#if GTEST_HAS_PARAM_TEST
1056 // Returns ParameterizedTestCaseRegistry object used to keep track of
1057 // value-parameterized tests and instantiate and register them.
1058 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1059 return parameterized_test_registry_;
1060 }
1061#endif // GTEST_HAS_PARAM_TEST
1062
1063 // Sets the TestCase object for the test that's currently running.
1064 void set_current_test_case(TestCase* a_current_test_case) {
1065 current_test_case_ = a_current_test_case;
1066 }
1067
1068 // Sets the TestInfo object for the test that's currently running. If
1069 // current_test_info is NULL, the assertion results will be stored in
1070 // ad_hoc_test_result_.
1071 void set_current_test_info(TestInfo* a_current_test_info) {
1072 current_test_info_ = a_current_test_info;
1073 }
1074
1075 // Registers all parameterized tests defined using TEST_P and
1076 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1077 // combination. This method can be called more then once; it has guards
1078 // protecting from registering the tests more then once. If
1079 // value-parameterized tests are disabled, RegisterParameterizedTests is
1080 // present but does nothing.
1081 void RegisterParameterizedTests();
1082
1083 // Runs all tests in this UnitTest object, prints the result, and
1084 // returns true if all tests are successful. If any exception is
1085 // thrown during a test, this test is considered to be failed, but
1086 // the rest of the tests will still be run.
1087 bool RunAllTests();
1088
1089 // Clears the results of all tests, except the ad hoc tests.
1090 void ClearNonAdHocTestResult() {
1091 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1092 }
1093
1094 // Clears the results of ad-hoc test assertions.
1095 void ClearAdHocTestResult() {
1096 ad_hoc_test_result_.Clear();
1097 }
1098
1099 enum ReactionToSharding {
1100 HONOR_SHARDING_PROTOCOL,
1101 IGNORE_SHARDING_PROTOCOL
1102 };
1103
1104 // Matches the full name of each test against the user-specified
1105 // filter to decide whether the test should run, then records the
1106 // result in each TestCase and TestInfo object.
1107 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1108 // based on sharding variables in the environment.
1109 // Returns the number of tests that should run.
1110 int FilterTests(ReactionToSharding shard_tests);
1111
1112 // Prints the names of the tests matching the user-specified filter flag.
1113 void ListTestsMatchingFilter();
1114
1115 const TestCase* current_test_case() const { return current_test_case_; }
1116 TestInfo* current_test_info() { return current_test_info_; }
1117 const TestInfo* current_test_info() const { return current_test_info_; }
1118
1119 // Returns the vector of environments that need to be set-up/torn-down
1120 // before/after the tests are run.
1121 std::vector<Environment*>& environments() { return environments_; }
1122
1123 // Getters for the per-thread Google Test trace stack.
1124 std::vector<TraceInfo>& gtest_trace_stack() {
1125 return *(gtest_trace_stack_.pointer());
1126 }
1127 const std::vector<TraceInfo>& gtest_trace_stack() const {
1128 return gtest_trace_stack_.get();
1129 }
1130
1131#if GTEST_HAS_DEATH_TEST
1132 void InitDeathTestSubprocessControlInfo() {
1133 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1134 }
1135 // Returns a pointer to the parsed --gtest_internal_run_death_test
1136 // flag, or NULL if that flag was not specified.
1137 // This information is useful only in a death test child process.
1138 // Must not be called before a call to InitGoogleTest.
1139 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1140 return internal_run_death_test_flag_.get();
1141 }
1142
1143 // Returns a pointer to the current death test factory.
1144 internal::DeathTestFactory* death_test_factory() {
1145 return death_test_factory_.get();
1146 }
1147
1148 void SuppressTestEventsIfInSubprocess();
1149
1150 friend class ReplaceDeathTestFactory;
1151#endif // GTEST_HAS_DEATH_TEST
1152
1153 // Initializes the event listener performing XML output as specified by
1154 // UnitTestOptions. Must not be called before InitGoogleTest.
1155 void ConfigureXmlOutput();
1156
1157#if GTEST_CAN_STREAM_RESULTS_
1158 // Initializes the event listener for streaming test results to a socket.
1159 // Must not be called before InitGoogleTest.
1160 void ConfigureStreamingOutput();
1161#endif
1162
1163 // Performs initialization dependent upon flag values obtained in
1164 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1165 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1166 // this function is also called from RunAllTests. Since this function can be
1167 // called more than once, it has to be idempotent.
1168 void PostFlagParsingInit();
1169
1170 // Gets the random seed used at the start of the current test iteration.
1171 int random_seed() const { return random_seed_; }
1172
1173 // Gets the random number generator.
1174 internal::Random* random() { return &random_; }
1175
1176 // Shuffles all test cases, and the tests within each test case,
1177 // making sure that death tests are still run first.
1178 void ShuffleTests();
1179
1180 // Restores the test cases and tests to their order before the first shuffle.
1181 void UnshuffleTests();
1182
1183 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1184 // UnitTest::Run() starts.
1185 bool catch_exceptions() const { return catch_exceptions_; }
1186
1187 private:
1188 friend class ::testing::UnitTest;
1189
1190 // Used by UnitTest::Run() to capture the state of
1191 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1192 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1193
1194 // The UnitTest object that owns this implementation object.
1195 UnitTest* const parent_;
1196
1197 // The working directory when the first TEST() or TEST_F() was
1198 // executed.
1199 internal::FilePath original_working_dir_;
1200
1201 // The default test part result reporters.
1202 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1203 DefaultPerThreadTestPartResultReporter
1204 default_per_thread_test_part_result_reporter_;
1205
1206 // Points to (but doesn't own) the global test part result reporter.
1207 TestPartResultReporterInterface* global_test_part_result_repoter_;
1208
1209 // Protects read and write access to global_test_part_result_reporter_.
1210 internal::Mutex global_test_part_result_reporter_mutex_;
1211
1212 // Points to (but doesn't own) the per-thread test part result reporter.
1213 internal::ThreadLocal<TestPartResultReporterInterface*>
1214 per_thread_test_part_result_reporter_;
1215
1216 // The vector of environments that need to be set-up/torn-down
1217 // before/after the tests are run.
1218 std::vector<Environment*> environments_;
1219
1220 // The vector of TestCases in their original order. It owns the
1221 // elements in the vector.
1222 std::vector<TestCase*> test_cases_;
1223
1224 // Provides a level of indirection for the test case list to allow
1225 // easy shuffling and restoring the test case order. The i-th
1226 // element of this vector is the index of the i-th test case in the
1227 // shuffled order.
1228 std::vector<int> test_case_indices_;
1229
1230#if GTEST_HAS_PARAM_TEST
1231 // ParameterizedTestRegistry object used to register value-parameterized
1232 // tests.
1233 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1234
1235 // Indicates whether RegisterParameterizedTests() has been called already.
1236 bool parameterized_tests_registered_;
1237#endif // GTEST_HAS_PARAM_TEST
1238
1239 // Index of the last death test case registered. Initially -1.
1240 int last_death_test_case_;
1241
1242 // This points to the TestCase for the currently running test. It
1243 // changes as Google Test goes through one test case after another.
1244 // When no test is running, this is set to NULL and Google Test
1245 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1246 TestCase* current_test_case_;
1247
1248 // This points to the TestInfo for the currently running test. It
1249 // changes as Google Test goes through one test after another. When
1250 // no test is running, this is set to NULL and Google Test stores
1251 // assertion results in ad_hoc_test_result_. Initially NULL.
1252 TestInfo* current_test_info_;
1253
1254 // Normally, a user only writes assertions inside a TEST or TEST_F,
1255 // or inside a function called by a TEST or TEST_F. Since Google
1256 // Test keeps track of which test is current running, it can
1257 // associate such an assertion with the test it belongs to.
1258 //
1259 // If an assertion is encountered when no TEST or TEST_F is running,
1260 // Google Test attributes the assertion result to an imaginary "ad hoc"
1261 // test, and records the result in ad_hoc_test_result_.
1262 TestResult ad_hoc_test_result_;
1263
1264 // The list of event listeners that can be used to track events inside
1265 // Google Test.
1266 TestEventListeners listeners_;
1267
1268 // The OS stack trace getter. Will be deleted when the UnitTest
1269 // object is destructed. By default, an OsStackTraceGetter is used,
1270 // but the user can set this field to use a custom getter if that is
1271 // desired.
1272 OsStackTraceGetterInterface* os_stack_trace_getter_;
1273
1274 // True iff PostFlagParsingInit() has been called.
1275 bool post_flag_parse_init_performed_;
1276
1277 // The random number seed used at the beginning of the test run.
1278 int random_seed_;
1279
1280 // Our random number generator.
1281 internal::Random random_;
1282
1283 // How long the test took to run, in milliseconds.
1284 TimeInMillis elapsed_time_;
1285
1286#if GTEST_HAS_DEATH_TEST
1287 // The decomposed components of the gtest_internal_run_death_test flag,
1288 // parsed when RUN_ALL_TESTS is called.
1289 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1290 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1291#endif // GTEST_HAS_DEATH_TEST
1292
1293 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1294 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1295
1296 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1297 // starts.
1298 bool catch_exceptions_;
1299
1300 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1301}; // class UnitTestImpl
1302
1303// Convenience function for accessing the global UnitTest
1304// implementation object.
1305inline UnitTestImpl* GetUnitTestImpl() {
1306 return UnitTest::GetInstance()->impl();
1307}
1308
1309#if GTEST_USES_SIMPLE_RE
1310
1311// Internal helper functions for implementing the simple regular
1312// expression matcher.
1313GTEST_API_ bool IsInSet(char ch, const char* str);
1314GTEST_API_ bool IsAsciiDigit(char ch);
1315GTEST_API_ bool IsAsciiPunct(char ch);
1316GTEST_API_ bool IsRepeat(char ch);
1317GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1318GTEST_API_ bool IsAsciiWordChar(char ch);
1319GTEST_API_ bool IsValidEscape(char ch);
1320GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1321GTEST_API_ bool ValidateRegex(const char* regex);
1322GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1323GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1324 bool escaped, char ch, char repeat, const char* regex, const char* str);
1325GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1326
1327#endif // GTEST_USES_SIMPLE_RE
1328
1329// Parses the command line for Google Test flags, without initializing
1330// other parts of Google Test.
1331GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1332GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1333
1334#if GTEST_HAS_DEATH_TEST
1335
1336// Returns the message describing the last system error, regardless of the
1337// platform.
1338GTEST_API_ String GetLastErrnoDescription();
1339
1340# if GTEST_OS_WINDOWS
1341// Provides leak-safe Windows kernel handle ownership.
1342class AutoHandle {
1343 public:
1344 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1345 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1346
1347 ~AutoHandle() { Reset(); }
1348
1349 HANDLE Get() const { return handle_; }
1350 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1351 void Reset(HANDLE handle) {
1352 if (handle != handle_) {
1353 if (handle_ != INVALID_HANDLE_VALUE)
1354 ::CloseHandle(handle_);
1355 handle_ = handle;
1356 }
1357 }
1358
1359 private:
1360 HANDLE handle_;
1361
1362 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1363};
1364# endif // GTEST_OS_WINDOWS
1365
1366// Attempts to parse a string into a positive integer pointed to by the
1367// number parameter. Returns true if that is possible.
1368// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1369// it here.
1370template <typename Integer>
1371bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1372 // Fail fast if the given string does not begin with a digit;
1373 // this bypasses strtoXXX's "optional leading whitespace and plus
1374 // or minus sign" semantics, which are undesirable here.
1375 if (str.empty() || !IsDigit(str[0])) {
1376 return false;
1377 }
1378 errno = 0;
1379
1380 char* end;
1381 // BiggestConvertible is the largest integer type that system-provided
1382 // string-to-number conversion routines can return.
1383
1384# if GTEST_OS_WINDOWS && !defined(__GNUC__)
1385
1386 // MSVC and C++ Builder define __int64 instead of the standard long long.
1387 typedef unsigned __int64 BiggestConvertible;
1388 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1389
1390# else
1391
1392 typedef unsigned long long BiggestConvertible; // NOLINT
1393 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1394
1395# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1396
1397 const bool parse_success = *end == '\0' && errno == 0;
1398
1399 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1400 // available.
1401 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1402
1403 const Integer result = static_cast<Integer>(parsed);
1404 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1405 *number = result;
1406 return true;
1407 }
1408 return false;
1409}
1410#endif // GTEST_HAS_DEATH_TEST
1411
1412// TestResult contains some private methods that should be hidden from
1413// Google Test user but are required for testing. This class allow our tests
1414// to access them.
1415//
1416// This class is supplied only for the purpose of testing Google Test's own
1417// constructs. Do not use it in user tests, either directly or indirectly.
1418class TestResultAccessor {
1419 public:
1420 static void RecordProperty(TestResult* test_result,
1421 const TestProperty& property) {
1422 test_result->RecordProperty(property);
1423 }
1424
1425 static void ClearTestPartResults(TestResult* test_result) {
1426 test_result->ClearTestPartResults();
1427 }
1428
1429 static const std::vector<testing::TestPartResult>& test_part_results(
1430 const TestResult& test_result) {
1431 return test_result.test_part_results();
1432 }
1433};
1434
1435} // namespace internal
1436} // namespace testing
1437
1438#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1439#undef GTEST_IMPLEMENTATION_
1440
1441#if GTEST_OS_WINDOWS
1442# define vsnprintf _vsnprintf
1443#endif // GTEST_OS_WINDOWS
1444
1445namespace testing {
1446
1447using internal::CountIf;
1448using internal::ForEach;
1449using internal::GetElementOr;
1450using internal::Shuffle;
1451
1452// Constants.
1453
1454// A test whose test case name or test name matches this filter is
1455// disabled and not run.
1456static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1457
1458// A test case whose name matches this filter is considered a death
1459// test case and will be run before test cases whose name doesn't
1460// match this filter.
1461static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1462
1463// A test filter that matches everything.
1464static const char kUniversalFilter[] = "*";
1465
1466// The default output file for XML output.
1467static const char kDefaultOutputFile[] = "test_detail.xml";
1468
1469// The environment variable name for the test shard index.
1470static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1471// The environment variable name for the total number of test shards.
1472static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1473// The environment variable name for the test shard status file.
1474static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1475
1476namespace internal {
1477
1478// The text used in failure messages to indicate the start of the
1479// stack trace.
1480const char kStackTraceMarker[] = "\nStack trace:\n";
1481
1482// g_help_flag is true iff the --help flag or an equivalent form is
1483// specified on the command line.
1484bool g_help_flag = false;
1485
1486} // namespace internal
1487
1488GTEST_DEFINE_bool_(
1489 also_run_disabled_tests,
1490 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1491 "Run disabled tests too, in addition to the tests normally being run.");
1492
1493GTEST_DEFINE_bool_(
1494 break_on_failure,
1495 internal::BoolFromGTestEnv("break_on_failure", false),
1496 "True iff a failed assertion should be a debugger break-point.");
1497
1498GTEST_DEFINE_bool_(
1499 catch_exceptions,
1500 internal::BoolFromGTestEnv("catch_exceptions", true),
1501 "True iff " GTEST_NAME_
1502 " should catch exceptions and treat them as test failures.");
1503
1504GTEST_DEFINE_string_(
1505 color,
1506 internal::StringFromGTestEnv("color", "auto"),
1507 "Whether to use colors in the output. Valid values: yes, no, "
1508 "and auto. 'auto' means to use colors if the output is "
1509 "being sent to a terminal and the TERM environment variable "
1510 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
1511
1512GTEST_DEFINE_string_(
1513 filter,
1514 internal::StringFromGTestEnv("filter", kUniversalFilter),
1515 "A colon-separated list of glob (not regex) patterns "
1516 "for filtering the tests to run, optionally followed by a "
1517 "'-' and a : separated list of negative patterns (tests to "
1518 "exclude). A test is run if it matches one of the positive "
1519 "patterns and does not match any of the negative patterns.");
1520
1521GTEST_DEFINE_bool_(list_tests, false,
1522 "List all tests without running them.");
1523
1524GTEST_DEFINE_string_(
1525 output,
1526 internal::StringFromGTestEnv("output", ""),
1527 "A format (currently must be \"xml\"), optionally followed "
1528 "by a colon and an output file name or directory. A directory "
1529 "is indicated by a trailing pathname separator. "
1530 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1531 "If a directory is specified, output files will be created "
1532 "within that directory, with file-names based on the test "
1533 "executable's name and, if necessary, made unique by adding "
1534 "digits.");
1535
1536GTEST_DEFINE_bool_(
1537 print_time,
1538 internal::BoolFromGTestEnv("print_time", true),
1539 "True iff " GTEST_NAME_
1540 " should display elapsed time in text output.");
1541
1542GTEST_DEFINE_int32_(
1543 random_seed,
1544 internal::Int32FromGTestEnv("random_seed", 0),
1545 "Random number seed to use when shuffling test orders. Must be in range "
1546 "[1, 99999], or 0 to use a seed based on the current time.");
1547
1548GTEST_DEFINE_int32_(
1549 repeat,
1550 internal::Int32FromGTestEnv("repeat", 1),
1551 "How many times to repeat each test. Specify a negative number "
1552 "for repeating forever. Useful for shaking out flaky tests.");
1553
1554GTEST_DEFINE_bool_(
1555 show_internal_stack_frames, false,
1556 "True iff " GTEST_NAME_ " should include internal stack frames when "
1557 "printing test failure stack traces.");
1558
1559GTEST_DEFINE_bool_(
1560 shuffle,
1561 internal::BoolFromGTestEnv("shuffle", false),
1562 "True iff " GTEST_NAME_
1563 " should randomize tests' order on every run.");
1564
1565GTEST_DEFINE_int32_(
1566 stack_trace_depth,
1567 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1568 "The maximum number of stack frames to print when an "
1569 "assertion fails. The valid range is 0 through 100, inclusive.");
1570
1571GTEST_DEFINE_string_(
1572 stream_result_to,
1573 internal::StringFromGTestEnv("stream_result_to", ""),
1574 "This flag specifies the host name and the port number on which to stream "
1575 "test results. Example: \"localhost:555\". The flag is effective only on "
1576 "Linux.");
1577
1578GTEST_DEFINE_bool_(
1579 throw_on_failure,
1580 internal::BoolFromGTestEnv("throw_on_failure", false),
1581 "When this flag is specified, a failed assertion will throw an exception "
1582 "if exceptions are enabled or exit the program with a non-zero code "
1583 "otherwise.");
1584
1585namespace internal {
1586
1587// Generates a random number from [0, range), using a Linear
1588// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1589// than kMaxRange.
1590UInt32 Random::Generate(UInt32 range) {
1591 // These constants are the same as are used in glibc's rand(3).
1592 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1593
1594 GTEST_CHECK_(range > 0)
1595 << "Cannot generate a number in the range [0, 0).";
1596 GTEST_CHECK_(range <= kMaxRange)
1597 << "Generation of a number in [0, " << range << ") was requested, "
1598 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1599
1600 // Converting via modulus introduces a bit of downward bias, but
1601 // it's simple, and a linear congruential generator isn't too good
1602 // to begin with.
1603 return state_ % range;
1604}
1605
1606// GTestIsInitialized() returns true iff the user has initialized
1607// Google Test. Useful for catching the user mistake of not initializing
1608// Google Test before calling RUN_ALL_TESTS().
1609//
1610// A user must call testing::InitGoogleTest() to initialize Google
1611// Test. g_init_gtest_count is set to the number of times
1612// InitGoogleTest() has been called. We don't protect this variable
1613// under a mutex as it is only accessed in the main thread.
1614int g_init_gtest_count = 0;
1615static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1616
1617// Iterates over a vector of TestCases, keeping a running sum of the
1618// results of calling a given int-returning method on each.
1619// Returns the sum.
1620static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1621 int (TestCase::*method)() const) {
1622 int sum = 0;
1623 for (size_t i = 0; i < case_list.size(); i++) {
1624 sum += (case_list[i]->*method)();
1625 }
1626 return sum;
1627}
1628
1629// Returns true iff the test case passed.
1630static bool TestCasePassed(const TestCase* test_case) {
1631 return test_case->should_run() && test_case->Passed();
1632}
1633
1634// Returns true iff the test case failed.
1635static bool TestCaseFailed(const TestCase* test_case) {
1636 return test_case->should_run() && test_case->Failed();
1637}
1638
1639// Returns true iff test_case contains at least one test that should
1640// run.
1641static bool ShouldRunTestCase(const TestCase* test_case) {
1642 return test_case->should_run();
1643}
1644
1645// AssertHelper constructor.
1646AssertHelper::AssertHelper(TestPartResult::Type type,
1647 const char* file,
1648 int line,
1649 const char* message)
1650 : data_(new AssertHelperData(type, file, line, message)) {
1651}
1652
1653AssertHelper::~AssertHelper() {
1654 delete data_;
1655}
1656
1657// Message assignment, for assertion streaming support.
1658void AssertHelper::operator=(const Message& message) const {
1659 UnitTest::GetInstance()->
1660 AddTestPartResult(data_->type, data_->file, data_->line,
1661 AppendUserMessage(data_->message, message),
1662 UnitTest::GetInstance()->impl()
1663 ->CurrentOsStackTraceExceptTop(1)
1664 // Skips the stack frame for this function itself.
1665 ); // NOLINT
1666}
1667
1668// Mutex for linked pointers.
1669GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1670
1671// Application pathname gotten in InitGoogleTest.
1672String g_executable_path;
1673
1674// Returns the current application's name, removing directory path if that
1675// is present.
1676FilePath GetCurrentExecutableName() {
1677 FilePath result;
1678
1679#if GTEST_OS_WINDOWS
1680 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1681#else
1682 result.Set(FilePath(g_executable_path));
1683#endif // GTEST_OS_WINDOWS
1684
1685 return result.RemoveDirectoryName();
1686}
1687
1688// Functions for processing the gtest_output flag.
1689
1690// Returns the output format, or "" for normal printed output.
1691String UnitTestOptions::GetOutputFormat() {
1692 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1693 if (gtest_output_flag == NULL) return String("");
1694
1695 const char* const colon = strchr(gtest_output_flag, ':');
1696 return (colon == NULL) ?
1697 String(gtest_output_flag) :
1698 String(gtest_output_flag, colon - gtest_output_flag);
1699}
1700
1701// Returns the name of the requested output file, or the default if none
1702// was explicitly specified.
1703String UnitTestOptions::GetAbsolutePathToOutputFile() {
1704 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1705 if (gtest_output_flag == NULL)
1706 return String("");
1707
1708 const char* const colon = strchr(gtest_output_flag, ':');
1709 if (colon == NULL)
1710 return String(internal::FilePath::ConcatPaths(
1711 internal::FilePath(
1712 UnitTest::GetInstance()->original_working_dir()),
1713 internal::FilePath(kDefaultOutputFile)).ToString() );
1714
1715 internal::FilePath output_name(colon + 1);
1716 if (!output_name.IsAbsolutePath())
1717 // TODO(wan@google.com): on Windows \some\path is not an absolute
1718 // path (as its meaning depends on the current drive), yet the
1719 // following logic for turning it into an absolute path is wrong.
1720 // Fix it.
1721 output_name = internal::FilePath::ConcatPaths(
1722 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1723 internal::FilePath(colon + 1));
1724
1725 if (!output_name.IsDirectory())
1726 return output_name.ToString();
1727
1728 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1729 output_name, internal::GetCurrentExecutableName(),
1730 GetOutputFormat().c_str()));
1731 return result.ToString();
1732}
1733
1734// Returns true iff the wildcard pattern matches the string. The
1735// first ':' or '\0' character in pattern marks the end of it.
1736//
1737// This recursive algorithm isn't very efficient, but is clear and
1738// works well enough for matching test names, which are short.
1739bool UnitTestOptions::PatternMatchesString(const char *pattern,
1740 const char *str) {
1741 switch (*pattern) {
1742 case '\0':
1743 case ':': // Either ':' or '\0' marks the end of the pattern.
1744 return *str == '\0';
1745 case '?': // Matches any single character.
1746 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1747 case '*': // Matches any string (possibly empty) of characters.
1748 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1749 PatternMatchesString(pattern + 1, str);
1750 default: // Non-special character. Matches itself.
1751 return *pattern == *str &&
1752 PatternMatchesString(pattern + 1, str + 1);
1753 }
1754}
1755
1756bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
1757 const char *cur_pattern = filter;
1758 for (;;) {
1759 if (PatternMatchesString(cur_pattern, name.c_str())) {
1760 return true;
1761 }
1762
1763 // Finds the next pattern in the filter.
1764 cur_pattern = strchr(cur_pattern, ':');
1765
1766 // Returns if no more pattern can be found.
1767 if (cur_pattern == NULL) {
1768 return false;
1769 }
1770
1771 // Skips the pattern separater (the ':' character).
1772 cur_pattern++;
1773 }
1774}
1775
1776// TODO(keithray): move String function implementations to gtest-string.cc.
1777
1778// Returns true iff the user-specified filter matches the test case
1779// name and the test name.
1780bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
1781 const String &test_name) {
1782 const String& full_name = String::Format("%s.%s",
1783 test_case_name.c_str(),
1784 test_name.c_str());
1785
1786 // Split --gtest_filter at '-', if there is one, to separate into
1787 // positive filter and negative filter portions
1788 const char* const p = GTEST_FLAG(filter).c_str();
1789 const char* const dash = strchr(p, '-');
1790 String positive;
1791 String negative;
1792 if (dash == NULL) {
1793 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1794 negative = String("");
1795 } else {
1796 positive = String(p, dash - p); // Everything up to the dash
1797 negative = String(dash+1); // Everything after the dash
1798 if (positive.empty()) {
1799 // Treat '-test1' as the same as '*-test1'
1800 positive = kUniversalFilter;
1801 }
1802 }
1803
1804 // A filter is a colon-separated list of patterns. It matches a
1805 // test if any pattern in it matches the test.
1806 return (MatchesFilter(full_name, positive.c_str()) &&
1807 !MatchesFilter(full_name, negative.c_str()));
1808}
1809
1810#if GTEST_HAS_SEH
1811// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1812// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1813// This function is useful as an __except condition.
1814int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1815 // Google Test should handle a SEH exception if:
1816 // 1. the user wants it to, AND
1817 // 2. this is not a breakpoint exception, AND
1818 // 3. this is not a C++ exception (VC++ implements them via SEH,
1819 // apparently).
1820 //
1821 // SEH exception code for C++ exceptions.
1822 // (see http://support.microsoft.com/kb/185294 for more information).
1823 const DWORD kCxxExceptionCode = 0xe06d7363;
1824
1825 bool should_handle = true;
1826
1827 if (!GTEST_FLAG(catch_exceptions))
1828 should_handle = false;
1829 else if (exception_code == EXCEPTION_BREAKPOINT)
1830 should_handle = false;
1831 else if (exception_code == kCxxExceptionCode)
1832 should_handle = false;
1833
1834 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
1835}
1836#endif // GTEST_HAS_SEH
1837
1838} // namespace internal
1839
1840// The c'tor sets this object as the test part result reporter used by
1841// Google Test. The 'result' parameter specifies where to report the
1842// results. Intercepts only failures from the current thread.
1843ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1844 TestPartResultArray* result)
1845 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
1846 result_(result) {
1847 Init();
1848}
1849
1850// The c'tor sets this object as the test part result reporter used by
1851// Google Test. The 'result' parameter specifies where to report the
1852// results.
1853ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1854 InterceptMode intercept_mode, TestPartResultArray* result)
1855 : intercept_mode_(intercept_mode),
1856 result_(result) {
1857 Init();
1858}
1859
1860void ScopedFakeTestPartResultReporter::Init() {
1861 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1862 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1863 old_reporter_ = impl->GetGlobalTestPartResultReporter();
1864 impl->SetGlobalTestPartResultReporter(this);
1865 } else {
1866 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
1867 impl->SetTestPartResultReporterForCurrentThread(this);
1868 }
1869}
1870
1871// The d'tor restores the test part result reporter used by Google Test
1872// before.
1873ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
1874 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1875 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1876 impl->SetGlobalTestPartResultReporter(old_reporter_);
1877 } else {
1878 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
1879 }
1880}
1881
1882// Increments the test part result count and remembers the result.
1883// This method is from the TestPartResultReporterInterface interface.
1884void ScopedFakeTestPartResultReporter::ReportTestPartResult(
1885 const TestPartResult& result) {
1886 result_->Append(result);
1887}
1888
1889namespace internal {
1890
1891// Returns the type ID of ::testing::Test. We should always call this
1892// instead of GetTypeId< ::testing::Test>() to get the type ID of
1893// testing::Test. This is to work around a suspected linker bug when
1894// using Google Test as a framework on Mac OS X. The bug causes
1895// GetTypeId< ::testing::Test>() to return different values depending
1896// on whether the call is from the Google Test framework itself or
1897// from user test code. GetTestTypeId() is guaranteed to always
1898// return the same value, as it always calls GetTypeId<>() from the
1899// gtest.cc, which is within the Google Test framework.
1900TypeId GetTestTypeId() {
1901 return GetTypeId<Test>();
1902}
1903
1904// The value of GetTestTypeId() as seen from within the Google Test
1905// library. This is solely for testing GetTestTypeId().
1906extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1907
1908// This predicate-formatter checks that 'results' contains a test part
1909// failure of the given type and that the failure message contains the
1910// given substring.
1911AssertionResult HasOneFailure(const char* /* results_expr */,
1912 const char* /* type_expr */,
1913 const char* /* substr_expr */,
1914 const TestPartResultArray& results,
1915 TestPartResult::Type type,
1916 const string& substr) {
1917 const String expected(type == TestPartResult::kFatalFailure ?
1918 "1 fatal failure" :
1919 "1 non-fatal failure");
1920 Message msg;
1921 if (results.size() != 1) {
1922 msg << "Expected: " << expected << "\n"
1923 << " Actual: " << results.size() << " failures";
1924 for (int i = 0; i < results.size(); i++) {
1925 msg << "\n" << results.GetTestPartResult(i);
1926 }
1927 return AssertionFailure() << msg;
1928 }
1929
1930 const TestPartResult& r = results.GetTestPartResult(0);
1931 if (r.type() != type) {
1932 return AssertionFailure() << "Expected: " << expected << "\n"
1933 << " Actual:\n"
1934 << r;
1935 }
1936
1937 if (strstr(r.message(), substr.c_str()) == NULL) {
1938 return AssertionFailure() << "Expected: " << expected << " containing \""
1939 << substr << "\"\n"
1940 << " Actual:\n"
1941 << r;
1942 }
1943
1944 return AssertionSuccess();
1945}
1946
1947// The constructor of SingleFailureChecker remembers where to look up
1948// test part results, what type of failure we expect, and what
1949// substring the failure message should contain.
1950SingleFailureChecker:: SingleFailureChecker(
1951 const TestPartResultArray* results,
1952 TestPartResult::Type type,
1953 const string& substr)
1954 : results_(results),
1955 type_(type),
1956 substr_(substr) {}
1957
1958// The destructor of SingleFailureChecker verifies that the given
1959// TestPartResultArray contains exactly one failure that has the given
1960// type and contains the given substring. If that's not the case, a
1961// non-fatal failure will be generated.
1962SingleFailureChecker::~SingleFailureChecker() {
1963 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
1964}
1965
1966DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1967 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1968
1969void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1970 const TestPartResult& result) {
1971 unit_test_->current_test_result()->AddTestPartResult(result);
1972 unit_test_->listeners()->repeater()->OnTestPartResult(result);
1973}
1974
1975DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1976 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1977
1978void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
1979 const TestPartResult& result) {
1980 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1981}
1982
1983// Returns the global test part result reporter.
1984TestPartResultReporterInterface*
1985UnitTestImpl::GetGlobalTestPartResultReporter() {
1986 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1987 return global_test_part_result_repoter_;
1988}
1989
1990// Sets the global test part result reporter.
1991void UnitTestImpl::SetGlobalTestPartResultReporter(
1992 TestPartResultReporterInterface* reporter) {
1993 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1994 global_test_part_result_repoter_ = reporter;
1995}
1996
1997// Returns the test part result reporter for the current thread.
1998TestPartResultReporterInterface*
1999UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2000 return per_thread_test_part_result_reporter_.get();
2001}
2002
2003// Sets the test part result reporter for the current thread.
2004void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2005 TestPartResultReporterInterface* reporter) {
2006 per_thread_test_part_result_reporter_.set(reporter);
2007}
2008
2009// Gets the number of successful test cases.
2010int UnitTestImpl::successful_test_case_count() const {
2011 return CountIf(test_cases_, TestCasePassed);
2012}
2013
2014// Gets the number of failed test cases.
2015int UnitTestImpl::failed_test_case_count() const {
2016 return CountIf(test_cases_, TestCaseFailed);
2017}
2018
2019// Gets the number of all test cases.
2020int UnitTestImpl::total_test_case_count() const {
2021 return static_cast<int>(test_cases_.size());
2022}
2023
2024// Gets the number of all test cases that contain at least one test
2025// that should run.
2026int UnitTestImpl::test_case_to_run_count() const {
2027 return CountIf(test_cases_, ShouldRunTestCase);
2028}
2029
2030// Gets the number of successful tests.
2031int UnitTestImpl::successful_test_count() const {
2032 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2033}
2034
2035// Gets the number of failed tests.
2036int UnitTestImpl::failed_test_count() const {
2037 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2038}
2039
2040// Gets the number of disabled tests.
2041int UnitTestImpl::disabled_test_count() const {
2042 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2043}
2044
2045// Gets the number of all tests.
2046int UnitTestImpl::total_test_count() const {
2047 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2048}
2049
2050// Gets the number of tests that should run.
2051int UnitTestImpl::test_to_run_count() const {
2052 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2053}
2054
2055// Returns the current OS stack trace as a String.
2056//
2057// The maximum number of stack frames to be included is specified by
2058// the gtest_stack_trace_depth flag. The skip_count parameter
2059// specifies the number of top frames to be skipped, which doesn't
2060// count against the number of frames to be included.
2061//
2062// For example, if Foo() calls Bar(), which in turn calls
2063// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2064// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2065String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2066 (void)skip_count;
2067 return String("");
2068}
2069
2070// Returns the current time in milliseconds.
2071TimeInMillis GetTimeInMillis() {
2072#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2073 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2074 // http://analogous.blogspot.com/2005/04/epoch.html
2075 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2076 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2077 const DWORD kTenthMicrosInMilliSecond = 10000;
2078
2079 SYSTEMTIME now_systime;
2080 FILETIME now_filetime;
2081 ULARGE_INTEGER now_int64;
2082 // TODO(kenton@google.com): Shouldn't this just use
2083 // GetSystemTimeAsFileTime()?
2084 GetSystemTime(&now_systime);
2085 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2086 now_int64.LowPart = now_filetime.dwLowDateTime;
2087 now_int64.HighPart = now_filetime.dwHighDateTime;
2088 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2089 kJavaEpochToWinFileTimeDelta;
2090 return now_int64.QuadPart;
2091 }
2092 return 0;
2093#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2094 __timeb64 now;
2095
2096# ifdef _MSC_VER
2097
2098 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2099 // (deprecated function) there.
2100 // TODO(kenton@google.com): Use GetTickCount()? Or use
2101 // SystemTimeToFileTime()
2102# pragma warning(push) // Saves the current warning state.
2103# pragma warning(disable:4996) // Temporarily disables warning 4996.
2104 _ftime64(&now);
2105# pragma warning(pop) // Restores the warning state.
2106# else
2107
2108 _ftime64(&now);
2109
2110# endif // _MSC_VER
2111
2112 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2113#elif GTEST_HAS_GETTIMEOFDAY_
2114 struct timeval now;
2115 gettimeofday(&now, NULL);
2116 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2117#else
2118# error "Don't know how to get the current time on your system."
2119#endif
2120}
2121
2122// Utilities
2123
2124// class String
2125
2126// Returns the input enclosed in double quotes if it's not NULL;
2127// otherwise returns "(null)". For example, "\"Hello\"" is returned
2128// for input "Hello".
2129//
2130// This is useful for printing a C string in the syntax of a literal.
2131//
2132// Known issue: escape sequences are not handled yet.
2133String String::ShowCStringQuoted(const char* c_str) {
2134 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
2135}
2136
2137// Copies at most length characters from str into a newly-allocated
2138// piece of memory of size length+1. The memory is allocated with new[].
2139// A terminating null byte is written to the memory, and a pointer to it
2140// is returned. If str is NULL, NULL is returned.
2141static char* CloneString(const char* str, size_t length) {
2142 if (str == NULL) {
2143 return NULL;
2144 } else {
2145 char* const clone = new char[length + 1];
2146 posix::StrNCpy(clone, str, length);
2147 clone[length] = '\0';
2148 return clone;
2149 }
2150}
2151
2152// Clones a 0-terminated C string, allocating memory using new. The
2153// caller is responsible for deleting[] the return value. Returns the
2154// cloned string, or NULL if the input is NULL.
2155const char * String::CloneCString(const char* c_str) {
2156 return (c_str == NULL) ?
2157 NULL : CloneString(c_str, strlen(c_str));
2158}
2159
2160#if GTEST_OS_WINDOWS_MOBILE
2161// Creates a UTF-16 wide string from the given ANSI string, allocating
2162// memory using new. The caller is responsible for deleting the return
2163// value using delete[]. Returns the wide string, or NULL if the
2164// input is NULL.
2165LPCWSTR String::AnsiToUtf16(const char* ansi) {
2166 if (!ansi) return NULL;
2167 const int length = strlen(ansi);
2168 const int unicode_length =
2169 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2170 NULL, 0);
2171 WCHAR* unicode = new WCHAR[unicode_length + 1];
2172 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2173 unicode, unicode_length);
2174 unicode[unicode_length] = 0;
2175 return unicode;
2176}
2177
2178// Creates an ANSI string from the given wide string, allocating
2179// memory using new. The caller is responsible for deleting the return
2180// value using delete[]. Returns the ANSI string, or NULL if the
2181// input is NULL.
2182const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2183 if (!utf16_str) return NULL;
2184 const int ansi_length =
2185 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2186 NULL, 0, NULL, NULL);
2187 char* ansi = new char[ansi_length + 1];
2188 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2189 ansi, ansi_length, NULL, NULL);
2190 ansi[ansi_length] = 0;
2191 return ansi;
2192}
2193
2194#endif // GTEST_OS_WINDOWS_MOBILE
2195
2196// Compares two C strings. Returns true iff they have the same content.
2197//
2198// Unlike strcmp(), this function can handle NULL argument(s). A NULL
2199// C string is considered different to any non-NULL C string,
2200// including the empty string.
2201bool String::CStringEquals(const char * lhs, const char * rhs) {
2202 if ( lhs == NULL ) return rhs == NULL;
2203
2204 if ( rhs == NULL ) return false;
2205
2206 return strcmp(lhs, rhs) == 0;
2207}
2208
2209#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2210
2211// Converts an array of wide chars to a narrow string using the UTF-8
2212// encoding, and streams the result to the given Message object.
2213static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2214 Message* msg) {
2215 // TODO(wan): consider allowing a testing::String object to
2216 // contain '\0'. This will make it behave more like std::string,
2217 // and will allow ToUtf8String() to return the correct encoding
2218 // for '\0' s.t. we can get rid of the conditional here (and in
2219 // several other places).
2220 for (size_t i = 0; i != length; ) { // NOLINT
2221 if (wstr[i] != L'\0') {
2222 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2223 while (i != length && wstr[i] != L'\0')
2224 i++;
2225 } else {
2226 *msg << '\0';
2227 i++;
2228 }
2229 }
2230}
2231
2232#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2233
2234} // namespace internal
2235
2236#if GTEST_HAS_STD_WSTRING
2237// Converts the given wide string to a narrow string using the UTF-8
2238// encoding, and streams the result to this Message object.
2239Message& Message::operator <<(const ::std::wstring& wstr) {
2240 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2241 return *this;
2242}
2243#endif // GTEST_HAS_STD_WSTRING
2244
2245#if GTEST_HAS_GLOBAL_WSTRING
2246// Converts the given wide string to a narrow string using the UTF-8
2247// encoding, and streams the result to this Message object.
2248Message& Message::operator <<(const ::wstring& wstr) {
2249 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2250 return *this;
2251}
2252#endif // GTEST_HAS_GLOBAL_WSTRING
2253
2254// AssertionResult constructors.
2255// Used in EXPECT_TRUE/FALSE(assertion_result).
2256AssertionResult::AssertionResult(const AssertionResult& other)
2257 : success_(other.success_),
2258 message_(other.message_.get() != NULL ?
2259 new ::std::string(*other.message_) :
2260 static_cast< ::std::string*>(NULL)) {
2261}
2262
2263// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2264AssertionResult AssertionResult::operator!() const {
2265 AssertionResult negation(!success_);
2266 if (message_.get() != NULL)
2267 negation << *message_;
2268 return negation;
2269}
2270
2271// Makes a successful assertion result.
2272AssertionResult AssertionSuccess() {
2273 return AssertionResult(true);
2274}
2275
2276// Makes a failed assertion result.
2277AssertionResult AssertionFailure() {
2278 return AssertionResult(false);
2279}
2280
2281// Makes a failed assertion result with the given failure message.
2282// Deprecated; use AssertionFailure() << message.
2283AssertionResult AssertionFailure(const Message& message) {
2284 return AssertionFailure() << message;
2285}
2286
2287namespace internal {
2288
2289// Constructs and returns the message for an equality assertion
2290// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2291//
2292// The first four parameters are the expressions used in the assertion
2293// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2294// where foo is 5 and bar is 6, we have:
2295//
2296// expected_expression: "foo"
2297// actual_expression: "bar"
2298// expected_value: "5"
2299// actual_value: "6"
2300//
2301// The ignoring_case parameter is true iff the assertion is a
2302// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2303// be inserted into the message.
2304AssertionResult EqFailure(const char* expected_expression,
2305 const char* actual_expression,
2306 const String& expected_value,
2307 const String& actual_value,
2308 bool ignoring_case) {
2309 Message msg;
2310 msg << "Value of: " << actual_expression;
2311 if (actual_value != actual_expression) {
2312 msg << "\n Actual: " << actual_value;
2313 }
2314
2315 msg << "\nExpected: " << expected_expression;
2316 if (ignoring_case) {
2317 msg << " (ignoring case)";
2318 }
2319 if (expected_value != expected_expression) {
2320 msg << "\nWhich is: " << expected_value;
2321 }
2322
2323 return AssertionFailure() << msg;
2324}
2325
2326// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2327String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
2328 const char* expression_text,
2329 const char* actual_predicate_value,
2330 const char* expected_predicate_value) {
2331 const char* actual_message = assertion_result.message();
2332 Message msg;
2333 msg << "Value of: " << expression_text
2334 << "\n Actual: " << actual_predicate_value;
2335 if (actual_message[0] != '\0')
2336 msg << " (" << actual_message << ")";
2337 msg << "\nExpected: " << expected_predicate_value;
2338 return msg.GetString();
2339}
2340
2341// Helper function for implementing ASSERT_NEAR.
2342AssertionResult DoubleNearPredFormat(const char* expr1,
2343 const char* expr2,
2344 const char* abs_error_expr,
2345 double val1,
2346 double val2,
2347 double abs_error) {
2348 const double diff = fabs(val1 - val2);
2349 if (diff <= abs_error) return AssertionSuccess();
2350
2351 // TODO(wan): do not print the value of an expression if it's
2352 // already a literal.
2353 return AssertionFailure()
2354 << "The difference between " << expr1 << " and " << expr2
2355 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2356 << expr1 << " evaluates to " << val1 << ",\n"
2357 << expr2 << " evaluates to " << val2 << ", and\n"
2358 << abs_error_expr << " evaluates to " << abs_error << ".";
2359}
2360
2361
2362// Helper template for implementing FloatLE() and DoubleLE().
2363template <typename RawType>
2364AssertionResult FloatingPointLE(const char* expr1,
2365 const char* expr2,
2366 RawType val1,
2367 RawType val2) {
2368 // Returns success if val1 is less than val2,
2369 if (val1 < val2) {
2370 return AssertionSuccess();
2371 }
2372
2373 // or if val1 is almost equal to val2.
2374 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2375 if (lhs.AlmostEquals(rhs)) {
2376 return AssertionSuccess();
2377 }
2378
2379 // Note that the above two checks will both fail if either val1 or
2380 // val2 is NaN, as the IEEE floating-point standard requires that
2381 // any predicate involving a NaN must return false.
2382
2383 ::std::stringstream val1_ss;
2384 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2385 << val1;
2386
2387 ::std::stringstream val2_ss;
2388 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2389 << val2;
2390
2391 return AssertionFailure()
2392 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2393 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2394 << StringStreamToString(&val2_ss);
2395}
2396
2397} // namespace internal
2398
2399// Asserts that val1 is less than, or almost equal to, val2. Fails
2400// otherwise. In particular, it fails if either val1 or val2 is NaN.
2401AssertionResult FloatLE(const char* expr1, const char* expr2,
2402 float val1, float val2) {
2403 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2404}
2405
2406// Asserts that val1 is less than, or almost equal to, val2. Fails
2407// otherwise. In particular, it fails if either val1 or val2 is NaN.
2408AssertionResult DoubleLE(const char* expr1, const char* expr2,
2409 double val1, double val2) {
2410 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2411}
2412
2413namespace internal {
2414
2415// The helper function for {ASSERT|EXPECT}_EQ with int or enum
2416// arguments.
2417AssertionResult CmpHelperEQ(const char* expected_expression,
2418 const char* actual_expression,
2419 BiggestInt expected,
2420 BiggestInt actual) {
2421 if (expected == actual) {
2422 return AssertionSuccess();
2423 }
2424
2425 return EqFailure(expected_expression,
2426 actual_expression,
2427 FormatForComparisonFailureMessage(expected, actual),
2428 FormatForComparisonFailureMessage(actual, expected),
2429 false);
2430}
2431
2432// A macro for implementing the helper functions needed to implement
2433// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2434// just to avoid copy-and-paste of similar code.
2435#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2436AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2437 BiggestInt val1, BiggestInt val2) {\
2438 if (val1 op val2) {\
2439 return AssertionSuccess();\
2440 } else {\
2441 return AssertionFailure() \
2442 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2443 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2444 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2445 }\
2446}
2447
2448// Implements the helper function for {ASSERT|EXPECT}_NE with int or
2449// enum arguments.
2450GTEST_IMPL_CMP_HELPER_(NE, !=)
2451// Implements the helper function for {ASSERT|EXPECT}_LE with int or
2452// enum arguments.
2453GTEST_IMPL_CMP_HELPER_(LE, <=)
2454// Implements the helper function for {ASSERT|EXPECT}_LT with int or
2455// enum arguments.
2456GTEST_IMPL_CMP_HELPER_(LT, < )
2457// Implements the helper function for {ASSERT|EXPECT}_GE with int or
2458// enum arguments.
2459GTEST_IMPL_CMP_HELPER_(GE, >=)
2460// Implements the helper function for {ASSERT|EXPECT}_GT with int or
2461// enum arguments.
2462GTEST_IMPL_CMP_HELPER_(GT, > )
2463
2464#undef GTEST_IMPL_CMP_HELPER_
2465
2466// The helper function for {ASSERT|EXPECT}_STREQ.
2467AssertionResult CmpHelperSTREQ(const char* expected_expression,
2468 const char* actual_expression,
2469 const char* expected,
2470 const char* actual) {
2471 if (String::CStringEquals(expected, actual)) {
2472 return AssertionSuccess();
2473 }
2474
2475 return EqFailure(expected_expression,
2476 actual_expression,
2477 String::ShowCStringQuoted(expected),
2478 String::ShowCStringQuoted(actual),
2479 false);
2480}
2481
2482// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2483AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2484 const char* actual_expression,
2485 const char* expected,
2486 const char* actual) {
2487 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2488 return AssertionSuccess();
2489 }
2490
2491 return EqFailure(expected_expression,
2492 actual_expression,
2493 String::ShowCStringQuoted(expected),
2494 String::ShowCStringQuoted(actual),
2495 true);
2496}
2497
2498// The helper function for {ASSERT|EXPECT}_STRNE.
2499AssertionResult CmpHelperSTRNE(const char* s1_expression,
2500 const char* s2_expression,
2501 const char* s1,
2502 const char* s2) {
2503 if (!String::CStringEquals(s1, s2)) {
2504 return AssertionSuccess();
2505 } else {
2506 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2507 << s2_expression << "), actual: \""
2508 << s1 << "\" vs \"" << s2 << "\"";
2509 }
2510}
2511
2512// The helper function for {ASSERT|EXPECT}_STRCASENE.
2513AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2514 const char* s2_expression,
2515 const char* s1,
2516 const char* s2) {
2517 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2518 return AssertionSuccess();
2519 } else {
2520 return AssertionFailure()
2521 << "Expected: (" << s1_expression << ") != ("
2522 << s2_expression << ") (ignoring case), actual: \""
2523 << s1 << "\" vs \"" << s2 << "\"";
2524 }
2525}
2526
2527} // namespace internal
2528
2529namespace {
2530
2531// Helper functions for implementing IsSubString() and IsNotSubstring().
2532
2533// This group of overloaded functions return true iff needle is a
2534// substring of haystack. NULL is considered a substring of itself
2535// only.
2536
2537bool IsSubstringPred(const char* needle, const char* haystack) {
2538 if (needle == NULL || haystack == NULL)
2539 return needle == haystack;
2540
2541 return strstr(haystack, needle) != NULL;
2542}
2543
2544bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2545 if (needle == NULL || haystack == NULL)
2546 return needle == haystack;
2547
2548 return wcsstr(haystack, needle) != NULL;
2549}
2550
2551// StringType here can be either ::std::string or ::std::wstring.
2552template <typename StringType>
2553bool IsSubstringPred(const StringType& needle,
2554 const StringType& haystack) {
2555 return haystack.find(needle) != StringType::npos;
2556}
2557
2558// This function implements either IsSubstring() or IsNotSubstring(),
2559// depending on the value of the expected_to_be_substring parameter.
2560// StringType here can be const char*, const wchar_t*, ::std::string,
2561// or ::std::wstring.
2562template <typename StringType>
2563AssertionResult IsSubstringImpl(
2564 bool expected_to_be_substring,
2565 const char* needle_expr, const char* haystack_expr,
2566 const StringType& needle, const StringType& haystack) {
2567 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2568 return AssertionSuccess();
2569
2570 const bool is_wide_string = sizeof(needle[0]) > 1;
2571 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2572 return AssertionFailure()
2573 << "Value of: " << needle_expr << "\n"
2574 << " Actual: " << begin_string_quote << needle << "\"\n"
2575 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2576 << "a substring of " << haystack_expr << "\n"
2577 << "Which is: " << begin_string_quote << haystack << "\"";
2578}
2579
2580} // namespace
2581
2582// IsSubstring() and IsNotSubstring() check whether needle is a
2583// substring of haystack (NULL is considered a substring of itself
2584// only), and return an appropriate error message when they fail.
2585
2586AssertionResult IsSubstring(
2587 const char* needle_expr, const char* haystack_expr,
2588 const char* needle, const char* haystack) {
2589 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2590}
2591
2592AssertionResult IsSubstring(
2593 const char* needle_expr, const char* haystack_expr,
2594 const wchar_t* needle, const wchar_t* haystack) {
2595 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2596}
2597
2598AssertionResult IsNotSubstring(
2599 const char* needle_expr, const char* haystack_expr,
2600 const char* needle, const char* haystack) {
2601 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2602}
2603
2604AssertionResult IsNotSubstring(
2605 const char* needle_expr, const char* haystack_expr,
2606 const wchar_t* needle, const wchar_t* haystack) {
2607 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2608}
2609
2610AssertionResult IsSubstring(
2611 const char* needle_expr, const char* haystack_expr,
2612 const ::std::string& needle, const ::std::string& haystack) {
2613 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2614}
2615
2616AssertionResult IsNotSubstring(
2617 const char* needle_expr, const char* haystack_expr,
2618 const ::std::string& needle, const ::std::string& haystack) {
2619 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2620}
2621
2622#if GTEST_HAS_STD_WSTRING
2623AssertionResult IsSubstring(
2624 const char* needle_expr, const char* haystack_expr,
2625 const ::std::wstring& needle, const ::std::wstring& haystack) {
2626 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2627}
2628
2629AssertionResult IsNotSubstring(
2630 const char* needle_expr, const char* haystack_expr,
2631 const ::std::wstring& needle, const ::std::wstring& haystack) {
2632 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2633}
2634#endif // GTEST_HAS_STD_WSTRING
2635
2636namespace internal {
2637
2638#if GTEST_OS_WINDOWS
2639
2640namespace {
2641
2642// Helper function for IsHRESULT{SuccessFailure} predicates
2643AssertionResult HRESULTFailureHelper(const char* expr,
2644 const char* expected,
2645 long hr) { // NOLINT
2646# if GTEST_OS_WINDOWS_MOBILE
2647
2648 // Windows CE doesn't support FormatMessage.
2649 const char error_text[] = "";
2650
2651# else
2652
2653 // Looks up the human-readable system message for the HRESULT code
2654 // and since we're not passing any params to FormatMessage, we don't
2655 // want inserts expanded.
2656 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2657 FORMAT_MESSAGE_IGNORE_INSERTS;
2658 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
2659 // Gets the system's human readable message string for this HRESULT.
2660 char error_text[kBufSize] = { '\0' };
2661 DWORD message_length = ::FormatMessageA(kFlags,
2662 0, // no source, we're asking system
2663 hr, // the error
2664 0, // no line width restrictions
2665 error_text, // output buffer
2666 kBufSize, // buf size
2667 NULL); // no arguments for inserts
2668 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
2669 for (; message_length && IsSpace(error_text[message_length - 1]);
2670 --message_length) {
2671 error_text[message_length - 1] = '\0';
2672 }
2673
2674# endif // GTEST_OS_WINDOWS_MOBILE
2675
2676 const String error_hex(String::Format("0x%08X ", hr));
2677 return ::testing::AssertionFailure()
2678 << "Expected: " << expr << " " << expected << ".\n"
2679 << " Actual: " << error_hex << error_text << "\n";
2680}
2681
2682} // namespace
2683
2684AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2685 if (SUCCEEDED(hr)) {
2686 return AssertionSuccess();
2687 }
2688 return HRESULTFailureHelper(expr, "succeeds", hr);
2689}
2690
2691AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2692 if (FAILED(hr)) {
2693 return AssertionSuccess();
2694 }
2695 return HRESULTFailureHelper(expr, "fails", hr);
2696}
2697
2698#endif // GTEST_OS_WINDOWS
2699
2700// Utility functions for encoding Unicode text (wide strings) in
2701// UTF-8.
2702
2703// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2704// like this:
2705//
2706// Code-point length Encoding
2707// 0 - 7 bits 0xxxxxxx
2708// 8 - 11 bits 110xxxxx 10xxxxxx
2709// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2710// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2711
2712// The maximum code-point a one-byte UTF-8 sequence can represent.
2713const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2714
2715// The maximum code-point a two-byte UTF-8 sequence can represent.
2716const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2717
2718// The maximum code-point a three-byte UTF-8 sequence can represent.
2719const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2720
2721// The maximum code-point a four-byte UTF-8 sequence can represent.
2722const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2723
2724// Chops off the n lowest bits from a bit pattern. Returns the n
2725// lowest bits. As a side effect, the original bit pattern will be
2726// shifted to the right by n bits.
2727inline UInt32 ChopLowBits(UInt32* bits, int n) {
2728 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2729 *bits >>= n;
2730 return low_bits;
2731}
2732
2733// Converts a Unicode code point to a narrow string in UTF-8 encoding.
2734// code_point parameter is of type UInt32 because wchar_t may not be
2735// wide enough to contain a code point.
2736// The output buffer str must containt at least 32 characters.
2737// The function returns the address of the output buffer.
2738// If the code_point is not a valid Unicode code point
2739// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2740// as '(Invalid Unicode 0xXXXXXXXX)'.
2741char* CodePointToUtf8(UInt32 code_point, char* str) {
2742 if (code_point <= kMaxCodePoint1) {
2743 str[1] = '\0';
2744 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2745 } else if (code_point <= kMaxCodePoint2) {
2746 str[2] = '\0';
2747 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2748 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2749 } else if (code_point <= kMaxCodePoint3) {
2750 str[3] = '\0';
2751 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2752 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2753 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2754 } else if (code_point <= kMaxCodePoint4) {
2755 str[4] = '\0';
2756 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2757 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2758 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2759 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2760 } else {
2761 // The longest string String::Format can produce when invoked
2762 // with these parameters is 28 character long (not including
2763 // the terminating nul character). We are asking for 32 character
2764 // buffer just in case. This is also enough for strncpy to
2765 // null-terminate the destination string.
2766 posix::StrNCpy(
2767 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2768 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
2769 // the result unterminated.
2770 }
2771 return str;
2772}
2773
2774// The following two functions only make sense if the the system
2775// uses UTF-16 for wide string encoding. All supported systems
2776// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2777
2778// Determines if the arguments constitute UTF-16 surrogate pair
2779// and thus should be combined into a single Unicode code point
2780// using CreateCodePointFromUtf16SurrogatePair.
2781inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2782 return sizeof(wchar_t) == 2 &&
2783 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2784}
2785
2786// Creates a Unicode code point from UTF16 surrogate pair.
2787inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2788 wchar_t second) {
2789 const UInt32 mask = (1 << 10) - 1;
2790 return (sizeof(wchar_t) == 2) ?
2791 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2792 // This function should not be called when the condition is
2793 // false, but we provide a sensible default in case it is.
2794 static_cast<UInt32>(first);
2795}
2796
2797// Converts a wide string to a narrow string in UTF-8 encoding.
2798// The wide string is assumed to have the following encoding:
2799// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2800// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2801// Parameter str points to a null-terminated wide string.
2802// Parameter num_chars may additionally limit the number
2803// of wchar_t characters processed. -1 is used when the entire string
2804// should be processed.
2805// If the string contains code points that are not valid Unicode code points
2806// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2807// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2808// and contains invalid UTF-16 surrogate pairs, values in those pairs
2809// will be encoded as individual Unicode characters from Basic Normal Plane.
2810String WideStringToUtf8(const wchar_t* str, int num_chars) {
2811 if (num_chars == -1)
2812 num_chars = static_cast<int>(wcslen(str));
2813
2814 ::std::stringstream stream;
2815 for (int i = 0; i < num_chars; ++i) {
2816 UInt32 unicode_code_point;
2817
2818 if (str[i] == L'\0') {
2819 break;
2820 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2821 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2822 str[i + 1]);
2823 i++;
2824 } else {
2825 unicode_code_point = static_cast<UInt32>(str[i]);
2826 }
2827
2828 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
2829 stream << CodePointToUtf8(unicode_code_point, buffer);
2830 }
2831 return StringStreamToString(&stream);
2832}
2833
2834// Converts a wide C string to a String using the UTF-8 encoding.
2835// NULL will be converted to "(null)".
2836String String::ShowWideCString(const wchar_t * wide_c_str) {
2837 if (wide_c_str == NULL) return String("(null)");
2838
2839 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
2840}
2841
2842// Similar to ShowWideCString(), except that this function encloses
2843// the converted string in double quotes.
2844String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
2845 if (wide_c_str == NULL) return String("(null)");
2846
2847 return String::Format("L\"%s\"",
2848 String::ShowWideCString(wide_c_str).c_str());
2849}
2850
2851// Compares two wide C strings. Returns true iff they have the same
2852// content.
2853//
2854// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2855// C string is considered different to any non-NULL C string,
2856// including the empty string.
2857bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
2858 if (lhs == NULL) return rhs == NULL;
2859
2860 if (rhs == NULL) return false;
2861
2862 return wcscmp(lhs, rhs) == 0;
2863}
2864
2865// Helper function for *_STREQ on wide strings.
2866AssertionResult CmpHelperSTREQ(const char* expected_expression,
2867 const char* actual_expression,
2868 const wchar_t* expected,
2869 const wchar_t* actual) {
2870 if (String::WideCStringEquals(expected, actual)) {
2871 return AssertionSuccess();
2872 }
2873
2874 return EqFailure(expected_expression,
2875 actual_expression,
2876 String::ShowWideCStringQuoted(expected),
2877 String::ShowWideCStringQuoted(actual),
2878 false);
2879}
2880
2881// Helper function for *_STRNE on wide strings.
2882AssertionResult CmpHelperSTRNE(const char* s1_expression,
2883 const char* s2_expression,
2884 const wchar_t* s1,
2885 const wchar_t* s2) {
2886 if (!String::WideCStringEquals(s1, s2)) {
2887 return AssertionSuccess();
2888 }
2889
2890 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2891 << s2_expression << "), actual: "
2892 << String::ShowWideCStringQuoted(s1)
2893 << " vs " << String::ShowWideCStringQuoted(s2);
2894}
2895
2896// Compares two C strings, ignoring case. Returns true iff they have
2897// the same content.
2898//
2899// Unlike strcasecmp(), this function can handle NULL argument(s). A
2900// NULL C string is considered different to any non-NULL C string,
2901// including the empty string.
2902bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
2903 if (lhs == NULL)
2904 return rhs == NULL;
2905 if (rhs == NULL)
2906 return false;
2907 return posix::StrCaseCmp(lhs, rhs) == 0;
2908}
2909
2910 // Compares two wide C strings, ignoring case. Returns true iff they
2911 // have the same content.
2912 //
2913 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2914 // A NULL C string is considered different to any non-NULL wide C string,
2915 // including the empty string.
2916 // NB: The implementations on different platforms slightly differ.
2917 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2918 // environment variable. On GNU platform this method uses wcscasecmp
2919 // which compares according to LC_CTYPE category of the current locale.
2920 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2921 // current locale.
2922bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2923 const wchar_t* rhs) {
2924 if (lhs == NULL) return rhs == NULL;
2925
2926 if (rhs == NULL) return false;
2927
2928#if GTEST_OS_WINDOWS
2929 return _wcsicmp(lhs, rhs) == 0;
2930#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2931 return wcscasecmp(lhs, rhs) == 0;
2932#else
2933 // Android, Mac OS X and Cygwin don't define wcscasecmp.
2934 // Other unknown OSes may not define it either.
2935 wint_t left, right;
2936 do {
2937 left = towlower(*lhs++);
2938 right = towlower(*rhs++);
2939 } while (left && left == right);
2940 return left == right;
2941#endif // OS selector
2942}
2943
2944// Compares this with another String.
2945// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
2946// if this is greater than rhs.
2947int String::Compare(const String & rhs) const {
2948 const char* const lhs_c_str = c_str();
2949 const char* const rhs_c_str = rhs.c_str();
2950
2951 if (lhs_c_str == NULL) {
2952 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
2953 } else if (rhs_c_str == NULL) {
2954 return 1;
2955 }
2956
2957 const size_t shorter_str_len =
2958 length() <= rhs.length() ? length() : rhs.length();
2959 for (size_t i = 0; i != shorter_str_len; i++) {
2960 if (lhs_c_str[i] < rhs_c_str[i]) {
2961 return -1;
2962 } else if (lhs_c_str[i] > rhs_c_str[i]) {
2963 return 1;
2964 }
2965 }
2966 return (length() < rhs.length()) ? -1 :
2967 (length() > rhs.length()) ? 1 : 0;
2968}
2969
2970// Returns true iff this String ends with the given suffix. *Any*
2971// String is considered to end with a NULL or empty suffix.
2972bool String::EndsWith(const char* suffix) const {
2973 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2974
2975 if (c_str() == NULL) return false;
2976
2977 const size_t this_len = strlen(c_str());
2978 const size_t suffix_len = strlen(suffix);
2979 return (this_len >= suffix_len) &&
2980 CStringEquals(c_str() + this_len - suffix_len, suffix);
2981}
2982
2983// Returns true iff this String ends with the given suffix, ignoring case.
2984// Any String is considered to end with a NULL or empty suffix.
2985bool String::EndsWithCaseInsensitive(const char* suffix) const {
2986 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2987
2988 if (c_str() == NULL) return false;
2989
2990 const size_t this_len = strlen(c_str());
2991 const size_t suffix_len = strlen(suffix);
2992 return (this_len >= suffix_len) &&
2993 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
2994}
2995
2996// Formats a list of arguments to a String, using the same format
2997// spec string as for printf.
2998//
2999// We do not use the StringPrintf class as it is not universally
3000// available.
3001//
3002// The result is limited to 4096 characters (including the tailing 0).
3003// If 4096 characters are not enough to format the input, or if
3004// there's an error, "<formatting error or buffer exceeded>" is
3005// returned.
3006String String::Format(const char * format, ...) {
3007 va_list args;
3008 va_start(args, format);
3009
3010 char buffer[4096];
3011 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
3012
3013 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
3014 // 4996 (deprecated function) there.
3015#ifdef _MSC_VER // We are using MSVC.
3016# pragma warning(push) // Saves the current warning state.
3017# pragma warning(disable:4996) // Temporarily disables warning 4996.
3018
3019 const int size = vsnprintf(buffer, kBufferSize, format, args);
3020
3021# pragma warning(pop) // Restores the warning state.
3022#else // We are not using MSVC.
3023 const int size = vsnprintf(buffer, kBufferSize, format, args);
3024#endif // _MSC_VER
3025 va_end(args);
3026
3027 // vsnprintf()'s behavior is not portable. When the buffer is not
3028 // big enough, it returns a negative value in MSVC, and returns the
3029 // needed buffer size on Linux. When there is an output error, it
3030 // always returns a negative value. For simplicity, we lump the two
3031 // error cases together.
3032 if (size < 0 || size >= kBufferSize) {
3033 return String("<formatting error or buffer exceeded>");
3034 } else {
3035 return String(buffer, size);
3036 }
3037}
3038
3039// Converts the buffer in a stringstream to a String, converting NUL
3040// bytes to "\\0" along the way.
3041String StringStreamToString(::std::stringstream* ss) {
3042 const ::std::string& str = ss->str();
3043 const char* const start = str.c_str();
3044 const char* const end = start + str.length();
3045
3046 // We need to use a helper stringstream to do this transformation
3047 // because String doesn't support push_back().
3048 ::std::stringstream helper;
3049 for (const char* ch = start; ch != end; ++ch) {
3050 if (*ch == '\0') {
3051 helper << "\\0"; // Replaces NUL with "\\0";
3052 } else {
3053 helper.put(*ch);
3054 }
3055 }
3056
3057 return String(helper.str().c_str());
3058}
3059
3060// Appends the user-supplied message to the Google-Test-generated message.
3061String AppendUserMessage(const String& gtest_msg,
3062 const Message& user_msg) {
3063 // Appends the user message if it's non-empty.
3064 const String user_msg_string = user_msg.GetString();
3065 if (user_msg_string.empty()) {
3066 return gtest_msg;
3067 }
3068
3069 Message msg;
3070 msg << gtest_msg << "\n" << user_msg_string;
3071
3072 return msg.GetString();
3073}
3074
3075} // namespace internal
3076
3077// class TestResult
3078
3079// Creates an empty TestResult.
3080TestResult::TestResult()
3081 : death_test_count_(0),
3082 elapsed_time_(0) {
3083}
3084
3085// D'tor.
3086TestResult::~TestResult() {
3087}
3088
3089// Returns the i-th test part result among all the results. i can
3090// range from 0 to total_part_count() - 1. If i is not in that range,
3091// aborts the program.
3092const TestPartResult& TestResult::GetTestPartResult(int i) const {
3093 if (i < 0 || i >= total_part_count())
3094 internal::posix::Abort();
3095 return test_part_results_.at(i);
3096}
3097
3098// Returns the i-th test property. i can range from 0 to
3099// test_property_count() - 1. If i is not in that range, aborts the
3100// program.
3101const TestProperty& TestResult::GetTestProperty(int i) const {
3102 if (i < 0 || i >= test_property_count())
3103 internal::posix::Abort();
3104 return test_properties_.at(i);
3105}
3106
3107// Clears the test part results.
3108void TestResult::ClearTestPartResults() {
3109 test_part_results_.clear();
3110}
3111
3112// Adds a test part result to the list.
3113void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3114 test_part_results_.push_back(test_part_result);
3115}
3116
3117// Adds a test property to the list. If a property with the same key as the
3118// supplied property is already represented, the value of this test_property
3119// replaces the old value for that key.
3120void TestResult::RecordProperty(const TestProperty& test_property) {
3121 if (!ValidateTestProperty(test_property)) {
3122 return;
3123 }
3124 internal::MutexLock lock(&test_properites_mutex_);
3125 const std::vector<TestProperty>::iterator property_with_matching_key =
3126 std::find_if(test_properties_.begin(), test_properties_.end(),
3127 internal::TestPropertyKeyIs(test_property.key()));
3128 if (property_with_matching_key == test_properties_.end()) {
3129 test_properties_.push_back(test_property);
3130 return;
3131 }
3132 property_with_matching_key->SetValue(test_property.value());
3133}
3134
3135// Adds a failure if the key is a reserved attribute of Google Test
3136// testcase tags. Returns true if the property is valid.
3137bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
3138 internal::String key(test_property.key());
3139 if (key == "name" || key == "status" || key == "time" || key == "classname") {
3140 ADD_FAILURE()
3141 << "Reserved key used in RecordProperty(): "
3142 << key
3143 << " ('name', 'status', 'time', and 'classname' are reserved by "
3144 << GTEST_NAME_ << ")";
3145 return false;
3146 }
3147 return true;
3148}
3149
3150// Clears the object.
3151void TestResult::Clear() {
3152 test_part_results_.clear();
3153 test_properties_.clear();
3154 death_test_count_ = 0;
3155 elapsed_time_ = 0;
3156}
3157
3158// Returns true iff the test failed.
3159bool TestResult::Failed() const {
3160 for (int i = 0; i < total_part_count(); ++i) {
3161 if (GetTestPartResult(i).failed())
3162 return true;
3163 }
3164 return false;
3165}
3166
3167// Returns true iff the test part fatally failed.
3168static bool TestPartFatallyFailed(const TestPartResult& result) {
3169 return result.fatally_failed();
3170}
3171
3172// Returns true iff the test fatally failed.
3173bool TestResult::HasFatalFailure() const {
3174 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3175}
3176
3177// Returns true iff the test part non-fatally failed.
3178static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3179 return result.nonfatally_failed();
3180}
3181
3182// Returns true iff the test has a non-fatal failure.
3183bool TestResult::HasNonfatalFailure() const {
3184 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3185}
3186
3187// Gets the number of all test parts. This is the sum of the number
3188// of successful test parts and the number of failed test parts.
3189int TestResult::total_part_count() const {
3190 return static_cast<int>(test_part_results_.size());
3191}
3192
3193// Returns the number of the test properties.
3194int TestResult::test_property_count() const {
3195 return static_cast<int>(test_properties_.size());
3196}
3197
3198// class Test
3199
3200// Creates a Test object.
3201
3202// The c'tor saves the values of all Google Test flags.
3203Test::Test()
3204 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3205}
3206
3207// The d'tor restores the values of all Google Test flags.
3208Test::~Test() {
3209 delete gtest_flag_saver_;
3210}
3211
3212// Sets up the test fixture.
3213//
3214// A sub-class may override this.
3215void Test::SetUp() {
3216}
3217
3218// Tears down the test fixture.
3219//
3220// A sub-class may override this.
3221void Test::TearDown() {
3222}
3223
3224// Allows user supplied key value pairs to be recorded for later output.
3225void Test::RecordProperty(const char* key, const char* value) {
3226 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
3227}
3228
3229// Allows user supplied key value pairs to be recorded for later output.
3230void Test::RecordProperty(const char* key, int value) {
3231 Message value_message;
3232 value_message << value;
3233 RecordProperty(key, value_message.GetString().c_str());
3234}
3235
3236namespace internal {
3237
3238void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3239 const String& message) {
3240 // This function is a friend of UnitTest and as such has access to
3241 // AddTestPartResult.
3242 UnitTest::GetInstance()->AddTestPartResult(
3243 result_type,
3244 NULL, // No info about the source file where the exception occurred.
3245 -1, // We have no info on which line caused the exception.
3246 message,
3247 String()); // No stack trace, either.
3248}
3249
3250} // namespace internal
3251
3252// Google Test requires all tests in the same test case to use the same test
3253// fixture class. This function checks if the current test has the
3254// same fixture class as the first test in the current test case. If
3255// yes, it returns true; otherwise it generates a Google Test failure and
3256// returns false.
3257bool Test::HasSameFixtureClass() {
3258 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3259 const TestCase* const test_case = impl->current_test_case();
3260
3261 // Info about the first test in the current test case.
3262 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3263 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3264 const char* const first_test_name = first_test_info->name();
3265
3266 // Info about the current test.
3267 const TestInfo* const this_test_info = impl->current_test_info();
3268 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3269 const char* const this_test_name = this_test_info->name();
3270
3271 if (this_fixture_id != first_fixture_id) {
3272 // Is the first test defined using TEST?
3273 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3274 // Is this test defined using TEST?
3275 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3276
3277 if (first_is_TEST || this_is_TEST) {
3278 // The user mixed TEST and TEST_F in this test case - we'll tell
3279 // him/her how to fix it.
3280
3281 // Gets the name of the TEST and the name of the TEST_F. Note
3282 // that first_is_TEST and this_is_TEST cannot both be true, as
3283 // the fixture IDs are different for the two tests.
3284 const char* const TEST_name =
3285 first_is_TEST ? first_test_name : this_test_name;
3286 const char* const TEST_F_name =
3287 first_is_TEST ? this_test_name : first_test_name;
3288
3289 ADD_FAILURE()
3290 << "All tests in the same test case must use the same test fixture\n"
3291 << "class, so mixing TEST_F and TEST in the same test case is\n"
3292 << "illegal. In test case " << this_test_info->test_case_name()
3293 << ",\n"
3294 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3295 << "test " << TEST_name << " is defined using TEST. You probably\n"
3296 << "want to change the TEST to TEST_F or move it to another test\n"
3297 << "case.";
3298 } else {
3299 // The user defined two fixture classes with the same name in
3300 // two namespaces - we'll tell him/her how to fix it.
3301 ADD_FAILURE()
3302 << "All tests in the same test case must use the same test fixture\n"
3303 << "class. However, in test case "
3304 << this_test_info->test_case_name() << ",\n"
3305 << "you defined test " << first_test_name
3306 << " and test " << this_test_name << "\n"
3307 << "using two different test fixture classes. This can happen if\n"
3308 << "the two classes are from different namespaces or translation\n"
3309 << "units and have the same name. You should probably rename one\n"
3310 << "of the classes to put the tests into different test cases.";
3311 }
3312 return false;
3313 }
3314
3315 return true;
3316}
3317
3318#if GTEST_HAS_SEH
3319
3320// Adds an "exception thrown" fatal failure to the current test. This
3321// function returns its result via an output parameter pointer because VC++
3322// prohibits creation of objects with destructors on stack in functions
3323// using __try (see error C2712).
3324static internal::String* FormatSehExceptionMessage(DWORD exception_code,
3325 const char* location) {
3326 Message message;
3327 message << "SEH exception with code 0x" << std::setbase(16) <<
3328 exception_code << std::setbase(10) << " thrown in " << location << ".";
3329
3330 return new internal::String(message.GetString());
3331}
3332
3333#endif // GTEST_HAS_SEH
3334
3335#if GTEST_HAS_EXCEPTIONS
3336
3337// Adds an "exception thrown" fatal failure to the current test.
3338static internal::String FormatCxxExceptionMessage(const char* description,
3339 const char* location) {
3340 Message message;
3341 if (description != NULL) {
3342 message << "C++ exception with description \"" << description << "\"";
3343 } else {
3344 message << "Unknown C++ exception";
3345 }
3346 message << " thrown in " << location << ".";
3347
3348 return message.GetString();
3349}
3350
3351static internal::String PrintTestPartResultToString(
3352 const TestPartResult& test_part_result);
3353
3354// A failed Google Test assertion will throw an exception of this type when
3355// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
3356// derive it from std::runtime_error, which is for errors presumably
3357// detectable only at run time. Since std::runtime_error inherits from
3358// std::exception, many testing frameworks know how to extract and print the
3359// message inside it.
3360class GoogleTestFailureException : public ::std::runtime_error {
3361 public:
3362 explicit GoogleTestFailureException(const TestPartResult& failure)
3363 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3364};
3365#endif // GTEST_HAS_EXCEPTIONS
3366
3367namespace internal {
3368// We put these helper functions in the internal namespace as IBM's xlC
3369// compiler rejects the code if they were declared static.
3370
3371// Runs the given method and handles SEH exceptions it throws, when
3372// SEH is supported; returns the 0-value for type Result in case of an
3373// SEH exception. (Microsoft compilers cannot handle SEH and C++
3374// exceptions in the same function. Therefore, we provide a separate
3375// wrapper function for handling SEH exceptions.)
3376template <class T, typename Result>
3377Result HandleSehExceptionsInMethodIfSupported(
3378 T* object, Result (T::*method)(), const char* location) {
3379#if GTEST_HAS_SEH
3380 __try {
3381 return (object->*method)();
3382 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3383 GetExceptionCode())) {
3384 // We create the exception message on the heap because VC++ prohibits
3385 // creation of objects with destructors on stack in functions using __try
3386 // (see error C2712).
3387 internal::String* exception_message = FormatSehExceptionMessage(
3388 GetExceptionCode(), location);
3389 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3390 *exception_message);
3391 delete exception_message;
3392 return static_cast<Result>(0);
3393 }
3394#else
3395 (void)location;
3396 return (object->*method)();
3397#endif // GTEST_HAS_SEH
3398}
3399
3400// Runs the given method and catches and reports C++ and/or SEH-style
3401// exceptions, if they are supported; returns the 0-value for type
3402// Result in case of an SEH exception.
3403template <class T, typename Result>
3404Result HandleExceptionsInMethodIfSupported(
3405 T* object, Result (T::*method)(), const char* location) {
3406 // NOTE: The user code can affect the way in which Google Test handles
3407 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3408 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3409 // after the exception is caught and either report or re-throw the
3410 // exception based on the flag's value:
3411 //
3412 // try {
3413 // // Perform the test method.
3414 // } catch (...) {
3415 // if (GTEST_FLAG(catch_exceptions))
3416 // // Report the exception as failure.
3417 // else
3418 // throw; // Re-throws the original exception.
3419 // }
3420 //
3421 // However, the purpose of this flag is to allow the program to drop into
3422 // the debugger when the exception is thrown. On most platforms, once the
3423 // control enters the catch block, the exception origin information is
3424 // lost and the debugger will stop the program at the point of the
3425 // re-throw in this function -- instead of at the point of the original
3426 // throw statement in the code under test. For this reason, we perform
3427 // the check early, sacrificing the ability to affect Google Test's
3428 // exception handling in the method where the exception is thrown.
3429 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3430#if GTEST_HAS_EXCEPTIONS
3431 try {
3432 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3433 } catch (const GoogleTestFailureException&) { // NOLINT
3434 // This exception doesn't originate in code under test. It makes no
3435 // sense to report it as a test failure.
3436 throw;
3437 } catch (const std::exception& e) { // NOLINT
3438 internal::ReportFailureInUnknownLocation(
3439 TestPartResult::kFatalFailure,
3440 FormatCxxExceptionMessage(e.what(), location));
3441 } catch (...) { // NOLINT
3442 internal::ReportFailureInUnknownLocation(
3443 TestPartResult::kFatalFailure,
3444 FormatCxxExceptionMessage(NULL, location));
3445 }
3446 return static_cast<Result>(0);
3447#else
3448 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3449#endif // GTEST_HAS_EXCEPTIONS
3450 } else {
3451 return (object->*method)();
3452 }
3453}
3454
3455} // namespace internal
3456
3457// Runs the test and updates the test result.
3458void Test::Run() {
3459 if (!HasSameFixtureClass()) return;
3460
3461 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3462 impl->os_stack_trace_getter()->UponLeavingGTest();
3463 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3464 // We will run the test only if SetUp() was successful.
3465 if (!HasFatalFailure()) {
3466 impl->os_stack_trace_getter()->UponLeavingGTest();
3467 internal::HandleExceptionsInMethodIfSupported(
3468 this, &Test::TestBody, "the test body");
3469 }
3470
3471 // However, we want to clean up as much as possible. Hence we will
3472 // always call TearDown(), even if SetUp() or the test body has
3473 // failed.
3474 impl->os_stack_trace_getter()->UponLeavingGTest();
3475 internal::HandleExceptionsInMethodIfSupported(
3476 this, &Test::TearDown, "TearDown()");
3477}
3478
3479// Returns true iff the current test has a fatal failure.
3480bool Test::HasFatalFailure() {
3481 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3482}
3483
3484// Returns true iff the current test has a non-fatal failure.
3485bool Test::HasNonfatalFailure() {
3486 return internal::GetUnitTestImpl()->current_test_result()->
3487 HasNonfatalFailure();
3488}
3489
3490// class TestInfo
3491
3492// Constructs a TestInfo object. It assumes ownership of the test factory
3493// object.
3494// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
3495// to signify they cannot be NULLs.
3496TestInfo::TestInfo(const char* a_test_case_name,
3497 const char* a_name,
3498 const char* a_type_param,
3499 const char* a_value_param,
3500 internal::TypeId fixture_class_id,
3501 internal::TestFactoryBase* factory)
3502 : test_case_name_(a_test_case_name),
3503 name_(a_name),
3504 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3505 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3506 fixture_class_id_(fixture_class_id),
3507 should_run_(false),
3508 is_disabled_(false),
3509 matches_filter_(false),
3510 factory_(factory),
3511 result_() {}
3512
3513// Destructs a TestInfo object.
3514TestInfo::~TestInfo() { delete factory_; }
3515
3516namespace internal {
3517
3518// Creates a new TestInfo object and registers it with Google Test;
3519// returns the created object.
3520//
3521// Arguments:
3522//
3523// test_case_name: name of the test case
3524// name: name of the test
3525// type_param: the name of the test's type parameter, or NULL if
3526// this is not a typed or a type-parameterized test.
3527// value_param: text representation of the test's value parameter,
3528// or NULL if this is not a value-parameterized test.
3529// fixture_class_id: ID of the test fixture class
3530// set_up_tc: pointer to the function that sets up the test case
3531// tear_down_tc: pointer to the function that tears down the test case
3532// factory: pointer to the factory that creates a test object.
3533// The newly created TestInfo instance will assume
3534// ownership of the factory object.
3535TestInfo* MakeAndRegisterTestInfo(
3536 const char* test_case_name, const char* name,
3537 const char* type_param,
3538 const char* value_param,
3539 TypeId fixture_class_id,
3540 SetUpTestCaseFunc set_up_tc,
3541 TearDownTestCaseFunc tear_down_tc,
3542 TestFactoryBase* factory) {
3543 TestInfo* const test_info =
3544 new TestInfo(test_case_name, name, type_param, value_param,
3545 fixture_class_id, factory);
3546 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3547 return test_info;
3548}
3549
3550#if GTEST_HAS_PARAM_TEST
3551void ReportInvalidTestCaseType(const char* test_case_name,
3552 const char* file, int line) {
3553 Message errors;
3554 errors
3555 << "Attempted redefinition of test case " << test_case_name << ".\n"
3556 << "All tests in the same test case must use the same test fixture\n"
3557 << "class. However, in test case " << test_case_name << ", you tried\n"
3558 << "to define a test using a fixture class different from the one\n"
3559 << "used earlier. This can happen if the two fixture classes are\n"
3560 << "from different namespaces and have the same name. You should\n"
3561 << "probably rename one of the classes to put the tests into different\n"
3562 << "test cases.";
3563
3564 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3565 errors.GetString().c_str());
3566}
3567#endif // GTEST_HAS_PARAM_TEST
3568
3569} // namespace internal
3570
3571namespace {
3572
3573// A predicate that checks the test name of a TestInfo against a known
3574// value.
3575//
3576// This is used for implementation of the TestCase class only. We put
3577// it in the anonymous namespace to prevent polluting the outer
3578// namespace.
3579//
3580// TestNameIs is copyable.
3581class TestNameIs {
3582 public:
3583 // Constructor.
3584 //
3585 // TestNameIs has NO default constructor.
3586 explicit TestNameIs(const char* name)
3587 : name_(name) {}
3588
3589 // Returns true iff the test name of test_info matches name_.
3590 bool operator()(const TestInfo * test_info) const {
3591 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
3592 }
3593
3594 private:
3595 internal::String name_;
3596};
3597
3598} // namespace
3599
3600namespace internal {
3601
3602// This method expands all parameterized tests registered with macros TEST_P
3603// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3604// This will be done just once during the program runtime.
3605void UnitTestImpl::RegisterParameterizedTests() {
3606#if GTEST_HAS_PARAM_TEST
3607 if (!parameterized_tests_registered_) {
3608 parameterized_test_registry_.RegisterTests();
3609 parameterized_tests_registered_ = true;
3610 }
3611#endif
3612}
3613
3614} // namespace internal
3615
3616// Creates the test object, runs it, records its result, and then
3617// deletes it.
3618void TestInfo::Run() {
3619 if (!should_run_) return;
3620
3621 // Tells UnitTest where to store test result.
3622 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3623 impl->set_current_test_info(this);
3624
3625 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3626
3627 // Notifies the unit test event listeners that a test is about to start.
3628 repeater->OnTestStart(*this);
3629
3630 const TimeInMillis start = internal::GetTimeInMillis();
3631
3632 impl->os_stack_trace_getter()->UponLeavingGTest();
3633
3634 // Creates the test object.
3635 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3636 factory_, &internal::TestFactoryBase::CreateTest,
3637 "the test fixture's constructor");
3638
3639 // Runs the test only if the test object was created and its
3640 // constructor didn't generate a fatal failure.
3641 if ((test != NULL) && !Test::HasFatalFailure()) {
3642 // This doesn't throw as all user code that can throw are wrapped into
3643 // exception handling code.
3644 test->Run();
3645 }
3646
3647 // Deletes the test object.
3648 impl->os_stack_trace_getter()->UponLeavingGTest();
3649 internal::HandleExceptionsInMethodIfSupported(
3650 test, &Test::DeleteSelf_, "the test fixture's destructor");
3651
3652 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3653
3654 // Notifies the unit test event listener that a test has just finished.
3655 repeater->OnTestEnd(*this);
3656
3657 // Tells UnitTest to stop associating assertion results to this
3658 // test.
3659 impl->set_current_test_info(NULL);
3660}
3661
3662// class TestCase
3663
3664// Gets the number of successful tests in this test case.
3665int TestCase::successful_test_count() const {
3666 return CountIf(test_info_list_, TestPassed);
3667}
3668
3669// Gets the number of failed tests in this test case.
3670int TestCase::failed_test_count() const {
3671 return CountIf(test_info_list_, TestFailed);
3672}
3673
3674int TestCase::disabled_test_count() const {
3675 return CountIf(test_info_list_, TestDisabled);
3676}
3677
3678// Get the number of tests in this test case that should run.
3679int TestCase::test_to_run_count() const {
3680 return CountIf(test_info_list_, ShouldRunTest);
3681}
3682
3683// Gets the number of all tests.
3684int TestCase::total_test_count() const {
3685 return static_cast<int>(test_info_list_.size());
3686}
3687
3688// Creates a TestCase with the given name.
3689//
3690// Arguments:
3691//
3692// name: name of the test case
3693// a_type_param: the name of the test case's type parameter, or NULL if
3694// this is not a typed or a type-parameterized test case.
3695// set_up_tc: pointer to the function that sets up the test case
3696// tear_down_tc: pointer to the function that tears down the test case
3697TestCase::TestCase(const char* a_name, const char* a_type_param,
3698 Test::SetUpTestCaseFunc set_up_tc,
3699 Test::TearDownTestCaseFunc tear_down_tc)
3700 : name_(a_name),
3701 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3702 set_up_tc_(set_up_tc),
3703 tear_down_tc_(tear_down_tc),
3704 should_run_(false),
3705 elapsed_time_(0) {
3706}
3707
3708// Destructor of TestCase.
3709TestCase::~TestCase() {
3710 // Deletes every Test in the collection.
3711 ForEach(test_info_list_, internal::Delete<TestInfo>);
3712}
3713
3714// Returns the i-th test among all the tests. i can range from 0 to
3715// total_test_count() - 1. If i is not in that range, returns NULL.
3716const TestInfo* TestCase::GetTestInfo(int i) const {
3717 const int index = GetElementOr(test_indices_, i, -1);
3718 return index < 0 ? NULL : test_info_list_[index];
3719}
3720
3721// Returns the i-th test among all the tests. i can range from 0 to
3722// total_test_count() - 1. If i is not in that range, returns NULL.
3723TestInfo* TestCase::GetMutableTestInfo(int i) {
3724 const int index = GetElementOr(test_indices_, i, -1);
3725 return index < 0 ? NULL : test_info_list_[index];
3726}
3727
3728// Adds a test to this test case. Will delete the test upon
3729// destruction of the TestCase object.
3730void TestCase::AddTestInfo(TestInfo * test_info) {
3731 test_info_list_.push_back(test_info);
3732 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3733}
3734
3735// Runs every test in this TestCase.
3736void TestCase::Run() {
3737 if (!should_run_) return;
3738
3739 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3740 impl->set_current_test_case(this);
3741
3742 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3743
3744 repeater->OnTestCaseStart(*this);
3745 impl->os_stack_trace_getter()->UponLeavingGTest();
3746 internal::HandleExceptionsInMethodIfSupported(
3747 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3748
3749 const internal::TimeInMillis start = internal::GetTimeInMillis();
3750 for (int i = 0; i < total_test_count(); i++) {
3751 GetMutableTestInfo(i)->Run();
3752 }
3753 elapsed_time_ = internal::GetTimeInMillis() - start;
3754
3755 impl->os_stack_trace_getter()->UponLeavingGTest();
3756 internal::HandleExceptionsInMethodIfSupported(
3757 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3758
3759 repeater->OnTestCaseEnd(*this);
3760 impl->set_current_test_case(NULL);
3761}
3762
3763// Clears the results of all tests in this test case.
3764void TestCase::ClearResult() {
3765 ForEach(test_info_list_, TestInfo::ClearTestResult);
3766}
3767
3768// Shuffles the tests in this test case.
3769void TestCase::ShuffleTests(internal::Random* random) {
3770 Shuffle(random, &test_indices_);
3771}
3772
3773// Restores the test order to before the first shuffle.
3774void TestCase::UnshuffleTests() {
3775 for (size_t i = 0; i < test_indices_.size(); i++) {
3776 test_indices_[i] = static_cast<int>(i);
3777 }
3778}
3779
3780// Formats a countable noun. Depending on its quantity, either the
3781// singular form or the plural form is used. e.g.
3782//
3783// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3784// FormatCountableNoun(5, "book", "books") returns "5 books".
3785static internal::String FormatCountableNoun(int count,
3786 const char * singular_form,
3787 const char * plural_form) {
3788 return internal::String::Format("%d %s", count,
3789 count == 1 ? singular_form : plural_form);
3790}
3791
3792// Formats the count of tests.
3793static internal::String FormatTestCount(int test_count) {
3794 return FormatCountableNoun(test_count, "test", "tests");
3795}
3796
3797// Formats the count of test cases.
3798static internal::String FormatTestCaseCount(int test_case_count) {
3799 return FormatCountableNoun(test_case_count, "test case", "test cases");
3800}
3801
3802// Converts a TestPartResult::Type enum to human-friendly string
3803// representation. Both kNonFatalFailure and kFatalFailure are translated
3804// to "Failure", as the user usually doesn't care about the difference
3805// between the two when viewing the test result.
3806static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3807 switch (type) {
3808 case TestPartResult::kSuccess:
3809 return "Success";
3810
3811 case TestPartResult::kNonFatalFailure:
3812 case TestPartResult::kFatalFailure:
3813#ifdef _MSC_VER
3814 return "error: ";
3815#else
3816 return "Failure\n";
3817#endif
3818 default:
3819 return "Unknown result type";
3820 }
3821}
3822
3823// Prints a TestPartResult to a String.
3824static internal::String PrintTestPartResultToString(
3825 const TestPartResult& test_part_result) {
3826 return (Message()
3827 << internal::FormatFileLocation(test_part_result.file_name(),
3828 test_part_result.line_number())
3829 << " " << TestPartResultTypeToString(test_part_result.type())
3830 << test_part_result.message()).GetString();
3831}
3832
3833// Prints a TestPartResult.
3834static void PrintTestPartResult(const TestPartResult& test_part_result) {
3835 const internal::String& result =
3836 PrintTestPartResultToString(test_part_result);
3837 printf("%s\n", result.c_str());
3838 fflush(stdout);
3839 // If the test program runs in Visual Studio or a debugger, the
3840 // following statements add the test part result message to the Output
3841 // window such that the user can double-click on it to jump to the
3842 // corresponding source code location; otherwise they do nothing.
3843#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3844 // We don't call OutputDebugString*() on Windows Mobile, as printing
3845 // to stdout is done by OutputDebugString() there already - we don't
3846 // want the same message printed twice.
3847 ::OutputDebugStringA(result.c_str());
3848 ::OutputDebugStringA("\n");
3849#endif
3850}
3851
3852// class PrettyUnitTestResultPrinter
3853
3854namespace internal {
3855
3856enum GTestColor {
3857 COLOR_DEFAULT,
3858 COLOR_RED,
3859 COLOR_GREEN,
3860 COLOR_YELLOW
3861};
3862
3863#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3864
3865// Returns the character attribute for the given color.
3866WORD GetColorAttribute(GTestColor color) {
3867 switch (color) {
3868 case COLOR_RED: return FOREGROUND_RED;
3869 case COLOR_GREEN: return FOREGROUND_GREEN;
3870 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
3871 default: return 0;
3872 }
3873}
3874
3875#else
3876
3877// Returns the ANSI color code for the given color. COLOR_DEFAULT is
3878// an invalid input.
3879const char* GetAnsiColorCode(GTestColor color) {
3880 switch (color) {
3881 case COLOR_RED: return "1";
3882 case COLOR_GREEN: return "2";
3883 case COLOR_YELLOW: return "3";
3884 default: return NULL;
3885 };
3886}
3887
3888#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3889
3890// Returns true iff Google Test should use colors in the output.
3891bool ShouldUseColor(bool stdout_is_tty) {
3892 const char* const gtest_color = GTEST_FLAG(color).c_str();
3893
3894 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3895#if GTEST_OS_WINDOWS
3896 // On Windows the TERM variable is usually not set, but the
3897 // console there does support colors.
3898 return stdout_is_tty;
3899#else
3900 // On non-Windows platforms, we rely on the TERM variable.
3901 const char* const term = posix::GetEnv("TERM");
3902 const bool term_supports_color =
3903 String::CStringEquals(term, "xterm") ||
3904 String::CStringEquals(term, "xterm-color") ||
3905 String::CStringEquals(term, "xterm-256color") ||
3906 String::CStringEquals(term, "screen") ||
3907 String::CStringEquals(term, "linux") ||
3908 String::CStringEquals(term, "cygwin");
3909 return stdout_is_tty && term_supports_color;
3910#endif // GTEST_OS_WINDOWS
3911 }
3912
3913 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3914 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3915 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3916 String::CStringEquals(gtest_color, "1");
3917 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3918 // value is neither one of these nor "auto", we treat it as "no" to
3919 // be conservative.
3920}
3921
3922// Helpers for printing colored strings to stdout. Note that on Windows, we
3923// cannot simply emit special characters and have the terminal change colors.
3924// This routine must actually emit the characters rather than return a string
3925// that would be colored when printed, as can be done on Linux.
3926void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3927 va_list args;
3928 va_start(args, fmt);
3929
3930#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3931 const bool use_color = false;
3932#else
3933 static const bool in_color_mode =
3934 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3935 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3936#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3937 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3938
3939 if (!use_color) {
3940 vprintf(fmt, args);
3941 va_end(args);
3942 return;
3943 }
3944
3945#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3946 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3947
3948 // Gets the current text color.
3949 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3950 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3951 const WORD old_color_attrs = buffer_info.wAttributes;
3952
3953 // We need to flush the stream buffers into the console before each
3954 // SetConsoleTextAttribute call lest it affect the text that is already
3955 // printed but has not yet reached the console.
3956 fflush(stdout);
3957 SetConsoleTextAttribute(stdout_handle,
3958 GetColorAttribute(color) | FOREGROUND_INTENSITY);
3959 vprintf(fmt, args);
3960
3961 fflush(stdout);
3962 // Restores the text color.
3963 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3964#else
3965 printf("\033[0;3%sm", GetAnsiColorCode(color));
3966 vprintf(fmt, args);
3967 printf("\033[m"); // Resets the terminal to default.
3968#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3969 va_end(args);
3970}
3971
3972void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3973 const char* const type_param = test_info.type_param();
3974 const char* const value_param = test_info.value_param();
3975
3976 if (type_param != NULL || value_param != NULL) {
3977 printf(", where ");
3978 if (type_param != NULL) {
3979 printf("TypeParam = %s", type_param);
3980 if (value_param != NULL)
3981 printf(" and ");
3982 }
3983 if (value_param != NULL) {
3984 printf("GetParam() = %s", value_param);
3985 }
3986 }
3987}
3988
3989// This class implements the TestEventListener interface.
3990//
3991// Class PrettyUnitTestResultPrinter is copyable.
3992class PrettyUnitTestResultPrinter : public TestEventListener {
3993 public:
3994 PrettyUnitTestResultPrinter() {}
3995 static void PrintTestName(const char * test_case, const char * test) {
3996 printf("%s.%s", test_case, test);
3997 }
3998
3999 // The following methods override what's in the TestEventListener class.
4000 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4001 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4002 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4003 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4004 virtual void OnTestCaseStart(const TestCase& test_case);
4005 virtual void OnTestStart(const TestInfo& test_info);
4006 virtual void OnTestPartResult(const TestPartResult& result);
4007 virtual void OnTestEnd(const TestInfo& test_info);
4008 virtual void OnTestCaseEnd(const TestCase& test_case);
4009 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4010 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4011 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4012 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4013
4014 private:
4015 static void PrintFailedTests(const UnitTest& unit_test);
4016
4017 internal::String test_case_name_;
4018};
4019
4020 // Fired before each iteration of tests starts.
4021void PrettyUnitTestResultPrinter::OnTestIterationStart(
4022 const UnitTest& unit_test, int iteration) {
4023 if (GTEST_FLAG(repeat) != 1)
4024 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4025
4026 const char* const filter = GTEST_FLAG(filter).c_str();
4027
4028 // Prints the filter if it's not *. This reminds the user that some
4029 // tests may be skipped.
4030 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
4031 ColoredPrintf(COLOR_YELLOW,
4032 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4033 }
4034
4035 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4036 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4037 ColoredPrintf(COLOR_YELLOW,
4038 "Note: This is test shard %d of %s.\n",
4039 static_cast<int>(shard_index) + 1,
4040 internal::posix::GetEnv(kTestTotalShards));
4041 }
4042
4043 if (GTEST_FLAG(shuffle)) {
4044 ColoredPrintf(COLOR_YELLOW,
4045 "Note: Randomizing tests' orders with a seed of %d .\n",
4046 unit_test.random_seed());
4047 }
4048
4049 ColoredPrintf(COLOR_GREEN, "[==========] ");
4050 printf("Running %s from %s.\n",
4051 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4052 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4053 fflush(stdout);
4054}
4055
4056void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4057 const UnitTest& /*unit_test*/) {
4058 ColoredPrintf(COLOR_GREEN, "[----------] ");
4059 printf("Global test environment set-up.\n");
4060 fflush(stdout);
4061}
4062
4063void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4064 test_case_name_ = test_case.name();
4065 const internal::String counts =
4066 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4067 ColoredPrintf(COLOR_GREEN, "[----------] ");
4068 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
4069 if (test_case.type_param() == NULL) {
4070 printf("\n");
4071 } else {
4072 printf(", where TypeParam = %s\n", test_case.type_param());
4073 }
4074 fflush(stdout);
4075}
4076
4077void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4078 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4079 PrintTestName(test_case_name_.c_str(), test_info.name());
4080 printf("\n");
4081 fflush(stdout);
4082}
4083
4084// Called after an assertion failure.
4085void PrettyUnitTestResultPrinter::OnTestPartResult(
4086 const TestPartResult& result) {
4087 // If the test part succeeded, we don't need to do anything.
4088 if (result.type() == TestPartResult::kSuccess)
4089 return;
4090
4091 // Print failure message from the assertion (e.g. expected this and got that).
4092 PrintTestPartResult(result);
4093 fflush(stdout);
4094}
4095
4096void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4097 if (test_info.result()->Passed()) {
4098 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4099 } else {
4100 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4101 }
4102 PrintTestName(test_case_name_.c_str(), test_info.name());
4103 if (test_info.result()->Failed())
4104 PrintFullTestCommentIfPresent(test_info);
4105
4106 if (GTEST_FLAG(print_time)) {
4107 printf(" (%s ms)\n", internal::StreamableToString(
4108 test_info.result()->elapsed_time()).c_str());
4109 } else {
4110 printf("\n");
4111 }
4112 fflush(stdout);
4113}
4114
4115void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4116 if (!GTEST_FLAG(print_time)) return;
4117
4118 test_case_name_ = test_case.name();
4119 const internal::String counts =
4120 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4121 ColoredPrintf(COLOR_GREEN, "[----------] ");
4122 printf("%s from %s (%s ms total)\n\n",
4123 counts.c_str(), test_case_name_.c_str(),
4124 internal::StreamableToString(test_case.elapsed_time()).c_str());
4125 fflush(stdout);
4126}
4127
4128void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4129 const UnitTest& /*unit_test*/) {
4130 ColoredPrintf(COLOR_GREEN, "[----------] ");
4131 printf("Global test environment tear-down\n");
4132 fflush(stdout);
4133}
4134
4135// Internal helper for printing the list of failed tests.
4136void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4137 const int failed_test_count = unit_test.failed_test_count();
4138 if (failed_test_count == 0) {
4139 return;
4140 }
4141
4142 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4143 const TestCase& test_case = *unit_test.GetTestCase(i);
4144 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4145 continue;
4146 }
4147 for (int j = 0; j < test_case.total_test_count(); ++j) {
4148 const TestInfo& test_info = *test_case.GetTestInfo(j);
4149 if (!test_info.should_run() || test_info.result()->Passed()) {
4150 continue;
4151 }
4152 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4153 printf("%s.%s", test_case.name(), test_info.name());
4154 PrintFullTestCommentIfPresent(test_info);
4155 printf("\n");
4156 }
4157 }
4158}
4159
4160void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4161 int /*iteration*/) {
4162 ColoredPrintf(COLOR_GREEN, "[==========] ");
4163 printf("%s from %s ran.",
4164 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4165 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4166 if (GTEST_FLAG(print_time)) {
4167 printf(" (%s ms total)",
4168 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4169 }
4170 printf("\n");
4171 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4172 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4173
4174 int num_failures = unit_test.failed_test_count();
4175 if (!unit_test.Passed()) {
4176 const int failed_test_count = unit_test.failed_test_count();
4177 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4178 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4179 PrintFailedTests(unit_test);
4180 printf("\n%2d FAILED %s\n", num_failures,
4181 num_failures == 1 ? "TEST" : "TESTS");
4182 }
4183
4184 int num_disabled = unit_test.disabled_test_count();
4185 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4186 if (!num_failures) {
4187 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4188 }
4189 ColoredPrintf(COLOR_YELLOW,
4190 " YOU HAVE %d DISABLED %s\n\n",
4191 num_disabled,
4192 num_disabled == 1 ? "TEST" : "TESTS");
4193 }
4194 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4195 fflush(stdout);
4196}
4197
4198// End PrettyUnitTestResultPrinter
4199
4200// class TestEventRepeater
4201//
4202// This class forwards events to other event listeners.
4203class TestEventRepeater : public TestEventListener {
4204 public:
4205 TestEventRepeater() : forwarding_enabled_(true) {}
4206 virtual ~TestEventRepeater();
4207 void Append(TestEventListener *listener);
4208 TestEventListener* Release(TestEventListener* listener);
4209
4210 // Controls whether events will be forwarded to listeners_. Set to false
4211 // in death test child processes.
4212 bool forwarding_enabled() const { return forwarding_enabled_; }
4213 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4214
4215 virtual void OnTestProgramStart(const UnitTest& unit_test);
4216 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4217 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4218 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4219 virtual void OnTestCaseStart(const TestCase& test_case);
4220 virtual void OnTestStart(const TestInfo& test_info);
4221 virtual void OnTestPartResult(const TestPartResult& result);
4222 virtual void OnTestEnd(const TestInfo& test_info);
4223 virtual void OnTestCaseEnd(const TestCase& test_case);
4224 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4225 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4226 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4227 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4228
4229 private:
4230 // Controls whether events will be forwarded to listeners_. Set to false
4231 // in death test child processes.
4232 bool forwarding_enabled_;
4233 // The list of listeners that receive events.
4234 std::vector<TestEventListener*> listeners_;
4235
4236 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4237};
4238
4239TestEventRepeater::~TestEventRepeater() {
4240 ForEach(listeners_, Delete<TestEventListener>);
4241}
4242
4243void TestEventRepeater::Append(TestEventListener *listener) {
4244 listeners_.push_back(listener);
4245}
4246
4247// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4248TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4249 for (size_t i = 0; i < listeners_.size(); ++i) {
4250 if (listeners_[i] == listener) {
4251 listeners_.erase(listeners_.begin() + i);
4252 return listener;
4253 }
4254 }
4255
4256 return NULL;
4257}
4258
4259// Since most methods are very similar, use macros to reduce boilerplate.
4260// This defines a member that forwards the call to all listeners.
4261#define GTEST_REPEATER_METHOD_(Name, Type) \
4262void TestEventRepeater::Name(const Type& parameter) { \
4263 if (forwarding_enabled_) { \
4264 for (size_t i = 0; i < listeners_.size(); i++) { \
4265 listeners_[i]->Name(parameter); \
4266 } \
4267 } \
4268}
4269// This defines a member that forwards the call to all listeners in reverse
4270// order.
4271#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4272void TestEventRepeater::Name(const Type& parameter) { \
4273 if (forwarding_enabled_) { \
4274 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4275 listeners_[i]->Name(parameter); \
4276 } \
4277 } \
4278}
4279
4280GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4281GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4282GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4283GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4284GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4285GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4286GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4287GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4288GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4289GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4290GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4291
4292#undef GTEST_REPEATER_METHOD_
4293#undef GTEST_REVERSE_REPEATER_METHOD_
4294
4295void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4296 int iteration) {
4297 if (forwarding_enabled_) {
4298 for (size_t i = 0; i < listeners_.size(); i++) {
4299 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4300 }
4301 }
4302}
4303
4304void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4305 int iteration) {
4306 if (forwarding_enabled_) {
4307 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4308 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4309 }
4310 }
4311}
4312
4313// End TestEventRepeater
4314
4315// This class generates an XML output file.
4316class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4317 public:
4318 explicit XmlUnitTestResultPrinter(const char* output_file);
4319
4320 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4321
4322 private:
4323 // Is c a whitespace character that is normalized to a space character
4324 // when it appears in an XML attribute value?
4325 static bool IsNormalizableWhitespace(char c) {
4326 return c == 0x9 || c == 0xA || c == 0xD;
4327 }
4328
4329 // May c appear in a well-formed XML document?
4330 static bool IsValidXmlCharacter(char c) {
4331 return IsNormalizableWhitespace(c) || c >= 0x20;
4332 }
4333
4334 // Returns an XML-escaped copy of the input string str. If
4335 // is_attribute is true, the text is meant to appear as an attribute
4336 // value, and normalizable whitespace is preserved by replacing it
4337 // with character references.
4338 static String EscapeXml(const char* str, bool is_attribute);
4339
4340 // Returns the given string with all characters invalid in XML removed.
4341 static string RemoveInvalidXmlCharacters(const string& str);
4342
4343 // Convenience wrapper around EscapeXml when str is an attribute value.
4344 static String EscapeXmlAttribute(const char* str) {
4345 return EscapeXml(str, true);
4346 }
4347
4348 // Convenience wrapper around EscapeXml when str is not an attribute value.
4349 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
4350
4351 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4352 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4353
4354 // Streams an XML representation of a TestInfo object.
4355 static void OutputXmlTestInfo(::std::ostream* stream,
4356 const char* test_case_name,
4357 const TestInfo& test_info);
4358
4359 // Prints an XML representation of a TestCase object
4360 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
4361
4362 // Prints an XML summary of unit_test to output stream out.
4363 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
4364
4365 // Produces a string representing the test properties in a result as space
4366 // delimited XML attributes based on the property key="value" pairs.
4367 // When the String is not empty, it includes a space at the beginning,
4368 // to delimit this attribute from prior attributes.
4369 static String TestPropertiesAsXmlAttributes(const TestResult& result);
4370
4371 // The output file.
4372 const String output_file_;
4373
4374 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4375};
4376
4377// Creates a new XmlUnitTestResultPrinter.
4378XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4379 : output_file_(output_file) {
4380 if (output_file_.c_str() == NULL || output_file_.empty()) {
4381 fprintf(stderr, "XML output file may not be null\n");
4382 fflush(stderr);
4383 exit(EXIT_FAILURE);
4384 }
4385}
4386
4387// Called after the unit test ends.
4388void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4389 int /*iteration*/) {
4390 FILE* xmlout = NULL;
4391 FilePath output_file(output_file_);
4392 FilePath output_dir(output_file.RemoveFileName());
4393
4394 if (output_dir.CreateDirectoriesRecursively()) {
4395 xmlout = posix::FOpen(output_file_.c_str(), "w");
4396 }
4397 if (xmlout == NULL) {
4398 // TODO(wan): report the reason of the failure.
4399 //
4400 // We don't do it for now as:
4401 //
4402 // 1. There is no urgent need for it.
4403 // 2. It's a bit involved to make the errno variable thread-safe on
4404 // all three operating systems (Linux, Windows, and Mac OS).
4405 // 3. To interpret the meaning of errno in a thread-safe way,
4406 // we need the strerror_r() function, which is not available on
4407 // Windows.
4408 fprintf(stderr,
4409 "Unable to open file \"%s\"\n",
4410 output_file_.c_str());
4411 fflush(stderr);
4412 exit(EXIT_FAILURE);
4413 }
4414 PrintXmlUnitTest(xmlout, unit_test);
4415 fclose(xmlout);
4416}
4417
4418// Returns an XML-escaped copy of the input string str. If is_attribute
4419// is true, the text is meant to appear as an attribute value, and
4420// normalizable whitespace is preserved by replacing it with character
4421// references.
4422//
4423// Invalid XML characters in str, if any, are stripped from the output.
4424// It is expected that most, if not all, of the text processed by this
4425// module will consist of ordinary English text.
4426// If this module is ever modified to produce version 1.1 XML output,
4427// most invalid characters can be retained using character references.
4428// TODO(wan): It might be nice to have a minimally invasive, human-readable
4429// escaping scheme for invalid characters, rather than dropping them.
4430String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
4431 Message m;
4432
4433 if (str != NULL) {
4434 for (const char* src = str; *src; ++src) {
4435 switch (*src) {
4436 case '<':
4437 m << "&lt;";
4438 break;
4439 case '>':
4440 m << "&gt;";
4441 break;
4442 case '&':
4443 m << "&amp;";
4444 break;
4445 case '\'':
4446 if (is_attribute)
4447 m << "&apos;";
4448 else
4449 m << '\'';
4450 break;
4451 case '"':
4452 if (is_attribute)
4453 m << "&quot;";
4454 else
4455 m << '"';
4456 break;
4457 default:
4458 if (IsValidXmlCharacter(*src)) {
4459 if (is_attribute && IsNormalizableWhitespace(*src))
4460 m << String::Format("&#x%02X;", unsigned(*src));
4461 else
4462 m << *src;
4463 }
4464 break;
4465 }
4466 }
4467 }
4468
4469 return m.GetString();
4470}
4471
4472// Returns the given string with all characters invalid in XML removed.
4473// Currently invalid characters are dropped from the string. An
4474// alternative is to replace them with certain characters such as . or ?.
4475string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
4476 string output;
4477 output.reserve(str.size());
4478 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
4479 if (IsValidXmlCharacter(*it))
4480 output.push_back(*it);
4481
4482 return output;
4483}
4484
4485// The following routines generate an XML representation of a UnitTest
4486// object.
4487//
4488// This is how Google Test concepts map to the DTD:
4489//
4490// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4491// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4492// <testcase name="test-name"> <-- corresponds to a TestInfo object
4493// <failure message="...">...</failure>
4494// <failure message="...">...</failure>
4495// <failure message="...">...</failure>
4496// <-- individual assertion failures
4497// </testcase>
4498// </testsuite>
4499// </testsuites>
4500
4501// Formats the given time in milliseconds as seconds.
4502std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4503 ::std::stringstream ss;
4504 ss << ms/1000.0;
4505 return ss.str();
4506}
4507
4508// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4509void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4510 const char* data) {
4511 const char* segment = data;
4512 *stream << "<![CDATA[";
4513 for (;;) {
4514 const char* const next_segment = strstr(segment, "]]>");
4515 if (next_segment != NULL) {
4516 stream->write(
4517 segment, static_cast<std::streamsize>(next_segment - segment));
4518 *stream << "]]>]]&gt;<![CDATA[";
4519 segment = next_segment + strlen("]]>");
4520 } else {
4521 *stream << segment;
4522 break;
4523 }
4524 }
4525 *stream << "]]>";
4526}
4527
4528// Prints an XML representation of a TestInfo object.
4529// TODO(wan): There is also value in printing properties with the plain printer.
4530void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4531 const char* test_case_name,
4532 const TestInfo& test_info) {
4533 const TestResult& result = *test_info.result();
4534 *stream << " <testcase name=\""
4535 << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
4536
4537 if (test_info.value_param() != NULL) {
4538 *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
4539 << "\"";
4540 }
4541 if (test_info.type_param() != NULL) {
4542 *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
4543 << "\"";
4544 }
4545
4546 *stream << " status=\""
4547 << (test_info.should_run() ? "run" : "notrun")
4548 << "\" time=\""
4549 << FormatTimeInMillisAsSeconds(result.elapsed_time())
4550 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
4551 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
4552
4553 int failures = 0;
4554 for (int i = 0; i < result.total_part_count(); ++i) {
4555 const TestPartResult& part = result.GetTestPartResult(i);
4556 if (part.failed()) {
4557 if (++failures == 1)
4558 *stream << ">\n";
4559 *stream << " <failure message=\""
4560 << EscapeXmlAttribute(part.summary()).c_str()
4561 << "\" type=\"\">";
4562 const string location = internal::FormatCompilerIndependentFileLocation(
4563 part.file_name(), part.line_number());
4564 const string message = location + "\n" + part.message();
4565 OutputXmlCDataSection(stream,
4566 RemoveInvalidXmlCharacters(message).c_str());
4567 *stream << "</failure>\n";
4568 }
4569 }
4570
4571 if (failures == 0)
4572 *stream << " />\n";
4573 else
4574 *stream << " </testcase>\n";
4575}
4576
4577// Prints an XML representation of a TestCase object
4578void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
4579 const TestCase& test_case) {
4580 fprintf(out,
4581 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
4582 "disabled=\"%d\" ",
4583 EscapeXmlAttribute(test_case.name()).c_str(),
4584 test_case.total_test_count(),
4585 test_case.failed_test_count(),
4586 test_case.disabled_test_count());
4587 fprintf(out,
4588 "errors=\"0\" time=\"%s\">\n",
4589 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
4590 for (int i = 0; i < test_case.total_test_count(); ++i) {
4591 ::std::stringstream stream;
4592 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
4593 fprintf(out, "%s", StringStreamToString(&stream).c_str());
4594 }
4595 fprintf(out, " </testsuite>\n");
4596}
4597
4598// Prints an XML summary of unit_test to output stream out.
4599void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
4600 const UnitTest& unit_test) {
4601 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
4602 fprintf(out,
4603 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
4604 "errors=\"0\" time=\"%s\" ",
4605 unit_test.total_test_count(),
4606 unit_test.failed_test_count(),
4607 unit_test.disabled_test_count(),
4608 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
4609 if (GTEST_FLAG(shuffle)) {
4610 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
4611 }
4612 fprintf(out, "name=\"AllTests\">\n");
4613 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
4614 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
4615 fprintf(out, "</testsuites>\n");
4616}
4617
4618// Produces a string representing the test properties in a result as space
4619// delimited XML attributes based on the property key="value" pairs.
4620String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4621 const TestResult& result) {
4622 Message attributes;
4623 for (int i = 0; i < result.test_property_count(); ++i) {
4624 const TestProperty& property = result.GetTestProperty(i);
4625 attributes << " " << property.key() << "="
4626 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4627 }
4628 return attributes.GetString();
4629}
4630
4631// End XmlUnitTestResultPrinter
4632
4633#if GTEST_CAN_STREAM_RESULTS_
4634
4635// Streams test results to the given port on the given host machine.
4636class StreamingListener : public EmptyTestEventListener {
4637 public:
4638 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
4639 static string UrlEncode(const char* str);
4640
4641 StreamingListener(const string& host, const string& port)
4642 : sockfd_(-1), host_name_(host), port_num_(port) {
4643 MakeConnection();
4644 Send("gtest_streaming_protocol_version=1.0\n");
4645 }
4646
4647 virtual ~StreamingListener() {
4648 if (sockfd_ != -1)
4649 CloseConnection();
4650 }
4651
4652 void OnTestProgramStart(const UnitTest& /* unit_test */) {
4653 Send("event=TestProgramStart\n");
4654 }
4655
4656 void OnTestProgramEnd(const UnitTest& unit_test) {
4657 // Note that Google Test current only report elapsed time for each
4658 // test iteration, not for the entire test program.
4659 Send(String::Format("event=TestProgramEnd&passed=%d\n",
4660 unit_test.Passed()));
4661
4662 // Notify the streaming server to stop.
4663 CloseConnection();
4664 }
4665
4666 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
4667 Send(String::Format("event=TestIterationStart&iteration=%d\n",
4668 iteration));
4669 }
4670
4671 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
4672 Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
4673 unit_test.Passed(),
4674 StreamableToString(unit_test.elapsed_time()).c_str()));
4675 }
4676
4677 void OnTestCaseStart(const TestCase& test_case) {
4678 Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
4679 }
4680
4681 void OnTestCaseEnd(const TestCase& test_case) {
4682 Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
4683 test_case.Passed(),
4684 StreamableToString(test_case.elapsed_time()).c_str()));
4685 }
4686
4687 void OnTestStart(const TestInfo& test_info) {
4688 Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
4689 }
4690
4691 void OnTestEnd(const TestInfo& test_info) {
4692 Send(String::Format(
4693 "event=TestEnd&passed=%d&elapsed_time=%sms\n",
4694 (test_info.result())->Passed(),
4695 StreamableToString((test_info.result())->elapsed_time()).c_str()));
4696 }
4697
4698 void OnTestPartResult(const TestPartResult& test_part_result) {
4699 const char* file_name = test_part_result.file_name();
4700 if (file_name == NULL)
4701 file_name = "";
4702 Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
4703 UrlEncode(file_name).c_str(),
4704 test_part_result.line_number()));
4705 Send(UrlEncode(test_part_result.message()) + "\n");
4706 }
4707
4708 private:
4709 // Creates a client socket and connects to the server.
4710 void MakeConnection();
4711
4712 // Closes the socket.
4713 void CloseConnection() {
4714 GTEST_CHECK_(sockfd_ != -1)
4715 << "CloseConnection() can be called only when there is a connection.";
4716
4717 close(sockfd_);
4718 sockfd_ = -1;
4719 }
4720
4721 // Sends a string to the socket.
4722 void Send(const string& message) {
4723 GTEST_CHECK_(sockfd_ != -1)
4724 << "Send() can be called only when there is a connection.";
4725
4726 const int len = static_cast<int>(message.length());
4727 if (write(sockfd_, message.c_str(), len) != len) {
4728 GTEST_LOG_(WARNING)
4729 << "stream_result_to: failed to stream to "
4730 << host_name_ << ":" << port_num_;
4731 }
4732 }
4733
4734 int sockfd_; // socket file descriptor
4735 const string host_name_;
4736 const string port_num_;
4737
4738 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
4739}; // class StreamingListener
4740
4741// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4742// replaces them by "%xx" where xx is their hexadecimal value. For
4743// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4744// in both time and space -- important as the input str may contain an
4745// arbitrarily long test failure message and stack trace.
4746string StreamingListener::UrlEncode(const char* str) {
4747 string result;
4748 result.reserve(strlen(str) + 1);
4749 for (char ch = *str; ch != '\0'; ch = *++str) {
4750 switch (ch) {
4751 case '%':
4752 case '=':
4753 case '&':
4754 case '\n':
4755 result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
4756 break;
4757 default:
4758 result.push_back(ch);
4759 break;
4760 }
4761 }
4762 return result;
4763}
4764
4765void StreamingListener::MakeConnection() {
4766 GTEST_CHECK_(sockfd_ == -1)
4767 << "MakeConnection() can't be called when there is already a connection.";
4768
4769 addrinfo hints;
4770 memset(&hints, 0, sizeof(hints));
4771 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4772 hints.ai_socktype = SOCK_STREAM;
4773 addrinfo* servinfo = NULL;
4774
4775 // Use the getaddrinfo() to get a linked list of IP addresses for
4776 // the given host name.
4777 const int error_num = getaddrinfo(
4778 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4779 if (error_num != 0) {
4780 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4781 << gai_strerror(error_num);
4782 }
4783
4784 // Loop through all the results and connect to the first we can.
4785 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4786 cur_addr = cur_addr->ai_next) {
4787 sockfd_ = socket(
4788 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4789 if (sockfd_ != -1) {
4790 // Connect the client socket to the server socket.
4791 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4792 close(sockfd_);
4793 sockfd_ = -1;
4794 }
4795 }
4796 }
4797
4798 freeaddrinfo(servinfo); // all done with this structure
4799
4800 if (sockfd_ == -1) {
4801 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4802 << host_name_ << ":" << port_num_;
4803 }
4804}
4805
4806// End of class Streaming Listener
4807#endif // GTEST_CAN_STREAM_RESULTS__
4808
4809// Class ScopedTrace
4810
4811// Pushes the given source file location and message onto a per-thread
4812// trace stack maintained by Google Test.
4813// L < UnitTest::mutex_
4814ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
4815 TraceInfo trace;
4816 trace.file = file;
4817 trace.line = line;
4818 trace.message = message.GetString();
4819
4820 UnitTest::GetInstance()->PushGTestTrace(trace);
4821}
4822
4823// Pops the info pushed by the c'tor.
4824// L < UnitTest::mutex_
4825ScopedTrace::~ScopedTrace() {
4826 UnitTest::GetInstance()->PopGTestTrace();
4827}
4828
4829
4830// class OsStackTraceGetter
4831
4832// Returns the current OS stack trace as a String. Parameters:
4833//
4834// max_depth - the maximum number of stack frames to be included
4835// in the trace.
4836// skip_count - the number of top frames to be skipped; doesn't count
4837// against max_depth.
4838//
4839// L < mutex_
4840// We use "L < mutex_" to denote that the function may acquire mutex_.
4841String OsStackTraceGetter::CurrentStackTrace(int, int) {
4842 return String("");
4843}
4844
4845// L < mutex_
4846void OsStackTraceGetter::UponLeavingGTest() {
4847}
4848
4849const char* const
4850OsStackTraceGetter::kElidedFramesMarker =
4851 "... " GTEST_NAME_ " internal frames ...";
4852
4853} // namespace internal
4854
4855// class TestEventListeners
4856
4857TestEventListeners::TestEventListeners()
4858 : repeater_(new internal::TestEventRepeater()),
4859 default_result_printer_(NULL),
4860 default_xml_generator_(NULL) {
4861}
4862
4863TestEventListeners::~TestEventListeners() { delete repeater_; }
4864
4865// Returns the standard listener responsible for the default console
4866// output. Can be removed from the listeners list to shut down default
4867// console output. Note that removing this object from the listener list
4868// with Release transfers its ownership to the user.
4869void TestEventListeners::Append(TestEventListener* listener) {
4870 repeater_->Append(listener);
4871}
4872
4873// Removes the given event listener from the list and returns it. It then
4874// becomes the caller's responsibility to delete the listener. Returns
4875// NULL if the listener is not found in the list.
4876TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4877 if (listener == default_result_printer_)
4878 default_result_printer_ = NULL;
4879 else if (listener == default_xml_generator_)
4880 default_xml_generator_ = NULL;
4881 return repeater_->Release(listener);
4882}
4883
4884// Returns repeater that broadcasts the TestEventListener events to all
4885// subscribers.
4886TestEventListener* TestEventListeners::repeater() { return repeater_; }
4887
4888// Sets the default_result_printer attribute to the provided listener.
4889// The listener is also added to the listener list and previous
4890// default_result_printer is removed from it and deleted. The listener can
4891// also be NULL in which case it will not be added to the list. Does
4892// nothing if the previous and the current listener objects are the same.
4893void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4894 if (default_result_printer_ != listener) {
4895 // It is an error to pass this method a listener that is already in the
4896 // list.
4897 delete Release(default_result_printer_);
4898 default_result_printer_ = listener;
4899 if (listener != NULL)
4900 Append(listener);
4901 }
4902}
4903
4904// Sets the default_xml_generator attribute to the provided listener. The
4905// listener is also added to the listener list and previous
4906// default_xml_generator is removed from it and deleted. The listener can
4907// also be NULL in which case it will not be added to the list. Does
4908// nothing if the previous and the current listener objects are the same.
4909void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4910 if (default_xml_generator_ != listener) {
4911 // It is an error to pass this method a listener that is already in the
4912 // list.
4913 delete Release(default_xml_generator_);
4914 default_xml_generator_ = listener;
4915 if (listener != NULL)
4916 Append(listener);
4917 }
4918}
4919
4920// Controls whether events will be forwarded by the repeater to the
4921// listeners in the list.
4922bool TestEventListeners::EventForwardingEnabled() const {
4923 return repeater_->forwarding_enabled();
4924}
4925
4926void TestEventListeners::SuppressEventForwarding() {
4927 repeater_->set_forwarding_enabled(false);
4928}
4929
4930// class UnitTest
4931
4932// Gets the singleton UnitTest object. The first time this method is
4933// called, a UnitTest object is constructed and returned. Consecutive
4934// calls will return the same object.
4935//
4936// We don't protect this under mutex_ as a user is not supposed to
4937// call this before main() starts, from which point on the return
4938// value will never change.
4939UnitTest * UnitTest::GetInstance() {
4940 // When compiled with MSVC 7.1 in optimized mode, destroying the
4941 // UnitTest object upon exiting the program messes up the exit code,
4942 // causing successful tests to appear failed. We have to use a
4943 // different implementation in this case to bypass the compiler bug.
4944 // This implementation makes the compiler happy, at the cost of
4945 // leaking the UnitTest object.
4946
4947 // CodeGear C++Builder insists on a public destructor for the
4948 // default implementation. Use this implementation to keep good OO
4949 // design with private destructor.
4950
4951#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4952 static UnitTest* const instance = new UnitTest;
4953 return instance;
4954#else
4955 static UnitTest instance;
4956 return &instance;
4957#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4958}
4959
4960// Gets the number of successful test cases.
4961int UnitTest::successful_test_case_count() const {
4962 return impl()->successful_test_case_count();
4963}
4964
4965// Gets the number of failed test cases.
4966int UnitTest::failed_test_case_count() const {
4967 return impl()->failed_test_case_count();
4968}
4969
4970// Gets the number of all test cases.
4971int UnitTest::total_test_case_count() const {
4972 return impl()->total_test_case_count();
4973}
4974
4975// Gets the number of all test cases that contain at least one test
4976// that should run.
4977int UnitTest::test_case_to_run_count() const {
4978 return impl()->test_case_to_run_count();
4979}
4980
4981// Gets the number of successful tests.
4982int UnitTest::successful_test_count() const {
4983 return impl()->successful_test_count();
4984}
4985
4986// Gets the number of failed tests.
4987int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4988
4989// Gets the number of disabled tests.
4990int UnitTest::disabled_test_count() const {
4991 return impl()->disabled_test_count();
4992}
4993
4994// Gets the number of all tests.
4995int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4996
4997// Gets the number of tests that should run.
4998int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4999
5000// Gets the elapsed time, in milliseconds.
5001internal::TimeInMillis UnitTest::elapsed_time() const {
5002 return impl()->elapsed_time();
5003}
5004
5005// Returns true iff the unit test passed (i.e. all test cases passed).
5006bool UnitTest::Passed() const { return impl()->Passed(); }
5007
5008// Returns true iff the unit test failed (i.e. some test case failed
5009// or something outside of all tests failed).
5010bool UnitTest::Failed() const { return impl()->Failed(); }
5011
5012// Gets the i-th test case among all the test cases. i can range from 0 to
5013// total_test_case_count() - 1. If i is not in that range, returns NULL.
5014const TestCase* UnitTest::GetTestCase(int i) const {
5015 return impl()->GetTestCase(i);
5016}
5017
5018// Gets the i-th test case among all the test cases. i can range from 0 to
5019// total_test_case_count() - 1. If i is not in that range, returns NULL.
5020TestCase* UnitTest::GetMutableTestCase(int i) {
5021 return impl()->GetMutableTestCase(i);
5022}
5023
5024// Returns the list of event listeners that can be used to track events
5025// inside Google Test.
5026TestEventListeners& UnitTest::listeners() {
5027 return *impl()->listeners();
5028}
5029
5030// Registers and returns a global test environment. When a test
5031// program is run, all global test environments will be set-up in the
5032// order they were registered. After all tests in the program have
5033// finished, all global test environments will be torn-down in the
5034// *reverse* order they were registered.
5035//
5036// The UnitTest object takes ownership of the given environment.
5037//
5038// We don't protect this under mutex_, as we only support calling it
5039// from the main thread.
5040Environment* UnitTest::AddEnvironment(Environment* env) {
5041 if (env == NULL) {
5042 return NULL;
5043 }
5044
5045 impl_->environments().push_back(env);
5046 return env;
5047}
5048
5049// Adds a TestPartResult to the current TestResult object. All Google Test
5050// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5051// this to report their results. The user code should use the
5052// assertion macros instead of calling this directly.
5053// L < mutex_
5054void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5055 const char* file_name,
5056 int line_number,
5057 const internal::String& message,
5058 const internal::String& os_stack_trace) {
5059 Message msg;
5060 msg << message;
5061
5062 internal::MutexLock lock(&mutex_);
5063 if (impl_->gtest_trace_stack().size() > 0) {
5064 msg << "\n" << GTEST_NAME_ << " trace:";
5065
5066 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5067 i > 0; --i) {
5068 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5069 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5070 << " " << trace.message;
5071 }
5072 }
5073
5074 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5075 msg << internal::kStackTraceMarker << os_stack_trace;
5076 }
5077
5078 const TestPartResult result =
5079 TestPartResult(result_type, file_name, line_number,
5080 msg.GetString().c_str());
5081 impl_->GetTestPartResultReporterForCurrentThread()->
5082 ReportTestPartResult(result);
5083
5084 if (result_type != TestPartResult::kSuccess) {
5085 // gtest_break_on_failure takes precedence over
5086 // gtest_throw_on_failure. This allows a user to set the latter
5087 // in the code (perhaps in order to use Google Test assertions
5088 // with another testing framework) and specify the former on the
5089 // command line for debugging.
5090 if (GTEST_FLAG(break_on_failure)) {
5091#if GTEST_OS_WINDOWS
5092 // Using DebugBreak on Windows allows gtest to still break into a debugger
5093 // when a failure happens and both the --gtest_break_on_failure and
5094 // the --gtest_catch_exceptions flags are specified.
5095 DebugBreak();
5096#else
5097 // Dereference NULL through a volatile pointer to prevent the compiler
5098 // from removing. We use this rather than abort() or __builtin_trap() for
5099 // portability: Symbian doesn't implement abort() well, and some debuggers
5100 // don't correctly trap abort().
5101 *static_cast<volatile int*>(NULL) = 1;
5102#endif // GTEST_OS_WINDOWS
5103 } else if (GTEST_FLAG(throw_on_failure)) {
5104#if GTEST_HAS_EXCEPTIONS
5105 throw GoogleTestFailureException(result);
5106#else
5107 // We cannot call abort() as it generates a pop-up in debug mode
5108 // that cannot be suppressed in VC 7.1 or below.
5109 exit(1);
5110#endif
5111 }
5112 }
5113}
5114
5115// Creates and adds a property to the current TestResult. If a property matching
5116// the supplied value already exists, updates its value instead.
5117void UnitTest::RecordPropertyForCurrentTest(const char* key,
5118 const char* value) {
5119 const TestProperty test_property(key, value);
5120 impl_->current_test_result()->RecordProperty(test_property);
5121}
5122
5123// Runs all tests in this UnitTest object and prints the result.
5124// Returns 0 if successful, or 1 otherwise.
5125//
5126// We don't protect this under mutex_, as we only support calling it
5127// from the main thread.
5128int UnitTest::Run() {
5129 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5130 // used for the duration of the program.
5131 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5132
5133#if GTEST_HAS_SEH
5134 const bool in_death_test_child_process =
5135 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5136
5137 // Either the user wants Google Test to catch exceptions thrown by the
5138 // tests or this is executing in the context of death test child
5139 // process. In either case the user does not want to see pop-up dialogs
5140 // about crashes - they are expected.
5141 if (impl()->catch_exceptions() || in_death_test_child_process) {
5142
5143# if !GTEST_OS_WINDOWS_MOBILE
5144 // SetErrorMode doesn't exist on CE.
5145 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5146 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5147# endif // !GTEST_OS_WINDOWS_MOBILE
5148
5149# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5150 // Death test children can be terminated with _abort(). On Windows,
5151 // _abort() can show a dialog with a warning message. This forces the
5152 // abort message to go to stderr instead.
5153 _set_error_mode(_OUT_TO_STDERR);
5154# endif
5155
5156# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5157 // In the debug version, Visual Studio pops up a separate dialog
5158 // offering a choice to debug the aborted program. We need to suppress
5159 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5160 // executed. Google Test will notify the user of any unexpected
5161 // failure via stderr.
5162 //
5163 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5164 // Users of prior VC versions shall suffer the agony and pain of
5165 // clicking through the countless debug dialogs.
5166 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5167 // debug mode when compiled with VC 7.1 or lower.
5168 if (!GTEST_FLAG(break_on_failure))
5169 _set_abort_behavior(
5170 0x0, // Clear the following flags:
5171 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5172# endif
5173
5174 }
5175#endif // GTEST_HAS_SEH
5176
5177 return internal::HandleExceptionsInMethodIfSupported(
5178 impl(),
5179 &internal::UnitTestImpl::RunAllTests,
5180 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5181}
5182
5183// Returns the working directory when the first TEST() or TEST_F() was
5184// executed.
5185const char* UnitTest::original_working_dir() const {
5186 return impl_->original_working_dir_.c_str();
5187}
5188
5189// Returns the TestCase object for the test that's currently running,
5190// or NULL if no test is running.
5191// L < mutex_
5192const TestCase* UnitTest::current_test_case() const {
5193 internal::MutexLock lock(&mutex_);
5194 return impl_->current_test_case();
5195}
5196
5197// Returns the TestInfo object for the test that's currently running,
5198// or NULL if no test is running.
5199// L < mutex_
5200const TestInfo* UnitTest::current_test_info() const {
5201 internal::MutexLock lock(&mutex_);
5202 return impl_->current_test_info();
5203}
5204
5205// Returns the random seed used at the start of the current test run.
5206int UnitTest::random_seed() const { return impl_->random_seed(); }
5207
5208#if GTEST_HAS_PARAM_TEST
5209// Returns ParameterizedTestCaseRegistry object used to keep track of
5210// value-parameterized tests and instantiate and register them.
5211// L < mutex_
5212internal::ParameterizedTestCaseRegistry&
5213 UnitTest::parameterized_test_registry() {
5214 return impl_->parameterized_test_registry();
5215}
5216#endif // GTEST_HAS_PARAM_TEST
5217
5218// Creates an empty UnitTest.
5219UnitTest::UnitTest() {
5220 impl_ = new internal::UnitTestImpl(this);
5221}
5222
5223// Destructor of UnitTest.
5224UnitTest::~UnitTest() {
5225 delete impl_;
5226}
5227
5228// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5229// Google Test trace stack.
5230// L < mutex_
5231void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
5232 internal::MutexLock lock(&mutex_);
5233 impl_->gtest_trace_stack().push_back(trace);
5234}
5235
5236// Pops a trace from the per-thread Google Test trace stack.
5237// L < mutex_
5238void UnitTest::PopGTestTrace() {
5239 internal::MutexLock lock(&mutex_);
5240 impl_->gtest_trace_stack().pop_back();
5241}
5242
5243namespace internal {
5244
5245UnitTestImpl::UnitTestImpl(UnitTest* parent)
5246 : parent_(parent),
5247#ifdef _MSC_VER
5248# pragma warning(push) // Saves the current warning state.
5249# pragma warning(disable:4355) // Temporarily disables warning 4355
5250 // (using this in initializer).
5251 default_global_test_part_result_reporter_(this),
5252 default_per_thread_test_part_result_reporter_(this),
5253# pragma warning(pop) // Restores the warning state again.
5254#else
5255 default_global_test_part_result_reporter_(this),
5256 default_per_thread_test_part_result_reporter_(this),
5257#endif // _MSC_VER
5258 global_test_part_result_repoter_(
5259 &default_global_test_part_result_reporter_),
5260 per_thread_test_part_result_reporter_(
5261 &default_per_thread_test_part_result_reporter_),
5262#if GTEST_HAS_PARAM_TEST
5263 parameterized_test_registry_(),
5264 parameterized_tests_registered_(false),
5265#endif // GTEST_HAS_PARAM_TEST
5266 last_death_test_case_(-1),
5267 current_test_case_(NULL),
5268 current_test_info_(NULL),
5269 ad_hoc_test_result_(),
5270 os_stack_trace_getter_(NULL),
5271 post_flag_parse_init_performed_(false),
5272 random_seed_(0), // Will be overridden by the flag before first use.
5273 random_(0), // Will be reseeded before first use.
5274 elapsed_time_(0),
5275#if GTEST_HAS_DEATH_TEST
5276 internal_run_death_test_flag_(NULL),
5277 death_test_factory_(new DefaultDeathTestFactory),
5278#endif
5279 // Will be overridden by the flag before first use.
5280 catch_exceptions_(false) {
5281 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5282}
5283
5284UnitTestImpl::~UnitTestImpl() {
5285 // Deletes every TestCase.
5286 ForEach(test_cases_, internal::Delete<TestCase>);
5287
5288 // Deletes every Environment.
5289 ForEach(environments_, internal::Delete<Environment>);
5290
5291 delete os_stack_trace_getter_;
5292}
5293
5294#if GTEST_HAS_DEATH_TEST
5295// Disables event forwarding if the control is currently in a death test
5296// subprocess. Must not be called before InitGoogleTest.
5297void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5298 if (internal_run_death_test_flag_.get() != NULL)
5299 listeners()->SuppressEventForwarding();
5300}
5301#endif // GTEST_HAS_DEATH_TEST
5302
5303// Initializes event listeners performing XML output as specified by
5304// UnitTestOptions. Must not be called before InitGoogleTest.
5305void UnitTestImpl::ConfigureXmlOutput() {
5306 const String& output_format = UnitTestOptions::GetOutputFormat();
5307 if (output_format == "xml") {
5308 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5309 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5310 } else if (output_format != "") {
5311 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5312 output_format.c_str());
5313 fflush(stdout);
5314 }
5315}
5316
5317#if GTEST_CAN_STREAM_RESULTS_
5318// Initializes event listeners for streaming test results in String form.
5319// Must not be called before InitGoogleTest.
5320void UnitTestImpl::ConfigureStreamingOutput() {
5321 const string& target = GTEST_FLAG(stream_result_to);
5322 if (!target.empty()) {
5323 const size_t pos = target.find(':');
5324 if (pos != string::npos) {
5325 listeners()->Append(new StreamingListener(target.substr(0, pos),
5326 target.substr(pos+1)));
5327 } else {
5328 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5329 target.c_str());
5330 fflush(stdout);
5331 }
5332 }
5333}
5334#endif // GTEST_CAN_STREAM_RESULTS_
5335
5336// Performs initialization dependent upon flag values obtained in
5337// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5338// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5339// this function is also called from RunAllTests. Since this function can be
5340// called more than once, it has to be idempotent.
5341void UnitTestImpl::PostFlagParsingInit() {
5342 // Ensures that this function does not execute more than once.
5343 if (!post_flag_parse_init_performed_) {
5344 post_flag_parse_init_performed_ = true;
5345
5346#if GTEST_HAS_DEATH_TEST
5347 InitDeathTestSubprocessControlInfo();
5348 SuppressTestEventsIfInSubprocess();
5349#endif // GTEST_HAS_DEATH_TEST
5350
5351 // Registers parameterized tests. This makes parameterized tests
5352 // available to the UnitTest reflection API without running
5353 // RUN_ALL_TESTS.
5354 RegisterParameterizedTests();
5355
5356 // Configures listeners for XML output. This makes it possible for users
5357 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5358 ConfigureXmlOutput();
5359
5360#if GTEST_CAN_STREAM_RESULTS_
5361 // Configures listeners for streaming test results to the specified server.
5362 ConfigureStreamingOutput();
5363#endif // GTEST_CAN_STREAM_RESULTS_
5364 }
5365}
5366
5367// A predicate that checks the name of a TestCase against a known
5368// value.
5369//
5370// This is used for implementation of the UnitTest class only. We put
5371// it in the anonymous namespace to prevent polluting the outer
5372// namespace.
5373//
5374// TestCaseNameIs is copyable.
5375class TestCaseNameIs {
5376 public:
5377 // Constructor.
5378 explicit TestCaseNameIs(const String& name)
5379 : name_(name) {}
5380
5381 // Returns true iff the name of test_case matches name_.
5382 bool operator()(const TestCase* test_case) const {
5383 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5384 }
5385
5386 private:
5387 String name_;
5388};
5389
5390// Finds and returns a TestCase with the given name. If one doesn't
5391// exist, creates one and returns it. It's the CALLER'S
5392// RESPONSIBILITY to ensure that this function is only called WHEN THE
5393// TESTS ARE NOT SHUFFLED.
5394//
5395// Arguments:
5396//
5397// test_case_name: name of the test case
5398// type_param: the name of the test case's type parameter, or NULL if
5399// this is not a typed or a type-parameterized test case.
5400// set_up_tc: pointer to the function that sets up the test case
5401// tear_down_tc: pointer to the function that tears down the test case
5402TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5403 const char* type_param,
5404 Test::SetUpTestCaseFunc set_up_tc,
5405 Test::TearDownTestCaseFunc tear_down_tc) {
5406 // Can we find a TestCase with the given name?
5407 const std::vector<TestCase*>::const_iterator test_case =
5408 std::find_if(test_cases_.begin(), test_cases_.end(),
5409 TestCaseNameIs(test_case_name));
5410
5411 if (test_case != test_cases_.end())
5412 return *test_case;
5413
5414 // No. Let's create one.
5415 TestCase* const new_test_case =
5416 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5417
5418 // Is this a death test case?
5419 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
5420 kDeathTestCaseFilter)) {
5421 // Yes. Inserts the test case after the last death test case
5422 // defined so far. This only works when the test cases haven't
5423 // been shuffled. Otherwise we may end up running a death test
5424 // after a non-death test.
5425 ++last_death_test_case_;
5426 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5427 new_test_case);
5428 } else {
5429 // No. Appends to the end of the list.
5430 test_cases_.push_back(new_test_case);
5431 }
5432
5433 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5434 return new_test_case;
5435}
5436
5437// Helpers for setting up / tearing down the given environment. They
5438// are for use in the ForEach() function.
5439static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5440static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5441
5442// Runs all tests in this UnitTest object, prints the result, and
5443// returns true if all tests are successful. If any exception is
5444// thrown during a test, the test is considered to be failed, but the
5445// rest of the tests will still be run.
5446//
5447// When parameterized tests are enabled, it expands and registers
5448// parameterized tests first in RegisterParameterizedTests().
5449// All other functions called from RunAllTests() may safely assume that
5450// parameterized tests are ready to be counted and run.
5451bool UnitTestImpl::RunAllTests() {
5452 // Makes sure InitGoogleTest() was called.
5453 if (!GTestIsInitialized()) {
5454 printf("%s",
5455 "\nThis test program did NOT call ::testing::InitGoogleTest "
5456 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5457 return false;
5458 }
5459
5460 // Do not run any test if the --help flag was specified.
5461 if (g_help_flag)
5462 return true;
5463
5464 // Repeats the call to the post-flag parsing initialization in case the
5465 // user didn't call InitGoogleTest.
5466 PostFlagParsingInit();
5467
5468 // Even if sharding is not on, test runners may want to use the
5469 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5470 // protocol.
5471 internal::WriteToShardStatusFileIfNeeded();
5472
5473 // True iff we are in a subprocess for running a thread-safe-style
5474 // death test.
5475 bool in_subprocess_for_death_test = false;
5476
5477#if GTEST_HAS_DEATH_TEST
5478 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5479#endif // GTEST_HAS_DEATH_TEST
5480
5481 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5482 in_subprocess_for_death_test);
5483
5484 // Compares the full test names with the filter to decide which
5485 // tests to run.
5486 const bool has_tests_to_run = FilterTests(should_shard
5487 ? HONOR_SHARDING_PROTOCOL
5488 : IGNORE_SHARDING_PROTOCOL) > 0;
5489
5490 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5491 if (GTEST_FLAG(list_tests)) {
5492 // This must be called *after* FilterTests() has been called.
5493 ListTestsMatchingFilter();
5494 return true;
5495 }
5496
5497 random_seed_ = GTEST_FLAG(shuffle) ?
5498 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5499
5500 // True iff at least one test has failed.
5501 bool failed = false;
5502
5503 TestEventListener* repeater = listeners()->repeater();
5504
5505 repeater->OnTestProgramStart(*parent_);
5506
5507 // How many times to repeat the tests? We don't want to repeat them
5508 // when we are inside the subprocess of a death test.
5509 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5510 // Repeats forever if the repeat count is negative.
5511 const bool forever = repeat < 0;
5512 for (int i = 0; forever || i != repeat; i++) {
5513 // We want to preserve failures generated by ad-hoc test
5514 // assertions executed before RUN_ALL_TESTS().
5515 ClearNonAdHocTestResult();
5516
5517 const TimeInMillis start = GetTimeInMillis();
5518
5519 // Shuffles test cases and tests if requested.
5520 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5521 random()->Reseed(random_seed_);
5522 // This should be done before calling OnTestIterationStart(),
5523 // such that a test event listener can see the actual test order
5524 // in the event.
5525 ShuffleTests();
5526 }
5527
5528 // Tells the unit test event listeners that the tests are about to start.
5529 repeater->OnTestIterationStart(*parent_, i);
5530
5531 // Runs each test case if there is at least one test to run.
5532 if (has_tests_to_run) {
5533 // Sets up all environments beforehand.
5534 repeater->OnEnvironmentsSetUpStart(*parent_);
5535 ForEach(environments_, SetUpEnvironment);
5536 repeater->OnEnvironmentsSetUpEnd(*parent_);
5537
5538 // Runs the tests only if there was no fatal failure during global
5539 // set-up.
5540 if (!Test::HasFatalFailure()) {
5541 for (int test_index = 0; test_index < total_test_case_count();
5542 test_index++) {
5543 GetMutableTestCase(test_index)->Run();
5544 }
5545 }
5546
5547 // Tears down all environments in reverse order afterwards.
5548 repeater->OnEnvironmentsTearDownStart(*parent_);
5549 std::for_each(environments_.rbegin(), environments_.rend(),
5550 TearDownEnvironment);
5551 repeater->OnEnvironmentsTearDownEnd(*parent_);
5552 }
5553
5554 elapsed_time_ = GetTimeInMillis() - start;
5555
5556 // Tells the unit test event listener that the tests have just finished.
5557 repeater->OnTestIterationEnd(*parent_, i);
5558
5559 // Gets the result and clears it.
5560 if (!Passed()) {
5561 failed = true;
5562 }
5563
5564 // Restores the original test order after the iteration. This
5565 // allows the user to quickly repro a failure that happens in the
5566 // N-th iteration without repeating the first (N - 1) iterations.
5567 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5568 // case the user somehow changes the value of the flag somewhere
5569 // (it's always safe to unshuffle the tests).
5570 UnshuffleTests();
5571
5572 if (GTEST_FLAG(shuffle)) {
5573 // Picks a new random seed for each iteration.
5574 random_seed_ = GetNextRandomSeed(random_seed_);
5575 }
5576 }
5577
5578 repeater->OnTestProgramEnd(*parent_);
5579
5580 return !failed;
5581}
5582
5583// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5584// if the variable is present. If a file already exists at this location, this
5585// function will write over it. If the variable is present, but the file cannot
5586// be created, prints an error and exits.
5587void WriteToShardStatusFileIfNeeded() {
5588 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5589 if (test_shard_file != NULL) {
5590 FILE* const file = posix::FOpen(test_shard_file, "w");
5591 if (file == NULL) {
5592 ColoredPrintf(COLOR_RED,
5593 "Could not write to the test shard status file \"%s\" "
5594 "specified by the %s environment variable.\n",
5595 test_shard_file, kTestShardStatusFile);
5596 fflush(stdout);
5597 exit(EXIT_FAILURE);
5598 }
5599 fclose(file);
5600 }
5601}
5602
5603// Checks whether sharding is enabled by examining the relevant
5604// environment variable values. If the variables are present,
5605// but inconsistent (i.e., shard_index >= total_shards), prints
5606// an error and exits. If in_subprocess_for_death_test, sharding is
5607// disabled because it must only be applied to the original test
5608// process. Otherwise, we could filter out death tests we intended to execute.
5609bool ShouldShard(const char* total_shards_env,
5610 const char* shard_index_env,
5611 bool in_subprocess_for_death_test) {
5612 if (in_subprocess_for_death_test) {
5613 return false;
5614 }
5615
5616 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5617 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5618
5619 if (total_shards == -1 && shard_index == -1) {
5620 return false;
5621 } else if (total_shards == -1 && shard_index != -1) {
5622 const Message msg = Message()
5623 << "Invalid environment variables: you have "
5624 << kTestShardIndex << " = " << shard_index
5625 << ", but have left " << kTestTotalShards << " unset.\n";
5626 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5627 fflush(stdout);
5628 exit(EXIT_FAILURE);
5629 } else if (total_shards != -1 && shard_index == -1) {
5630 const Message msg = Message()
5631 << "Invalid environment variables: you have "
5632 << kTestTotalShards << " = " << total_shards
5633 << ", but have left " << kTestShardIndex << " unset.\n";
5634 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5635 fflush(stdout);
5636 exit(EXIT_FAILURE);
5637 } else if (shard_index < 0 || shard_index >= total_shards) {
5638 const Message msg = Message()
5639 << "Invalid environment variables: we require 0 <= "
5640 << kTestShardIndex << " < " << kTestTotalShards
5641 << ", but you have " << kTestShardIndex << "=" << shard_index
5642 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5643 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5644 fflush(stdout);
5645 exit(EXIT_FAILURE);
5646 }
5647
5648 return total_shards > 1;
5649}
5650
5651// Parses the environment variable var as an Int32. If it is unset,
5652// returns default_val. If it is not an Int32, prints an error
5653// and aborts.
5654Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5655 const char* str_val = posix::GetEnv(var);
5656 if (str_val == NULL) {
5657 return default_val;
5658 }
5659
5660 Int32 result;
5661 if (!ParseInt32(Message() << "The value of environment variable " << var,
5662 str_val, &result)) {
5663 exit(EXIT_FAILURE);
5664 }
5665 return result;
5666}
5667
5668// Given the total number of shards, the shard index, and the test id,
5669// returns true iff the test should be run on this shard. The test id is
5670// some arbitrary but unique non-negative integer assigned to each test
5671// method. Assumes that 0 <= shard_index < total_shards.
5672bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5673 return (test_id % total_shards) == shard_index;
5674}
5675
5676// Compares the name of each test with the user-specified filter to
5677// decide whether the test should be run, then records the result in
5678// each TestCase and TestInfo object.
5679// If shard_tests == true, further filters tests based on sharding
5680// variables in the environment - see
5681// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5682// Returns the number of tests that should run.
5683int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5684 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5685 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5686 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5687 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5688
5689 // num_runnable_tests are the number of tests that will
5690 // run across all shards (i.e., match filter and are not disabled).
5691 // num_selected_tests are the number of tests to be run on
5692 // this shard.
5693 int num_runnable_tests = 0;
5694 int num_selected_tests = 0;
5695 for (size_t i = 0; i < test_cases_.size(); i++) {
5696 TestCase* const test_case = test_cases_[i];
5697 const String &test_case_name = test_case->name();
5698 test_case->set_should_run(false);
5699
5700 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5701 TestInfo* const test_info = test_case->test_info_list()[j];
5702 const String test_name(test_info->name());
5703 // A test is disabled if test case name or test name matches
5704 // kDisableTestFilter.
5705 const bool is_disabled =
5706 internal::UnitTestOptions::MatchesFilter(test_case_name,
5707 kDisableTestFilter) ||
5708 internal::UnitTestOptions::MatchesFilter(test_name,
5709 kDisableTestFilter);
5710 test_info->is_disabled_ = is_disabled;
5711
5712 const bool matches_filter =
5713 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5714 test_name);
5715 test_info->matches_filter_ = matches_filter;
5716
5717 const bool is_runnable =
5718 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5719 matches_filter;
5720
5721 const bool is_selected = is_runnable &&
5722 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5723 ShouldRunTestOnShard(total_shards, shard_index,
5724 num_runnable_tests));
5725
5726 num_runnable_tests += is_runnable;
5727 num_selected_tests += is_selected;
5728
5729 test_info->should_run_ = is_selected;
5730 test_case->set_should_run(test_case->should_run() || is_selected);
5731 }
5732 }
5733 return num_selected_tests;
5734}
5735
5736// Prints the names of the tests matching the user-specified filter flag.
5737void UnitTestImpl::ListTestsMatchingFilter() {
5738 for (size_t i = 0; i < test_cases_.size(); i++) {
5739 const TestCase* const test_case = test_cases_[i];
5740 bool printed_test_case_name = false;
5741
5742 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5743 const TestInfo* const test_info =
5744 test_case->test_info_list()[j];
5745 if (test_info->matches_filter_) {
5746 if (!printed_test_case_name) {
5747 printed_test_case_name = true;
5748 printf("%s.\n", test_case->name());
5749 }
5750 printf(" %s\n", test_info->name());
5751 }
5752 }
5753 }
5754 fflush(stdout);
5755}
5756
5757// Sets the OS stack trace getter.
5758//
5759// Does nothing if the input and the current OS stack trace getter are
5760// the same; otherwise, deletes the old getter and makes the input the
5761// current getter.
5762void UnitTestImpl::set_os_stack_trace_getter(
5763 OsStackTraceGetterInterface* getter) {
5764 if (os_stack_trace_getter_ != getter) {
5765 delete os_stack_trace_getter_;
5766 os_stack_trace_getter_ = getter;
5767 }
5768}
5769
5770// Returns the current OS stack trace getter if it is not NULL;
5771// otherwise, creates an OsStackTraceGetter, makes it the current
5772// getter, and returns it.
5773OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5774 if (os_stack_trace_getter_ == NULL) {
5775 os_stack_trace_getter_ = new OsStackTraceGetter;
5776 }
5777
5778 return os_stack_trace_getter_;
5779}
5780
5781// Returns the TestResult for the test that's currently running, or
5782// the TestResult for the ad hoc test if no test is running.
5783TestResult* UnitTestImpl::current_test_result() {
5784 return current_test_info_ ?
5785 &(current_test_info_->result_) : &ad_hoc_test_result_;
5786}
5787
5788// Shuffles all test cases, and the tests within each test case,
5789// making sure that death tests are still run first.
5790void UnitTestImpl::ShuffleTests() {
5791 // Shuffles the death test cases.
5792 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5793
5794 // Shuffles the non-death test cases.
5795 ShuffleRange(random(), last_death_test_case_ + 1,
5796 static_cast<int>(test_cases_.size()), &test_case_indices_);
5797
5798 // Shuffles the tests inside each test case.
5799 for (size_t i = 0; i < test_cases_.size(); i++) {
5800 test_cases_[i]->ShuffleTests(random());
5801 }
5802}
5803
5804// Restores the test cases and tests to their order before the first shuffle.
5805void UnitTestImpl::UnshuffleTests() {
5806 for (size_t i = 0; i < test_cases_.size(); i++) {
5807 // Unshuffles the tests in each test case.
5808 test_cases_[i]->UnshuffleTests();
5809 // Resets the index of each test case.
5810 test_case_indices_[i] = static_cast<int>(i);
5811 }
5812}
5813
5814// Returns the current OS stack trace as a String.
5815//
5816// The maximum number of stack frames to be included is specified by
5817// the gtest_stack_trace_depth flag. The skip_count parameter
5818// specifies the number of top frames to be skipped, which doesn't
5819// count against the number of frames to be included.
5820//
5821// For example, if Foo() calls Bar(), which in turn calls
5822// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5823// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5824String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5825 int skip_count) {
5826 // We pass skip_count + 1 to skip this wrapper function in addition
5827 // to what the user really wants to skip.
5828 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5829}
5830
5831// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5832// suppress unreachable code warnings.
5833namespace {
5834class ClassUniqueToAlwaysTrue {};
5835}
5836
5837bool IsTrue(bool condition) { return condition; }
5838
5839bool AlwaysTrue() {
5840#if GTEST_HAS_EXCEPTIONS
5841 // This condition is always false so AlwaysTrue() never actually throws,
5842 // but it makes the compiler think that it may throw.
5843 if (IsTrue(false))
5844 throw ClassUniqueToAlwaysTrue();
5845#endif // GTEST_HAS_EXCEPTIONS
5846 return true;
5847}
5848
5849// If *pstr starts with the given prefix, modifies *pstr to be right
5850// past the prefix and returns true; otherwise leaves *pstr unchanged
5851// and returns false. None of pstr, *pstr, and prefix can be NULL.
5852bool SkipPrefix(const char* prefix, const char** pstr) {
5853 const size_t prefix_len = strlen(prefix);
5854 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5855 *pstr += prefix_len;
5856 return true;
5857 }
5858 return false;
5859}
5860
5861// Parses a string as a command line flag. The string should have
5862// the format "--flag=value". When def_optional is true, the "=value"
5863// part can be omitted.
5864//
5865// Returns the value of the flag, or NULL if the parsing failed.
5866const char* ParseFlagValue(const char* str,
5867 const char* flag,
5868 bool def_optional) {
5869 // str and flag must not be NULL.
5870 if (str == NULL || flag == NULL) return NULL;
5871
5872 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5873 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
5874 const size_t flag_len = flag_str.length();
5875 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5876
5877 // Skips the flag name.
5878 const char* flag_end = str + flag_len;
5879
5880 // When def_optional is true, it's OK to not have a "=value" part.
5881 if (def_optional && (flag_end[0] == '\0')) {
5882 return flag_end;
5883 }
5884
5885 // If def_optional is true and there are more characters after the
5886 // flag name, or if def_optional is false, there must be a '=' after
5887 // the flag name.
5888 if (flag_end[0] != '=') return NULL;
5889
5890 // Returns the string after "=".
5891 return flag_end + 1;
5892}
5893
5894// Parses a string for a bool flag, in the form of either
5895// "--flag=value" or "--flag".
5896//
5897// In the former case, the value is taken as true as long as it does
5898// not start with '0', 'f', or 'F'.
5899//
5900// In the latter case, the value is taken as true.
5901//
5902// On success, stores the value of the flag in *value, and returns
5903// true. On failure, returns false without changing *value.
5904bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5905 // Gets the value of the flag as a string.
5906 const char* const value_str = ParseFlagValue(str, flag, true);
5907
5908 // Aborts if the parsing failed.
5909 if (value_str == NULL) return false;
5910
5911 // Converts the string value to a bool.
5912 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5913 return true;
5914}
5915
5916// Parses a string for an Int32 flag, in the form of
5917// "--flag=value".
5918//
5919// On success, stores the value of the flag in *value, and returns
5920// true. On failure, returns false without changing *value.
5921bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5922 // Gets the value of the flag as a string.
5923 const char* const value_str = ParseFlagValue(str, flag, false);
5924
5925 // Aborts if the parsing failed.
5926 if (value_str == NULL) return false;
5927
5928 // Sets *value to the value of the flag.
5929 return ParseInt32(Message() << "The value of flag --" << flag,
5930 value_str, value);
5931}
5932
5933// Parses a string for a string flag, in the form of
5934// "--flag=value".
5935//
5936// On success, stores the value of the flag in *value, and returns
5937// true. On failure, returns false without changing *value.
5938bool ParseStringFlag(const char* str, const char* flag, String* value) {
5939 // Gets the value of the flag as a string.
5940 const char* const value_str = ParseFlagValue(str, flag, false);
5941
5942 // Aborts if the parsing failed.
5943 if (value_str == NULL) return false;
5944
5945 // Sets *value to the value of the flag.
5946 *value = value_str;
5947 return true;
5948}
5949
5950// Determines whether a string has a prefix that Google Test uses for its
5951// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5952// If Google Test detects that a command line flag has its prefix but is not
5953// recognized, it will print its help message. Flags starting with
5954// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5955// internal flags and do not trigger the help message.
5956static bool HasGoogleTestFlagPrefix(const char* str) {
5957 return (SkipPrefix("--", &str) ||
5958 SkipPrefix("-", &str) ||
5959 SkipPrefix("/", &str)) &&
5960 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5961 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5962 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5963}
5964
5965// Prints a string containing code-encoded text. The following escape
5966// sequences can be used in the string to control the text color:
5967//
5968// @@ prints a single '@' character.
5969// @R changes the color to red.
5970// @G changes the color to green.
5971// @Y changes the color to yellow.
5972// @D changes to the default terminal text color.
5973//
5974// TODO(wan@google.com): Write tests for this once we add stdout
5975// capturing to Google Test.
5976static void PrintColorEncoded(const char* str) {
5977 GTestColor color = COLOR_DEFAULT; // The current color.
5978
5979 // Conceptually, we split the string into segments divided by escape
5980 // sequences. Then we print one segment at a time. At the end of
5981 // each iteration, the str pointer advances to the beginning of the
5982 // next segment.
5983 for (;;) {
5984 const char* p = strchr(str, '@');
5985 if (p == NULL) {
5986 ColoredPrintf(color, "%s", str);
5987 return;
5988 }
5989
5990 ColoredPrintf(color, "%s", String(str, p - str).c_str());
5991
5992 const char ch = p[1];
5993 str = p + 2;
5994 if (ch == '@') {
5995 ColoredPrintf(color, "@");
5996 } else if (ch == 'D') {
5997 color = COLOR_DEFAULT;
5998 } else if (ch == 'R') {
5999 color = COLOR_RED;
6000 } else if (ch == 'G') {
6001 color = COLOR_GREEN;
6002 } else if (ch == 'Y') {
6003 color = COLOR_YELLOW;
6004 } else {
6005 --str;
6006 }
6007 }
6008}
6009
6010static const char kColorEncodedHelpMessage[] =
6011"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6012"following command line flags to control its behavior:\n"
6013"\n"
6014"Test Selection:\n"
6015" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6016" List the names of all tests instead of running them. The name of\n"
6017" TEST(Foo, Bar) is \"Foo.Bar\".\n"
6018" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6019 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6020" Run only the tests whose name matches one of the positive patterns but\n"
6021" none of the negative patterns. '?' matches any single character; '*'\n"
6022" matches any substring; ':' separates two patterns.\n"
6023" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6024" Run all disabled tests too.\n"
6025"\n"
6026"Test Execution:\n"
6027" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6028" Run the tests repeatedly; use a negative count to repeat forever.\n"
6029" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6030" Randomize tests' orders on every iteration.\n"
6031" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6032" Random number seed to use for shuffling test orders (between 1 and\n"
6033" 99999, or 0 to use a seed based on the current time).\n"
6034"\n"
6035"Test Output:\n"
6036" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6037" Enable/disable colored output. The default is @Gauto@D.\n"
6038" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6039" Don't print the elapsed time of each test.\n"
6040" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6041 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6042" Generate an XML report in the given directory or with the given file\n"
6043" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6044#if GTEST_CAN_STREAM_RESULTS_
6045" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6046" Stream test results to the given server.\n"
6047#endif // GTEST_CAN_STREAM_RESULTS_
6048"\n"
6049"Assertion Behavior:\n"
6050#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6051" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6052" Set the default death test style.\n"
6053#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6054" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6055" Turn assertion failures into debugger break-points.\n"
6056" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6057" Turn assertion failures into C++ exceptions.\n"
6058" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6059" Do not report exceptions as test failures. Instead, allow them\n"
6060" to crash the program or throw a pop-up (on Windows).\n"
6061"\n"
6062"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6063 "the corresponding\n"
6064"environment variable of a flag (all letters in upper-case). For example, to\n"
6065"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6066 "color=no@D or set\n"
6067"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6068"\n"
6069"For more information, please read the " GTEST_NAME_ " documentation at\n"
6070"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6071"(not one in your own code or tests), please report it to\n"
6072"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6073
6074// Parses the command line for Google Test flags, without initializing
6075// other parts of Google Test. The type parameter CharType can be
6076// instantiated to either char or wchar_t.
6077template <typename CharType>
6078void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6079 for (int i = 1; i < *argc; i++) {
6080 const String arg_string = StreamableToString(argv[i]);
6081 const char* const arg = arg_string.c_str();
6082
6083 using internal::ParseBoolFlag;
6084 using internal::ParseInt32Flag;
6085 using internal::ParseStringFlag;
6086
6087 // Do we see a Google Test flag?
6088 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6089 &GTEST_FLAG(also_run_disabled_tests)) ||
6090 ParseBoolFlag(arg, kBreakOnFailureFlag,
6091 &GTEST_FLAG(break_on_failure)) ||
6092 ParseBoolFlag(arg, kCatchExceptionsFlag,
6093 &GTEST_FLAG(catch_exceptions)) ||
6094 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6095 ParseStringFlag(arg, kDeathTestStyleFlag,
6096 &GTEST_FLAG(death_test_style)) ||
6097 ParseBoolFlag(arg, kDeathTestUseFork,
6098 &GTEST_FLAG(death_test_use_fork)) ||
6099 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6100 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6101 &GTEST_FLAG(internal_run_death_test)) ||
6102 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6103 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6104 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6105 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6106 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6107 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6108 ParseInt32Flag(arg, kStackTraceDepthFlag,
6109 &GTEST_FLAG(stack_trace_depth)) ||
6110 ParseStringFlag(arg, kStreamResultToFlag,
6111 &GTEST_FLAG(stream_result_to)) ||
6112 ParseBoolFlag(arg, kThrowOnFailureFlag,
6113 &GTEST_FLAG(throw_on_failure))
6114 ) {
6115 // Yes. Shift the remainder of the argv list left by one. Note
6116 // that argv has (*argc + 1) elements, the last one always being
6117 // NULL. The following loop moves the trailing NULL element as
6118 // well.
6119 for (int j = i; j != *argc; j++) {
6120 argv[j] = argv[j + 1];
6121 }
6122
6123 // Decrements the argument count.
6124 (*argc)--;
6125
6126 // We also need to decrement the iterator as we just removed
6127 // an element.
6128 i--;
6129 } else if (arg_string == "--help" || arg_string == "-h" ||
6130 arg_string == "-?" || arg_string == "/?" ||
6131 HasGoogleTestFlagPrefix(arg)) {
6132 // Both help flag and unrecognized Google Test flags (excluding
6133 // internal ones) trigger help display.
6134 g_help_flag = true;
6135 }
6136 }
6137
6138 if (g_help_flag) {
6139 // We print the help here instead of in RUN_ALL_TESTS(), as the
6140 // latter may not be called at all if the user is using Google
6141 // Test with another testing framework.
6142 PrintColorEncoded(kColorEncodedHelpMessage);
6143 }
6144}
6145
6146// Parses the command line for Google Test flags, without initializing
6147// other parts of Google Test.
6148void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6149 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6150}
6151void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6152 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6153}
6154
6155// The internal implementation of InitGoogleTest().
6156//
6157// The type parameter CharType can be instantiated to either char or
6158// wchar_t.
6159template <typename CharType>
6160void InitGoogleTestImpl(int* argc, CharType** argv) {
6161 g_init_gtest_count++;
6162
6163 // We don't want to run the initialization code twice.
6164 if (g_init_gtest_count != 1) return;
6165
6166 if (*argc <= 0) return;
6167
6168 internal::g_executable_path = internal::StreamableToString(argv[0]);
6169
6170#if GTEST_HAS_DEATH_TEST
6171
6172 g_argvs.clear();
6173 for (int i = 0; i != *argc; i++) {
6174 g_argvs.push_back(StreamableToString(argv[i]));
6175 }
6176
6177#endif // GTEST_HAS_DEATH_TEST
6178
6179 ParseGoogleTestFlagsOnly(argc, argv);
6180 GetUnitTestImpl()->PostFlagParsingInit();
6181}
6182
6183} // namespace internal
6184
6185// Initializes Google Test. This must be called before calling
6186// RUN_ALL_TESTS(). In particular, it parses a command line for the
6187// flags that Google Test recognizes. Whenever a Google Test flag is
6188// seen, it is removed from argv, and *argc is decremented.
6189//
6190// No value is returned. Instead, the Google Test flag variables are
6191// updated.
6192//
6193// Calling the function for the second time has no user-visible effect.
6194void InitGoogleTest(int* argc, char** argv) {
6195 internal::InitGoogleTestImpl(argc, argv);
6196}
6197
6198// This overloaded version can be used in Windows programs compiled in
6199// UNICODE mode.
6200void InitGoogleTest(int* argc, wchar_t** argv) {
6201 internal::InitGoogleTestImpl(argc, argv);
6202}
6203
6204} // namespace testing
6205// Copyright 2005, Google Inc.
6206// All rights reserved.
6207//
6208// Redistribution and use in source and binary forms, with or without
6209// modification, are permitted provided that the following conditions are
6210// met:
6211//
6212// * Redistributions of source code must retain the above copyright
6213// notice, this list of conditions and the following disclaimer.
6214// * Redistributions in binary form must reproduce the above
6215// copyright notice, this list of conditions and the following disclaimer
6216// in the documentation and/or other materials provided with the
6217// distribution.
6218// * Neither the name of Google Inc. nor the names of its
6219// contributors may be used to endorse or promote products derived from
6220// this software without specific prior written permission.
6221//
6222// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6223// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6224// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6225// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6226// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6227// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6228// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6229// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6230// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6231// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6232// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6233//
6234// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6235//
6236// This file implements death tests.
6237
6238
6239#if GTEST_HAS_DEATH_TEST
6240
6241# if GTEST_OS_MAC
6242# include <crt_externs.h>
6243# endif // GTEST_OS_MAC
6244
6245# include <errno.h>
6246# include <fcntl.h>
6247# include <limits.h>
6248# include <stdarg.h>
6249
6250# if GTEST_OS_WINDOWS
6251# include <windows.h>
6252# else
6253# include <sys/mman.h>
6254# include <sys/wait.h>
6255# endif // GTEST_OS_WINDOWS
6256
6257#endif // GTEST_HAS_DEATH_TEST
6258
6259
6260// Indicates that this translation unit is part of Google Test's
6261// implementation. It must come before gtest-internal-inl.h is
6262// included, or there will be a compiler error. This trick is to
6263// prevent a user from accidentally including gtest-internal-inl.h in
6264// his code.
6265#define GTEST_IMPLEMENTATION_ 1
6266#undef GTEST_IMPLEMENTATION_
6267
6268namespace testing {
6269
6270// Constants.
6271
6272// The default death test style.
6273static const char kDefaultDeathTestStyle[] = "fast";
6274
6275GTEST_DEFINE_string_(
6276 death_test_style,
6277 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6278 "Indicates how to run a death test in a forked child process: "
6279 "\"threadsafe\" (child process re-executes the test binary "
6280 "from the beginning, running only the specific death test) or "
6281 "\"fast\" (child process runs the death test immediately "
6282 "after forking).");
6283
6284GTEST_DEFINE_bool_(
6285 death_test_use_fork,
6286 internal::BoolFromGTestEnv("death_test_use_fork", false),
6287 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6288 "Ignored and always uses fork() on POSIX systems where clone() is not "
6289 "implemented. Useful when running under valgrind or similar tools if "
6290 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6291 "it sees an unsupported combination of clone() flags. "
6292 "It is not recommended to use this flag w/o valgrind though it will "
6293 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6294 "most likely be removed.");
6295
6296namespace internal {
6297GTEST_DEFINE_string_(
6298 internal_run_death_test, "",
6299 "Indicates the file, line number, temporal index of "
6300 "the single death test to run, and a file descriptor to "
6301 "which a success code may be sent, all separated by "
6302 "colons. This flag is specified if and only if the current "
6303 "process is a sub-process launched for running a thread-safe "
6304 "death test. FOR INTERNAL USE ONLY.");
6305} // namespace internal
6306
6307#if GTEST_HAS_DEATH_TEST
6308
6309// ExitedWithCode constructor.
6310ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6311}
6312
6313// ExitedWithCode function-call operator.
6314bool ExitedWithCode::operator()(int exit_status) const {
6315# if GTEST_OS_WINDOWS
6316
6317 return exit_status == exit_code_;
6318
6319# else
6320
6321 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6322
6323# endif // GTEST_OS_WINDOWS
6324}
6325
6326# if !GTEST_OS_WINDOWS
6327// KilledBySignal constructor.
6328KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6329}
6330
6331// KilledBySignal function-call operator.
6332bool KilledBySignal::operator()(int exit_status) const {
6333 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6334}
6335# endif // !GTEST_OS_WINDOWS
6336
6337namespace internal {
6338
6339// Utilities needed for death tests.
6340
6341// Generates a textual description of a given exit code, in the format
6342// specified by wait(2).
6343static String ExitSummary(int exit_code) {
6344 Message m;
6345
6346# if GTEST_OS_WINDOWS
6347
6348 m << "Exited with exit status " << exit_code;
6349
6350# else
6351
6352 if (WIFEXITED(exit_code)) {
6353 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6354 } else if (WIFSIGNALED(exit_code)) {
6355 m << "Terminated by signal " << WTERMSIG(exit_code);
6356 }
6357# ifdef WCOREDUMP
6358 if (WCOREDUMP(exit_code)) {
6359 m << " (core dumped)";
6360 }
6361# endif
6362# endif // GTEST_OS_WINDOWS
6363
6364 return m.GetString();
6365}
6366
6367// Returns true if exit_status describes a process that was terminated
6368// by a signal, or exited normally with a nonzero exit code.
6369bool ExitedUnsuccessfully(int exit_status) {
6370 return !ExitedWithCode(0)(exit_status);
6371}
6372
6373# if !GTEST_OS_WINDOWS
6374// Generates a textual failure message when a death test finds more than
6375// one thread running, or cannot determine the number of threads, prior
6376// to executing the given statement. It is the responsibility of the
6377// caller not to pass a thread_count of 1.
6378static String DeathTestThreadWarning(size_t thread_count) {
6379 Message msg;
6380 msg << "Death tests use fork(), which is unsafe particularly"
6381 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6382 if (thread_count == 0)
6383 msg << "couldn't detect the number of threads.";
6384 else
6385 msg << "detected " << thread_count << " threads.";
6386 return msg.GetString();
6387}
6388# endif // !GTEST_OS_WINDOWS
6389
6390// Flag characters for reporting a death test that did not die.
6391static const char kDeathTestLived = 'L';
6392static const char kDeathTestReturned = 'R';
6393static const char kDeathTestThrew = 'T';
6394static const char kDeathTestInternalError = 'I';
6395
6396// An enumeration describing all of the possible ways that a death test can
6397// conclude. DIED means that the process died while executing the test
6398// code; LIVED means that process lived beyond the end of the test code;
6399// RETURNED means that the test statement attempted to execute a return
6400// statement, which is not allowed; THREW means that the test statement
6401// returned control by throwing an exception. IN_PROGRESS means the test
6402// has not yet concluded.
6403// TODO(vladl@google.com): Unify names and possibly values for
6404// AbortReason, DeathTestOutcome, and flag characters above.
6405enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6406
6407// Routine for aborting the program which is safe to call from an
6408// exec-style death test child process, in which case the error
6409// message is propagated back to the parent process. Otherwise, the
6410// message is simply printed to stderr. In either case, the program
6411// then exits with status 1.
6412void DeathTestAbort(const String& message) {
6413 // On a POSIX system, this function may be called from a threadsafe-style
6414 // death test child process, which operates on a very small stack. Use
6415 // the heap for any additional non-minuscule memory requirements.
6416 const InternalRunDeathTestFlag* const flag =
6417 GetUnitTestImpl()->internal_run_death_test_flag();
6418 if (flag != NULL) {
6419 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6420 fputc(kDeathTestInternalError, parent);
6421 fprintf(parent, "%s", message.c_str());
6422 fflush(parent);
6423 _exit(1);
6424 } else {
6425 fprintf(stderr, "%s", message.c_str());
6426 fflush(stderr);
6427 posix::Abort();
6428 }
6429}
6430
6431// A replacement for CHECK that calls DeathTestAbort if the assertion
6432// fails.
6433# define GTEST_DEATH_TEST_CHECK_(expression) \
6434 do { \
6435 if (!::testing::internal::IsTrue(expression)) { \
6436 DeathTestAbort(::testing::internal::String::Format( \
6437 "CHECK failed: File %s, line %d: %s", \
6438 __FILE__, __LINE__, #expression)); \
6439 } \
6440 } while (::testing::internal::AlwaysFalse())
6441
6442// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6443// evaluating any system call that fulfills two conditions: it must return
6444// -1 on failure, and set errno to EINTR when it is interrupted and
6445// should be tried again. The macro expands to a loop that repeatedly
6446// evaluates the expression as long as it evaluates to -1 and sets
6447// errno to EINTR. If the expression evaluates to -1 but errno is
6448// something other than EINTR, DeathTestAbort is called.
6449# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6450 do { \
6451 int gtest_retval; \
6452 do { \
6453 gtest_retval = (expression); \
6454 } while (gtest_retval == -1 && errno == EINTR); \
6455 if (gtest_retval == -1) { \
6456 DeathTestAbort(::testing::internal::String::Format( \
6457 "CHECK failed: File %s, line %d: %s != -1", \
6458 __FILE__, __LINE__, #expression)); \
6459 } \
6460 } while (::testing::internal::AlwaysFalse())
6461
6462// Returns the message describing the last system error in errno.
6463String GetLastErrnoDescription() {
6464 return String(errno == 0 ? "" : posix::StrError(errno));
6465}
6466
6467// This is called from a death test parent process to read a failure
6468// message from the death test child process and log it with the FATAL
6469// severity. On Windows, the message is read from a pipe handle. On other
6470// platforms, it is read from a file descriptor.
6471static void FailFromInternalError(int fd) {
6472 Message error;
6473 char buffer[256];
6474 int num_read;
6475
6476 do {
6477 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6478 buffer[num_read] = '\0';
6479 error << buffer;
6480 }
6481 } while (num_read == -1 && errno == EINTR);
6482
6483 if (num_read == 0) {
6484 GTEST_LOG_(FATAL) << error.GetString();
6485 } else {
6486 const int last_error = errno;
6487 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6488 << GetLastErrnoDescription() << " [" << last_error << "]";
6489 }
6490}
6491
6492// Death test constructor. Increments the running death test count
6493// for the current test.
6494DeathTest::DeathTest() {
6495 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6496 if (info == NULL) {
6497 DeathTestAbort("Cannot run a death test outside of a TEST or "
6498 "TEST_F construct");
6499 }
6500}
6501
6502// Creates and returns a death test by dispatching to the current
6503// death test factory.
6504bool DeathTest::Create(const char* statement, const RE* regex,
6505 const char* file, int line, DeathTest** test) {
6506 return GetUnitTestImpl()->death_test_factory()->Create(
6507 statement, regex, file, line, test);
6508}
6509
6510const char* DeathTest::LastMessage() {
6511 return last_death_test_message_.c_str();
6512}
6513
6514void DeathTest::set_last_death_test_message(const String& message) {
6515 last_death_test_message_ = message;
6516}
6517
6518String DeathTest::last_death_test_message_;
6519
6520// Provides cross platform implementation for some death functionality.
6521class DeathTestImpl : public DeathTest {
6522 protected:
6523 DeathTestImpl(const char* a_statement, const RE* a_regex)
6524 : statement_(a_statement),
6525 regex_(a_regex),
6526 spawned_(false),
6527 status_(-1),
6528 outcome_(IN_PROGRESS),
6529 read_fd_(-1),
6530 write_fd_(-1) {}
6531
6532 // read_fd_ is expected to be closed and cleared by a derived class.
6533 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6534
6535 void Abort(AbortReason reason);
6536 virtual bool Passed(bool status_ok);
6537
6538 const char* statement() const { return statement_; }
6539 const RE* regex() const { return regex_; }
6540 bool spawned() const { return spawned_; }
6541 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6542 int status() const { return status_; }
6543 void set_status(int a_status) { status_ = a_status; }
6544 DeathTestOutcome outcome() const { return outcome_; }
6545 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6546 int read_fd() const { return read_fd_; }
6547 void set_read_fd(int fd) { read_fd_ = fd; }
6548 int write_fd() const { return write_fd_; }
6549 void set_write_fd(int fd) { write_fd_ = fd; }
6550
6551 // Called in the parent process only. Reads the result code of the death
6552 // test child process via a pipe, interprets it to set the outcome_
6553 // member, and closes read_fd_. Outputs diagnostics and terminates in
6554 // case of unexpected codes.
6555 void ReadAndInterpretStatusByte();
6556
6557 private:
6558 // The textual content of the code this object is testing. This class
6559 // doesn't own this string and should not attempt to delete it.
6560 const char* const statement_;
6561 // The regular expression which test output must match. DeathTestImpl
6562 // doesn't own this object and should not attempt to delete it.
6563 const RE* const regex_;
6564 // True if the death test child process has been successfully spawned.
6565 bool spawned_;
6566 // The exit status of the child process.
6567 int status_;
6568 // How the death test concluded.
6569 DeathTestOutcome outcome_;
6570 // Descriptor to the read end of the pipe to the child process. It is
6571 // always -1 in the child process. The child keeps its write end of the
6572 // pipe in write_fd_.
6573 int read_fd_;
6574 // Descriptor to the child's write end of the pipe to the parent process.
6575 // It is always -1 in the parent process. The parent keeps its end of the
6576 // pipe in read_fd_.
6577 int write_fd_;
6578};
6579
6580// Called in the parent process only. Reads the result code of the death
6581// test child process via a pipe, interprets it to set the outcome_
6582// member, and closes read_fd_. Outputs diagnostics and terminates in
6583// case of unexpected codes.
6584void DeathTestImpl::ReadAndInterpretStatusByte() {
6585 char flag;
6586 int bytes_read;
6587
6588 // The read() here blocks until data is available (signifying the
6589 // failure of the death test) or until the pipe is closed (signifying
6590 // its success), so it's okay to call this in the parent before
6591 // the child process has exited.
6592 do {
6593 bytes_read = posix::Read(read_fd(), &flag, 1);
6594 } while (bytes_read == -1 && errno == EINTR);
6595
6596 if (bytes_read == 0) {
6597 set_outcome(DIED);
6598 } else if (bytes_read == 1) {
6599 switch (flag) {
6600 case kDeathTestReturned:
6601 set_outcome(RETURNED);
6602 break;
6603 case kDeathTestThrew:
6604 set_outcome(THREW);
6605 break;
6606 case kDeathTestLived:
6607 set_outcome(LIVED);
6608 break;
6609 case kDeathTestInternalError:
6610 FailFromInternalError(read_fd()); // Does not return.
6611 break;
6612 default:
6613 GTEST_LOG_(FATAL) << "Death test child process reported "
6614 << "unexpected status byte ("
6615 << static_cast<unsigned int>(flag) << ")";
6616 }
6617 } else {
6618 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6619 << GetLastErrnoDescription();
6620 }
6621 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6622 set_read_fd(-1);
6623}
6624
6625// Signals that the death test code which should have exited, didn't.
6626// Should be called only in a death test child process.
6627// Writes a status byte to the child's status file descriptor, then
6628// calls _exit(1).
6629void DeathTestImpl::Abort(AbortReason reason) {
6630 // The parent process considers the death test to be a failure if
6631 // it finds any data in our pipe. So, here we write a single flag byte
6632 // to the pipe, then exit.
6633 const char status_ch =
6634 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6635 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6636
6637 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6638 // We are leaking the descriptor here because on some platforms (i.e.,
6639 // when built as Windows DLL), destructors of global objects will still
6640 // run after calling _exit(). On such systems, write_fd_ will be
6641 // indirectly closed from the destructor of UnitTestImpl, causing double
6642 // close if it is also closed here. On debug configurations, double close
6643 // may assert. As there are no in-process buffers to flush here, we are
6644 // relying on the OS to close the descriptor after the process terminates
6645 // when the destructors are not run.
6646 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6647}
6648
6649// Returns an indented copy of stderr output for a death test.
6650// This makes distinguishing death test output lines from regular log lines
6651// much easier.
6652static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6653 ::std::string ret;
6654 for (size_t at = 0; ; ) {
6655 const size_t line_end = output.find('\n', at);
6656 ret += "[ DEATH ] ";
6657 if (line_end == ::std::string::npos) {
6658 ret += output.substr(at);
6659 break;
6660 }
6661 ret += output.substr(at, line_end + 1 - at);
6662 at = line_end + 1;
6663 }
6664 return ret;
6665}
6666
6667// Assesses the success or failure of a death test, using both private
6668// members which have previously been set, and one argument:
6669//
6670// Private data members:
6671// outcome: An enumeration describing how the death test
6672// concluded: DIED, LIVED, THREW, or RETURNED. The death test
6673// fails in the latter three cases.
6674// status: The exit status of the child process. On *nix, it is in the
6675// in the format specified by wait(2). On Windows, this is the
6676// value supplied to the ExitProcess() API or a numeric code
6677// of the exception that terminated the program.
6678// regex: A regular expression object to be applied to
6679// the test's captured standard error output; the death test
6680// fails if it does not match.
6681//
6682// Argument:
6683// status_ok: true if exit_status is acceptable in the context of
6684// this particular death test, which fails if it is false
6685//
6686// Returns true iff all of the above conditions are met. Otherwise, the
6687// first failing condition, in the order given above, is the one that is
6688// reported. Also sets the last death test message string.
6689bool DeathTestImpl::Passed(bool status_ok) {
6690 if (!spawned())
6691 return false;
6692
6693 const String error_message = GetCapturedStderr();
6694
6695 bool success = false;
6696 Message buffer;
6697
6698 buffer << "Death test: " << statement() << "\n";
6699 switch (outcome()) {
6700 case LIVED:
6701 buffer << " Result: failed to die.\n"
6702 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6703 break;
6704 case THREW:
6705 buffer << " Result: threw an exception.\n"
6706 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6707 break;
6708 case RETURNED:
6709 buffer << " Result: illegal return in test statement.\n"
6710 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6711 break;
6712 case DIED:
6713 if (status_ok) {
6714 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6715 if (matched) {
6716 success = true;
6717 } else {
6718 buffer << " Result: died but not with expected error.\n"
6719 << " Expected: " << regex()->pattern() << "\n"
6720 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6721 }
6722 } else {
6723 buffer << " Result: died but not with expected exit code:\n"
6724 << " " << ExitSummary(status()) << "\n"
6725 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6726 }
6727 break;
6728 case IN_PROGRESS:
6729 default:
6730 GTEST_LOG_(FATAL)
6731 << "DeathTest::Passed somehow called before conclusion of test";
6732 }
6733
6734 DeathTest::set_last_death_test_message(buffer.GetString());
6735 return success;
6736}
6737
6738# if GTEST_OS_WINDOWS
6739// WindowsDeathTest implements death tests on Windows. Due to the
6740// specifics of starting new processes on Windows, death tests there are
6741// always threadsafe, and Google Test considers the
6742// --gtest_death_test_style=fast setting to be equivalent to
6743// --gtest_death_test_style=threadsafe there.
6744//
6745// A few implementation notes: Like the Linux version, the Windows
6746// implementation uses pipes for child-to-parent communication. But due to
6747// the specifics of pipes on Windows, some extra steps are required:
6748//
6749// 1. The parent creates a communication pipe and stores handles to both
6750// ends of it.
6751// 2. The parent starts the child and provides it with the information
6752// necessary to acquire the handle to the write end of the pipe.
6753// 3. The child acquires the write end of the pipe and signals the parent
6754// using a Windows event.
6755// 4. Now the parent can release the write end of the pipe on its side. If
6756// this is done before step 3, the object's reference count goes down to
6757// 0 and it is destroyed, preventing the child from acquiring it. The
6758// parent now has to release it, or read operations on the read end of
6759// the pipe will not return when the child terminates.
6760// 5. The parent reads child's output through the pipe (outcome code and
6761// any possible error messages) from the pipe, and its stderr and then
6762// determines whether to fail the test.
6763//
6764// Note: to distinguish Win32 API calls from the local method and function
6765// calls, the former are explicitly resolved in the global namespace.
6766//
6767class WindowsDeathTest : public DeathTestImpl {
6768 public:
6769 WindowsDeathTest(const char* a_statement,
6770 const RE* a_regex,
6771 const char* file,
6772 int line)
6773 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
6774
6775 // All of these virtual functions are inherited from DeathTest.
6776 virtual int Wait();
6777 virtual TestRole AssumeRole();
6778
6779 private:
6780 // The name of the file in which the death test is located.
6781 const char* const file_;
6782 // The line number on which the death test is located.
6783 const int line_;
6784 // Handle to the write end of the pipe to the child process.
6785 AutoHandle write_handle_;
6786 // Child process handle.
6787 AutoHandle child_handle_;
6788 // Event the child process uses to signal the parent that it has
6789 // acquired the handle to the write end of the pipe. After seeing this
6790 // event the parent can release its own handles to make sure its
6791 // ReadFile() calls return when the child terminates.
6792 AutoHandle event_handle_;
6793};
6794
6795// Waits for the child in a death test to exit, returning its exit
6796// status, or 0 if no child process exists. As a side effect, sets the
6797// outcome data member.
6798int WindowsDeathTest::Wait() {
6799 if (!spawned())
6800 return 0;
6801
6802 // Wait until the child either signals that it has acquired the write end
6803 // of the pipe or it dies.
6804 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
6805 switch (::WaitForMultipleObjects(2,
6806 wait_handles,
6807 FALSE, // Waits for any of the handles.
6808 INFINITE)) {
6809 case WAIT_OBJECT_0:
6810 case WAIT_OBJECT_0 + 1:
6811 break;
6812 default:
6813 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
6814 }
6815
6816 // The child has acquired the write end of the pipe or exited.
6817 // We release the handle on our side and continue.
6818 write_handle_.Reset();
6819 event_handle_.Reset();
6820
6821 ReadAndInterpretStatusByte();
6822
6823 // Waits for the child process to exit if it haven't already. This
6824 // returns immediately if the child has already exited, regardless of
6825 // whether previous calls to WaitForMultipleObjects synchronized on this
6826 // handle or not.
6827 GTEST_DEATH_TEST_CHECK_(
6828 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
6829 INFINITE));
6830 DWORD status_code;
6831 GTEST_DEATH_TEST_CHECK_(
6832 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
6833 child_handle_.Reset();
6834 set_status(static_cast<int>(status_code));
6835 return status();
6836}
6837
6838// The AssumeRole process for a Windows death test. It creates a child
6839// process with the same executable as the current process to run the
6840// death test. The child process is given the --gtest_filter and
6841// --gtest_internal_run_death_test flags such that it knows to run the
6842// current death test only.
6843DeathTest::TestRole WindowsDeathTest::AssumeRole() {
6844 const UnitTestImpl* const impl = GetUnitTestImpl();
6845 const InternalRunDeathTestFlag* const flag =
6846 impl->internal_run_death_test_flag();
6847 const TestInfo* const info = impl->current_test_info();
6848 const int death_test_index = info->result()->death_test_count();
6849
6850 if (flag != NULL) {
6851 // ParseInternalRunDeathTestFlag() has performed all the necessary
6852 // processing.
6853 set_write_fd(flag->write_fd());
6854 return EXECUTE_TEST;
6855 }
6856
6857 // WindowsDeathTest uses an anonymous pipe to communicate results of
6858 // a death test.
6859 SECURITY_ATTRIBUTES handles_are_inheritable = {
6860 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
6861 HANDLE read_handle, write_handle;
6862 GTEST_DEATH_TEST_CHECK_(
6863 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
6864 0) // Default buffer size.
6865 != FALSE);
6866 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
6867 O_RDONLY));
6868 write_handle_.Reset(write_handle);
6869 event_handle_.Reset(::CreateEvent(
6870 &handles_are_inheritable,
6871 TRUE, // The event will automatically reset to non-signaled state.
6872 FALSE, // The initial state is non-signalled.
6873 NULL)); // The even is unnamed.
6874 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
6875 const String filter_flag = String::Format("--%s%s=%s.%s",
6876 GTEST_FLAG_PREFIX_, kFilterFlag,
6877 info->test_case_name(),
6878 info->name());
6879 const String internal_flag = String::Format(
6880 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
6881 GTEST_FLAG_PREFIX_,
6882 kInternalRunDeathTestFlag,
6883 file_, line_,
6884 death_test_index,
6885 static_cast<unsigned int>(::GetCurrentProcessId()),
6886 // size_t has the same with as pointers on both 32-bit and 64-bit
6887 // Windows platforms.
6888 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
6889 reinterpret_cast<size_t>(write_handle),
6890 reinterpret_cast<size_t>(event_handle_.Get()));
6891
6892 char executable_path[_MAX_PATH + 1]; // NOLINT
6893 GTEST_DEATH_TEST_CHECK_(
6894 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
6895 executable_path,
6896 _MAX_PATH));
6897
6898 String command_line = String::Format("%s %s \"%s\"",
6899 ::GetCommandLineA(),
6900 filter_flag.c_str(),
6901 internal_flag.c_str());
6902
6903 DeathTest::set_last_death_test_message("");
6904
6905 CaptureStderr();
6906 // Flush the log buffers since the log streams are shared with the child.
6907 FlushInfoLog();
6908
6909 // The child process will share the standard handles with the parent.
6910 STARTUPINFOA startup_info;
6911 memset(&startup_info, 0, sizeof(STARTUPINFO));
6912 startup_info.dwFlags = STARTF_USESTDHANDLES;
6913 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
6914 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
6915 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
6916
6917 PROCESS_INFORMATION process_info;
6918 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
6919 executable_path,
6920 const_cast<char*>(command_line.c_str()),
6921 NULL, // Retuned process handle is not inheritable.
6922 NULL, // Retuned thread handle is not inheritable.
6923 TRUE, // Child inherits all inheritable handles (for write_handle_).
6924 0x0, // Default creation flags.
6925 NULL, // Inherit the parent's environment.
6926 UnitTest::GetInstance()->original_working_dir(),
6927 &startup_info,
6928 &process_info) != FALSE);
6929 child_handle_.Reset(process_info.hProcess);
6930 ::CloseHandle(process_info.hThread);
6931 set_spawned(true);
6932 return OVERSEE_TEST;
6933}
6934# else // We are not on Windows.
6935
6936// ForkingDeathTest provides implementations for most of the abstract
6937// methods of the DeathTest interface. Only the AssumeRole method is
6938// left undefined.
6939class ForkingDeathTest : public DeathTestImpl {
6940 public:
6941 ForkingDeathTest(const char* statement, const RE* regex);
6942
6943 // All of these virtual functions are inherited from DeathTest.
6944 virtual int Wait();
6945
6946 protected:
6947 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
6948
6949 private:
6950 // PID of child process during death test; 0 in the child process itself.
6951 pid_t child_pid_;
6952};
6953
6954// Constructs a ForkingDeathTest.
6955ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
6956 : DeathTestImpl(a_statement, a_regex),
6957 child_pid_(-1) {}
6958
6959// Waits for the child in a death test to exit, returning its exit
6960// status, or 0 if no child process exists. As a side effect, sets the
6961// outcome data member.
6962int ForkingDeathTest::Wait() {
6963 if (!spawned())
6964 return 0;
6965
6966 ReadAndInterpretStatusByte();
6967
6968 int status_value;
6969 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
6970 set_status(status_value);
6971 return status_value;
6972}
6973
6974// A concrete death test class that forks, then immediately runs the test
6975// in the child process.
6976class NoExecDeathTest : public ForkingDeathTest {
6977 public:
6978 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
6979 ForkingDeathTest(a_statement, a_regex) { }
6980 virtual TestRole AssumeRole();
6981};
6982
6983// The AssumeRole process for a fork-and-run death test. It implements a
6984// straightforward fork, with a simple pipe to transmit the status byte.
6985DeathTest::TestRole NoExecDeathTest::AssumeRole() {
6986 const size_t thread_count = GetThreadCount();
6987 if (thread_count != 1) {
6988 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
6989 }
6990
6991 int pipe_fd[2];
6992 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
6993
6994 DeathTest::set_last_death_test_message("");
6995 CaptureStderr();
6996 // When we fork the process below, the log file buffers are copied, but the
6997 // file descriptors are shared. We flush all log files here so that closing
6998 // the file descriptors in the child process doesn't throw off the
6999 // synchronization between descriptors and buffers in the parent process.
7000 // This is as close to the fork as possible to avoid a race condition in case
7001 // there are multiple threads running before the death test, and another
7002 // thread writes to the log file.
7003 FlushInfoLog();
7004
7005 const pid_t child_pid = fork();
7006 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7007 set_child_pid(child_pid);
7008 if (child_pid == 0) {
7009 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7010 set_write_fd(pipe_fd[1]);
7011 // Redirects all logging to stderr in the child process to prevent
7012 // concurrent writes to the log files. We capture stderr in the parent
7013 // process and append the child process' output to a log.
7014 LogToStderr();
7015 // Event forwarding to the listeners of event listener API mush be shut
7016 // down in death test subprocesses.
7017 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7018 return EXECUTE_TEST;
7019 } else {
7020 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7021 set_read_fd(pipe_fd[0]);
7022 set_spawned(true);
7023 return OVERSEE_TEST;
7024 }
7025}
7026
7027// A concrete death test class that forks and re-executes the main
7028// program from the beginning, with command-line flags set that cause
7029// only this specific death test to be run.
7030class ExecDeathTest : public ForkingDeathTest {
7031 public:
7032 ExecDeathTest(const char* a_statement, const RE* a_regex,
7033 const char* file, int line) :
7034 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7035 virtual TestRole AssumeRole();
7036 private:
7037 // The name of the file in which the death test is located.
7038 const char* const file_;
7039 // The line number on which the death test is located.
7040 const int line_;
7041};
7042
7043// Utility class for accumulating command-line arguments.
7044class Arguments {
7045 public:
7046 Arguments() {
7047 args_.push_back(NULL);
7048 }
7049
7050 ~Arguments() {
7051 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7052 ++i) {
7053 free(*i);
7054 }
7055 }
7056 void AddArgument(const char* argument) {
7057 args_.insert(args_.end() - 1, posix::StrDup(argument));
7058 }
7059
7060 template <typename Str>
7061 void AddArguments(const ::std::vector<Str>& arguments) {
7062 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7063 i != arguments.end();
7064 ++i) {
7065 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7066 }
7067 }
7068 char* const* Argv() {
7069 return &args_[0];
7070 }
7071 private:
7072 std::vector<char*> args_;
7073};
7074
7075// A struct that encompasses the arguments to the child process of a
7076// threadsafe-style death test process.
7077struct ExecDeathTestArgs {
7078 char* const* argv; // Command-line arguments for the child's call to exec
7079 int close_fd; // File descriptor to close; the read end of a pipe
7080};
7081
7082# if GTEST_OS_MAC
7083inline char** GetEnviron() {
7084 // When Google Test is built as a framework on MacOS X, the environ variable
7085 // is unavailable. Apple's documentation (man environ) recommends using
7086 // _NSGetEnviron() instead.
7087 return *_NSGetEnviron();
7088}
7089# else
7090// Some POSIX platforms expect you to declare environ. extern "C" makes
7091// it reside in the global namespace.
7092extern "C" char** environ;
7093inline char** GetEnviron() { return environ; }
7094# endif // GTEST_OS_MAC
7095
7096// The main function for a threadsafe-style death test child process.
7097// This function is called in a clone()-ed process and thus must avoid
7098// any potentially unsafe operations like malloc or libc functions.
7099static int ExecDeathTestChildMain(void* child_arg) {
7100 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7101 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7102
7103 // We need to execute the test program in the same environment where
7104 // it was originally invoked. Therefore we change to the original
7105 // working directory first.
7106 const char* const original_dir =
7107 UnitTest::GetInstance()->original_working_dir();
7108 // We can safely call chdir() as it's a direct system call.
7109 if (chdir(original_dir) != 0) {
7110 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
7111 original_dir,
7112 GetLastErrnoDescription().c_str()));
7113 return EXIT_FAILURE;
7114 }
7115
7116 // We can safely call execve() as it's a direct system call. We
7117 // cannot use execvp() as it's a libc function and thus potentially
7118 // unsafe. Since execve() doesn't search the PATH, the user must
7119 // invoke the test program via a valid path that contains at least
7120 // one path separator.
7121 execve(args->argv[0], args->argv, GetEnviron());
7122 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
7123 args->argv[0],
7124 original_dir,
7125 GetLastErrnoDescription().c_str()));
7126 return EXIT_FAILURE;
7127}
7128
7129// Two utility routines that together determine the direction the stack
7130// grows.
7131// This could be accomplished more elegantly by a single recursive
7132// function, but we want to guard against the unlikely possibility of
7133// a smart compiler optimizing the recursion away.
7134//
7135// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7136// StackLowerThanAddress into StackGrowsDown, which then doesn't give
7137// correct answer.
7138bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_;
7139bool StackLowerThanAddress(const void* ptr) {
7140 int dummy;
7141 return &dummy < ptr;
7142}
7143
7144bool StackGrowsDown() {
7145 int dummy;
7146 return StackLowerThanAddress(&dummy);
7147}
7148
7149// A threadsafe implementation of fork(2) for threadsafe-style death tests
7150// that uses clone(2). It dies with an error message if anything goes
7151// wrong.
7152static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
7153 ExecDeathTestArgs args = { argv, close_fd };
7154 pid_t child_pid = -1;
7155
7156# if GTEST_HAS_CLONE
7157 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7158
7159 if (!use_fork) {
7160 static const bool stack_grows_down = StackGrowsDown();
7161 const size_t stack_size = getpagesize();
7162 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7163 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7164 MAP_ANON | MAP_PRIVATE, -1, 0);
7165 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7166 void* const stack_top =
7167 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
7168
7169 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7170
7171 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7172 }
7173# else
7174 const bool use_fork = true;
7175# endif // GTEST_HAS_CLONE
7176
7177 if (use_fork && (child_pid = fork()) == 0) {
7178 ExecDeathTestChildMain(&args);
7179 _exit(0);
7180 }
7181
7182 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7183 return child_pid;
7184}
7185
7186// The AssumeRole process for a fork-and-exec death test. It re-executes the
7187// main program from the beginning, setting the --gtest_filter
7188// and --gtest_internal_run_death_test flags to cause only the current
7189// death test to be re-run.
7190DeathTest::TestRole ExecDeathTest::AssumeRole() {
7191 const UnitTestImpl* const impl = GetUnitTestImpl();
7192 const InternalRunDeathTestFlag* const flag =
7193 impl->internal_run_death_test_flag();
7194 const TestInfo* const info = impl->current_test_info();
7195 const int death_test_index = info->result()->death_test_count();
7196
7197 if (flag != NULL) {
7198 set_write_fd(flag->write_fd());
7199 return EXECUTE_TEST;
7200 }
7201
7202 int pipe_fd[2];
7203 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7204 // Clear the close-on-exec flag on the write end of the pipe, lest
7205 // it be closed when the child process does an exec:
7206 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7207
7208 const String filter_flag =
7209 String::Format("--%s%s=%s.%s",
7210 GTEST_FLAG_PREFIX_, kFilterFlag,
7211 info->test_case_name(), info->name());
7212 const String internal_flag =
7213 String::Format("--%s%s=%s|%d|%d|%d",
7214 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
7215 file_, line_, death_test_index, pipe_fd[1]);
7216 Arguments args;
7217 args.AddArguments(GetArgvs());
7218 args.AddArgument(filter_flag.c_str());
7219 args.AddArgument(internal_flag.c_str());
7220
7221 DeathTest::set_last_death_test_message("");
7222
7223 CaptureStderr();
7224 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7225 // is necessary.
7226 FlushInfoLog();
7227
7228 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
7229 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7230 set_child_pid(child_pid);
7231 set_read_fd(pipe_fd[0]);
7232 set_spawned(true);
7233 return OVERSEE_TEST;
7234}
7235
7236# endif // !GTEST_OS_WINDOWS
7237
7238// Creates a concrete DeathTest-derived class that depends on the
7239// --gtest_death_test_style flag, and sets the pointer pointed to
7240// by the "test" argument to its address. If the test should be
7241// skipped, sets that pointer to NULL. Returns true, unless the
7242// flag is set to an invalid value.
7243bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7244 const char* file, int line,
7245 DeathTest** test) {
7246 UnitTestImpl* const impl = GetUnitTestImpl();
7247 const InternalRunDeathTestFlag* const flag =
7248 impl->internal_run_death_test_flag();
7249 const int death_test_index = impl->current_test_info()
7250 ->increment_death_test_count();
7251
7252 if (flag != NULL) {
7253 if (death_test_index > flag->index()) {
7254 DeathTest::set_last_death_test_message(String::Format(
7255 "Death test count (%d) somehow exceeded expected maximum (%d)",
7256 death_test_index, flag->index()));
7257 return false;
7258 }
7259
7260 if (!(flag->file() == file && flag->line() == line &&
7261 flag->index() == death_test_index)) {
7262 *test = NULL;
7263 return true;
7264 }
7265 }
7266
7267# if GTEST_OS_WINDOWS
7268
7269 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7270 GTEST_FLAG(death_test_style) == "fast") {
7271 *test = new WindowsDeathTest(statement, regex, file, line);
7272 }
7273
7274# else
7275
7276 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7277 *test = new ExecDeathTest(statement, regex, file, line);
7278 } else if (GTEST_FLAG(death_test_style) == "fast") {
7279 *test = new NoExecDeathTest(statement, regex);
7280 }
7281
7282# endif // GTEST_OS_WINDOWS
7283
7284 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7285 DeathTest::set_last_death_test_message(String::Format(
7286 "Unknown death test style \"%s\" encountered",
7287 GTEST_FLAG(death_test_style).c_str()));
7288 return false;
7289 }
7290
7291 return true;
7292}
7293
7294// Splits a given string on a given delimiter, populating a given
7295// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7296// ::std::string, so we can use it here.
7297static void SplitString(const ::std::string& str, char delimiter,
7298 ::std::vector< ::std::string>* dest) {
7299 ::std::vector< ::std::string> parsed;
7300 ::std::string::size_type pos = 0;
7301 while (::testing::internal::AlwaysTrue()) {
7302 const ::std::string::size_type colon = str.find(delimiter, pos);
7303 if (colon == ::std::string::npos) {
7304 parsed.push_back(str.substr(pos));
7305 break;
7306 } else {
7307 parsed.push_back(str.substr(pos, colon - pos));
7308 pos = colon + 1;
7309 }
7310 }
7311 dest->swap(parsed);
7312}
7313
7314# if GTEST_OS_WINDOWS
7315// Recreates the pipe and event handles from the provided parameters,
7316// signals the event, and returns a file descriptor wrapped around the pipe
7317// handle. This function is called in the child process only.
7318int GetStatusFileDescriptor(unsigned int parent_process_id,
7319 size_t write_handle_as_size_t,
7320 size_t event_handle_as_size_t) {
7321 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7322 FALSE, // Non-inheritable.
7323 parent_process_id));
7324 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7325 DeathTestAbort(String::Format("Unable to open parent process %u",
7326 parent_process_id));
7327 }
7328
7329 // TODO(vladl@google.com): Replace the following check with a
7330 // compile-time assertion when available.
7331 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7332
7333 const HANDLE write_handle =
7334 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7335 HANDLE dup_write_handle;
7336
7337 // The newly initialized handle is accessible only in in the parent
7338 // process. To obtain one accessible within the child, we need to use
7339 // DuplicateHandle.
7340 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7341 ::GetCurrentProcess(), &dup_write_handle,
7342 0x0, // Requested privileges ignored since
7343 // DUPLICATE_SAME_ACCESS is used.
7344 FALSE, // Request non-inheritable handler.
7345 DUPLICATE_SAME_ACCESS)) {
7346 DeathTestAbort(String::Format(
7347 "Unable to duplicate the pipe handle %Iu from the parent process %u",
7348 write_handle_as_size_t, parent_process_id));
7349 }
7350
7351 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7352 HANDLE dup_event_handle;
7353
7354 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7355 ::GetCurrentProcess(), &dup_event_handle,
7356 0x0,
7357 FALSE,
7358 DUPLICATE_SAME_ACCESS)) {
7359 DeathTestAbort(String::Format(
7360 "Unable to duplicate the event handle %Iu from the parent process %u",
7361 event_handle_as_size_t, parent_process_id));
7362 }
7363
7364 const int write_fd =
7365 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7366 if (write_fd == -1) {
7367 DeathTestAbort(String::Format(
7368 "Unable to convert pipe handle %Iu to a file descriptor",
7369 write_handle_as_size_t));
7370 }
7371
7372 // Signals the parent that the write end of the pipe has been acquired
7373 // so the parent can release its own write end.
7374 ::SetEvent(dup_event_handle);
7375
7376 return write_fd;
7377}
7378# endif // GTEST_OS_WINDOWS
7379
7380// Returns a newly created InternalRunDeathTestFlag object with fields
7381// initialized from the GTEST_FLAG(internal_run_death_test) flag if
7382// the flag is specified; otherwise returns NULL.
7383InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7384 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7385
7386 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7387 // can use it here.
7388 int line = -1;
7389 int index = -1;
7390 ::std::vector< ::std::string> fields;
7391 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7392 int write_fd = -1;
7393
7394# if GTEST_OS_WINDOWS
7395
7396 unsigned int parent_process_id = 0;
7397 size_t write_handle_as_size_t = 0;
7398 size_t event_handle_as_size_t = 0;
7399
7400 if (fields.size() != 6
7401 || !ParseNaturalNumber(fields[1], &line)
7402 || !ParseNaturalNumber(fields[2], &index)
7403 || !ParseNaturalNumber(fields[3], &parent_process_id)
7404 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7405 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7406 DeathTestAbort(String::Format(
7407 "Bad --gtest_internal_run_death_test flag: %s",
7408 GTEST_FLAG(internal_run_death_test).c_str()));
7409 }
7410 write_fd = GetStatusFileDescriptor(parent_process_id,
7411 write_handle_as_size_t,
7412 event_handle_as_size_t);
7413# else
7414
7415 if (fields.size() != 4
7416 || !ParseNaturalNumber(fields[1], &line)
7417 || !ParseNaturalNumber(fields[2], &index)
7418 || !ParseNaturalNumber(fields[3], &write_fd)) {
7419 DeathTestAbort(String::Format(
7420 "Bad --gtest_internal_run_death_test flag: %s",
7421 GTEST_FLAG(internal_run_death_test).c_str()));
7422 }
7423
7424# endif // GTEST_OS_WINDOWS
7425
7426 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7427}
7428
7429} // namespace internal
7430
7431#endif // GTEST_HAS_DEATH_TEST
7432
7433} // namespace testing
7434// Copyright 2008, Google Inc.
7435// All rights reserved.
7436//
7437// Redistribution and use in source and binary forms, with or without
7438// modification, are permitted provided that the following conditions are
7439// met:
7440//
7441// * Redistributions of source code must retain the above copyright
7442// notice, this list of conditions and the following disclaimer.
7443// * Redistributions in binary form must reproduce the above
7444// copyright notice, this list of conditions and the following disclaimer
7445// in the documentation and/or other materials provided with the
7446// distribution.
7447// * Neither the name of Google Inc. nor the names of its
7448// contributors may be used to endorse or promote products derived from
7449// this software without specific prior written permission.
7450//
7451// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7452// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7453// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7454// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7455// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7456// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7457// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7458// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7459// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7460// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7461// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7462//
7463// Authors: keith.ray@gmail.com (Keith Ray)
7464
7465
7466#include <stdlib.h>
7467
7468#if GTEST_OS_WINDOWS_MOBILE
7469# include <windows.h>
7470#elif GTEST_OS_WINDOWS
7471# include <direct.h>
7472# include <io.h>
7473#elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
7474// Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
7475# include <sys/syslimits.h>
7476#else
7477# include <limits.h>
7478# include <climits> // Some Linux distributions define PATH_MAX here.
7479#endif // GTEST_OS_WINDOWS_MOBILE
7480
7481#if GTEST_OS_WINDOWS
7482# define GTEST_PATH_MAX_ _MAX_PATH
7483#elif defined(PATH_MAX)
7484# define GTEST_PATH_MAX_ PATH_MAX
7485#elif defined(_XOPEN_PATH_MAX)
7486# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7487#else
7488# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7489#endif // GTEST_OS_WINDOWS
7490
7491
7492namespace testing {
7493namespace internal {
7494
7495#if GTEST_OS_WINDOWS
7496// On Windows, '\\' is the standard path separator, but many tools and the
7497// Windows API also accept '/' as an alternate path separator. Unless otherwise
7498// noted, a file path can contain either kind of path separators, or a mixture
7499// of them.
7500const char kPathSeparator = '\\';
7501const char kAlternatePathSeparator = '/';
7502const char kPathSeparatorString[] = "\\";
7503const char kAlternatePathSeparatorString[] = "/";
7504# if GTEST_OS_WINDOWS_MOBILE
7505// Windows CE doesn't have a current directory. You should not use
7506// the current directory in tests on Windows CE, but this at least
7507// provides a reasonable fallback.
7508const char kCurrentDirectoryString[] = "\\";
7509// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7510const DWORD kInvalidFileAttributes = 0xffffffff;
7511# else
7512const char kCurrentDirectoryString[] = ".\\";
7513# endif // GTEST_OS_WINDOWS_MOBILE
7514#else
7515const char kPathSeparator = '/';
7516const char kPathSeparatorString[] = "/";
7517const char kCurrentDirectoryString[] = "./";
7518#endif // GTEST_OS_WINDOWS
7519
7520// Returns whether the given character is a valid path separator.
7521static bool IsPathSeparator(char c) {
7522#if GTEST_HAS_ALT_PATH_SEP_
7523 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7524#else
7525 return c == kPathSeparator;
7526#endif
7527}
7528
7529// Returns the current working directory, or "" if unsuccessful.
7530FilePath FilePath::GetCurrentDir() {
7531#if GTEST_OS_WINDOWS_MOBILE
7532 // Windows CE doesn't have a current directory, so we just return
7533 // something reasonable.
7534 return FilePath(kCurrentDirectoryString);
7535#elif GTEST_OS_WINDOWS
7536 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7537 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7538#else
7539 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7540 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7541#endif // GTEST_OS_WINDOWS_MOBILE
7542}
7543
7544// Returns a copy of the FilePath with the case-insensitive extension removed.
7545// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7546// FilePath("dir/file"). If a case-insensitive extension is not
7547// found, returns a copy of the original FilePath.
7548FilePath FilePath::RemoveExtension(const char* extension) const {
7549 String dot_extension(String::Format(".%s", extension));
7550 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
7551 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
7552 }
7553 return *this;
7554}
7555
7556// Returns a pointer to the last occurence of a valid path separator in
7557// the FilePath. On Windows, for example, both '/' and '\' are valid path
7558// separators. Returns NULL if no path separator was found.
7559const char* FilePath::FindLastPathSeparator() const {
7560 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7561#if GTEST_HAS_ALT_PATH_SEP_
7562 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7563 // Comparing two pointers of which only one is NULL is undefined.
7564 if (last_alt_sep != NULL &&
7565 (last_sep == NULL || last_alt_sep > last_sep)) {
7566 return last_alt_sep;
7567 }
7568#endif
7569 return last_sep;
7570}
7571
7572// Returns a copy of the FilePath with the directory part removed.
7573// Example: FilePath("path/to/file").RemoveDirectoryName() returns
7574// FilePath("file"). If there is no directory part ("just_a_file"), it returns
7575// the FilePath unmodified. If there is no file part ("just_a_dir/") it
7576// returns an empty FilePath ("").
7577// On Windows platform, '\' is the path separator, otherwise it is '/'.
7578FilePath FilePath::RemoveDirectoryName() const {
7579 const char* const last_sep = FindLastPathSeparator();
7580 return last_sep ? FilePath(String(last_sep + 1)) : *this;
7581}
7582
7583// RemoveFileName returns the directory path with the filename removed.
7584// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7585// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7586// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7587// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7588// On Windows platform, '\' is the path separator, otherwise it is '/'.
7589FilePath FilePath::RemoveFileName() const {
7590 const char* const last_sep = FindLastPathSeparator();
7591 String dir;
7592 if (last_sep) {
7593 dir = String(c_str(), last_sep + 1 - c_str());
7594 } else {
7595 dir = kCurrentDirectoryString;
7596 }
7597 return FilePath(dir);
7598}
7599
7600// Helper functions for naming files in a directory for xml output.
7601
7602// Given directory = "dir", base_name = "test", number = 0,
7603// extension = "xml", returns "dir/test.xml". If number is greater
7604// than zero (e.g., 12), returns "dir/test_12.xml".
7605// On Windows platform, uses \ as the separator rather than /.
7606FilePath FilePath::MakeFileName(const FilePath& directory,
7607 const FilePath& base_name,
7608 int number,
7609 const char* extension) {
7610 String file;
7611 if (number == 0) {
7612 file = String::Format("%s.%s", base_name.c_str(), extension);
7613 } else {
7614 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
7615 }
7616 return ConcatPaths(directory, FilePath(file));
7617}
7618
7619// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7620// On Windows, uses \ as the separator rather than /.
7621FilePath FilePath::ConcatPaths(const FilePath& directory,
7622 const FilePath& relative_path) {
7623 if (directory.IsEmpty())
7624 return relative_path;
7625 const FilePath dir(directory.RemoveTrailingPathSeparator());
7626 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
7627 relative_path.c_str()));
7628}
7629
7630// Returns true if pathname describes something findable in the file-system,
7631// either a file, directory, or whatever.
7632bool FilePath::FileOrDirectoryExists() const {
7633#if GTEST_OS_WINDOWS_MOBILE
7634 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7635 const DWORD attributes = GetFileAttributes(unicode);
7636 delete [] unicode;
7637 return attributes != kInvalidFileAttributes;
7638#else
7639 posix::StatStruct file_stat;
7640 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7641#endif // GTEST_OS_WINDOWS_MOBILE
7642}
7643
7644// Returns true if pathname describes a directory in the file-system
7645// that exists.
7646bool FilePath::DirectoryExists() const {
7647 bool result = false;
7648#if GTEST_OS_WINDOWS
7649 // Don't strip off trailing separator if path is a root directory on
7650 // Windows (like "C:\\").
7651 const FilePath& path(IsRootDirectory() ? *this :
7652 RemoveTrailingPathSeparator());
7653#else
7654 const FilePath& path(*this);
7655#endif
7656
7657#if GTEST_OS_WINDOWS_MOBILE
7658 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7659 const DWORD attributes = GetFileAttributes(unicode);
7660 delete [] unicode;
7661 if ((attributes != kInvalidFileAttributes) &&
7662 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7663 result = true;
7664 }
7665#else
7666 posix::StatStruct file_stat;
7667 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
7668 posix::IsDir(file_stat);
7669#endif // GTEST_OS_WINDOWS_MOBILE
7670
7671 return result;
7672}
7673
7674// Returns true if pathname describes a root directory. (Windows has one
7675// root directory per disk drive.)
7676bool FilePath::IsRootDirectory() const {
7677#if GTEST_OS_WINDOWS
7678 // TODO(wan@google.com): on Windows a network share like
7679 // \\server\share can be a root directory, although it cannot be the
7680 // current directory. Handle this properly.
7681 return pathname_.length() == 3 && IsAbsolutePath();
7682#else
7683 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7684#endif
7685}
7686
7687// Returns true if pathname describes an absolute path.
7688bool FilePath::IsAbsolutePath() const {
7689 const char* const name = pathname_.c_str();
7690#if GTEST_OS_WINDOWS
7691 return pathname_.length() >= 3 &&
7692 ((name[0] >= 'a' && name[0] <= 'z') ||
7693 (name[0] >= 'A' && name[0] <= 'Z')) &&
7694 name[1] == ':' &&
7695 IsPathSeparator(name[2]);
7696#else
7697 return IsPathSeparator(name[0]);
7698#endif
7699}
7700
7701// Returns a pathname for a file that does not currently exist. The pathname
7702// will be directory/base_name.extension or
7703// directory/base_name_<number>.extension if directory/base_name.extension
7704// already exists. The number will be incremented until a pathname is found
7705// that does not already exist.
7706// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7707// There could be a race condition if two or more processes are calling this
7708// function at the same time -- they could both pick the same filename.
7709FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7710 const FilePath& base_name,
7711 const char* extension) {
7712 FilePath full_pathname;
7713 int number = 0;
7714 do {
7715 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7716 } while (full_pathname.FileOrDirectoryExists());
7717 return full_pathname;
7718}
7719
7720// Returns true if FilePath ends with a path separator, which indicates that
7721// it is intended to represent a directory. Returns false otherwise.
7722// This does NOT check that a directory (or file) actually exists.
7723bool FilePath::IsDirectory() const {
7724 return !pathname_.empty() &&
7725 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7726}
7727
7728// Create directories so that path exists. Returns true if successful or if
7729// the directories already exist; returns false if unable to create directories
7730// for any reason.
7731bool FilePath::CreateDirectoriesRecursively() const {
7732 if (!this->IsDirectory()) {
7733 return false;
7734 }
7735
7736 if (pathname_.length() == 0 || this->DirectoryExists()) {
7737 return true;
7738 }
7739
7740 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7741 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7742}
7743
7744// Create the directory so that path exists. Returns true if successful or
7745// if the directory already exists; returns false if unable to create the
7746// directory for any reason, including if the parent directory does not
7747// exist. Not named "CreateDirectory" because that's a macro on Windows.
7748bool FilePath::CreateFolder() const {
7749#if GTEST_OS_WINDOWS_MOBILE
7750 FilePath removed_sep(this->RemoveTrailingPathSeparator());
7751 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
7752 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
7753 delete [] unicode;
7754#elif GTEST_OS_WINDOWS
7755 int result = _mkdir(pathname_.c_str());
7756#else
7757 int result = mkdir(pathname_.c_str(), 0777);
7758#endif // GTEST_OS_WINDOWS_MOBILE
7759
7760 if (result == -1) {
7761 return this->DirectoryExists(); // An error is OK if the directory exists.
7762 }
7763 return true; // No error.
7764}
7765
7766// If input name has a trailing separator character, remove it and return the
7767// name, otherwise return the name string unmodified.
7768// On Windows platform, uses \ as the separator, other platforms use /.
7769FilePath FilePath::RemoveTrailingPathSeparator() const {
7770 return IsDirectory()
7771 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
7772 : *this;
7773}
7774
7775// Removes any redundant separators that might be in the pathname.
7776// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
7777// redundancies that might be in a pathname involving "." or "..".
7778// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
7779void FilePath::Normalize() {
7780 if (pathname_.c_str() == NULL) {
7781 pathname_ = "";
7782 return;
7783 }
7784 const char* src = pathname_.c_str();
7785 char* const dest = new char[pathname_.length() + 1];
7786 char* dest_ptr = dest;
7787 memset(dest_ptr, 0, pathname_.length() + 1);
7788
7789 while (*src != '\0') {
7790 *dest_ptr = *src;
7791 if (!IsPathSeparator(*src)) {
7792 src++;
7793 } else {
7794#if GTEST_HAS_ALT_PATH_SEP_
7795 if (*dest_ptr == kAlternatePathSeparator) {
7796 *dest_ptr = kPathSeparator;
7797 }
7798#endif
7799 while (IsPathSeparator(*src))
7800 src++;
7801 }
7802 dest_ptr++;
7803 }
7804 *dest_ptr = '\0';
7805 pathname_ = dest;
7806 delete[] dest;
7807}
7808
7809} // namespace internal
7810} // namespace testing
7811// Copyright 2008, Google Inc.
7812// All rights reserved.
7813//
7814// Redistribution and use in source and binary forms, with or without
7815// modification, are permitted provided that the following conditions are
7816// met:
7817//
7818// * Redistributions of source code must retain the above copyright
7819// notice, this list of conditions and the following disclaimer.
7820// * Redistributions in binary form must reproduce the above
7821// copyright notice, this list of conditions and the following disclaimer
7822// in the documentation and/or other materials provided with the
7823// distribution.
7824// * Neither the name of Google Inc. nor the names of its
7825// contributors may be used to endorse or promote products derived from
7826// this software without specific prior written permission.
7827//
7828// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7829// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7830// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7831// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7832// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7833// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7834// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7835// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7836// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7837// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7838// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7839//
7840// Author: wan@google.com (Zhanyong Wan)
7841
7842
7843#include <limits.h>
7844#include <stdlib.h>
7845#include <stdio.h>
7846#include <string.h>
7847
7848#if GTEST_OS_WINDOWS_MOBILE
7849# include <windows.h> // For TerminateProcess()
7850#elif GTEST_OS_WINDOWS
7851# include <io.h>
7852# include <sys/stat.h>
7853#else
7854# include <unistd.h>
7855#endif // GTEST_OS_WINDOWS_MOBILE
7856
7857#if GTEST_OS_MAC
7858# include <mach/mach_init.h>
7859# include <mach/task.h>
7860# include <mach/vm_map.h>
7861#endif // GTEST_OS_MAC
7862
7863
7864// Indicates that this translation unit is part of Google Test's
7865// implementation. It must come before gtest-internal-inl.h is
7866// included, or there will be a compiler error. This trick is to
7867// prevent a user from accidentally including gtest-internal-inl.h in
7868// his code.
7869#define GTEST_IMPLEMENTATION_ 1
7870#undef GTEST_IMPLEMENTATION_
7871
7872namespace testing {
7873namespace internal {
7874
7875#if defined(_MSC_VER) || defined(__BORLANDC__)
7876// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
7877const int kStdOutFileno = 1;
7878const int kStdErrFileno = 2;
7879#else
7880const int kStdOutFileno = STDOUT_FILENO;
7881const int kStdErrFileno = STDERR_FILENO;
7882#endif // _MSC_VER
7883
7884#if GTEST_OS_MAC
7885
7886// Returns the number of threads running in the process, or 0 to indicate that
7887// we cannot detect it.
7888size_t GetThreadCount() {
7889 const task_t task = mach_task_self();
7890 mach_msg_type_number_t thread_count;
7891 thread_act_array_t thread_list;
7892 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
7893 if (status == KERN_SUCCESS) {
7894 // task_threads allocates resources in thread_list and we need to free them
7895 // to avoid leaks.
7896 vm_deallocate(task,
7897 reinterpret_cast<vm_address_t>(thread_list),
7898 sizeof(thread_t) * thread_count);
7899 return static_cast<size_t>(thread_count);
7900 } else {
7901 return 0;
7902 }
7903}
7904
7905#else
7906
7907size_t GetThreadCount() {
7908 // There's no portable way to detect the number of threads, so we just
7909 // return 0 to indicate that we cannot detect it.
7910 return 0;
7911}
7912
7913#endif // GTEST_OS_MAC
7914
7915#if GTEST_USES_POSIX_RE
7916
7917// Implements RE. Currently only needed for death tests.
7918
7919RE::~RE() {
7920 if (is_valid_) {
7921 // regfree'ing an invalid regex might crash because the content
7922 // of the regex is undefined. Since the regex's are essentially
7923 // the same, one cannot be valid (or invalid) without the other
7924 // being so too.
7925 regfree(&partial_regex_);
7926 regfree(&full_regex_);
7927 }
7928 free(const_cast<char*>(pattern_));
7929}
7930
7931// Returns true iff regular expression re matches the entire str.
7932bool RE::FullMatch(const char* str, const RE& re) {
7933 if (!re.is_valid_) return false;
7934
7935 regmatch_t match;
7936 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
7937}
7938
7939// Returns true iff regular expression re matches a substring of str
7940// (including str itself).
7941bool RE::PartialMatch(const char* str, const RE& re) {
7942 if (!re.is_valid_) return false;
7943
7944 regmatch_t match;
7945 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
7946}
7947
7948// Initializes an RE from its string representation.
7949void RE::Init(const char* regex) {
7950 pattern_ = posix::StrDup(regex);
7951
7952 // Reserves enough bytes to hold the regular expression used for a
7953 // full match.
7954 const size_t full_regex_len = strlen(regex) + 10;
7955 char* const full_pattern = new char[full_regex_len];
7956
7957 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
7958 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
7959 // We want to call regcomp(&partial_regex_, ...) even if the
7960 // previous expression returns false. Otherwise partial_regex_ may
7961 // not be properly initialized can may cause trouble when it's
7962 // freed.
7963 //
7964 // Some implementation of POSIX regex (e.g. on at least some
7965 // versions of Cygwin) doesn't accept the empty string as a valid
7966 // regex. We change it to an equivalent form "()" to be safe.
7967 if (is_valid_) {
7968 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
7969 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
7970 }
7971 EXPECT_TRUE(is_valid_)
7972 << "Regular expression \"" << regex
7973 << "\" is not a valid POSIX Extended regular expression.";
7974
7975 delete[] full_pattern;
7976}
7977
7978#elif GTEST_USES_SIMPLE_RE
7979
7980// Returns true iff ch appears anywhere in str (excluding the
7981// terminating '\0' character).
7982bool IsInSet(char ch, const char* str) {
7983 return ch != '\0' && strchr(str, ch) != NULL;
7984}
7985
7986// Returns true iff ch belongs to the given classification. Unlike
7987// similar functions in <ctype.h>, these aren't affected by the
7988// current locale.
7989bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
7990bool IsAsciiPunct(char ch) {
7991 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
7992}
7993bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
7994bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
7995bool IsAsciiWordChar(char ch) {
7996 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
7997 ('0' <= ch && ch <= '9') || ch == '_';
7998}
7999
8000// Returns true iff "\\c" is a supported escape sequence.
8001bool IsValidEscape(char c) {
8002 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8003}
8004
8005// Returns true iff the given atom (specified by escaped and pattern)
8006// matches ch. The result is undefined if the atom is invalid.
8007bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8008 if (escaped) { // "\\p" where p is pattern_char.
8009 switch (pattern_char) {
8010 case 'd': return IsAsciiDigit(ch);
8011 case 'D': return !IsAsciiDigit(ch);
8012 case 'f': return ch == '\f';
8013 case 'n': return ch == '\n';
8014 case 'r': return ch == '\r';
8015 case 's': return IsAsciiWhiteSpace(ch);
8016 case 'S': return !IsAsciiWhiteSpace(ch);
8017 case 't': return ch == '\t';
8018 case 'v': return ch == '\v';
8019 case 'w': return IsAsciiWordChar(ch);
8020 case 'W': return !IsAsciiWordChar(ch);
8021 }
8022 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8023 }
8024
8025 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8026}
8027
8028// Helper function used by ValidateRegex() to format error messages.
8029String FormatRegexSyntaxError(const char* regex, int index) {
8030 return (Message() << "Syntax error at index " << index
8031 << " in simple regular expression \"" << regex << "\": ").GetString();
8032}
8033
8034// Generates non-fatal failures and returns false if regex is invalid;
8035// otherwise returns true.
8036bool ValidateRegex(const char* regex) {
8037 if (regex == NULL) {
8038 // TODO(wan@google.com): fix the source file location in the
8039 // assertion failures to match where the regex is used in user
8040 // code.
8041 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8042 return false;
8043 }
8044
8045 bool is_valid = true;
8046
8047 // True iff ?, *, or + can follow the previous atom.
8048 bool prev_repeatable = false;
8049 for (int i = 0; regex[i]; i++) {
8050 if (regex[i] == '\\') { // An escape sequence
8051 i++;
8052 if (regex[i] == '\0') {
8053 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8054 << "'\\' cannot appear at the end.";
8055 return false;
8056 }
8057
8058 if (!IsValidEscape(regex[i])) {
8059 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8060 << "invalid escape sequence \"\\" << regex[i] << "\".";
8061 is_valid = false;
8062 }
8063 prev_repeatable = true;
8064 } else { // Not an escape sequence.
8065 const char ch = regex[i];
8066
8067 if (ch == '^' && i > 0) {
8068 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8069 << "'^' can only appear at the beginning.";
8070 is_valid = false;
8071 } else if (ch == '$' && regex[i + 1] != '\0') {
8072 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8073 << "'$' can only appear at the end.";
8074 is_valid = false;
8075 } else if (IsInSet(ch, "()[]{}|")) {
8076 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8077 << "'" << ch << "' is unsupported.";
8078 is_valid = false;
8079 } else if (IsRepeat(ch) && !prev_repeatable) {
8080 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8081 << "'" << ch << "' can only follow a repeatable token.";
8082 is_valid = false;
8083 }
8084
8085 prev_repeatable = !IsInSet(ch, "^$?*+");
8086 }
8087 }
8088
8089 return is_valid;
8090}
8091
8092// Matches a repeated regex atom followed by a valid simple regular
8093// expression. The regex atom is defined as c if escaped is false,
8094// or \c otherwise. repeat is the repetition meta character (?, *,
8095// or +). The behavior is undefined if str contains too many
8096// characters to be indexable by size_t, in which case the test will
8097// probably time out anyway. We are fine with this limitation as
8098// std::string has it too.
8099bool MatchRepetitionAndRegexAtHead(
8100 bool escaped, char c, char repeat, const char* regex,
8101 const char* str) {
8102 const size_t min_count = (repeat == '+') ? 1 : 0;
8103 const size_t max_count = (repeat == '?') ? 1 :
8104 static_cast<size_t>(-1) - 1;
8105 // We cannot call numeric_limits::max() as it conflicts with the
8106 // max() macro on Windows.
8107
8108 for (size_t i = 0; i <= max_count; ++i) {
8109 // We know that the atom matches each of the first i characters in str.
8110 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8111 // We have enough matches at the head, and the tail matches too.
8112 // Since we only care about *whether* the pattern matches str
8113 // (as opposed to *how* it matches), there is no need to find a
8114 // greedy match.
8115 return true;
8116 }
8117 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8118 return false;
8119 }
8120 return false;
8121}
8122
8123// Returns true iff regex matches a prefix of str. regex must be a
8124// valid simple regular expression and not start with "^", or the
8125// result is undefined.
8126bool MatchRegexAtHead(const char* regex, const char* str) {
8127 if (*regex == '\0') // An empty regex matches a prefix of anything.
8128 return true;
8129
8130 // "$" only matches the end of a string. Note that regex being
8131 // valid guarantees that there's nothing after "$" in it.
8132 if (*regex == '$')
8133 return *str == '\0';
8134
8135 // Is the first thing in regex an escape sequence?
8136 const bool escaped = *regex == '\\';
8137 if (escaped)
8138 ++regex;
8139 if (IsRepeat(regex[1])) {
8140 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8141 // here's an indirect recursion. It terminates as the regex gets
8142 // shorter in each recursion.
8143 return MatchRepetitionAndRegexAtHead(
8144 escaped, regex[0], regex[1], regex + 2, str);
8145 } else {
8146 // regex isn't empty, isn't "$", and doesn't start with a
8147 // repetition. We match the first atom of regex with the first
8148 // character of str and recurse.
8149 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8150 MatchRegexAtHead(regex + 1, str + 1);
8151 }
8152}
8153
8154// Returns true iff regex matches any substring of str. regex must be
8155// a valid simple regular expression, or the result is undefined.
8156//
8157// The algorithm is recursive, but the recursion depth doesn't exceed
8158// the regex length, so we won't need to worry about running out of
8159// stack space normally. In rare cases the time complexity can be
8160// exponential with respect to the regex length + the string length,
8161// but usually it's must faster (often close to linear).
8162bool MatchRegexAnywhere(const char* regex, const char* str) {
8163 if (regex == NULL || str == NULL)
8164 return false;
8165
8166 if (*regex == '^')
8167 return MatchRegexAtHead(regex + 1, str);
8168
8169 // A successful match can be anywhere in str.
8170 do {
8171 if (MatchRegexAtHead(regex, str))
8172 return true;
8173 } while (*str++ != '\0');
8174 return false;
8175}
8176
8177// Implements the RE class.
8178
8179RE::~RE() {
8180 free(const_cast<char*>(pattern_));
8181 free(const_cast<char*>(full_pattern_));
8182}
8183
8184// Returns true iff regular expression re matches the entire str.
8185bool RE::FullMatch(const char* str, const RE& re) {
8186 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8187}
8188
8189// Returns true iff regular expression re matches a substring of str
8190// (including str itself).
8191bool RE::PartialMatch(const char* str, const RE& re) {
8192 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8193}
8194
8195// Initializes an RE from its string representation.
8196void RE::Init(const char* regex) {
8197 pattern_ = full_pattern_ = NULL;
8198 if (regex != NULL) {
8199 pattern_ = posix::StrDup(regex);
8200 }
8201
8202 is_valid_ = ValidateRegex(regex);
8203 if (!is_valid_) {
8204 // No need to calculate the full pattern when the regex is invalid.
8205 return;
8206 }
8207
8208 const size_t len = strlen(regex);
8209 // Reserves enough bytes to hold the regular expression used for a
8210 // full match: we need space to prepend a '^', append a '$', and
8211 // terminate the string with '\0'.
8212 char* buffer = static_cast<char*>(malloc(len + 3));
8213 full_pattern_ = buffer;
8214
8215 if (*regex != '^')
8216 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8217
8218 // We don't use snprintf or strncpy, as they trigger a warning when
8219 // compiled with VC++ 8.0.
8220 memcpy(buffer, regex, len);
8221 buffer += len;
8222
8223 if (len == 0 || regex[len - 1] != '$')
8224 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8225
8226 *buffer = '\0';
8227}
8228
8229#endif // GTEST_USES_POSIX_RE
8230
8231const char kUnknownFile[] = "unknown file";
8232
8233// Formats a source file path and a line number as they would appear
8234// in an error message from the compiler used to compile this code.
8235GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8236 const char* const file_name = file == NULL ? kUnknownFile : file;
8237
8238 if (line < 0) {
8239 return String::Format("%s:", file_name).c_str();
8240 }
8241#ifdef _MSC_VER
8242 return String::Format("%s(%d):", file_name, line).c_str();
8243#else
8244 return String::Format("%s:%d:", file_name, line).c_str();
8245#endif // _MSC_VER
8246}
8247
8248// Formats a file location for compiler-independent XML output.
8249// Although this function is not platform dependent, we put it next to
8250// FormatFileLocation in order to contrast the two functions.
8251// Note that FormatCompilerIndependentFileLocation() does NOT append colon
8252// to the file location it produces, unlike FormatFileLocation().
8253GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8254 const char* file, int line) {
8255 const char* const file_name = file == NULL ? kUnknownFile : file;
8256
8257 if (line < 0)
8258 return file_name;
8259 else
8260 return String::Format("%s:%d", file_name, line).c_str();
8261}
8262
8263
8264GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8265 : severity_(severity) {
8266 const char* const marker =
8267 severity == GTEST_INFO ? "[ INFO ]" :
8268 severity == GTEST_WARNING ? "[WARNING]" :
8269 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8270 GetStream() << ::std::endl << marker << " "
8271 << FormatFileLocation(file, line).c_str() << ": ";
8272}
8273
8274// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8275GTestLog::~GTestLog() {
8276 GetStream() << ::std::endl;
8277 if (severity_ == GTEST_FATAL) {
8278 fflush(stderr);
8279 posix::Abort();
8280 }
8281}
8282// Disable Microsoft deprecation warnings for POSIX functions called from
8283// this class (creat, dup, dup2, and close)
8284#ifdef _MSC_VER
8285# pragma warning(push)
8286# pragma warning(disable: 4996)
8287#endif // _MSC_VER
8288
8289#if GTEST_HAS_STREAM_REDIRECTION
8290
8291// Object that captures an output stream (stdout/stderr).
8292class CapturedStream {
8293 public:
8294 // The ctor redirects the stream to a temporary file.
8295 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8296
8297# if GTEST_OS_WINDOWS
8298 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8299 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8300
8301 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8302 const UINT success = ::GetTempFileNameA(temp_dir_path,
8303 "gtest_redir",
8304 0, // Generate unique file name.
8305 temp_file_path);
8306 GTEST_CHECK_(success != 0)
8307 << "Unable to create a temporary file in " << temp_dir_path;
8308 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8309 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8310 << temp_file_path;
8311 filename_ = temp_file_path;
8312# else
8313 // There's no guarantee that a test has write access to the
8314 // current directory, so we create the temporary file in the /tmp
8315 // directory instead.
8316 char name_template[] = "/tmp/captured_stream.XXXXXX";
8317 const int captured_fd = mkstemp(name_template);
8318 filename_ = name_template;
8319# endif // GTEST_OS_WINDOWS
8320 fflush(NULL);
8321 dup2(captured_fd, fd_);
8322 close(captured_fd);
8323 }
8324
8325 ~CapturedStream() {
8326 remove(filename_.c_str());
8327 }
8328
8329 String GetCapturedString() {
8330 if (uncaptured_fd_ != -1) {
8331 // Restores the original stream.
8332 fflush(NULL);
8333 dup2(uncaptured_fd_, fd_);
8334 close(uncaptured_fd_);
8335 uncaptured_fd_ = -1;
8336 }
8337
8338 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8339 const String content = ReadEntireFile(file);
8340 posix::FClose(file);
8341 return content;
8342 }
8343
8344 private:
8345 // Reads the entire content of a file as a String.
8346 static String ReadEntireFile(FILE* file);
8347
8348 // Returns the size (in bytes) of a file.
8349 static size_t GetFileSize(FILE* file);
8350
8351 const int fd_; // A stream to capture.
8352 int uncaptured_fd_;
8353 // Name of the temporary file holding the stderr output.
8354 ::std::string filename_;
8355
8356 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8357};
8358
8359// Returns the size (in bytes) of a file.
8360size_t CapturedStream::GetFileSize(FILE* file) {
8361 fseek(file, 0, SEEK_END);
8362 return static_cast<size_t>(ftell(file));
8363}
8364
8365// Reads the entire content of a file as a string.
8366String CapturedStream::ReadEntireFile(FILE* file) {
8367 const size_t file_size = GetFileSize(file);
8368 char* const buffer = new char[file_size];
8369
8370 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8371 size_t bytes_read = 0; // # of bytes read so far
8372
8373 fseek(file, 0, SEEK_SET);
8374
8375 // Keeps reading the file until we cannot read further or the
8376 // pre-determined file size is reached.
8377 do {
8378 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8379 bytes_read += bytes_last_read;
8380 } while (bytes_last_read > 0 && bytes_read < file_size);
8381
8382 const String content(buffer, bytes_read);
8383 delete[] buffer;
8384
8385 return content;
8386}
8387
8388# ifdef _MSC_VER
8389# pragma warning(pop)
8390# endif // _MSC_VER
8391
8392static CapturedStream* g_captured_stderr = NULL;
8393static CapturedStream* g_captured_stdout = NULL;
8394
8395// Starts capturing an output stream (stdout/stderr).
8396void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8397 if (*stream != NULL) {
8398 GTEST_LOG_(FATAL) << "Only one " << stream_name
8399 << " capturer can exist at a time.";
8400 }
8401 *stream = new CapturedStream(fd);
8402}
8403
8404// Stops capturing the output stream and returns the captured string.
8405String GetCapturedStream(CapturedStream** captured_stream) {
8406 const String content = (*captured_stream)->GetCapturedString();
8407
8408 delete *captured_stream;
8409 *captured_stream = NULL;
8410
8411 return content;
8412}
8413
8414// Starts capturing stdout.
8415void CaptureStdout() {
8416 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8417}
8418
8419// Starts capturing stderr.
8420void CaptureStderr() {
8421 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8422}
8423
8424// Stops capturing stdout and returns the captured string.
8425String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
8426
8427// Stops capturing stderr and returns the captured string.
8428String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
8429
8430#endif // GTEST_HAS_STREAM_REDIRECTION
8431
8432#if GTEST_HAS_DEATH_TEST
8433
8434// A copy of all command line arguments. Set by InitGoogleTest().
8435::std::vector<String> g_argvs;
8436
8437// Returns the command line as a vector of strings.
8438const ::std::vector<String>& GetArgvs() { return g_argvs; }
8439
8440#endif // GTEST_HAS_DEATH_TEST
8441
8442#if GTEST_OS_WINDOWS_MOBILE
8443namespace posix {
8444void Abort() {
8445 DebugBreak();
8446 TerminateProcess(GetCurrentProcess(), 1);
8447}
8448} // namespace posix
8449#endif // GTEST_OS_WINDOWS_MOBILE
8450
8451// Returns the name of the environment variable corresponding to the
8452// given flag. For example, FlagToEnvVar("foo") will return
8453// "GTEST_FOO" in the open-source version.
8454static String FlagToEnvVar(const char* flag) {
8455 const String full_flag =
8456 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8457
8458 Message env_var;
8459 for (size_t i = 0; i != full_flag.length(); i++) {
8460 env_var << ToUpper(full_flag.c_str()[i]);
8461 }
8462
8463 return env_var.GetString();
8464}
8465
8466// Parses 'str' for a 32-bit signed integer. If successful, writes
8467// the result to *value and returns true; otherwise leaves *value
8468// unchanged and returns false.
8469bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8470 // Parses the environment variable as a decimal integer.
8471 char* end = NULL;
8472 const long long_value = strtol(str, &end, 10); // NOLINT
8473
8474 // Has strtol() consumed all characters in the string?
8475 if (*end != '\0') {
8476 // No - an invalid character was encountered.
8477 Message msg;
8478 msg << "WARNING: " << src_text
8479 << " is expected to be a 32-bit integer, but actually"
8480 << " has value \"" << str << "\".\n";
8481 printf("%s", msg.GetString().c_str());
8482 fflush(stdout);
8483 return false;
8484 }
8485
8486 // Is the parsed value in the range of an Int32?
8487 const Int32 result = static_cast<Int32>(long_value);
8488 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8489 // The parsed value overflows as a long. (strtol() returns
8490 // LONG_MAX or LONG_MIN when the input overflows.)
8491 result != long_value
8492 // The parsed value overflows as an Int32.
8493 ) {
8494 Message msg;
8495 msg << "WARNING: " << src_text
8496 << " is expected to be a 32-bit integer, but actually"
8497 << " has value " << str << ", which overflows.\n";
8498 printf("%s", msg.GetString().c_str());
8499 fflush(stdout);
8500 return false;
8501 }
8502
8503 *value = result;
8504 return true;
8505}
8506
8507// Reads and returns the Boolean environment variable corresponding to
8508// the given flag; if it's not set, returns default_value.
8509//
8510// The value is considered true iff it's not "0".
8511bool BoolFromGTestEnv(const char* flag, bool default_value) {
8512 const String env_var = FlagToEnvVar(flag);
8513 const char* const string_value = posix::GetEnv(env_var.c_str());
8514 return string_value == NULL ?
8515 default_value : strcmp(string_value, "0") != 0;
8516}
8517
8518// Reads and returns a 32-bit integer stored in the environment
8519// variable corresponding to the given flag; if it isn't set or
8520// doesn't represent a valid 32-bit integer, returns default_value.
8521Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8522 const String env_var = FlagToEnvVar(flag);
8523 const char* const string_value = posix::GetEnv(env_var.c_str());
8524 if (string_value == NULL) {
8525 // The environment variable is not set.
8526 return default_value;
8527 }
8528
8529 Int32 result = default_value;
8530 if (!ParseInt32(Message() << "Environment variable " << env_var,
8531 string_value, &result)) {
8532 printf("The default value %s is used.\n",
8533 (Message() << default_value).GetString().c_str());
8534 fflush(stdout);
8535 return default_value;
8536 }
8537
8538 return result;
8539}
8540
8541// Reads and returns the string environment variable corresponding to
8542// the given flag; if it's not set, returns default_value.
8543const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8544 const String env_var = FlagToEnvVar(flag);
8545 const char* const value = posix::GetEnv(env_var.c_str());
8546 return value == NULL ? default_value : value;
8547}
8548
8549} // namespace internal
8550} // namespace testing
8551// Copyright 2007, Google Inc.
8552// All rights reserved.
8553//
8554// Redistribution and use in source and binary forms, with or without
8555// modification, are permitted provided that the following conditions are
8556// met:
8557//
8558// * Redistributions of source code must retain the above copyright
8559// notice, this list of conditions and the following disclaimer.
8560// * Redistributions in binary form must reproduce the above
8561// copyright notice, this list of conditions and the following disclaimer
8562// in the documentation and/or other materials provided with the
8563// distribution.
8564// * Neither the name of Google Inc. nor the names of its
8565// contributors may be used to endorse or promote products derived from
8566// this software without specific prior written permission.
8567//
8568// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8569// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8570// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8571// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8572// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8573// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8574// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8575// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8576// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8577// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8578// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8579//
8580// Author: wan@google.com (Zhanyong Wan)
8581
8582// Google Test - The Google C++ Testing Framework
8583//
8584// This file implements a universal value printer that can print a
8585// value of any type T:
8586//
8587// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8588//
8589// It uses the << operator when possible, and prints the bytes in the
8590// object otherwise. A user can override its behavior for a class
8591// type Foo by defining either operator<<(::std::ostream&, const Foo&)
8592// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8593// defines Foo.
8594
8595#include <ctype.h>
8596#include <stdio.h>
8597#include <ostream> // NOLINT
8598#include <string>
8599
8600namespace testing {
8601
8602namespace {
8603
8604using ::std::ostream;
8605
8606#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
8607# define snprintf _snprintf
8608#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
8609# define snprintf _snprintf_s
8610#elif _MSC_VER
8611# define snprintf _snprintf
8612#endif // GTEST_OS_WINDOWS_MOBILE
8613
8614// Prints a segment of bytes in the given object.
8615void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8616 size_t count, ostream* os) {
8617 char text[5] = "";
8618 for (size_t i = 0; i != count; i++) {
8619 const size_t j = start + i;
8620 if (i != 0) {
8621 // Organizes the bytes into groups of 2 for easy parsing by
8622 // human.
8623 if ((j % 2) == 0)
8624 *os << ' ';
8625 else
8626 *os << '-';
8627 }
8628 snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
8629 *os << text;
8630 }
8631}
8632
8633// Prints the bytes in the given value to the given ostream.
8634void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
8635 ostream* os) {
8636 // Tells the user how big the object is.
8637 *os << count << "-byte object <";
8638
8639 const size_t kThreshold = 132;
8640 const size_t kChunkSize = 64;
8641 // If the object size is bigger than kThreshold, we'll have to omit
8642 // some details by printing only the first and the last kChunkSize
8643 // bytes.
8644 // TODO(wan): let the user control the threshold using a flag.
8645 if (count < kThreshold) {
8646 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
8647 } else {
8648 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
8649 *os << " ... ";
8650 // Rounds up to 2-byte boundary.
8651 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
8652 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
8653 }
8654 *os << ">";
8655}
8656
8657} // namespace
8658
8659namespace internal2 {
8660
8661// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8662// given object. The delegation simplifies the implementation, which
8663// uses the << operator and thus is easier done outside of the
8664// ::testing::internal namespace, which contains a << operator that
8665// sometimes conflicts with the one in STL.
8666void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
8667 ostream* os) {
8668 PrintBytesInObjectToImpl(obj_bytes, count, os);
8669}
8670
8671} // namespace internal2
8672
8673namespace internal {
8674
8675// Depending on the value of a char (or wchar_t), we print it in one
8676// of three formats:
8677// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8678// - as a hexidecimal escape sequence (e.g. '\x7F'), or
8679// - as a special escape sequence (e.g. '\r', '\n').
8680enum CharFormat {
8681 kAsIs,
8682 kHexEscape,
8683 kSpecialEscape
8684};
8685
8686// Returns true if c is a printable ASCII character. We test the
8687// value of c directly instead of calling isprint(), which is buggy on
8688// Windows Mobile.
8689inline bool IsPrintableAscii(wchar_t c) {
8690 return 0x20 <= c && c <= 0x7E;
8691}
8692
8693// Prints a wide or narrow char c as a character literal without the
8694// quotes, escaping it when necessary; returns how c was formatted.
8695// The template argument UnsignedChar is the unsigned version of Char,
8696// which is the type of c.
8697template <typename UnsignedChar, typename Char>
8698static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
8699 switch (static_cast<wchar_t>(c)) {
8700 case L'\0':
8701 *os << "\\0";
8702 break;
8703 case L'\'':
8704 *os << "\\'";
8705 break;
8706 case L'\\':
8707 *os << "\\\\";
8708 break;
8709 case L'\a':
8710 *os << "\\a";
8711 break;
8712 case L'\b':
8713 *os << "\\b";
8714 break;
8715 case L'\f':
8716 *os << "\\f";
8717 break;
8718 case L'\n':
8719 *os << "\\n";
8720 break;
8721 case L'\r':
8722 *os << "\\r";
8723 break;
8724 case L'\t':
8725 *os << "\\t";
8726 break;
8727 case L'\v':
8728 *os << "\\v";
8729 break;
8730 default:
8731 if (IsPrintableAscii(c)) {
8732 *os << static_cast<char>(c);
8733 return kAsIs;
8734 } else {
8735 *os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
8736 return kHexEscape;
8737 }
8738 }
8739 return kSpecialEscape;
8740}
8741
8742// Prints a char c as if it's part of a string literal, escaping it when
8743// necessary; returns how c was formatted.
8744static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
8745 switch (c) {
8746 case L'\'':
8747 *os << "'";
8748 return kAsIs;
8749 case L'"':
8750 *os << "\\\"";
8751 return kSpecialEscape;
8752 default:
8753 return PrintAsCharLiteralTo<wchar_t>(c, os);
8754 }
8755}
8756
8757// Prints a char c as if it's part of a string literal, escaping it when
8758// necessary; returns how c was formatted.
8759static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
8760 return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
8761}
8762
8763// Prints a wide or narrow character c and its code. '\0' is printed
8764// as "'\\0'", other unprintable characters are also properly escaped
8765// using the standard C++ escape sequence. The template argument
8766// UnsignedChar is the unsigned version of Char, which is the type of c.
8767template <typename UnsignedChar, typename Char>
8768void PrintCharAndCodeTo(Char c, ostream* os) {
8769 // First, print c as a literal in the most readable form we can find.
8770 *os << ((sizeof(c) > 1) ? "L'" : "'");
8771 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
8772 *os << "'";
8773
8774 // To aid user debugging, we also print c's code in decimal, unless
8775 // it's 0 (in which case c was printed as '\\0', making the code
8776 // obvious).
8777 if (c == 0)
8778 return;
8779 *os << " (" << String::Format("%d", c).c_str();
8780
8781 // For more convenience, we print c's code again in hexidecimal,
8782 // unless c was already printed in the form '\x##' or the code is in
8783 // [1, 9].
8784 if (format == kHexEscape || (1 <= c && c <= 9)) {
8785 // Do nothing.
8786 } else {
8787 *os << String::Format(", 0x%X",
8788 static_cast<UnsignedChar>(c)).c_str();
8789 }
8790 *os << ")";
8791}
8792
8793void PrintTo(unsigned char c, ::std::ostream* os) {
8794 PrintCharAndCodeTo<unsigned char>(c, os);
8795}
8796void PrintTo(signed char c, ::std::ostream* os) {
8797 PrintCharAndCodeTo<unsigned char>(c, os);
8798}
8799
8800// Prints a wchar_t as a symbol if it is printable or as its internal
8801// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
8802void PrintTo(wchar_t wc, ostream* os) {
8803 PrintCharAndCodeTo<wchar_t>(wc, os);
8804}
8805
8806// Prints the given array of characters to the ostream.
8807// The array starts at *begin, the length is len, it may include '\0' characters
8808// and may not be null-terminated.
8809static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
8810 *os << "\"";
8811 bool is_previous_hex = false;
8812 for (size_t index = 0; index < len; ++index) {
8813 const char cur = begin[index];
8814 if (is_previous_hex && IsXDigit(cur)) {
8815 // Previous character is of '\x..' form and this character can be
8816 // interpreted as another hexadecimal digit in its number. Break string to
8817 // disambiguate.
8818 *os << "\" \"";
8819 }
8820 is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
8821 }
8822 *os << "\"";
8823}
8824
8825// Prints a (const) char array of 'len' elements, starting at address 'begin'.
8826void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
8827 PrintCharsAsStringTo(begin, len, os);
8828}
8829
8830// Prints the given array of wide characters to the ostream.
8831// The array starts at *begin, the length is len, it may include L'\0'
8832// characters and may not be null-terminated.
8833static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
8834 ostream* os) {
8835 *os << "L\"";
8836 bool is_previous_hex = false;
8837 for (size_t index = 0; index < len; ++index) {
8838 const wchar_t cur = begin[index];
8839 if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
8840 // Previous character is of '\x..' form and this character can be
8841 // interpreted as another hexadecimal digit in its number. Break string to
8842 // disambiguate.
8843 *os << "\" L\"";
8844 }
8845 is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
8846 }
8847 *os << "\"";
8848}
8849
8850// Prints the given C string to the ostream.
8851void PrintTo(const char* s, ostream* os) {
8852 if (s == NULL) {
8853 *os << "NULL";
8854 } else {
8855 *os << ImplicitCast_<const void*>(s) << " pointing to ";
8856 PrintCharsAsStringTo(s, strlen(s), os);
8857 }
8858}
8859
8860// MSVC compiler can be configured to define whar_t as a typedef
8861// of unsigned short. Defining an overload for const wchar_t* in that case
8862// would cause pointers to unsigned shorts be printed as wide strings,
8863// possibly accessing more memory than intended and causing invalid
8864// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
8865// wchar_t is implemented as a native type.
8866#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
8867// Prints the given wide C string to the ostream.
8868void PrintTo(const wchar_t* s, ostream* os) {
8869 if (s == NULL) {
8870 *os << "NULL";
8871 } else {
8872 *os << ImplicitCast_<const void*>(s) << " pointing to ";
8873 PrintWideCharsAsStringTo(s, wcslen(s), os);
8874 }
8875}
8876#endif // wchar_t is native
8877
8878// Prints a ::string object.
8879#if GTEST_HAS_GLOBAL_STRING
8880void PrintStringTo(const ::string& s, ostream* os) {
8881 PrintCharsAsStringTo(s.data(), s.size(), os);
8882}
8883#endif // GTEST_HAS_GLOBAL_STRING
8884
8885void PrintStringTo(const ::std::string& s, ostream* os) {
8886 PrintCharsAsStringTo(s.data(), s.size(), os);
8887}
8888
8889// Prints a ::wstring object.
8890#if GTEST_HAS_GLOBAL_WSTRING
8891void PrintWideStringTo(const ::wstring& s, ostream* os) {
8892 PrintWideCharsAsStringTo(s.data(), s.size(), os);
8893}
8894#endif // GTEST_HAS_GLOBAL_WSTRING
8895
8896#if GTEST_HAS_STD_WSTRING
8897void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
8898 PrintWideCharsAsStringTo(s.data(), s.size(), os);
8899}
8900#endif // GTEST_HAS_STD_WSTRING
8901
8902} // namespace internal
8903
8904} // namespace testing
8905// Copyright 2008, Google Inc.
8906// All rights reserved.
8907//
8908// Redistribution and use in source and binary forms, with or without
8909// modification, are permitted provided that the following conditions are
8910// met:
8911//
8912// * Redistributions of source code must retain the above copyright
8913// notice, this list of conditions and the following disclaimer.
8914// * Redistributions in binary form must reproduce the above
8915// copyright notice, this list of conditions and the following disclaimer
8916// in the documentation and/or other materials provided with the
8917// distribution.
8918// * Neither the name of Google Inc. nor the names of its
8919// contributors may be used to endorse or promote products derived from
8920// this software without specific prior written permission.
8921//
8922// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8923// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8924// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8925// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8926// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8927// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8928// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8929// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8930// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8931// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8932// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8933//
8934// Author: mheule@google.com (Markus Heule)
8935//
8936// The Google C++ Testing Framework (Google Test)
8937
8938
8939// Indicates that this translation unit is part of Google Test's
8940// implementation. It must come before gtest-internal-inl.h is
8941// included, or there will be a compiler error. This trick is to
8942// prevent a user from accidentally including gtest-internal-inl.h in
8943// his code.
8944#define GTEST_IMPLEMENTATION_ 1
8945#undef GTEST_IMPLEMENTATION_
8946
8947namespace testing {
8948
8949using internal::GetUnitTestImpl;
8950
8951// Gets the summary of the failure message by omitting the stack trace
8952// in it.
8953internal::String TestPartResult::ExtractSummary(const char* message) {
8954 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
8955 return stack_trace == NULL ? internal::String(message) :
8956 internal::String(message, stack_trace - message);
8957}
8958
8959// Prints a TestPartResult object.
8960std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
8961 return os
8962 << result.file_name() << ":" << result.line_number() << ": "
8963 << (result.type() == TestPartResult::kSuccess ? "Success" :
8964 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
8965 "Non-fatal failure") << ":\n"
8966 << result.message() << std::endl;
8967}
8968
8969// Appends a TestPartResult to the array.
8970void TestPartResultArray::Append(const TestPartResult& result) {
8971 array_.push_back(result);
8972}
8973
8974// Returns the TestPartResult at the given index (0-based).
8975const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
8976 if (index < 0 || index >= size()) {
8977 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
8978 internal::posix::Abort();
8979 }
8980
8981 return array_[index];
8982}
8983
8984// Returns the number of TestPartResult objects in the array.
8985int TestPartResultArray::size() const {
8986 return static_cast<int>(array_.size());
8987}
8988
8989namespace internal {
8990
8991HasNewFatalFailureHelper::HasNewFatalFailureHelper()
8992 : has_new_fatal_failure_(false),
8993 original_reporter_(GetUnitTestImpl()->
8994 GetTestPartResultReporterForCurrentThread()) {
8995 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
8996}
8997
8998HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
8999 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9000 original_reporter_);
9001}
9002
9003void HasNewFatalFailureHelper::ReportTestPartResult(
9004 const TestPartResult& result) {
9005 if (result.fatally_failed())
9006 has_new_fatal_failure_ = true;
9007 original_reporter_->ReportTestPartResult(result);
9008}
9009
9010} // namespace internal
9011
9012} // namespace testing
9013// Copyright 2008 Google Inc.
9014// All Rights Reserved.
9015//
9016// Redistribution and use in source and binary forms, with or without
9017// modification, are permitted provided that the following conditions are
9018// met:
9019//
9020// * Redistributions of source code must retain the above copyright
9021// notice, this list of conditions and the following disclaimer.
9022// * Redistributions in binary form must reproduce the above
9023// copyright notice, this list of conditions and the following disclaimer
9024// in the documentation and/or other materials provided with the
9025// distribution.
9026// * Neither the name of Google Inc. nor the names of its
9027// contributors may be used to endorse or promote products derived from
9028// this software without specific prior written permission.
9029//
9030// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9031// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9032// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9033// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9034// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9035// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9036// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9037// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9038// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9039// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9040// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9041//
9042// Author: wan@google.com (Zhanyong Wan)
9043
9044
9045namespace testing {
9046namespace internal {
9047
9048#if GTEST_HAS_TYPED_TEST_P
9049
9050// Skips to the first non-space char in str. Returns an empty string if str
9051// contains only whitespace characters.
9052static const char* SkipSpaces(const char* str) {
9053 while (IsSpace(*str))
9054 str++;
9055 return str;
9056}
9057
9058// Verifies that registered_tests match the test names in
9059// defined_test_names_; returns registered_tests if successful, or
9060// aborts the program otherwise.
9061const char* TypedTestCasePState::VerifyRegisteredTestNames(
9062 const char* file, int line, const char* registered_tests) {
9063 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9064 registered_ = true;
9065
9066 // Skip initial whitespace in registered_tests since some
9067 // preprocessors prefix stringizied literals with whitespace.
9068 registered_tests = SkipSpaces(registered_tests);
9069
9070 Message errors;
9071 ::std::set<String> tests;
9072 for (const char* names = registered_tests; names != NULL;
9073 names = SkipComma(names)) {
9074 const String name = GetPrefixUntilComma(names);
9075 if (tests.count(name) != 0) {
9076 errors << "Test " << name << " is listed more than once.\n";
9077 continue;
9078 }
9079
9080 bool found = false;
9081 for (DefinedTestIter it = defined_test_names_.begin();
9082 it != defined_test_names_.end();
9083 ++it) {
9084 if (name == *it) {
9085 found = true;
9086 break;
9087 }
9088 }
9089
9090 if (found) {
9091 tests.insert(name);
9092 } else {
9093 errors << "No test named " << name
9094 << " can be found in this test case.\n";
9095 }
9096 }
9097
9098 for (DefinedTestIter it = defined_test_names_.begin();
9099 it != defined_test_names_.end();
9100 ++it) {
9101 if (tests.count(*it) == 0) {
9102 errors << "You forgot to list test " << *it << ".\n";
9103 }
9104 }
9105
9106 const String& errors_str = errors.GetString();
9107 if (errors_str != "") {
9108 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9109 errors_str.c_str());
9110 fflush(stderr);
9111 posix::Abort();
9112 }
9113
9114 return registered_tests;
9115}
9116
9117#endif // GTEST_HAS_TYPED_TEST_P
9118
9119} // namespace internal
9120} // namespace testing
9121// Copyright 2008, Google Inc.
9122// All rights reserved.
9123//
9124// Redistribution and use in source and binary forms, with or without
9125// modification, are permitted provided that the following conditions are
9126// met:
9127//
9128// * Redistributions of source code must retain the above copyright
9129// notice, this list of conditions and the following disclaimer.
9130// * Redistributions in binary form must reproduce the above
9131// copyright notice, this list of conditions and the following disclaimer
9132// in the documentation and/or other materials provided with the
9133// distribution.
9134// * Neither the name of Google Inc. nor the names of its
9135// contributors may be used to endorse or promote products derived from
9136// this software without specific prior written permission.
9137//
9138// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9139// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9140// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9141// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9142// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9143// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9144// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9145// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9146// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9147// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9148// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9149//
9150// Author: wan@google.com (Zhanyong Wan)
9151//
9152// Google C++ Mocking Framework (Google Mock)
9153//
9154// This file #includes all Google Mock implementation .cc files. The
9155// purpose is to allow a user to build Google Mock by compiling this
9156// file alone.
9157
9158// This line ensures that gmock.h can be compiled on its own, even
9159// when it's fused.
9160#include "gmock/gmock.h"
9161
9162// The following lines pull in the real gmock *.cc files.
9163// Copyright 2007, Google Inc.
9164// All rights reserved.
9165//
9166// Redistribution and use in source and binary forms, with or without
9167// modification, are permitted provided that the following conditions are
9168// met:
9169//
9170// * Redistributions of source code must retain the above copyright
9171// notice, this list of conditions and the following disclaimer.
9172// * Redistributions in binary form must reproduce the above
9173// copyright notice, this list of conditions and the following disclaimer
9174// in the documentation and/or other materials provided with the
9175// distribution.
9176// * Neither the name of Google Inc. nor the names of its
9177// contributors may be used to endorse or promote products derived from
9178// this software without specific prior written permission.
9179//
9180// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9181// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9182// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9183// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9184// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9185// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9186// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9187// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9188// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9189// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9190// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9191//
9192// Author: wan@google.com (Zhanyong Wan)
9193
9194// Google Mock - a framework for writing C++ mock classes.
9195//
9196// This file implements cardinalities.
9197
9198
9199#include <limits.h>
9200#include <ostream> // NOLINT
9201#include <sstream>
9202#include <string>
9203
9204namespace testing {
9205
9206namespace {
9207
9208// Implements the Between(m, n) cardinality.
9209class BetweenCardinalityImpl : public CardinalityInterface {
9210 public:
9211 BetweenCardinalityImpl(int min, int max)
9212 : min_(min >= 0 ? min : 0),
9213 max_(max >= min_ ? max : min_) {
9214 std::stringstream ss;
9215 if (min < 0) {
9216 ss << "The invocation lower bound must be >= 0, "
9217 << "but is actually " << min << ".";
9218 internal::Expect(false, __FILE__, __LINE__, ss.str());
9219 } else if (max < 0) {
9220 ss << "The invocation upper bound must be >= 0, "
9221 << "but is actually " << max << ".";
9222 internal::Expect(false, __FILE__, __LINE__, ss.str());
9223 } else if (min > max) {
9224 ss << "The invocation upper bound (" << max
9225 << ") must be >= the invocation lower bound (" << min
9226 << ").";
9227 internal::Expect(false, __FILE__, __LINE__, ss.str());
9228 }
9229 }
9230
9231 // Conservative estimate on the lower/upper bound of the number of
9232 // calls allowed.
9233 virtual int ConservativeLowerBound() const { return min_; }
9234 virtual int ConservativeUpperBound() const { return max_; }
9235
9236 virtual bool IsSatisfiedByCallCount(int call_count) const {
9237 return min_ <= call_count && call_count <= max_ ;
9238 }
9239
9240 virtual bool IsSaturatedByCallCount(int call_count) const {
9241 return call_count >= max_;
9242 }
9243
9244 virtual void DescribeTo(::std::ostream* os) const;
9245 private:
9246 const int min_;
9247 const int max_;
9248
9249 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
9250};
9251
9252// Formats "n times" in a human-friendly way.
9253inline internal::string FormatTimes(int n) {
9254 if (n == 1) {
9255 return "once";
9256 } else if (n == 2) {
9257 return "twice";
9258 } else {
9259 std::stringstream ss;
9260 ss << n << " times";
9261 return ss.str();
9262 }
9263}
9264
9265// Describes the Between(m, n) cardinality in human-friendly text.
9266void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
9267 if (min_ == 0) {
9268 if (max_ == 0) {
9269 *os << "never called";
9270 } else if (max_ == INT_MAX) {
9271 *os << "called any number of times";
9272 } else {
9273 *os << "called at most " << FormatTimes(max_);
9274 }
9275 } else if (min_ == max_) {
9276 *os << "called " << FormatTimes(min_);
9277 } else if (max_ == INT_MAX) {
9278 *os << "called at least " << FormatTimes(min_);
9279 } else {
9280 // 0 < min_ < max_ < INT_MAX
9281 *os << "called between " << min_ << " and " << max_ << " times";
9282 }
9283}
9284
9285} // Unnamed namespace
9286
9287// Describes the given call count to an ostream.
9288void Cardinality::DescribeActualCallCountTo(int actual_call_count,
9289 ::std::ostream* os) {
9290 if (actual_call_count > 0) {
9291 *os << "called " << FormatTimes(actual_call_count);
9292 } else {
9293 *os << "never called";
9294 }
9295}
9296
9297// Creates a cardinality that allows at least n calls.
9298Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
9299
9300// Creates a cardinality that allows at most n calls.
9301Cardinality AtMost(int n) { return Between(0, n); }
9302
9303// Creates a cardinality that allows any number of calls.
9304Cardinality AnyNumber() { return AtLeast(0); }
9305
9306// Creates a cardinality that allows between min and max calls.
9307Cardinality Between(int min, int max) {
9308 return Cardinality(new BetweenCardinalityImpl(min, max));
9309}
9310
9311// Creates a cardinality that allows exactly n calls.
9312Cardinality Exactly(int n) { return Between(n, n); }
9313
9314} // namespace testing
9315// Copyright 2007, Google Inc.
9316// All rights reserved.
9317//
9318// Redistribution and use in source and binary forms, with or without
9319// modification, are permitted provided that the following conditions are
9320// met:
9321//
9322// * Redistributions of source code must retain the above copyright
9323// notice, this list of conditions and the following disclaimer.
9324// * Redistributions in binary form must reproduce the above
9325// copyright notice, this list of conditions and the following disclaimer
9326// in the documentation and/or other materials provided with the
9327// distribution.
9328// * Neither the name of Google Inc. nor the names of its
9329// contributors may be used to endorse or promote products derived from
9330// this software without specific prior written permission.
9331//
9332// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9333// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9334// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9335// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9336// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9337// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9338// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9339// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9340// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9341// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9342// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9343//
9344// Author: wan@google.com (Zhanyong Wan)
9345
9346// Google Mock - a framework for writing C++ mock classes.
9347//
9348// This file defines some utilities useful for implementing Google
9349// Mock. They are subject to change without notice, so please DO NOT
9350// USE THEM IN USER CODE.
9351
9352
9353#include <ctype.h>
9354#include <ostream> // NOLINT
9355#include <string>
9356
9357namespace testing {
9358namespace internal {
9359
9360// Converts an identifier name to a space-separated list of lower-case
9361// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9362// treated as one word. For example, both "FooBar123" and
9363// "foo_bar_123" are converted to "foo bar 123".
9364string ConvertIdentifierNameToWords(const char* id_name) {
9365 string result;
9366 char prev_char = '\0';
9367 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
9368 // We don't care about the current locale as the input is
9369 // guaranteed to be a valid C++ identifier name.
9370 const bool starts_new_word = IsUpper(*p) ||
9371 (!IsAlpha(prev_char) && IsLower(*p)) ||
9372 (!IsDigit(prev_char) && IsDigit(*p));
9373
9374 if (IsAlNum(*p)) {
9375 if (starts_new_word && result != "")
9376 result += ' ';
9377 result += ToLower(*p);
9378 }
9379 }
9380 return result;
9381}
9382
9383// This class reports Google Mock failures as Google Test failures. A
9384// user can define another class in a similar fashion if he intends to
9385// use Google Mock with a testing framework other than Google Test.
9386class GoogleTestFailureReporter : public FailureReporterInterface {
9387 public:
9388 virtual void ReportFailure(FailureType type, const char* file, int line,
9389 const string& message) {
9390 AssertHelper(type == FATAL ?
9391 TestPartResult::kFatalFailure :
9392 TestPartResult::kNonFatalFailure,
9393 file,
9394 line,
9395 message.c_str()) = Message();
9396 if (type == FATAL) {
9397 posix::Abort();
9398 }
9399 }
9400};
9401
9402// Returns the global failure reporter. Will create a
9403// GoogleTestFailureReporter and return it the first time called.
9404FailureReporterInterface* GetFailureReporter() {
9405 // Points to the global failure reporter used by Google Mock. gcc
9406 // guarantees that the following use of failure_reporter is
9407 // thread-safe. We may need to add additional synchronization to
9408 // protect failure_reporter if we port Google Mock to other
9409 // compilers.
9410 static FailureReporterInterface* const failure_reporter =
9411 new GoogleTestFailureReporter();
9412 return failure_reporter;
9413}
9414
9415// Protects global resources (stdout in particular) used by Log().
9416static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
9417
9418// Returns true iff a log with the given severity is visible according
9419// to the --gmock_verbose flag.
9420bool LogIsVisible(LogSeverity severity) {
9421 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
9422 // Always show the log if --gmock_verbose=info.
9423 return true;
9424 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
9425 // Always hide it if --gmock_verbose=error.
9426 return false;
9427 } else {
9428 // If --gmock_verbose is neither "info" nor "error", we treat it
9429 // as "warning" (its default value).
9430 return severity == WARNING;
9431 }
9432}
9433
9434// Prints the given message to stdout iff 'severity' >= the level
9435// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
9436// 0, also prints the stack trace excluding the top
9437// stack_frames_to_skip frames. In opt mode, any positive
9438// stack_frames_to_skip is treated as 0, since we don't know which
9439// function calls will be inlined by the compiler and need to be
9440// conservative.
9441void Log(LogSeverity severity, const string& message,
9442 int stack_frames_to_skip) {
9443 if (!LogIsVisible(severity))
9444 return;
9445
9446 // Ensures that logs from different threads don't interleave.
9447 MutexLock l(&g_log_mutex);
9448
9449 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9450 // macro.
9451
9452 if (severity == WARNING) {
9453 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9454 std::cout << "\nGMOCK WARNING:";
9455 }
9456 // Pre-pends a new-line to message if it doesn't start with one.
9457 if (message.empty() || message[0] != '\n') {
9458 std::cout << "\n";
9459 }
9460 std::cout << message;
9461 if (stack_frames_to_skip >= 0) {
9462#ifdef NDEBUG
9463 // In opt mode, we have to be conservative and skip no stack frame.
9464 const int actual_to_skip = 0;
9465#else
9466 // In dbg mode, we can do what the caller tell us to do (plus one
9467 // for skipping this function's stack frame).
9468 const int actual_to_skip = stack_frames_to_skip + 1;
9469#endif // NDEBUG
9470
9471 // Appends a new-line to message if it doesn't end with one.
9472 if (!message.empty() && *message.rbegin() != '\n') {
9473 std::cout << "\n";
9474 }
9475 std::cout << "Stack trace:\n"
9476 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
9477 ::testing::UnitTest::GetInstance(), actual_to_skip);
9478 }
9479 std::cout << ::std::flush;
9480}
9481
9482} // namespace internal
9483} // namespace testing
9484// Copyright 2007, Google Inc.
9485// All rights reserved.
9486//
9487// Redistribution and use in source and binary forms, with or without
9488// modification, are permitted provided that the following conditions are
9489// met:
9490//
9491// * Redistributions of source code must retain the above copyright
9492// notice, this list of conditions and the following disclaimer.
9493// * Redistributions in binary form must reproduce the above
9494// copyright notice, this list of conditions and the following disclaimer
9495// in the documentation and/or other materials provided with the
9496// distribution.
9497// * Neither the name of Google Inc. nor the names of its
9498// contributors may be used to endorse or promote products derived from
9499// this software without specific prior written permission.
9500//
9501// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9502// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9503// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9504// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9505// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9506// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9507// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9508// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9509// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9510// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9511// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9512//
9513// Author: wan@google.com (Zhanyong Wan)
9514
9515// Google Mock - a framework for writing C++ mock classes.
9516//
9517// This file implements Matcher<const string&>, Matcher<string>, and
9518// utilities for defining matchers.
9519
9520
9521#include <string.h>
9522#include <sstream>
9523#include <string>
9524
9525namespace testing {
9526
9527// Constructs a matcher that matches a const string& whose value is
9528// equal to s.
9529Matcher<const internal::string&>::Matcher(const internal::string& s) {
9530 *this = Eq(s);
9531}
9532
9533// Constructs a matcher that matches a const string& whose value is
9534// equal to s.
9535Matcher<const internal::string&>::Matcher(const char* s) {
9536 *this = Eq(internal::string(s));
9537}
9538
9539// Constructs a matcher that matches a string whose value is equal to s.
9540Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
9541
9542// Constructs a matcher that matches a string whose value is equal to s.
9543Matcher<internal::string>::Matcher(const char* s) {
9544 *this = Eq(internal::string(s));
9545}
9546
9547namespace internal {
9548
9549// Joins a vector of strings as if they are fields of a tuple; returns
9550// the joined string.
9551string JoinAsTuple(const Strings& fields) {
9552 switch (fields.size()) {
9553 case 0:
9554 return "";
9555 case 1:
9556 return fields[0];
9557 default:
9558 string result = "(" + fields[0];
9559 for (size_t i = 1; i < fields.size(); i++) {
9560 result += ", ";
9561 result += fields[i];
9562 }
9563 result += ")";
9564 return result;
9565 }
9566}
9567
9568// Returns the description for a matcher defined using the MATCHER*()
9569// macro where the user-supplied description string is "", if
9570// 'negation' is false; otherwise returns the description of the
9571// negation of the matcher. 'param_values' contains a list of strings
9572// that are the print-out of the matcher's parameters.
9573string FormatMatcherDescription(bool negation, const char* matcher_name,
9574 const Strings& param_values) {
9575 string result = ConvertIdentifierNameToWords(matcher_name);
9576 if (param_values.size() >= 1)
9577 result += " " + JoinAsTuple(param_values);
9578 return negation ? "not (" + result + ")" : result;
9579}
9580
9581} // namespace internal
9582} // namespace testing
9583// Copyright 2007, Google Inc.
9584// All rights reserved.
9585//
9586// Redistribution and use in source and binary forms, with or without
9587// modification, are permitted provided that the following conditions are
9588// met:
9589//
9590// * Redistributions of source code must retain the above copyright
9591// notice, this list of conditions and the following disclaimer.
9592// * Redistributions in binary form must reproduce the above
9593// copyright notice, this list of conditions and the following disclaimer
9594// in the documentation and/or other materials provided with the
9595// distribution.
9596// * Neither the name of Google Inc. nor the names of its
9597// contributors may be used to endorse or promote products derived from
9598// this software without specific prior written permission.
9599//
9600// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9601// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9602// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9603// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9604// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9605// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9606// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9607// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9608// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9609// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9610// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9611//
9612// Author: wan@google.com (Zhanyong Wan)
9613
9614// Google Mock - a framework for writing C++ mock classes.
9615//
9616// This file implements the spec builder syntax (ON_CALL and
9617// EXPECT_CALL).
9618
9619
9620#include <stdlib.h>
9621#include <iostream> // NOLINT
9622#include <map>
9623#include <set>
9624#include <string>
9625
9626#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
9627# include <unistd.h> // NOLINT
9628#endif
9629
9630namespace testing {
9631namespace internal {
9632
9633// Protects the mock object registry (in class Mock), all function
9634// mockers, and all expectations.
9635GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
9636
9637// Logs a message including file and line number information.
9638void LogWithLocation(testing::internal::LogSeverity severity,
9639 const char* file, int line,
9640 const string& message) {
9641 ::std::ostringstream s;
9642 s << file << ":" << line << ": " << message << ::std::endl;
9643 Log(severity, s.str(), 0);
9644}
9645
9646// Constructs an ExpectationBase object.
9647ExpectationBase::ExpectationBase(const char* a_file,
9648 int a_line,
9649 const string& a_source_text)
9650 : file_(a_file),
9651 line_(a_line),
9652 source_text_(a_source_text),
9653 cardinality_specified_(false),
9654 cardinality_(Exactly(1)),
9655 call_count_(0),
9656 retired_(false),
9657 extra_matcher_specified_(false),
9658 repeated_action_specified_(false),
9659 retires_on_saturation_(false),
9660 last_clause_(kNone),
9661 action_count_checked_(false) {}
9662
9663// Destructs an ExpectationBase object.
9664ExpectationBase::~ExpectationBase() {}
9665
9666// Explicitly specifies the cardinality of this expectation. Used by
9667// the subclasses to implement the .Times() clause.
9668void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
9669 cardinality_specified_ = true;
9670 cardinality_ = a_cardinality;
9671}
9672
9673// Retires all pre-requisites of this expectation.
9674void ExpectationBase::RetireAllPreRequisites() {
9675 if (is_retired()) {
9676 // We can take this short-cut as we never retire an expectation
9677 // until we have retired all its pre-requisites.
9678 return;
9679 }
9680
9681 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
9682 it != immediate_prerequisites_.end(); ++it) {
9683 ExpectationBase* const prerequisite = it->expectation_base().get();
9684 if (!prerequisite->is_retired()) {
9685 prerequisite->RetireAllPreRequisites();
9686 prerequisite->Retire();
9687 }
9688 }
9689}
9690
9691// Returns true iff all pre-requisites of this expectation have been
9692// satisfied.
9693// L >= g_gmock_mutex
9694bool ExpectationBase::AllPrerequisitesAreSatisfied() const {
9695 g_gmock_mutex.AssertHeld();
9696 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
9697 it != immediate_prerequisites_.end(); ++it) {
9698 if (!(it->expectation_base()->IsSatisfied()) ||
9699 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
9700 return false;
9701 }
9702 return true;
9703}
9704
9705// Adds unsatisfied pre-requisites of this expectation to 'result'.
9706// L >= g_gmock_mutex
9707void ExpectationBase::FindUnsatisfiedPrerequisites(
9708 ExpectationSet* result) const {
9709 g_gmock_mutex.AssertHeld();
9710 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
9711 it != immediate_prerequisites_.end(); ++it) {
9712 if (it->expectation_base()->IsSatisfied()) {
9713 // If *it is satisfied and has a call count of 0, some of its
9714 // pre-requisites may not be satisfied yet.
9715 if (it->expectation_base()->call_count_ == 0) {
9716 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
9717 }
9718 } else {
9719 // Now that we know *it is unsatisfied, we are not so interested
9720 // in whether its pre-requisites are satisfied. Therefore we
9721 // don't recursively call FindUnsatisfiedPrerequisites() here.
9722 *result += *it;
9723 }
9724 }
9725}
9726
9727// Describes how many times a function call matching this
9728// expectation has occurred.
9729// L >= g_gmock_mutex
9730void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const {
9731 g_gmock_mutex.AssertHeld();
9732
9733 // Describes how many times the function is expected to be called.
9734 *os << " Expected: to be ";
9735 cardinality().DescribeTo(os);
9736 *os << "\n Actual: ";
9737 Cardinality::DescribeActualCallCountTo(call_count(), os);
9738
9739 // Describes the state of the expectation (e.g. is it satisfied?
9740 // is it active?).
9741 *os << " - " << (IsOverSaturated() ? "over-saturated" :
9742 IsSaturated() ? "saturated" :
9743 IsSatisfied() ? "satisfied" : "unsatisfied")
9744 << " and "
9745 << (is_retired() ? "retired" : "active");
9746}
9747
9748// Checks the action count (i.e. the number of WillOnce() and
9749// WillRepeatedly() clauses) against the cardinality if this hasn't
9750// been done before. Prints a warning if there are too many or too
9751// few actions.
9752// L < mutex_
9753void ExpectationBase::CheckActionCountIfNotDone() const {
9754 bool should_check = false;
9755 {
9756 MutexLock l(&mutex_);
9757 if (!action_count_checked_) {
9758 action_count_checked_ = true;
9759 should_check = true;
9760 }
9761 }
9762
9763 if (should_check) {
9764 if (!cardinality_specified_) {
9765 // The cardinality was inferred - no need to check the action
9766 // count against it.
9767 return;
9768 }
9769
9770 // The cardinality was explicitly specified.
9771 const int action_count = static_cast<int>(untyped_actions_.size());
9772 const int upper_bound = cardinality().ConservativeUpperBound();
9773 const int lower_bound = cardinality().ConservativeLowerBound();
9774 bool too_many; // True if there are too many actions, or false
9775 // if there are too few.
9776 if (action_count > upper_bound ||
9777 (action_count == upper_bound && repeated_action_specified_)) {
9778 too_many = true;
9779 } else if (0 < action_count && action_count < lower_bound &&
9780 !repeated_action_specified_) {
9781 too_many = false;
9782 } else {
9783 return;
9784 }
9785
9786 ::std::stringstream ss;
9787 DescribeLocationTo(&ss);
9788 ss << "Too " << (too_many ? "many" : "few")
9789 << " actions specified in " << source_text() << "...\n"
9790 << "Expected to be ";
9791 cardinality().DescribeTo(&ss);
9792 ss << ", but has " << (too_many ? "" : "only ")
9793 << action_count << " WillOnce()"
9794 << (action_count == 1 ? "" : "s");
9795 if (repeated_action_specified_) {
9796 ss << " and a WillRepeatedly()";
9797 }
9798 ss << ".";
9799 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
9800 }
9801}
9802
9803// Implements the .Times() clause.
9804void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
9805 if (last_clause_ == kTimes) {
9806 ExpectSpecProperty(false,
9807 ".Times() cannot appear "
9808 "more than once in an EXPECT_CALL().");
9809 } else {
9810 ExpectSpecProperty(last_clause_ < kTimes,
9811 ".Times() cannot appear after "
9812 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
9813 "or .RetiresOnSaturation().");
9814 }
9815 last_clause_ = kTimes;
9816
9817 SpecifyCardinality(a_cardinality);
9818}
9819
9820// Points to the implicit sequence introduced by a living InSequence
9821// object (if any) in the current thread or NULL.
9822ThreadLocal<Sequence*> g_gmock_implicit_sequence;
9823
9824// Reports an uninteresting call (whose description is in msg) in the
9825// manner specified by 'reaction'.
9826void ReportUninterestingCall(CallReaction reaction, const string& msg) {
9827 switch (reaction) {
9828 case ALLOW:
9829 Log(INFO, msg, 3);
9830 break;
9831 case WARN:
9832 Log(WARNING, msg, 3);
9833 break;
9834 default: // FAIL
9835 Expect(false, NULL, -1, msg);
9836 }
9837}
9838
9839UntypedFunctionMockerBase::UntypedFunctionMockerBase()
9840 : mock_obj_(NULL), name_("") {}
9841
9842UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
9843
9844// Sets the mock object this mock method belongs to, and registers
9845// this information in the global mock registry. Will be called
9846// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
9847// method.
9848// L < g_gmock_mutex
9849void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) {
9850 {
9851 MutexLock l(&g_gmock_mutex);
9852 mock_obj_ = mock_obj;
9853 }
9854 Mock::Register(mock_obj, this);
9855}
9856
9857// Sets the mock object this mock method belongs to, and sets the name
9858// of the mock function. Will be called upon each invocation of this
9859// mock function.
9860// L < g_gmock_mutex
9861void UntypedFunctionMockerBase::SetOwnerAndName(
9862 const void* mock_obj, const char* name) {
9863 // We protect name_ under g_gmock_mutex in case this mock function
9864 // is called from two threads concurrently.
9865 MutexLock l(&g_gmock_mutex);
9866 mock_obj_ = mock_obj;
9867 name_ = name;
9868}
9869
9870// Returns the name of the function being mocked. Must be called
9871// after RegisterOwner() or SetOwnerAndName() has been called.
9872// L < g_gmock_mutex
9873const void* UntypedFunctionMockerBase::MockObject() const {
9874 const void* mock_obj;
9875 {
9876 // We protect mock_obj_ under g_gmock_mutex in case this mock
9877 // function is called from two threads concurrently.
9878 MutexLock l(&g_gmock_mutex);
9879 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
9880 "MockObject() must not be called before RegisterOwner() or "
9881 "SetOwnerAndName() has been called.");
9882 mock_obj = mock_obj_;
9883 }
9884 return mock_obj;
9885}
9886
9887// Returns the name of this mock method. Must be called after
9888// SetOwnerAndName() has been called.
9889// L < g_gmock_mutex
9890const char* UntypedFunctionMockerBase::Name() const {
9891 const char* name;
9892 {
9893 // We protect name_ under g_gmock_mutex in case this mock
9894 // function is called from two threads concurrently.
9895 MutexLock l(&g_gmock_mutex);
9896 Assert(name_ != NULL, __FILE__, __LINE__,
9897 "Name() must not be called before SetOwnerAndName() has "
9898 "been called.");
9899 name = name_;
9900 }
9901 return name;
9902}
9903
9904// Calculates the result of invoking this mock function with the given
9905// arguments, prints it, and returns it. The caller is responsible
9906// for deleting the result.
9907// L < g_gmock_mutex
9908const UntypedActionResultHolderBase*
9909UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
9910 if (untyped_expectations_.size() == 0) {
9911 // No expectation is set on this mock method - we have an
9912 // uninteresting call.
9913
9914 // We must get Google Mock's reaction on uninteresting calls
9915 // made on this mock object BEFORE performing the action,
9916 // because the action may DELETE the mock object and make the
9917 // following expression meaningless.
9918 const CallReaction reaction =
9919 Mock::GetReactionOnUninterestingCalls(MockObject());
9920
9921 // True iff we need to print this call's arguments and return
9922 // value. This definition must be kept in sync with
9923 // the behavior of ReportUninterestingCall().
9924 const bool need_to_report_uninteresting_call =
9925 // If the user allows this uninteresting call, we print it
9926 // only when he wants informational messages.
9927 reaction == ALLOW ? LogIsVisible(INFO) :
9928 // If the user wants this to be a warning, we print it only
9929 // when he wants to see warnings.
9930 reaction == WARN ? LogIsVisible(WARNING) :
9931 // Otherwise, the user wants this to be an error, and we
9932 // should always print detailed information in the error.
9933 true;
9934
9935 if (!need_to_report_uninteresting_call) {
9936 // Perform the action without printing the call information.
9937 return this->UntypedPerformDefaultAction(untyped_args, "");
9938 }
9939
9940 // Warns about the uninteresting call.
9941 ::std::stringstream ss;
9942 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
9943
9944 // Calculates the function result.
9945 const UntypedActionResultHolderBase* const result =
9946 this->UntypedPerformDefaultAction(untyped_args, ss.str());
9947
9948 // Prints the function result.
9949 if (result != NULL)
9950 result->PrintAsActionResult(&ss);
9951
9952 ReportUninterestingCall(reaction, ss.str());
9953 return result;
9954 }
9955
9956 bool is_excessive = false;
9957 ::std::stringstream ss;
9958 ::std::stringstream why;
9959 ::std::stringstream loc;
9960 const void* untyped_action = NULL;
9961
9962 // The UntypedFindMatchingExpectation() function acquires and
9963 // releases g_gmock_mutex.
9964 const ExpectationBase* const untyped_expectation =
9965 this->UntypedFindMatchingExpectation(
9966 untyped_args, &untyped_action, &is_excessive,
9967 &ss, &why);
9968 const bool found = untyped_expectation != NULL;
9969
9970 // True iff we need to print the call's arguments and return value.
9971 // This definition must be kept in sync with the uses of Expect()
9972 // and Log() in this function.
9973 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
9974 if (!need_to_report_call) {
9975 // Perform the action without printing the call information.
9976 return
9977 untyped_action == NULL ?
9978 this->UntypedPerformDefaultAction(untyped_args, "") :
9979 this->UntypedPerformAction(untyped_action, untyped_args);
9980 }
9981
9982 ss << " Function call: " << Name();
9983 this->UntypedPrintArgs(untyped_args, &ss);
9984
9985 // In case the action deletes a piece of the expectation, we
9986 // generate the message beforehand.
9987 if (found && !is_excessive) {
9988 untyped_expectation->DescribeLocationTo(&loc);
9989 }
9990
9991 const UntypedActionResultHolderBase* const result =
9992 untyped_action == NULL ?
9993 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
9994 this->UntypedPerformAction(untyped_action, untyped_args);
9995 if (result != NULL)
9996 result->PrintAsActionResult(&ss);
9997 ss << "\n" << why.str();
9998
9999 if (!found) {
10000 // No expectation matches this call - reports a failure.
10001 Expect(false, NULL, -1, ss.str());
10002 } else if (is_excessive) {
10003 // We had an upper-bound violation and the failure message is in ss.
10004 Expect(false, untyped_expectation->file(),
10005 untyped_expectation->line(), ss.str());
10006 } else {
10007 // We had an expected call and the matching expectation is
10008 // described in ss.
10009 Log(INFO, loc.str() + ss.str(), 2);
10010 }
10011
10012 return result;
10013}
10014
10015// Returns an Expectation object that references and co-owns exp,
10016// which must be an expectation on this mock function.
10017Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
10018 for (UntypedExpectations::const_iterator it =
10019 untyped_expectations_.begin();
10020 it != untyped_expectations_.end(); ++it) {
10021 if (it->get() == exp) {
10022 return Expectation(*it);
10023 }
10024 }
10025
10026 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
10027 return Expectation();
10028 // The above statement is just to make the code compile, and will
10029 // never be executed.
10030}
10031
10032// Verifies that all expectations on this mock function have been
10033// satisfied. Reports one or more Google Test non-fatal failures
10034// and returns false if not.
10035// L >= g_gmock_mutex
10036bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() {
10037 g_gmock_mutex.AssertHeld();
10038 bool expectations_met = true;
10039 for (UntypedExpectations::const_iterator it =
10040 untyped_expectations_.begin();
10041 it != untyped_expectations_.end(); ++it) {
10042 ExpectationBase* const untyped_expectation = it->get();
10043 if (untyped_expectation->IsOverSaturated()) {
10044 // There was an upper-bound violation. Since the error was
10045 // already reported when it occurred, there is no need to do
10046 // anything here.
10047 expectations_met = false;
10048 } else if (!untyped_expectation->IsSatisfied()) {
10049 expectations_met = false;
10050 ::std::stringstream ss;
10051 ss << "Actual function call count doesn't match "
10052 << untyped_expectation->source_text() << "...\n";
10053 // No need to show the source file location of the expectation
10054 // in the description, as the Expect() call that follows already
10055 // takes care of it.
10056 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
10057 untyped_expectation->DescribeCallCountTo(&ss);
10058 Expect(false, untyped_expectation->file(),
10059 untyped_expectation->line(), ss.str());
10060 }
10061 }
10062 untyped_expectations_.clear();
10063 return expectations_met;
10064}
10065
10066} // namespace internal
10067
10068// Class Mock.
10069
10070namespace {
10071
10072typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10073
10074// The current state of a mock object. Such information is needed for
10075// detecting leaked mock objects and explicitly verifying a mock's
10076// expectations.
10077struct MockObjectState {
10078 MockObjectState()
10079 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
10080
10081 // Where in the source file an ON_CALL or EXPECT_CALL is first
10082 // invoked on this mock object.
10083 const char* first_used_file;
10084 int first_used_line;
10085 ::std::string first_used_test_case;
10086 ::std::string first_used_test;
10087 bool leakable; // true iff it's OK to leak the object.
10088 FunctionMockers function_mockers; // All registered methods of the object.
10089};
10090
10091// A global registry holding the state of all mock objects that are
10092// alive. A mock object is added to this registry the first time
10093// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
10094// is removed from the registry in the mock object's destructor.
10095class MockObjectRegistry {
10096 public:
10097 // Maps a mock object (identified by its address) to its state.
10098 typedef std::map<const void*, MockObjectState> StateMap;
10099
10100 // This destructor will be called when a program exits, after all
10101 // tests in it have been run. By then, there should be no mock
10102 // object alive. Therefore we report any living object as test
10103 // failure, unless the user explicitly asked us to ignore it.
10104 ~MockObjectRegistry() {
10105 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
10106 // a macro.
10107
10108 if (!GMOCK_FLAG(catch_leaked_mocks))
10109 return;
10110
10111 int leaked_count = 0;
10112 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
10113 ++it) {
10114 if (it->second.leakable) // The user said it's fine to leak this object.
10115 continue;
10116
10117 // TODO(wan@google.com): Print the type of the leaked object.
10118 // This can help the user identify the leaked object.
10119 std::cout << "\n";
10120 const MockObjectState& state = it->second;
10121 std::cout << internal::FormatFileLocation(state.first_used_file,
10122 state.first_used_line);
10123 std::cout << " ERROR: this mock object";
10124 if (state.first_used_test != "") {
10125 std::cout << " (used in test " << state.first_used_test_case << "."
10126 << state.first_used_test << ")";
10127 }
10128 std::cout << " should be deleted but never is. Its address is @"
10129 << it->first << ".";
10130 leaked_count++;
10131 }
10132 if (leaked_count > 0) {
10133 std::cout << "\nERROR: " << leaked_count
10134 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
10135 << " found at program exit.\n";
10136 std::cout.flush();
10137 ::std::cerr.flush();
10138 // RUN_ALL_TESTS() has already returned when this destructor is
10139 // called. Therefore we cannot use the normal Google Test
10140 // failure reporting mechanism.
10141 _exit(1); // We cannot call exit() as it is not reentrant and
10142 // may already have been called.
10143 }
10144 }
10145
10146 StateMap& states() { return states_; }
10147 private:
10148 StateMap states_;
10149};
10150
10151// Protected by g_gmock_mutex.
10152MockObjectRegistry g_mock_object_registry;
10153
10154// Maps a mock object to the reaction Google Mock should have when an
10155// uninteresting method is called. Protected by g_gmock_mutex.
10156std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
10157
10158// Sets the reaction Google Mock should have when an uninteresting
10159// method of the given mock object is called.
10160// L < g_gmock_mutex
10161void SetReactionOnUninterestingCalls(const void* mock_obj,
10162 internal::CallReaction reaction) {
10163 internal::MutexLock l(&internal::g_gmock_mutex);
10164 g_uninteresting_call_reaction[mock_obj] = reaction;
10165}
10166
10167} // namespace
10168
10169// Tells Google Mock to allow uninteresting calls on the given mock
10170// object.
10171// L < g_gmock_mutex
10172void Mock::AllowUninterestingCalls(const void* mock_obj) {
10173 SetReactionOnUninterestingCalls(mock_obj, internal::ALLOW);
10174}
10175
10176// Tells Google Mock to warn the user about uninteresting calls on the
10177// given mock object.
10178// L < g_gmock_mutex
10179void Mock::WarnUninterestingCalls(const void* mock_obj) {
10180 SetReactionOnUninterestingCalls(mock_obj, internal::WARN);
10181}
10182
10183// Tells Google Mock to fail uninteresting calls on the given mock
10184// object.
10185// L < g_gmock_mutex
10186void Mock::FailUninterestingCalls(const void* mock_obj) {
10187 SetReactionOnUninterestingCalls(mock_obj, internal::FAIL);
10188}
10189
10190// Tells Google Mock the given mock object is being destroyed and its
10191// entry in the call-reaction table should be removed.
10192// L < g_gmock_mutex
10193void Mock::UnregisterCallReaction(const void* mock_obj) {
10194 internal::MutexLock l(&internal::g_gmock_mutex);
10195 g_uninteresting_call_reaction.erase(mock_obj);
10196}
10197
10198// Returns the reaction Google Mock will have on uninteresting calls
10199// made on the given mock object.
10200// L < g_gmock_mutex
10201internal::CallReaction Mock::GetReactionOnUninterestingCalls(
10202 const void* mock_obj) {
10203 internal::MutexLock l(&internal::g_gmock_mutex);
10204 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
10205 internal::WARN : g_uninteresting_call_reaction[mock_obj];
10206}
10207
10208// Tells Google Mock to ignore mock_obj when checking for leaked mock
10209// objects.
10210// L < g_gmock_mutex
10211void Mock::AllowLeak(const void* mock_obj) {
10212 internal::MutexLock l(&internal::g_gmock_mutex);
10213 g_mock_object_registry.states()[mock_obj].leakable = true;
10214}
10215
10216// Verifies and clears all expectations on the given mock object. If
10217// the expectations aren't satisfied, generates one or more Google
10218// Test non-fatal failures and returns false.
10219// L < g_gmock_mutex
10220bool Mock::VerifyAndClearExpectations(void* mock_obj) {
10221 internal::MutexLock l(&internal::g_gmock_mutex);
10222 return VerifyAndClearExpectationsLocked(mock_obj);
10223}
10224
10225// Verifies all expectations on the given mock object and clears its
10226// default actions and expectations. Returns true iff the
10227// verification was successful.
10228// L < g_gmock_mutex
10229bool Mock::VerifyAndClear(void* mock_obj) {
10230 internal::MutexLock l(&internal::g_gmock_mutex);
10231 ClearDefaultActionsLocked(mock_obj);
10232 return VerifyAndClearExpectationsLocked(mock_obj);
10233}
10234
10235// Verifies and clears all expectations on the given mock object. If
10236// the expectations aren't satisfied, generates one or more Google
10237// Test non-fatal failures and returns false.
10238// L >= g_gmock_mutex
10239bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
10240 internal::g_gmock_mutex.AssertHeld();
10241 if (g_mock_object_registry.states().count(mock_obj) == 0) {
10242 // No EXPECT_CALL() was set on the given mock object.
10243 return true;
10244 }
10245
10246 // Verifies and clears the expectations on each mock method in the
10247 // given mock object.
10248 bool expectations_met = true;
10249 FunctionMockers& mockers =
10250 g_mock_object_registry.states()[mock_obj].function_mockers;
10251 for (FunctionMockers::const_iterator it = mockers.begin();
10252 it != mockers.end(); ++it) {
10253 if (!(*it)->VerifyAndClearExpectationsLocked()) {
10254 expectations_met = false;
10255 }
10256 }
10257
10258 // We don't clear the content of mockers, as they may still be
10259 // needed by ClearDefaultActionsLocked().
10260 return expectations_met;
10261}
10262
10263// Registers a mock object and a mock method it owns.
10264// L < g_gmock_mutex
10265void Mock::Register(const void* mock_obj,
10266 internal::UntypedFunctionMockerBase* mocker) {
10267 internal::MutexLock l(&internal::g_gmock_mutex);
10268 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
10269}
10270
10271// Tells Google Mock where in the source code mock_obj is used in an
10272// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
10273// information helps the user identify which object it is.
10274// L < g_gmock_mutex
10275void Mock::RegisterUseByOnCallOrExpectCall(
10276 const void* mock_obj, const char* file, int line) {
10277 internal::MutexLock l(&internal::g_gmock_mutex);
10278 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
10279 if (state.first_used_file == NULL) {
10280 state.first_used_file = file;
10281 state.first_used_line = line;
10282 const TestInfo* const test_info =
10283 UnitTest::GetInstance()->current_test_info();
10284 if (test_info != NULL) {
10285 // TODO(wan@google.com): record the test case name when the
10286 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
10287 // TearDownTestCase().
10288 state.first_used_test_case = test_info->test_case_name();
10289 state.first_used_test = test_info->name();
10290 }
10291 }
10292}
10293
10294// Unregisters a mock method; removes the owning mock object from the
10295// registry when the last mock method associated with it has been
10296// unregistered. This is called only in the destructor of
10297// FunctionMockerBase.
10298// L >= g_gmock_mutex
10299void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
10300 internal::g_gmock_mutex.AssertHeld();
10301 for (MockObjectRegistry::StateMap::iterator it =
10302 g_mock_object_registry.states().begin();
10303 it != g_mock_object_registry.states().end(); ++it) {
10304 FunctionMockers& mockers = it->second.function_mockers;
10305 if (mockers.erase(mocker) > 0) {
10306 // mocker was in mockers and has been just removed.
10307 if (mockers.empty()) {
10308 g_mock_object_registry.states().erase(it);
10309 }
10310 return;
10311 }
10312 }
10313}
10314
10315// Clears all ON_CALL()s set on the given mock object.
10316// L >= g_gmock_mutex
10317void Mock::ClearDefaultActionsLocked(void* mock_obj) {
10318 internal::g_gmock_mutex.AssertHeld();
10319
10320 if (g_mock_object_registry.states().count(mock_obj) == 0) {
10321 // No ON_CALL() was set on the given mock object.
10322 return;
10323 }
10324
10325 // Clears the default actions for each mock method in the given mock
10326 // object.
10327 FunctionMockers& mockers =
10328 g_mock_object_registry.states()[mock_obj].function_mockers;
10329 for (FunctionMockers::const_iterator it = mockers.begin();
10330 it != mockers.end(); ++it) {
10331 (*it)->ClearDefaultActionsLocked();
10332 }
10333
10334 // We don't clear the content of mockers, as they may still be
10335 // needed by VerifyAndClearExpectationsLocked().
10336}
10337
10338Expectation::Expectation() {}
10339
10340Expectation::Expectation(
10341 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
10342 : expectation_base_(an_expectation_base) {}
10343
10344Expectation::~Expectation() {}
10345
10346// Adds an expectation to a sequence.
10347void Sequence::AddExpectation(const Expectation& expectation) const {
10348 if (*last_expectation_ != expectation) {
10349 if (last_expectation_->expectation_base() != NULL) {
10350 expectation.expectation_base()->immediate_prerequisites_
10351 += *last_expectation_;
10352 }
10353 *last_expectation_ = expectation;
10354 }
10355}
10356
10357// Creates the implicit sequence if there isn't one.
10358InSequence::InSequence() {
10359 if (internal::g_gmock_implicit_sequence.get() == NULL) {
10360 internal::g_gmock_implicit_sequence.set(new Sequence);
10361 sequence_created_ = true;
10362 } else {
10363 sequence_created_ = false;
10364 }
10365}
10366
10367// Deletes the implicit sequence if it was created by the constructor
10368// of this object.
10369InSequence::~InSequence() {
10370 if (sequence_created_) {
10371 delete internal::g_gmock_implicit_sequence.get();
10372 internal::g_gmock_implicit_sequence.set(NULL);
10373 }
10374}
10375
10376} // namespace testing
10377// Copyright 2008, Google Inc.
10378// All rights reserved.
10379//
10380// Redistribution and use in source and binary forms, with or without
10381// modification, are permitted provided that the following conditions are
10382// met:
10383//
10384// * Redistributions of source code must retain the above copyright
10385// notice, this list of conditions and the following disclaimer.
10386// * Redistributions in binary form must reproduce the above
10387// copyright notice, this list of conditions and the following disclaimer
10388// in the documentation and/or other materials provided with the
10389// distribution.
10390// * Neither the name of Google Inc. nor the names of its
10391// contributors may be used to endorse or promote products derived from
10392// this software without specific prior written permission.
10393//
10394// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10395// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10396// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10397// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10398// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10399// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10400// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10401// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10402// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10403// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10404// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10405//
10406// Author: wan@google.com (Zhanyong Wan)
10407
10408
10409namespace testing {
10410
10411// TODO(wan@google.com): support using environment variables to
10412// control the flag values, like what Google Test does.
10413
10414GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
10415 "true iff Google Mock should report leaked mock objects "
10416 "as failures.");
10417
10418GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
10419 "Controls how verbose Google Mock's output is."
10420 " Valid values:\n"
10421 " info - prints all messages.\n"
10422 " warning - prints warnings and errors.\n"
10423 " error - prints errors only.");
10424
10425namespace internal {
10426
10427// Parses a string as a command line flag. The string should have the
10428// format "--gmock_flag=value". When def_optional is true, the
10429// "=value" part can be omitted.
10430//
10431// Returns the value of the flag, or NULL if the parsing failed.
10432static const char* ParseGoogleMockFlagValue(const char* str,
10433 const char* flag,
10434 bool def_optional) {
10435 // str and flag must not be NULL.
10436 if (str == NULL || flag == NULL) return NULL;
10437
10438 // The flag must start with "--gmock_".
10439 const String flag_str = String::Format("--gmock_%s", flag);
10440 const size_t flag_len = flag_str.length();
10441 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
10442
10443 // Skips the flag name.
10444 const char* flag_end = str + flag_len;
10445
10446 // When def_optional is true, it's OK to not have a "=value" part.
10447 if (def_optional && (flag_end[0] == '\0')) {
10448 return flag_end;
10449 }
10450
10451 // If def_optional is true and there are more characters after the
10452 // flag name, or if def_optional is false, there must be a '=' after
10453 // the flag name.
10454 if (flag_end[0] != '=') return NULL;
10455
10456 // Returns the string after "=".
10457 return flag_end + 1;
10458}
10459
10460// Parses a string for a Google Mock bool flag, in the form of
10461// "--gmock_flag=value".
10462//
10463// On success, stores the value of the flag in *value, and returns
10464// true. On failure, returns false without changing *value.
10465static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
10466 bool* value) {
10467 // Gets the value of the flag as a string.
10468 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
10469
10470 // Aborts if the parsing failed.
10471 if (value_str == NULL) return false;
10472
10473 // Converts the string value to a bool.
10474 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
10475 return true;
10476}
10477
10478// Parses a string for a Google Mock string flag, in the form of
10479// "--gmock_flag=value".
10480//
10481// On success, stores the value of the flag in *value, and returns
10482// true. On failure, returns false without changing *value.
10483static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
10484 String* value) {
10485 // Gets the value of the flag as a string.
10486 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
10487
10488 // Aborts if the parsing failed.
10489 if (value_str == NULL) return false;
10490
10491 // Sets *value to the value of the flag.
10492 *value = value_str;
10493 return true;
10494}
10495
10496// The internal implementation of InitGoogleMock().
10497//
10498// The type parameter CharType can be instantiated to either char or
10499// wchar_t.
10500template <typename CharType>
10501void InitGoogleMockImpl(int* argc, CharType** argv) {
10502 // Makes sure Google Test is initialized. InitGoogleTest() is
10503 // idempotent, so it's fine if the user has already called it.
10504 InitGoogleTest(argc, argv);
10505 if (*argc <= 0) return;
10506
10507 for (int i = 1; i != *argc; i++) {
10508 const String arg_string = StreamableToString(argv[i]);
10509 const char* const arg = arg_string.c_str();
10510
10511 // Do we see a Google Mock flag?
10512 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
10513 &GMOCK_FLAG(catch_leaked_mocks)) ||
10514 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
10515 // Yes. Shift the remainder of the argv list left by one. Note
10516 // that argv has (*argc + 1) elements, the last one always being
10517 // NULL. The following loop moves the trailing NULL element as
10518 // well.
10519 for (int j = i; j != *argc; j++) {
10520 argv[j] = argv[j + 1];
10521 }
10522
10523 // Decrements the argument count.
10524 (*argc)--;
10525
10526 // We also need to decrement the iterator as we just removed
10527 // an element.
10528 i--;
10529 }
10530 }
10531}
10532
10533} // namespace internal
10534
10535// Initializes Google Mock. This must be called before running the
10536// tests. In particular, it parses a command line for the flags that
10537// Google Mock recognizes. Whenever a Google Mock flag is seen, it is
10538// removed from argv, and *argc is decremented.
10539//
10540// No value is returned. Instead, the Google Mock flag variables are
10541// updated.
10542//
10543// Since Google Test is needed for Google Mock to work, this function
10544// also initializes Google Test and parses its flags, if that hasn't
10545// been done.
10546void InitGoogleMock(int* argc, char** argv) {
10547 internal::InitGoogleMockImpl(argc, argv);
10548}
10549
10550// This overloaded version can be used in Windows programs compiled in
10551// UNICODE mode.
10552void InitGoogleMock(int* argc, wchar_t** argv) {
10553 internal::InitGoogleMockImpl(argc, argv);
10554}
10555
10556} // namespace testing