blob: 5b7ee8466991deb2edc49e43c6fadd5fd89c3f53 [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(\
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
Keir Mierle8ebb0732012-04-30 23:09:08 -0700300 &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>
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700312#include <time.h>
Keir Mierle8ebb0732012-04-30 23:09:08 -0700313#include <wchar.h>
314#include <wctype.h>
315
316#include <algorithm>
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700317#include <iomanip>
318#include <limits>
Keir Mierle8ebb0732012-04-30 23:09:08 -0700319#include <ostream> // NOLINT
320#include <sstream>
321#include <vector>
322
323#if GTEST_OS_LINUX
324
325// TODO(kenton@google.com): Use autoconf to detect availability of
326// gettimeofday().
327# define GTEST_HAS_GETTIMEOFDAY_ 1
328
329# include <fcntl.h> // NOLINT
330# include <limits.h> // NOLINT
331# include <sched.h> // NOLINT
332// Declares vsnprintf(). This header is not available on Windows.
333# include <strings.h> // NOLINT
334# include <sys/mman.h> // NOLINT
335# include <sys/time.h> // NOLINT
336# include <unistd.h> // NOLINT
337# include <string>
338
339#elif GTEST_OS_SYMBIAN
340# define GTEST_HAS_GETTIMEOFDAY_ 1
341# include <sys/time.h> // NOLINT
342
343#elif GTEST_OS_ZOS
344# define GTEST_HAS_GETTIMEOFDAY_ 1
345# include <sys/time.h> // NOLINT
346
347// On z/OS we additionally need strings.h for strcasecmp.
348# include <strings.h> // NOLINT
349
350#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
351
352# include <windows.h> // NOLINT
353
354#elif GTEST_OS_WINDOWS // We are on Windows proper.
355
356# include <io.h> // NOLINT
357# include <sys/timeb.h> // NOLINT
358# include <sys/types.h> // NOLINT
359# include <sys/stat.h> // NOLINT
360
361# if GTEST_OS_WINDOWS_MINGW
362// MinGW has gettimeofday() but not _ftime64().
363// TODO(kenton@google.com): Use autoconf to detect availability of
364// gettimeofday().
365// TODO(kenton@google.com): There are other ways to get the time on
366// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
367// supports these. consider using them instead.
368# define GTEST_HAS_GETTIMEOFDAY_ 1
369# include <sys/time.h> // NOLINT
370# endif // GTEST_OS_WINDOWS_MINGW
371
372// cpplint thinks that the header is already included, so we want to
373// silence it.
374# include <windows.h> // NOLINT
375
376#else
377
378// Assume other platforms have gettimeofday().
379// TODO(kenton@google.com): Use autoconf to detect availability of
380// gettimeofday().
381# define GTEST_HAS_GETTIMEOFDAY_ 1
382
383// cpplint thinks that the header is already included, so we want to
384// silence it.
385# include <sys/time.h> // NOLINT
386# include <unistd.h> // NOLINT
387
388#endif // GTEST_OS_LINUX
389
390#if GTEST_HAS_EXCEPTIONS
391# include <stdexcept>
392#endif
393
394#if GTEST_CAN_STREAM_RESULTS_
395# include <arpa/inet.h> // NOLINT
396# include <netdb.h> // NOLINT
397#endif
398
399// Indicates that this translation unit is part of Google Test's
400// implementation. It must come before gtest-internal-inl.h is
401// included, or there will be a compiler error. This trick is to
402// prevent a user from accidentally including gtest-internal-inl.h in
403// his code.
404#define GTEST_IMPLEMENTATION_ 1
405// Copyright 2005, Google Inc.
406// All rights reserved.
407//
408// Redistribution and use in source and binary forms, with or without
409// modification, are permitted provided that the following conditions are
410// met:
411//
412// * Redistributions of source code must retain the above copyright
413// notice, this list of conditions and the following disclaimer.
414// * Redistributions in binary form must reproduce the above
415// copyright notice, this list of conditions and the following disclaimer
416// in the documentation and/or other materials provided with the
417// distribution.
418// * Neither the name of Google Inc. nor the names of its
419// contributors may be used to endorse or promote products derived from
420// this software without specific prior written permission.
421//
422// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
423// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
424// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
425// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
426// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
427// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
428// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
429// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
430// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
431// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
432// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
433
434// Utility functions and classes used by the Google C++ testing framework.
435//
436// Author: wan@google.com (Zhanyong Wan)
437//
438// This file contains purely Google Test's internal implementation. Please
439// DO NOT #INCLUDE IT IN A USER PROGRAM.
440
441#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
442#define GTEST_SRC_GTEST_INTERNAL_INL_H_
443
444// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
445// part of Google Test's implementation; otherwise it's undefined.
446#if !GTEST_IMPLEMENTATION_
447// A user is trying to include this from his code - just say no.
448# error "gtest-internal-inl.h is part of Google Test's internal implementation."
449# error "It must not be included except by Google Test itself."
450#endif // GTEST_IMPLEMENTATION_
451
452#ifndef _WIN32_WCE
453# include <errno.h>
454#endif // !_WIN32_WCE
455#include <stddef.h>
456#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
457#include <string.h> // For memmove.
458
459#include <algorithm>
460#include <string>
461#include <vector>
462
463
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700464#if GTEST_CAN_STREAM_RESULTS_
465# include <arpa/inet.h> // NOLINT
466# include <netdb.h> // NOLINT
467#endif
468
Keir Mierle8ebb0732012-04-30 23:09:08 -0700469#if GTEST_OS_WINDOWS
470# include <windows.h> // NOLINT
471#endif // GTEST_OS_WINDOWS
472
473
474namespace testing {
475
476// Declares the flags.
477//
478// We don't want the users to modify this flag in the code, but want
479// Google Test's own unit tests to be able to access it. Therefore we
480// declare it here as opposed to in gtest.h.
481GTEST_DECLARE_bool_(death_test_use_fork);
482
483namespace internal {
484
485// The value of GetTestTypeId() as seen from within the Google Test
486// library. This is solely for testing GetTestTypeId().
487GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
488
489// Names of the flags (needed for parsing Google Test flags).
490const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
491const char kBreakOnFailureFlag[] = "break_on_failure";
492const char kCatchExceptionsFlag[] = "catch_exceptions";
493const char kColorFlag[] = "color";
494const char kFilterFlag[] = "filter";
495const char kListTestsFlag[] = "list_tests";
496const char kOutputFlag[] = "output";
497const char kPrintTimeFlag[] = "print_time";
498const char kRandomSeedFlag[] = "random_seed";
499const char kRepeatFlag[] = "repeat";
500const char kShuffleFlag[] = "shuffle";
501const char kStackTraceDepthFlag[] = "stack_trace_depth";
502const char kStreamResultToFlag[] = "stream_result_to";
503const char kThrowOnFailureFlag[] = "throw_on_failure";
504
505// A valid random seed must be in [1, kMaxRandomSeed].
506const int kMaxRandomSeed = 99999;
507
508// g_help_flag is true iff the --help flag or an equivalent form is
509// specified on the command line.
510GTEST_API_ extern bool g_help_flag;
511
512// Returns the current time in milliseconds.
513GTEST_API_ TimeInMillis GetTimeInMillis();
514
515// Returns true iff Google Test should use colors in the output.
516GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
517
518// Formats the given time in milliseconds as seconds.
519GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
520
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700521// Converts the given time in milliseconds to a date string in the ISO 8601
522// format, without the timezone information. N.B.: due to the use the
523// non-reentrant localtime() function, this function is not thread safe. Do
524// not use it in any code that can be called from multiple threads.
525GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
526
Keir Mierle8ebb0732012-04-30 23:09:08 -0700527// Parses a string for an Int32 flag, in the form of "--flag=value".
528//
529// On success, stores the value of the flag in *value, and returns
530// true. On failure, returns false without changing *value.
531GTEST_API_ bool ParseInt32Flag(
532 const char* str, const char* flag, Int32* value);
533
534// Returns a random seed in range [1, kMaxRandomSeed] based on the
535// given --gtest_random_seed flag value.
536inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
537 const unsigned int raw_seed = (random_seed_flag == 0) ?
538 static_cast<unsigned int>(GetTimeInMillis()) :
539 static_cast<unsigned int>(random_seed_flag);
540
541 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
542 // it's easy to type.
543 const int normalized_seed =
544 static_cast<int>((raw_seed - 1U) %
545 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
546 return normalized_seed;
547}
548
549// Returns the first valid random seed after 'seed'. The behavior is
550// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
551// considered to be 1.
552inline int GetNextRandomSeed(int seed) {
553 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
554 << "Invalid random seed " << seed << " - must be in [1, "
555 << kMaxRandomSeed << "].";
556 const int next_seed = seed + 1;
557 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
558}
559
560// This class saves the values of all Google Test flags in its c'tor, and
561// restores them in its d'tor.
562class GTestFlagSaver {
563 public:
564 // The c'tor.
565 GTestFlagSaver() {
566 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
567 break_on_failure_ = GTEST_FLAG(break_on_failure);
568 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
569 color_ = GTEST_FLAG(color);
570 death_test_style_ = GTEST_FLAG(death_test_style);
571 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
572 filter_ = GTEST_FLAG(filter);
573 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
574 list_tests_ = GTEST_FLAG(list_tests);
575 output_ = GTEST_FLAG(output);
576 print_time_ = GTEST_FLAG(print_time);
577 random_seed_ = GTEST_FLAG(random_seed);
578 repeat_ = GTEST_FLAG(repeat);
579 shuffle_ = GTEST_FLAG(shuffle);
580 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
581 stream_result_to_ = GTEST_FLAG(stream_result_to);
582 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
583 }
584
585 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
586 ~GTestFlagSaver() {
587 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
588 GTEST_FLAG(break_on_failure) = break_on_failure_;
589 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
590 GTEST_FLAG(color) = color_;
591 GTEST_FLAG(death_test_style) = death_test_style_;
592 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
593 GTEST_FLAG(filter) = filter_;
594 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
595 GTEST_FLAG(list_tests) = list_tests_;
596 GTEST_FLAG(output) = output_;
597 GTEST_FLAG(print_time) = print_time_;
598 GTEST_FLAG(random_seed) = random_seed_;
599 GTEST_FLAG(repeat) = repeat_;
600 GTEST_FLAG(shuffle) = shuffle_;
601 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
602 GTEST_FLAG(stream_result_to) = stream_result_to_;
603 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
604 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700605
Keir Mierle8ebb0732012-04-30 23:09:08 -0700606 private:
607 // Fields for saving the original values of flags.
608 bool also_run_disabled_tests_;
609 bool break_on_failure_;
610 bool catch_exceptions_;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700611 std::string color_;
612 std::string death_test_style_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700613 bool death_test_use_fork_;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700614 std::string filter_;
615 std::string internal_run_death_test_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700616 bool list_tests_;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700617 std::string output_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700618 bool print_time_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700619 internal::Int32 random_seed_;
620 internal::Int32 repeat_;
621 bool shuffle_;
622 internal::Int32 stack_trace_depth_;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700623 std::string stream_result_to_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700624 bool throw_on_failure_;
625} GTEST_ATTRIBUTE_UNUSED_;
626
627// Converts a Unicode code point to a narrow string in UTF-8 encoding.
628// code_point parameter is of type UInt32 because wchar_t may not be
629// wide enough to contain a code point.
Keir Mierle8ebb0732012-04-30 23:09:08 -0700630// If the code_point is not a valid Unicode code point
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700631// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
632// to "(Invalid Unicode 0xXXXXXXXX)".
633GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700634
635// Converts a wide string to a narrow string in UTF-8 encoding.
636// The wide string is assumed to have the following encoding:
637// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
638// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
639// Parameter str points to a null-terminated wide string.
640// Parameter num_chars may additionally limit the number
641// of wchar_t characters processed. -1 is used when the entire string
642// should be processed.
643// If the string contains code points that are not valid Unicode code points
644// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
645// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
646// and contains invalid UTF-16 surrogate pairs, values in those pairs
647// will be encoded as individual Unicode characters from Basic Normal Plane.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700648GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700649
650// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
651// if the variable is present. If a file already exists at this location, this
652// function will write over it. If the variable is present, but the file cannot
653// be created, prints an error and exits.
654void WriteToShardStatusFileIfNeeded();
655
656// Checks whether sharding is enabled by examining the relevant
657// environment variable values. If the variables are present,
658// but inconsistent (e.g., shard_index >= total_shards), prints
659// an error and exits. If in_subprocess_for_death_test, sharding is
660// disabled because it must only be applied to the original test
661// process. Otherwise, we could filter out death tests we intended to execute.
662GTEST_API_ bool ShouldShard(const char* total_shards_str,
663 const char* shard_index_str,
664 bool in_subprocess_for_death_test);
665
666// Parses the environment variable var as an Int32. If it is unset,
667// returns default_val. If it is not an Int32, prints an error and
668// and aborts.
669GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
670
671// Given the total number of shards, the shard index, and the test id,
672// returns true iff the test should be run on this shard. The test id is
673// some arbitrary but unique non-negative integer assigned to each test
674// method. Assumes that 0 <= shard_index < total_shards.
675GTEST_API_ bool ShouldRunTestOnShard(
676 int total_shards, int shard_index, int test_id);
677
678// STL container utilities.
679
680// Returns the number of elements in the given container that satisfy
681// the given predicate.
682template <class Container, typename Predicate>
683inline int CountIf(const Container& c, Predicate predicate) {
684 // Implemented as an explicit loop since std::count_if() in libCstd on
685 // Solaris has a non-standard signature.
686 int count = 0;
687 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
688 if (predicate(*it))
689 ++count;
690 }
691 return count;
692}
693
694// Applies a function/functor to each element in the container.
695template <class Container, typename Functor>
696void ForEach(const Container& c, Functor functor) {
697 std::for_each(c.begin(), c.end(), functor);
698}
699
700// Returns the i-th element of the vector, or default_value if i is not
701// in range [0, v.size()).
702template <typename E>
703inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
704 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
705}
706
707// Performs an in-place shuffle of a range of the vector's elements.
708// 'begin' and 'end' are element indices as an STL-style range;
709// i.e. [begin, end) are shuffled, where 'end' == size() means to
710// shuffle to the end of the vector.
711template <typename E>
712void ShuffleRange(internal::Random* random, int begin, int end,
713 std::vector<E>* v) {
714 const int size = static_cast<int>(v->size());
715 GTEST_CHECK_(0 <= begin && begin <= size)
716 << "Invalid shuffle range start " << begin << ": must be in range [0, "
717 << size << "].";
718 GTEST_CHECK_(begin <= end && end <= size)
719 << "Invalid shuffle range finish " << end << ": must be in range ["
720 << begin << ", " << size << "].";
721
722 // Fisher-Yates shuffle, from
723 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
724 for (int range_width = end - begin; range_width >= 2; range_width--) {
725 const int last_in_range = begin + range_width - 1;
726 const int selected = begin + random->Generate(range_width);
727 std::swap((*v)[selected], (*v)[last_in_range]);
728 }
729}
730
731// Performs an in-place shuffle of the vector's elements.
732template <typename E>
733inline void Shuffle(internal::Random* random, std::vector<E>* v) {
734 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
735}
736
737// A function for deleting an object. Handy for being used as a
738// functor.
739template <typename T>
740static void Delete(T* x) {
741 delete x;
742}
743
744// A predicate that checks the key of a TestProperty against a known key.
745//
746// TestPropertyKeyIs is copyable.
747class TestPropertyKeyIs {
748 public:
749 // Constructor.
750 //
751 // TestPropertyKeyIs has NO default constructor.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700752 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
Keir Mierle8ebb0732012-04-30 23:09:08 -0700753
754 // Returns true iff the test name of test property matches on key_.
755 bool operator()(const TestProperty& test_property) const {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700756 return test_property.key() == key_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700757 }
758
759 private:
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700760 std::string key_;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700761};
762
763// Class UnitTestOptions.
764//
765// This class contains functions for processing options the user
766// specifies when running the tests. It has only static members.
767//
768// In most cases, the user can specify an option using either an
769// environment variable or a command line flag. E.g. you can set the
770// test filter using either GTEST_FILTER or --gtest_filter. If both
771// the variable and the flag are present, the latter overrides the
772// former.
773class GTEST_API_ UnitTestOptions {
774 public:
775 // Functions for processing the gtest_output flag.
776
777 // Returns the output format, or "" for normal printed output.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700778 static std::string GetOutputFormat();
Keir Mierle8ebb0732012-04-30 23:09:08 -0700779
780 // Returns the absolute path of the requested output file, or the
781 // default (test_detail.xml in the original working directory) if
782 // none was explicitly specified.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700783 static std::string GetAbsolutePathToOutputFile();
Keir Mierle8ebb0732012-04-30 23:09:08 -0700784
785 // Functions for processing the gtest_filter flag.
786
787 // Returns true iff the wildcard pattern matches the string. The
788 // first ':' or '\0' character in pattern marks the end of it.
789 //
790 // This recursive algorithm isn't very efficient, but is clear and
791 // works well enough for matching test names, which are short.
792 static bool PatternMatchesString(const char *pattern, const char *str);
793
794 // Returns true iff the user-specified filter matches the test case
795 // name and the test name.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700796 static bool FilterMatchesTest(const std::string &test_case_name,
797 const std::string &test_name);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700798
799#if GTEST_OS_WINDOWS
800 // Function for supporting the gtest_catch_exception flag.
801
802 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
803 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
804 // This function is useful as an __except condition.
805 static int GTestShouldProcessSEH(DWORD exception_code);
806#endif // GTEST_OS_WINDOWS
807
808 // Returns true if "name" matches the ':' separated list of glob-style
809 // filters in "filter".
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700810 static bool MatchesFilter(const std::string& name, const char* filter);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700811};
812
813// Returns the current application's name, removing directory path if that
814// is present. Used by UnitTestOptions::GetOutputFile.
815GTEST_API_ FilePath GetCurrentExecutableName();
816
817// The role interface for getting the OS stack trace as a string.
818class OsStackTraceGetterInterface {
819 public:
820 OsStackTraceGetterInterface() {}
821 virtual ~OsStackTraceGetterInterface() {}
822
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700823 // Returns the current OS stack trace as an std::string. Parameters:
Keir Mierle8ebb0732012-04-30 23:09:08 -0700824 //
825 // max_depth - the maximum number of stack frames to be included
826 // in the trace.
827 // skip_count - the number of top frames to be skipped; doesn't count
828 // against max_depth.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700829 virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700830
831 // UponLeavingGTest() should be called immediately before Google Test calls
832 // user code. It saves some information about the current stack that
833 // CurrentStackTrace() will use to find and hide Google Test stack frames.
834 virtual void UponLeavingGTest() = 0;
835
836 private:
837 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
838};
839
840// A working implementation of the OsStackTraceGetterInterface interface.
841class OsStackTraceGetter : public OsStackTraceGetterInterface {
842 public:
843 OsStackTraceGetter() : caller_frame_(NULL) {}
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700844
845 virtual string CurrentStackTrace(int max_depth, int skip_count)
846 GTEST_LOCK_EXCLUDED_(mutex_);
847
848 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700849
850 // This string is inserted in place of stack frames that are part of
851 // Google Test's implementation.
852 static const char* const kElidedFramesMarker;
853
854 private:
855 Mutex mutex_; // protects all internal state
856
857 // We save the stack frame below the frame that calls user code.
858 // We do this because the address of the frame immediately below
859 // the user code changes between the call to UponLeavingGTest()
860 // and any calls to CurrentStackTrace() from within the user code.
861 void* caller_frame_;
862
863 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
864};
865
866// Information about a Google Test trace point.
867struct TraceInfo {
868 const char* file;
869 int line;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700870 std::string message;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700871};
872
873// This is the default global test part result reporter used in UnitTestImpl.
874// This class should only be used by UnitTestImpl.
875class DefaultGlobalTestPartResultReporter
876 : public TestPartResultReporterInterface {
877 public:
878 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
879 // Implements the TestPartResultReporterInterface. Reports the test part
880 // result in the current test.
881 virtual void ReportTestPartResult(const TestPartResult& result);
882
883 private:
884 UnitTestImpl* const unit_test_;
885
886 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
887};
888
889// This is the default per thread test part result reporter used in
890// UnitTestImpl. This class should only be used by UnitTestImpl.
891class DefaultPerThreadTestPartResultReporter
892 : public TestPartResultReporterInterface {
893 public:
894 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
895 // Implements the TestPartResultReporterInterface. The implementation just
896 // delegates to the current global test part result reporter of *unit_test_.
897 virtual void ReportTestPartResult(const TestPartResult& result);
898
899 private:
900 UnitTestImpl* const unit_test_;
901
902 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
903};
904
905// The private implementation of the UnitTest class. We don't protect
906// the methods under a mutex, as this class is not accessible by a
907// user and the UnitTest class that delegates work to this class does
908// proper locking.
909class GTEST_API_ UnitTestImpl {
910 public:
911 explicit UnitTestImpl(UnitTest* parent);
912 virtual ~UnitTestImpl();
913
914 // There are two different ways to register your own TestPartResultReporter.
915 // You can register your own repoter to listen either only for test results
916 // from the current thread or for results from all threads.
917 // By default, each per-thread test result repoter just passes a new
918 // TestPartResult to the global test result reporter, which registers the
919 // test part result for the currently running test.
920
921 // Returns the global test part result reporter.
922 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
923
924 // Sets the global test part result reporter.
925 void SetGlobalTestPartResultReporter(
926 TestPartResultReporterInterface* reporter);
927
928 // Returns the test part result reporter for the current thread.
929 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
930
931 // Sets the test part result reporter for the current thread.
932 void SetTestPartResultReporterForCurrentThread(
933 TestPartResultReporterInterface* reporter);
934
935 // Gets the number of successful test cases.
936 int successful_test_case_count() const;
937
938 // Gets the number of failed test cases.
939 int failed_test_case_count() const;
940
941 // Gets the number of all test cases.
942 int total_test_case_count() const;
943
944 // Gets the number of all test cases that contain at least one test
945 // that should run.
946 int test_case_to_run_count() const;
947
948 // Gets the number of successful tests.
949 int successful_test_count() const;
950
951 // Gets the number of failed tests.
952 int failed_test_count() const;
953
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700954 // Gets the number of disabled tests that will be reported in the XML report.
955 int reportable_disabled_test_count() const;
956
Keir Mierle8ebb0732012-04-30 23:09:08 -0700957 // Gets the number of disabled tests.
958 int disabled_test_count() const;
959
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700960 // Gets the number of tests to be printed in the XML report.
961 int reportable_test_count() const;
962
Keir Mierle8ebb0732012-04-30 23:09:08 -0700963 // Gets the number of all tests.
964 int total_test_count() const;
965
966 // Gets the number of tests that should run.
967 int test_to_run_count() const;
968
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -0700969 // Gets the time of the test program start, in ms from the start of the
970 // UNIX epoch.
971 TimeInMillis start_timestamp() const { return start_timestamp_; }
972
Keir Mierle8ebb0732012-04-30 23:09:08 -0700973 // Gets the elapsed time, in milliseconds.
974 TimeInMillis elapsed_time() const { return elapsed_time_; }
975
976 // Returns true iff the unit test passed (i.e. all test cases passed).
977 bool Passed() const { return !Failed(); }
978
979 // Returns true iff the unit test failed (i.e. some test case failed
980 // or something outside of all tests failed).
981 bool Failed() const {
982 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
983 }
984
985 // Gets the i-th test case among all the test cases. i can range from 0 to
986 // total_test_case_count() - 1. If i is not in that range, returns NULL.
987 const TestCase* GetTestCase(int i) const {
988 const int index = GetElementOr(test_case_indices_, i, -1);
989 return index < 0 ? NULL : test_cases_[i];
990 }
991
992 // Gets the i-th test case among all the test cases. i can range from 0 to
993 // total_test_case_count() - 1. If i is not in that range, returns NULL.
994 TestCase* GetMutableTestCase(int i) {
995 const int index = GetElementOr(test_case_indices_, i, -1);
996 return index < 0 ? NULL : test_cases_[index];
997 }
998
999 // Provides access to the event listener list.
1000 TestEventListeners* listeners() { return &listeners_; }
1001
1002 // Returns the TestResult for the test that's currently running, or
1003 // the TestResult for the ad hoc test if no test is running.
1004 TestResult* current_test_result();
1005
1006 // Returns the TestResult for the ad hoc test.
1007 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1008
1009 // Sets the OS stack trace getter.
1010 //
1011 // Does nothing if the input and the current OS stack trace getter
1012 // are the same; otherwise, deletes the old getter and makes the
1013 // input the current getter.
1014 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1015
1016 // Returns the current OS stack trace getter if it is not NULL;
1017 // otherwise, creates an OsStackTraceGetter, makes it the current
1018 // getter, and returns it.
1019 OsStackTraceGetterInterface* os_stack_trace_getter();
1020
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001021 // Returns the current OS stack trace as an std::string.
Keir Mierle8ebb0732012-04-30 23:09:08 -07001022 //
1023 // The maximum number of stack frames to be included is specified by
1024 // the gtest_stack_trace_depth flag. The skip_count parameter
1025 // specifies the number of top frames to be skipped, which doesn't
1026 // count against the number of frames to be included.
1027 //
1028 // For example, if Foo() calls Bar(), which in turn calls
1029 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1030 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001031 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07001032
1033 // Finds and returns a TestCase with the given name. If one doesn't
1034 // exist, creates one and returns it.
1035 //
1036 // Arguments:
1037 //
1038 // test_case_name: name of the test case
1039 // type_param: the name of the test's type parameter, or NULL if
1040 // this is not a typed or a type-parameterized test.
1041 // set_up_tc: pointer to the function that sets up the test case
1042 // tear_down_tc: pointer to the function that tears down the test case
1043 TestCase* GetTestCase(const char* test_case_name,
1044 const char* type_param,
1045 Test::SetUpTestCaseFunc set_up_tc,
1046 Test::TearDownTestCaseFunc tear_down_tc);
1047
1048 // Adds a TestInfo to the unit test.
1049 //
1050 // Arguments:
1051 //
1052 // set_up_tc: pointer to the function that sets up the test case
1053 // tear_down_tc: pointer to the function that tears down the test case
1054 // test_info: the TestInfo object
1055 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1056 Test::TearDownTestCaseFunc tear_down_tc,
1057 TestInfo* test_info) {
1058 // In order to support thread-safe death tests, we need to
1059 // remember the original working directory when the test program
1060 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1061 // the user may have changed the current directory before calling
1062 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1063 // AddTestInfo(), which is called to register a TEST or TEST_F
1064 // before main() is reached.
1065 if (original_working_dir_.IsEmpty()) {
1066 original_working_dir_.Set(FilePath::GetCurrentDir());
1067 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1068 << "Failed to get the current working directory.";
1069 }
1070
1071 GetTestCase(test_info->test_case_name(),
1072 test_info->type_param(),
1073 set_up_tc,
1074 tear_down_tc)->AddTestInfo(test_info);
1075 }
1076
1077#if GTEST_HAS_PARAM_TEST
1078 // Returns ParameterizedTestCaseRegistry object used to keep track of
1079 // value-parameterized tests and instantiate and register them.
1080 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1081 return parameterized_test_registry_;
1082 }
1083#endif // GTEST_HAS_PARAM_TEST
1084
1085 // Sets the TestCase object for the test that's currently running.
1086 void set_current_test_case(TestCase* a_current_test_case) {
1087 current_test_case_ = a_current_test_case;
1088 }
1089
1090 // Sets the TestInfo object for the test that's currently running. If
1091 // current_test_info is NULL, the assertion results will be stored in
1092 // ad_hoc_test_result_.
1093 void set_current_test_info(TestInfo* a_current_test_info) {
1094 current_test_info_ = a_current_test_info;
1095 }
1096
1097 // Registers all parameterized tests defined using TEST_P and
1098 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1099 // combination. This method can be called more then once; it has guards
1100 // protecting from registering the tests more then once. If
1101 // value-parameterized tests are disabled, RegisterParameterizedTests is
1102 // present but does nothing.
1103 void RegisterParameterizedTests();
1104
1105 // Runs all tests in this UnitTest object, prints the result, and
1106 // returns true if all tests are successful. If any exception is
1107 // thrown during a test, this test is considered to be failed, but
1108 // the rest of the tests will still be run.
1109 bool RunAllTests();
1110
1111 // Clears the results of all tests, except the ad hoc tests.
1112 void ClearNonAdHocTestResult() {
1113 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1114 }
1115
1116 // Clears the results of ad-hoc test assertions.
1117 void ClearAdHocTestResult() {
1118 ad_hoc_test_result_.Clear();
1119 }
1120
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001121 // Adds a TestProperty to the current TestResult object when invoked in a
1122 // context of a test or a test case, or to the global property set. If the
1123 // result already contains a property with the same key, the value will be
1124 // updated.
1125 void RecordProperty(const TestProperty& test_property);
1126
Keir Mierle8ebb0732012-04-30 23:09:08 -07001127 enum ReactionToSharding {
1128 HONOR_SHARDING_PROTOCOL,
1129 IGNORE_SHARDING_PROTOCOL
1130 };
1131
1132 // Matches the full name of each test against the user-specified
1133 // filter to decide whether the test should run, then records the
1134 // result in each TestCase and TestInfo object.
1135 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1136 // based on sharding variables in the environment.
1137 // Returns the number of tests that should run.
1138 int FilterTests(ReactionToSharding shard_tests);
1139
1140 // Prints the names of the tests matching the user-specified filter flag.
1141 void ListTestsMatchingFilter();
1142
1143 const TestCase* current_test_case() const { return current_test_case_; }
1144 TestInfo* current_test_info() { return current_test_info_; }
1145 const TestInfo* current_test_info() const { return current_test_info_; }
1146
1147 // Returns the vector of environments that need to be set-up/torn-down
1148 // before/after the tests are run.
1149 std::vector<Environment*>& environments() { return environments_; }
1150
1151 // Getters for the per-thread Google Test trace stack.
1152 std::vector<TraceInfo>& gtest_trace_stack() {
1153 return *(gtest_trace_stack_.pointer());
1154 }
1155 const std::vector<TraceInfo>& gtest_trace_stack() const {
1156 return gtest_trace_stack_.get();
1157 }
1158
1159#if GTEST_HAS_DEATH_TEST
1160 void InitDeathTestSubprocessControlInfo() {
1161 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1162 }
1163 // Returns a pointer to the parsed --gtest_internal_run_death_test
1164 // flag, or NULL if that flag was not specified.
1165 // This information is useful only in a death test child process.
1166 // Must not be called before a call to InitGoogleTest.
1167 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1168 return internal_run_death_test_flag_.get();
1169 }
1170
1171 // Returns a pointer to the current death test factory.
1172 internal::DeathTestFactory* death_test_factory() {
1173 return death_test_factory_.get();
1174 }
1175
1176 void SuppressTestEventsIfInSubprocess();
1177
1178 friend class ReplaceDeathTestFactory;
1179#endif // GTEST_HAS_DEATH_TEST
1180
1181 // Initializes the event listener performing XML output as specified by
1182 // UnitTestOptions. Must not be called before InitGoogleTest.
1183 void ConfigureXmlOutput();
1184
1185#if GTEST_CAN_STREAM_RESULTS_
1186 // Initializes the event listener for streaming test results to a socket.
1187 // Must not be called before InitGoogleTest.
1188 void ConfigureStreamingOutput();
1189#endif
1190
1191 // Performs initialization dependent upon flag values obtained in
1192 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1193 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1194 // this function is also called from RunAllTests. Since this function can be
1195 // called more than once, it has to be idempotent.
1196 void PostFlagParsingInit();
1197
1198 // Gets the random seed used at the start of the current test iteration.
1199 int random_seed() const { return random_seed_; }
1200
1201 // Gets the random number generator.
1202 internal::Random* random() { return &random_; }
1203
1204 // Shuffles all test cases, and the tests within each test case,
1205 // making sure that death tests are still run first.
1206 void ShuffleTests();
1207
1208 // Restores the test cases and tests to their order before the first shuffle.
1209 void UnshuffleTests();
1210
1211 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1212 // UnitTest::Run() starts.
1213 bool catch_exceptions() const { return catch_exceptions_; }
1214
1215 private:
1216 friend class ::testing::UnitTest;
1217
1218 // Used by UnitTest::Run() to capture the state of
1219 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1220 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1221
1222 // The UnitTest object that owns this implementation object.
1223 UnitTest* const parent_;
1224
1225 // The working directory when the first TEST() or TEST_F() was
1226 // executed.
1227 internal::FilePath original_working_dir_;
1228
1229 // The default test part result reporters.
1230 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1231 DefaultPerThreadTestPartResultReporter
1232 default_per_thread_test_part_result_reporter_;
1233
1234 // Points to (but doesn't own) the global test part result reporter.
1235 TestPartResultReporterInterface* global_test_part_result_repoter_;
1236
1237 // Protects read and write access to global_test_part_result_reporter_.
1238 internal::Mutex global_test_part_result_reporter_mutex_;
1239
1240 // Points to (but doesn't own) the per-thread test part result reporter.
1241 internal::ThreadLocal<TestPartResultReporterInterface*>
1242 per_thread_test_part_result_reporter_;
1243
1244 // The vector of environments that need to be set-up/torn-down
1245 // before/after the tests are run.
1246 std::vector<Environment*> environments_;
1247
1248 // The vector of TestCases in their original order. It owns the
1249 // elements in the vector.
1250 std::vector<TestCase*> test_cases_;
1251
1252 // Provides a level of indirection for the test case list to allow
1253 // easy shuffling and restoring the test case order. The i-th
1254 // element of this vector is the index of the i-th test case in the
1255 // shuffled order.
1256 std::vector<int> test_case_indices_;
1257
1258#if GTEST_HAS_PARAM_TEST
1259 // ParameterizedTestRegistry object used to register value-parameterized
1260 // tests.
1261 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1262
1263 // Indicates whether RegisterParameterizedTests() has been called already.
1264 bool parameterized_tests_registered_;
1265#endif // GTEST_HAS_PARAM_TEST
1266
1267 // Index of the last death test case registered. Initially -1.
1268 int last_death_test_case_;
1269
1270 // This points to the TestCase for the currently running test. It
1271 // changes as Google Test goes through one test case after another.
1272 // When no test is running, this is set to NULL and Google Test
1273 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1274 TestCase* current_test_case_;
1275
1276 // This points to the TestInfo for the currently running test. It
1277 // changes as Google Test goes through one test after another. When
1278 // no test is running, this is set to NULL and Google Test stores
1279 // assertion results in ad_hoc_test_result_. Initially NULL.
1280 TestInfo* current_test_info_;
1281
1282 // Normally, a user only writes assertions inside a TEST or TEST_F,
1283 // or inside a function called by a TEST or TEST_F. Since Google
1284 // Test keeps track of which test is current running, it can
1285 // associate such an assertion with the test it belongs to.
1286 //
1287 // If an assertion is encountered when no TEST or TEST_F is running,
1288 // Google Test attributes the assertion result to an imaginary "ad hoc"
1289 // test, and records the result in ad_hoc_test_result_.
1290 TestResult ad_hoc_test_result_;
1291
1292 // The list of event listeners that can be used to track events inside
1293 // Google Test.
1294 TestEventListeners listeners_;
1295
1296 // The OS stack trace getter. Will be deleted when the UnitTest
1297 // object is destructed. By default, an OsStackTraceGetter is used,
1298 // but the user can set this field to use a custom getter if that is
1299 // desired.
1300 OsStackTraceGetterInterface* os_stack_trace_getter_;
1301
1302 // True iff PostFlagParsingInit() has been called.
1303 bool post_flag_parse_init_performed_;
1304
1305 // The random number seed used at the beginning of the test run.
1306 int random_seed_;
1307
1308 // Our random number generator.
1309 internal::Random random_;
1310
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001311 // The time of the test program start, in ms from the start of the
1312 // UNIX epoch.
1313 TimeInMillis start_timestamp_;
1314
Keir Mierle8ebb0732012-04-30 23:09:08 -07001315 // How long the test took to run, in milliseconds.
1316 TimeInMillis elapsed_time_;
1317
1318#if GTEST_HAS_DEATH_TEST
1319 // The decomposed components of the gtest_internal_run_death_test flag,
1320 // parsed when RUN_ALL_TESTS is called.
1321 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1323#endif // GTEST_HAS_DEATH_TEST
1324
1325 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1326 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1327
1328 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329 // starts.
1330 bool catch_exceptions_;
1331
1332 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1333}; // class UnitTestImpl
1334
1335// Convenience function for accessing the global UnitTest
1336// implementation object.
1337inline UnitTestImpl* GetUnitTestImpl() {
1338 return UnitTest::GetInstance()->impl();
1339}
1340
1341#if GTEST_USES_SIMPLE_RE
1342
1343// Internal helper functions for implementing the simple regular
1344// expression matcher.
1345GTEST_API_ bool IsInSet(char ch, const char* str);
1346GTEST_API_ bool IsAsciiDigit(char ch);
1347GTEST_API_ bool IsAsciiPunct(char ch);
1348GTEST_API_ bool IsRepeat(char ch);
1349GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1350GTEST_API_ bool IsAsciiWordChar(char ch);
1351GTEST_API_ bool IsValidEscape(char ch);
1352GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1353GTEST_API_ bool ValidateRegex(const char* regex);
1354GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped, char ch, char repeat, const char* regex, const char* str);
1357GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1358
1359#endif // GTEST_USES_SIMPLE_RE
1360
1361// Parses the command line for Google Test flags, without initializing
1362// other parts of Google Test.
1363GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1365
1366#if GTEST_HAS_DEATH_TEST
1367
1368// Returns the message describing the last system error, regardless of the
1369// platform.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001370GTEST_API_ std::string GetLastErrnoDescription();
Keir Mierle8ebb0732012-04-30 23:09:08 -07001371
1372# if GTEST_OS_WINDOWS
1373// Provides leak-safe Windows kernel handle ownership.
1374class AutoHandle {
1375 public:
1376 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1377 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1378
1379 ~AutoHandle() { Reset(); }
1380
1381 HANDLE Get() const { return handle_; }
1382 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1383 void Reset(HANDLE handle) {
1384 if (handle != handle_) {
1385 if (handle_ != INVALID_HANDLE_VALUE)
1386 ::CloseHandle(handle_);
1387 handle_ = handle;
1388 }
1389 }
1390
1391 private:
1392 HANDLE handle_;
1393
1394 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1395};
1396# endif // GTEST_OS_WINDOWS
1397
1398// Attempts to parse a string into a positive integer pointed to by the
1399// number parameter. Returns true if that is possible.
1400// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1401// it here.
1402template <typename Integer>
1403bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1404 // Fail fast if the given string does not begin with a digit;
1405 // this bypasses strtoXXX's "optional leading whitespace and plus
1406 // or minus sign" semantics, which are undesirable here.
1407 if (str.empty() || !IsDigit(str[0])) {
1408 return false;
1409 }
1410 errno = 0;
1411
1412 char* end;
1413 // BiggestConvertible is the largest integer type that system-provided
1414 // string-to-number conversion routines can return.
1415
1416# if GTEST_OS_WINDOWS && !defined(__GNUC__)
1417
1418 // MSVC and C++ Builder define __int64 instead of the standard long long.
1419 typedef unsigned __int64 BiggestConvertible;
1420 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1421
1422# else
1423
1424 typedef unsigned long long BiggestConvertible; // NOLINT
1425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1426
1427# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1428
1429 const bool parse_success = *end == '\0' && errno == 0;
1430
1431 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1432 // available.
1433 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1434
1435 const Integer result = static_cast<Integer>(parsed);
1436 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1437 *number = result;
1438 return true;
1439 }
1440 return false;
1441}
1442#endif // GTEST_HAS_DEATH_TEST
1443
1444// TestResult contains some private methods that should be hidden from
1445// Google Test user but are required for testing. This class allow our tests
1446// to access them.
1447//
1448// This class is supplied only for the purpose of testing Google Test's own
1449// constructs. Do not use it in user tests, either directly or indirectly.
1450class TestResultAccessor {
1451 public:
1452 static void RecordProperty(TestResult* test_result,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001453 const std::string& xml_element,
Keir Mierle8ebb0732012-04-30 23:09:08 -07001454 const TestProperty& property) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001455 test_result->RecordProperty(xml_element, property);
Keir Mierle8ebb0732012-04-30 23:09:08 -07001456 }
1457
1458 static void ClearTestPartResults(TestResult* test_result) {
1459 test_result->ClearTestPartResults();
1460 }
1461
1462 static const std::vector<testing::TestPartResult>& test_part_results(
1463 const TestResult& test_result) {
1464 return test_result.test_part_results();
1465 }
1466};
1467
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001468#if GTEST_CAN_STREAM_RESULTS_
1469
1470// Streams test results to the given port on the given host machine.
1471class StreamingListener : public EmptyTestEventListener {
1472 public:
1473 // Abstract base class for writing strings to a socket.
1474 class AbstractSocketWriter {
1475 public:
1476 virtual ~AbstractSocketWriter() {}
1477
1478 // Sends a string to the socket.
1479 virtual void Send(const string& message) = 0;
1480
1481 // Closes the socket.
1482 virtual void CloseConnection() {}
1483
1484 // Sends a string and a newline to the socket.
1485 void SendLn(const string& message) {
1486 Send(message + "\n");
1487 }
1488 };
1489
1490 // Concrete class for actually writing strings to a socket.
1491 class SocketWriter : public AbstractSocketWriter {
1492 public:
1493 SocketWriter(const string& host, const string& port)
1494 : sockfd_(-1), host_name_(host), port_num_(port) {
1495 MakeConnection();
1496 }
1497
1498 virtual ~SocketWriter() {
1499 if (sockfd_ != -1)
1500 CloseConnection();
1501 }
1502
1503 // Sends a string to the socket.
1504 virtual void Send(const string& message) {
1505 GTEST_CHECK_(sockfd_ != -1)
1506 << "Send() can be called only when there is a connection.";
1507
1508 const int len = static_cast<int>(message.length());
1509 if (write(sockfd_, message.c_str(), len) != len) {
1510 GTEST_LOG_(WARNING)
1511 << "stream_result_to: failed to stream to "
1512 << host_name_ << ":" << port_num_;
1513 }
1514 }
1515
1516 private:
1517 // Creates a client socket and connects to the server.
1518 void MakeConnection();
1519
1520 // Closes the socket.
1521 void CloseConnection() {
1522 GTEST_CHECK_(sockfd_ != -1)
1523 << "CloseConnection() can be called only when there is a connection.";
1524
1525 close(sockfd_);
1526 sockfd_ = -1;
1527 }
1528
1529 int sockfd_; // socket file descriptor
1530 const string host_name_;
1531 const string port_num_;
1532
1533 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1534 }; // class SocketWriter
1535
1536 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1537 static string UrlEncode(const char* str);
1538
1539 StreamingListener(const string& host, const string& port)
1540 : socket_writer_(new SocketWriter(host, port)) { Start(); }
1541
1542 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543 : socket_writer_(socket_writer) { Start(); }
1544
1545 void OnTestProgramStart(const UnitTest& /* unit_test */) {
1546 SendLn("event=TestProgramStart");
1547 }
1548
1549 void OnTestProgramEnd(const UnitTest& unit_test) {
1550 // Note that Google Test current only report elapsed time for each
1551 // test iteration, not for the entire test program.
1552 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1553
1554 // Notify the streaming server to stop.
1555 socket_writer_->CloseConnection();
1556 }
1557
1558 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1559 SendLn("event=TestIterationStart&iteration=" +
1560 StreamableToString(iteration));
1561 }
1562
1563 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1564 SendLn("event=TestIterationEnd&passed=" +
1565 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1566 StreamableToString(unit_test.elapsed_time()) + "ms");
1567 }
1568
1569 void OnTestCaseStart(const TestCase& test_case) {
1570 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1571 }
1572
1573 void OnTestCaseEnd(const TestCase& test_case) {
1574 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1575 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1576 + "ms");
1577 }
1578
1579 void OnTestStart(const TestInfo& test_info) {
1580 SendLn(std::string("event=TestStart&name=") + test_info.name());
1581 }
1582
1583 void OnTestEnd(const TestInfo& test_info) {
1584 SendLn("event=TestEnd&passed=" +
1585 FormatBool((test_info.result())->Passed()) +
1586 "&elapsed_time=" +
1587 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1588 }
1589
1590 void OnTestPartResult(const TestPartResult& test_part_result) {
1591 const char* file_name = test_part_result.file_name();
1592 if (file_name == NULL)
1593 file_name = "";
1594 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1595 "&line=" + StreamableToString(test_part_result.line_number()) +
1596 "&message=" + UrlEncode(test_part_result.message()));
1597 }
1598
1599 private:
1600 // Sends the given message and a newline to the socket.
1601 void SendLn(const string& message) { socket_writer_->SendLn(message); }
1602
1603 // Called at the start of streaming to notify the receiver what
1604 // protocol we are using.
1605 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1606
1607 string FormatBool(bool value) { return value ? "1" : "0"; }
1608
1609 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1610
1611 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1612}; // class StreamingListener
1613
1614#endif // GTEST_CAN_STREAM_RESULTS_
1615
Keir Mierle8ebb0732012-04-30 23:09:08 -07001616} // namespace internal
1617} // namespace testing
1618
1619#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1620#undef GTEST_IMPLEMENTATION_
1621
1622#if GTEST_OS_WINDOWS
1623# define vsnprintf _vsnprintf
1624#endif // GTEST_OS_WINDOWS
1625
1626namespace testing {
1627
1628using internal::CountIf;
1629using internal::ForEach;
1630using internal::GetElementOr;
1631using internal::Shuffle;
1632
1633// Constants.
1634
1635// A test whose test case name or test name matches this filter is
1636// disabled and not run.
1637static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1638
1639// A test case whose name matches this filter is considered a death
1640// test case and will be run before test cases whose name doesn't
1641// match this filter.
1642static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1643
1644// A test filter that matches everything.
1645static const char kUniversalFilter[] = "*";
1646
1647// The default output file for XML output.
1648static const char kDefaultOutputFile[] = "test_detail.xml";
1649
1650// The environment variable name for the test shard index.
1651static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1652// The environment variable name for the total number of test shards.
1653static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1654// The environment variable name for the test shard status file.
1655static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1656
1657namespace internal {
1658
1659// The text used in failure messages to indicate the start of the
1660// stack trace.
1661const char kStackTraceMarker[] = "\nStack trace:\n";
1662
1663// g_help_flag is true iff the --help flag or an equivalent form is
1664// specified on the command line.
1665bool g_help_flag = false;
1666
1667} // namespace internal
1668
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001669static const char* GetDefaultFilter() {
1670 return kUniversalFilter;
1671}
1672
Keir Mierle8ebb0732012-04-30 23:09:08 -07001673GTEST_DEFINE_bool_(
1674 also_run_disabled_tests,
1675 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1676 "Run disabled tests too, in addition to the tests normally being run.");
1677
1678GTEST_DEFINE_bool_(
1679 break_on_failure,
1680 internal::BoolFromGTestEnv("break_on_failure", false),
1681 "True iff a failed assertion should be a debugger break-point.");
1682
1683GTEST_DEFINE_bool_(
1684 catch_exceptions,
1685 internal::BoolFromGTestEnv("catch_exceptions", true),
1686 "True iff " GTEST_NAME_
1687 " should catch exceptions and treat them as test failures.");
1688
1689GTEST_DEFINE_string_(
1690 color,
1691 internal::StringFromGTestEnv("color", "auto"),
1692 "Whether to use colors in the output. Valid values: yes, no, "
1693 "and auto. 'auto' means to use colors if the output is "
1694 "being sent to a terminal and the TERM environment variable "
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001695 "is set to a terminal type that supports colors.");
Keir Mierle8ebb0732012-04-30 23:09:08 -07001696
1697GTEST_DEFINE_string_(
1698 filter,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001699 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
Keir Mierle8ebb0732012-04-30 23:09:08 -07001700 "A colon-separated list of glob (not regex) patterns "
1701 "for filtering the tests to run, optionally followed by a "
1702 "'-' and a : separated list of negative patterns (tests to "
1703 "exclude). A test is run if it matches one of the positive "
1704 "patterns and does not match any of the negative patterns.");
1705
1706GTEST_DEFINE_bool_(list_tests, false,
1707 "List all tests without running them.");
1708
1709GTEST_DEFINE_string_(
1710 output,
1711 internal::StringFromGTestEnv("output", ""),
1712 "A format (currently must be \"xml\"), optionally followed "
1713 "by a colon and an output file name or directory. A directory "
1714 "is indicated by a trailing pathname separator. "
1715 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1716 "If a directory is specified, output files will be created "
1717 "within that directory, with file-names based on the test "
1718 "executable's name and, if necessary, made unique by adding "
1719 "digits.");
1720
1721GTEST_DEFINE_bool_(
1722 print_time,
1723 internal::BoolFromGTestEnv("print_time", true),
1724 "True iff " GTEST_NAME_
1725 " should display elapsed time in text output.");
1726
1727GTEST_DEFINE_int32_(
1728 random_seed,
1729 internal::Int32FromGTestEnv("random_seed", 0),
1730 "Random number seed to use when shuffling test orders. Must be in range "
1731 "[1, 99999], or 0 to use a seed based on the current time.");
1732
1733GTEST_DEFINE_int32_(
1734 repeat,
1735 internal::Int32FromGTestEnv("repeat", 1),
1736 "How many times to repeat each test. Specify a negative number "
1737 "for repeating forever. Useful for shaking out flaky tests.");
1738
1739GTEST_DEFINE_bool_(
1740 show_internal_stack_frames, false,
1741 "True iff " GTEST_NAME_ " should include internal stack frames when "
1742 "printing test failure stack traces.");
1743
1744GTEST_DEFINE_bool_(
1745 shuffle,
1746 internal::BoolFromGTestEnv("shuffle", false),
1747 "True iff " GTEST_NAME_
1748 " should randomize tests' order on every run.");
1749
1750GTEST_DEFINE_int32_(
1751 stack_trace_depth,
1752 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1753 "The maximum number of stack frames to print when an "
1754 "assertion fails. The valid range is 0 through 100, inclusive.");
1755
1756GTEST_DEFINE_string_(
1757 stream_result_to,
1758 internal::StringFromGTestEnv("stream_result_to", ""),
1759 "This flag specifies the host name and the port number on which to stream "
1760 "test results. Example: \"localhost:555\". The flag is effective only on "
1761 "Linux.");
1762
1763GTEST_DEFINE_bool_(
1764 throw_on_failure,
1765 internal::BoolFromGTestEnv("throw_on_failure", false),
1766 "When this flag is specified, a failed assertion will throw an exception "
1767 "if exceptions are enabled or exit the program with a non-zero code "
1768 "otherwise.");
1769
1770namespace internal {
1771
1772// Generates a random number from [0, range), using a Linear
1773// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1774// than kMaxRange.
1775UInt32 Random::Generate(UInt32 range) {
1776 // These constants are the same as are used in glibc's rand(3).
1777 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1778
1779 GTEST_CHECK_(range > 0)
1780 << "Cannot generate a number in the range [0, 0).";
1781 GTEST_CHECK_(range <= kMaxRange)
1782 << "Generation of a number in [0, " << range << ") was requested, "
1783 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1784
1785 // Converting via modulus introduces a bit of downward bias, but
1786 // it's simple, and a linear congruential generator isn't too good
1787 // to begin with.
1788 return state_ % range;
1789}
1790
1791// GTestIsInitialized() returns true iff the user has initialized
1792// Google Test. Useful for catching the user mistake of not initializing
1793// Google Test before calling RUN_ALL_TESTS().
1794//
1795// A user must call testing::InitGoogleTest() to initialize Google
1796// Test. g_init_gtest_count is set to the number of times
1797// InitGoogleTest() has been called. We don't protect this variable
1798// under a mutex as it is only accessed in the main thread.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001799GTEST_API_ int g_init_gtest_count = 0;
Keir Mierle8ebb0732012-04-30 23:09:08 -07001800static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1801
1802// Iterates over a vector of TestCases, keeping a running sum of the
1803// results of calling a given int-returning method on each.
1804// Returns the sum.
1805static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1806 int (TestCase::*method)() const) {
1807 int sum = 0;
1808 for (size_t i = 0; i < case_list.size(); i++) {
1809 sum += (case_list[i]->*method)();
1810 }
1811 return sum;
1812}
1813
1814// Returns true iff the test case passed.
1815static bool TestCasePassed(const TestCase* test_case) {
1816 return test_case->should_run() && test_case->Passed();
1817}
1818
1819// Returns true iff the test case failed.
1820static bool TestCaseFailed(const TestCase* test_case) {
1821 return test_case->should_run() && test_case->Failed();
1822}
1823
1824// Returns true iff test_case contains at least one test that should
1825// run.
1826static bool ShouldRunTestCase(const TestCase* test_case) {
1827 return test_case->should_run();
1828}
1829
1830// AssertHelper constructor.
1831AssertHelper::AssertHelper(TestPartResult::Type type,
1832 const char* file,
1833 int line,
1834 const char* message)
1835 : data_(new AssertHelperData(type, file, line, message)) {
1836}
1837
1838AssertHelper::~AssertHelper() {
1839 delete data_;
1840}
1841
1842// Message assignment, for assertion streaming support.
1843void AssertHelper::operator=(const Message& message) const {
1844 UnitTest::GetInstance()->
1845 AddTestPartResult(data_->type, data_->file, data_->line,
1846 AppendUserMessage(data_->message, message),
1847 UnitTest::GetInstance()->impl()
1848 ->CurrentOsStackTraceExceptTop(1)
1849 // Skips the stack frame for this function itself.
1850 ); // NOLINT
1851}
1852
1853// Mutex for linked pointers.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001854GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
Keir Mierle8ebb0732012-04-30 23:09:08 -07001855
1856// Application pathname gotten in InitGoogleTest.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001857std::string g_executable_path;
Keir Mierle8ebb0732012-04-30 23:09:08 -07001858
1859// Returns the current application's name, removing directory path if that
1860// is present.
1861FilePath GetCurrentExecutableName() {
1862 FilePath result;
1863
1864#if GTEST_OS_WINDOWS
1865 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1866#else
1867 result.Set(FilePath(g_executable_path));
1868#endif // GTEST_OS_WINDOWS
1869
1870 return result.RemoveDirectoryName();
1871}
1872
1873// Functions for processing the gtest_output flag.
1874
1875// Returns the output format, or "" for normal printed output.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001876std::string UnitTestOptions::GetOutputFormat() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07001877 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001878 if (gtest_output_flag == NULL) return std::string("");
Keir Mierle8ebb0732012-04-30 23:09:08 -07001879
1880 const char* const colon = strchr(gtest_output_flag, ':');
1881 return (colon == NULL) ?
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001882 std::string(gtest_output_flag) :
1883 std::string(gtest_output_flag, colon - gtest_output_flag);
Keir Mierle8ebb0732012-04-30 23:09:08 -07001884}
1885
1886// Returns the name of the requested output file, or the default if none
1887// was explicitly specified.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001888std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07001889 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1890 if (gtest_output_flag == NULL)
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001891 return "";
Keir Mierle8ebb0732012-04-30 23:09:08 -07001892
1893 const char* const colon = strchr(gtest_output_flag, ':');
1894 if (colon == NULL)
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001895 return internal::FilePath::ConcatPaths(
1896 internal::FilePath(
1897 UnitTest::GetInstance()->original_working_dir()),
1898 internal::FilePath(kDefaultOutputFile)).string();
Keir Mierle8ebb0732012-04-30 23:09:08 -07001899
1900 internal::FilePath output_name(colon + 1);
1901 if (!output_name.IsAbsolutePath())
1902 // TODO(wan@google.com): on Windows \some\path is not an absolute
1903 // path (as its meaning depends on the current drive), yet the
1904 // following logic for turning it into an absolute path is wrong.
1905 // Fix it.
1906 output_name = internal::FilePath::ConcatPaths(
1907 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1908 internal::FilePath(colon + 1));
1909
1910 if (!output_name.IsDirectory())
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001911 return output_name.string();
Keir Mierle8ebb0732012-04-30 23:09:08 -07001912
1913 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1914 output_name, internal::GetCurrentExecutableName(),
1915 GetOutputFormat().c_str()));
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001916 return result.string();
Keir Mierle8ebb0732012-04-30 23:09:08 -07001917}
1918
1919// Returns true iff the wildcard pattern matches the string. The
1920// first ':' or '\0' character in pattern marks the end of it.
1921//
1922// This recursive algorithm isn't very efficient, but is clear and
1923// works well enough for matching test names, which are short.
1924bool UnitTestOptions::PatternMatchesString(const char *pattern,
1925 const char *str) {
1926 switch (*pattern) {
1927 case '\0':
1928 case ':': // Either ':' or '\0' marks the end of the pattern.
1929 return *str == '\0';
1930 case '?': // Matches any single character.
1931 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1932 case '*': // Matches any string (possibly empty) of characters.
1933 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1934 PatternMatchesString(pattern + 1, str);
1935 default: // Non-special character. Matches itself.
1936 return *pattern == *str &&
1937 PatternMatchesString(pattern + 1, str + 1);
1938 }
1939}
1940
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001941bool UnitTestOptions::MatchesFilter(
1942 const std::string& name, const char* filter) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07001943 const char *cur_pattern = filter;
1944 for (;;) {
1945 if (PatternMatchesString(cur_pattern, name.c_str())) {
1946 return true;
1947 }
1948
1949 // Finds the next pattern in the filter.
1950 cur_pattern = strchr(cur_pattern, ':');
1951
1952 // Returns if no more pattern can be found.
1953 if (cur_pattern == NULL) {
1954 return false;
1955 }
1956
1957 // Skips the pattern separater (the ':' character).
1958 cur_pattern++;
1959 }
1960}
1961
Keir Mierle8ebb0732012-04-30 23:09:08 -07001962// Returns true iff the user-specified filter matches the test case
1963// name and the test name.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001964bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
1965 const std::string &test_name) {
1966 const std::string& full_name = test_case_name + "." + test_name.c_str();
Keir Mierle8ebb0732012-04-30 23:09:08 -07001967
1968 // Split --gtest_filter at '-', if there is one, to separate into
1969 // positive filter and negative filter portions
1970 const char* const p = GTEST_FLAG(filter).c_str();
1971 const char* const dash = strchr(p, '-');
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001972 std::string positive;
1973 std::string negative;
Keir Mierle8ebb0732012-04-30 23:09:08 -07001974 if (dash == NULL) {
1975 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001976 negative = "";
Keir Mierle8ebb0732012-04-30 23:09:08 -07001977 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07001978 positive = std::string(p, dash); // Everything up to the dash
1979 negative = std::string(dash + 1); // Everything after the dash
Keir Mierle8ebb0732012-04-30 23:09:08 -07001980 if (positive.empty()) {
1981 // Treat '-test1' as the same as '*-test1'
1982 positive = kUniversalFilter;
1983 }
1984 }
1985
1986 // A filter is a colon-separated list of patterns. It matches a
1987 // test if any pattern in it matches the test.
1988 return (MatchesFilter(full_name, positive.c_str()) &&
1989 !MatchesFilter(full_name, negative.c_str()));
1990}
1991
1992#if GTEST_HAS_SEH
1993// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1994// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1995// This function is useful as an __except condition.
1996int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1997 // Google Test should handle a SEH exception if:
1998 // 1. the user wants it to, AND
1999 // 2. this is not a breakpoint exception, AND
2000 // 3. this is not a C++ exception (VC++ implements them via SEH,
2001 // apparently).
2002 //
2003 // SEH exception code for C++ exceptions.
2004 // (see http://support.microsoft.com/kb/185294 for more information).
2005 const DWORD kCxxExceptionCode = 0xe06d7363;
2006
2007 bool should_handle = true;
2008
2009 if (!GTEST_FLAG(catch_exceptions))
2010 should_handle = false;
2011 else if (exception_code == EXCEPTION_BREAKPOINT)
2012 should_handle = false;
2013 else if (exception_code == kCxxExceptionCode)
2014 should_handle = false;
2015
2016 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2017}
2018#endif // GTEST_HAS_SEH
2019
2020} // namespace internal
2021
2022// The c'tor sets this object as the test part result reporter used by
2023// Google Test. The 'result' parameter specifies where to report the
2024// results. Intercepts only failures from the current thread.
2025ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2026 TestPartResultArray* result)
2027 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2028 result_(result) {
2029 Init();
2030}
2031
2032// The c'tor sets this object as the test part result reporter used by
2033// Google Test. The 'result' parameter specifies where to report the
2034// results.
2035ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2036 InterceptMode intercept_mode, TestPartResultArray* result)
2037 : intercept_mode_(intercept_mode),
2038 result_(result) {
2039 Init();
2040}
2041
2042void ScopedFakeTestPartResultReporter::Init() {
2043 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2044 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2045 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2046 impl->SetGlobalTestPartResultReporter(this);
2047 } else {
2048 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2049 impl->SetTestPartResultReporterForCurrentThread(this);
2050 }
2051}
2052
2053// The d'tor restores the test part result reporter used by Google Test
2054// before.
2055ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2056 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2057 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2058 impl->SetGlobalTestPartResultReporter(old_reporter_);
2059 } else {
2060 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2061 }
2062}
2063
2064// Increments the test part result count and remembers the result.
2065// This method is from the TestPartResultReporterInterface interface.
2066void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2067 const TestPartResult& result) {
2068 result_->Append(result);
2069}
2070
2071namespace internal {
2072
2073// Returns the type ID of ::testing::Test. We should always call this
2074// instead of GetTypeId< ::testing::Test>() to get the type ID of
2075// testing::Test. This is to work around a suspected linker bug when
2076// using Google Test as a framework on Mac OS X. The bug causes
2077// GetTypeId< ::testing::Test>() to return different values depending
2078// on whether the call is from the Google Test framework itself or
2079// from user test code. GetTestTypeId() is guaranteed to always
2080// return the same value, as it always calls GetTypeId<>() from the
2081// gtest.cc, which is within the Google Test framework.
2082TypeId GetTestTypeId() {
2083 return GetTypeId<Test>();
2084}
2085
2086// The value of GetTestTypeId() as seen from within the Google Test
2087// library. This is solely for testing GetTestTypeId().
2088extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2089
2090// This predicate-formatter checks that 'results' contains a test part
2091// failure of the given type and that the failure message contains the
2092// given substring.
2093AssertionResult HasOneFailure(const char* /* results_expr */,
2094 const char* /* type_expr */,
2095 const char* /* substr_expr */,
2096 const TestPartResultArray& results,
2097 TestPartResult::Type type,
2098 const string& substr) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002099 const std::string expected(type == TestPartResult::kFatalFailure ?
Keir Mierle8ebb0732012-04-30 23:09:08 -07002100 "1 fatal failure" :
2101 "1 non-fatal failure");
2102 Message msg;
2103 if (results.size() != 1) {
2104 msg << "Expected: " << expected << "\n"
2105 << " Actual: " << results.size() << " failures";
2106 for (int i = 0; i < results.size(); i++) {
2107 msg << "\n" << results.GetTestPartResult(i);
2108 }
2109 return AssertionFailure() << msg;
2110 }
2111
2112 const TestPartResult& r = results.GetTestPartResult(0);
2113 if (r.type() != type) {
2114 return AssertionFailure() << "Expected: " << expected << "\n"
2115 << " Actual:\n"
2116 << r;
2117 }
2118
2119 if (strstr(r.message(), substr.c_str()) == NULL) {
2120 return AssertionFailure() << "Expected: " << expected << " containing \""
2121 << substr << "\"\n"
2122 << " Actual:\n"
2123 << r;
2124 }
2125
2126 return AssertionSuccess();
2127}
2128
2129// The constructor of SingleFailureChecker remembers where to look up
2130// test part results, what type of failure we expect, and what
2131// substring the failure message should contain.
2132SingleFailureChecker:: SingleFailureChecker(
2133 const TestPartResultArray* results,
2134 TestPartResult::Type type,
2135 const string& substr)
2136 : results_(results),
2137 type_(type),
2138 substr_(substr) {}
2139
2140// The destructor of SingleFailureChecker verifies that the given
2141// TestPartResultArray contains exactly one failure that has the given
2142// type and contains the given substring. If that's not the case, a
2143// non-fatal failure will be generated.
2144SingleFailureChecker::~SingleFailureChecker() {
2145 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2146}
2147
2148DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2149 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2150
2151void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2152 const TestPartResult& result) {
2153 unit_test_->current_test_result()->AddTestPartResult(result);
2154 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2155}
2156
2157DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2158 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2159
2160void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2161 const TestPartResult& result) {
2162 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2163}
2164
2165// Returns the global test part result reporter.
2166TestPartResultReporterInterface*
2167UnitTestImpl::GetGlobalTestPartResultReporter() {
2168 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2169 return global_test_part_result_repoter_;
2170}
2171
2172// Sets the global test part result reporter.
2173void UnitTestImpl::SetGlobalTestPartResultReporter(
2174 TestPartResultReporterInterface* reporter) {
2175 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2176 global_test_part_result_repoter_ = reporter;
2177}
2178
2179// Returns the test part result reporter for the current thread.
2180TestPartResultReporterInterface*
2181UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2182 return per_thread_test_part_result_reporter_.get();
2183}
2184
2185// Sets the test part result reporter for the current thread.
2186void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2187 TestPartResultReporterInterface* reporter) {
2188 per_thread_test_part_result_reporter_.set(reporter);
2189}
2190
2191// Gets the number of successful test cases.
2192int UnitTestImpl::successful_test_case_count() const {
2193 return CountIf(test_cases_, TestCasePassed);
2194}
2195
2196// Gets the number of failed test cases.
2197int UnitTestImpl::failed_test_case_count() const {
2198 return CountIf(test_cases_, TestCaseFailed);
2199}
2200
2201// Gets the number of all test cases.
2202int UnitTestImpl::total_test_case_count() const {
2203 return static_cast<int>(test_cases_.size());
2204}
2205
2206// Gets the number of all test cases that contain at least one test
2207// that should run.
2208int UnitTestImpl::test_case_to_run_count() const {
2209 return CountIf(test_cases_, ShouldRunTestCase);
2210}
2211
2212// Gets the number of successful tests.
2213int UnitTestImpl::successful_test_count() const {
2214 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2215}
2216
2217// Gets the number of failed tests.
2218int UnitTestImpl::failed_test_count() const {
2219 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2220}
2221
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002222// Gets the number of disabled tests that will be reported in the XML report.
2223int UnitTestImpl::reportable_disabled_test_count() const {
2224 return SumOverTestCaseList(test_cases_,
2225 &TestCase::reportable_disabled_test_count);
2226}
2227
Keir Mierle8ebb0732012-04-30 23:09:08 -07002228// Gets the number of disabled tests.
2229int UnitTestImpl::disabled_test_count() const {
2230 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2231}
2232
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002233// Gets the number of tests to be printed in the XML report.
2234int UnitTestImpl::reportable_test_count() const {
2235 return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2236}
2237
Keir Mierle8ebb0732012-04-30 23:09:08 -07002238// Gets the number of all tests.
2239int UnitTestImpl::total_test_count() const {
2240 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2241}
2242
2243// Gets the number of tests that should run.
2244int UnitTestImpl::test_to_run_count() const {
2245 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2246}
2247
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002248// Returns the current OS stack trace as an std::string.
Keir Mierle8ebb0732012-04-30 23:09:08 -07002249//
2250// The maximum number of stack frames to be included is specified by
2251// the gtest_stack_trace_depth flag. The skip_count parameter
2252// specifies the number of top frames to be skipped, which doesn't
2253// count against the number of frames to be included.
2254//
2255// For example, if Foo() calls Bar(), which in turn calls
2256// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2257// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002258std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07002259 (void)skip_count;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002260 return "";
Keir Mierle8ebb0732012-04-30 23:09:08 -07002261}
2262
2263// Returns the current time in milliseconds.
2264TimeInMillis GetTimeInMillis() {
2265#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2266 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2267 // http://analogous.blogspot.com/2005/04/epoch.html
2268 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2269 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2270 const DWORD kTenthMicrosInMilliSecond = 10000;
2271
2272 SYSTEMTIME now_systime;
2273 FILETIME now_filetime;
2274 ULARGE_INTEGER now_int64;
2275 // TODO(kenton@google.com): Shouldn't this just use
2276 // GetSystemTimeAsFileTime()?
2277 GetSystemTime(&now_systime);
2278 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2279 now_int64.LowPart = now_filetime.dwLowDateTime;
2280 now_int64.HighPart = now_filetime.dwHighDateTime;
2281 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2282 kJavaEpochToWinFileTimeDelta;
2283 return now_int64.QuadPart;
2284 }
2285 return 0;
2286#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2287 __timeb64 now;
2288
2289# ifdef _MSC_VER
2290
2291 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2292 // (deprecated function) there.
2293 // TODO(kenton@google.com): Use GetTickCount()? Or use
2294 // SystemTimeToFileTime()
2295# pragma warning(push) // Saves the current warning state.
2296# pragma warning(disable:4996) // Temporarily disables warning 4996.
2297 _ftime64(&now);
2298# pragma warning(pop) // Restores the warning state.
2299# else
2300
2301 _ftime64(&now);
2302
2303# endif // _MSC_VER
2304
2305 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2306#elif GTEST_HAS_GETTIMEOFDAY_
2307 struct timeval now;
2308 gettimeofday(&now, NULL);
2309 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2310#else
2311# error "Don't know how to get the current time on your system."
2312#endif
2313}
2314
2315// Utilities
2316
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002317// class String.
Keir Mierle8ebb0732012-04-30 23:09:08 -07002318
2319#if GTEST_OS_WINDOWS_MOBILE
2320// Creates a UTF-16 wide string from the given ANSI string, allocating
2321// memory using new. The caller is responsible for deleting the return
2322// value using delete[]. Returns the wide string, or NULL if the
2323// input is NULL.
2324LPCWSTR String::AnsiToUtf16(const char* ansi) {
2325 if (!ansi) return NULL;
2326 const int length = strlen(ansi);
2327 const int unicode_length =
2328 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2329 NULL, 0);
2330 WCHAR* unicode = new WCHAR[unicode_length + 1];
2331 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2332 unicode, unicode_length);
2333 unicode[unicode_length] = 0;
2334 return unicode;
2335}
2336
2337// Creates an ANSI string from the given wide string, allocating
2338// memory using new. The caller is responsible for deleting the return
2339// value using delete[]. Returns the ANSI string, or NULL if the
2340// input is NULL.
2341const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2342 if (!utf16_str) return NULL;
2343 const int ansi_length =
2344 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2345 NULL, 0, NULL, NULL);
2346 char* ansi = new char[ansi_length + 1];
2347 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2348 ansi, ansi_length, NULL, NULL);
2349 ansi[ansi_length] = 0;
2350 return ansi;
2351}
2352
2353#endif // GTEST_OS_WINDOWS_MOBILE
2354
2355// Compares two C strings. Returns true iff they have the same content.
2356//
2357// Unlike strcmp(), this function can handle NULL argument(s). A NULL
2358// C string is considered different to any non-NULL C string,
2359// including the empty string.
2360bool String::CStringEquals(const char * lhs, const char * rhs) {
2361 if ( lhs == NULL ) return rhs == NULL;
2362
2363 if ( rhs == NULL ) return false;
2364
2365 return strcmp(lhs, rhs) == 0;
2366}
2367
2368#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2369
2370// Converts an array of wide chars to a narrow string using the UTF-8
2371// encoding, and streams the result to the given Message object.
2372static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2373 Message* msg) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07002374 for (size_t i = 0; i != length; ) { // NOLINT
2375 if (wstr[i] != L'\0') {
2376 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2377 while (i != length && wstr[i] != L'\0')
2378 i++;
2379 } else {
2380 *msg << '\0';
2381 i++;
2382 }
2383 }
2384}
2385
2386#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2387
2388} // namespace internal
2389
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002390// Constructs an empty Message.
2391// We allocate the stringstream separately because otherwise each use of
2392// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2393// stack frame leading to huge stack frames in some cases; gcc does not reuse
2394// the stack space.
2395Message::Message() : ss_(new ::std::stringstream) {
2396 // By default, we want there to be enough precision when printing
2397 // a double to a Message.
2398 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2399}
2400
2401// These two overloads allow streaming a wide C string to a Message
2402// using the UTF-8 encoding.
2403Message& Message::operator <<(const wchar_t* wide_c_str) {
2404 return *this << internal::String::ShowWideCString(wide_c_str);
2405}
2406Message& Message::operator <<(wchar_t* wide_c_str) {
2407 return *this << internal::String::ShowWideCString(wide_c_str);
2408}
2409
Keir Mierle8ebb0732012-04-30 23:09:08 -07002410#if GTEST_HAS_STD_WSTRING
2411// Converts the given wide string to a narrow string using the UTF-8
2412// encoding, and streams the result to this Message object.
2413Message& Message::operator <<(const ::std::wstring& wstr) {
2414 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2415 return *this;
2416}
2417#endif // GTEST_HAS_STD_WSTRING
2418
2419#if GTEST_HAS_GLOBAL_WSTRING
2420// Converts the given wide string to a narrow string using the UTF-8
2421// encoding, and streams the result to this Message object.
2422Message& Message::operator <<(const ::wstring& wstr) {
2423 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2424 return *this;
2425}
2426#endif // GTEST_HAS_GLOBAL_WSTRING
2427
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002428// Gets the text streamed to this object so far as an std::string.
2429// Each '\0' character in the buffer is replaced with "\\0".
2430std::string Message::GetString() const {
2431 return internal::StringStreamToString(ss_.get());
2432}
2433
Keir Mierle8ebb0732012-04-30 23:09:08 -07002434// AssertionResult constructors.
2435// Used in EXPECT_TRUE/FALSE(assertion_result).
2436AssertionResult::AssertionResult(const AssertionResult& other)
2437 : success_(other.success_),
2438 message_(other.message_.get() != NULL ?
2439 new ::std::string(*other.message_) :
2440 static_cast< ::std::string*>(NULL)) {
2441}
2442
2443// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2444AssertionResult AssertionResult::operator!() const {
2445 AssertionResult negation(!success_);
2446 if (message_.get() != NULL)
2447 negation << *message_;
2448 return negation;
2449}
2450
2451// Makes a successful assertion result.
2452AssertionResult AssertionSuccess() {
2453 return AssertionResult(true);
2454}
2455
2456// Makes a failed assertion result.
2457AssertionResult AssertionFailure() {
2458 return AssertionResult(false);
2459}
2460
2461// Makes a failed assertion result with the given failure message.
2462// Deprecated; use AssertionFailure() << message.
2463AssertionResult AssertionFailure(const Message& message) {
2464 return AssertionFailure() << message;
2465}
2466
2467namespace internal {
2468
2469// Constructs and returns the message for an equality assertion
2470// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2471//
2472// The first four parameters are the expressions used in the assertion
2473// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2474// where foo is 5 and bar is 6, we have:
2475//
2476// expected_expression: "foo"
2477// actual_expression: "bar"
2478// expected_value: "5"
2479// actual_value: "6"
2480//
2481// The ignoring_case parameter is true iff the assertion is a
2482// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2483// be inserted into the message.
2484AssertionResult EqFailure(const char* expected_expression,
2485 const char* actual_expression,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002486 const std::string& expected_value,
2487 const std::string& actual_value,
Keir Mierle8ebb0732012-04-30 23:09:08 -07002488 bool ignoring_case) {
2489 Message msg;
2490 msg << "Value of: " << actual_expression;
2491 if (actual_value != actual_expression) {
2492 msg << "\n Actual: " << actual_value;
2493 }
2494
2495 msg << "\nExpected: " << expected_expression;
2496 if (ignoring_case) {
2497 msg << " (ignoring case)";
2498 }
2499 if (expected_value != expected_expression) {
2500 msg << "\nWhich is: " << expected_value;
2501 }
2502
2503 return AssertionFailure() << msg;
2504}
2505
2506// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002507std::string GetBoolAssertionFailureMessage(
2508 const AssertionResult& assertion_result,
2509 const char* expression_text,
2510 const char* actual_predicate_value,
2511 const char* expected_predicate_value) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07002512 const char* actual_message = assertion_result.message();
2513 Message msg;
2514 msg << "Value of: " << expression_text
2515 << "\n Actual: " << actual_predicate_value;
2516 if (actual_message[0] != '\0')
2517 msg << " (" << actual_message << ")";
2518 msg << "\nExpected: " << expected_predicate_value;
2519 return msg.GetString();
2520}
2521
2522// Helper function for implementing ASSERT_NEAR.
2523AssertionResult DoubleNearPredFormat(const char* expr1,
2524 const char* expr2,
2525 const char* abs_error_expr,
2526 double val1,
2527 double val2,
2528 double abs_error) {
2529 const double diff = fabs(val1 - val2);
2530 if (diff <= abs_error) return AssertionSuccess();
2531
2532 // TODO(wan): do not print the value of an expression if it's
2533 // already a literal.
2534 return AssertionFailure()
2535 << "The difference between " << expr1 << " and " << expr2
2536 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2537 << expr1 << " evaluates to " << val1 << ",\n"
2538 << expr2 << " evaluates to " << val2 << ", and\n"
2539 << abs_error_expr << " evaluates to " << abs_error << ".";
2540}
2541
2542
2543// Helper template for implementing FloatLE() and DoubleLE().
2544template <typename RawType>
2545AssertionResult FloatingPointLE(const char* expr1,
2546 const char* expr2,
2547 RawType val1,
2548 RawType val2) {
2549 // Returns success if val1 is less than val2,
2550 if (val1 < val2) {
2551 return AssertionSuccess();
2552 }
2553
2554 // or if val1 is almost equal to val2.
2555 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2556 if (lhs.AlmostEquals(rhs)) {
2557 return AssertionSuccess();
2558 }
2559
2560 // Note that the above two checks will both fail if either val1 or
2561 // val2 is NaN, as the IEEE floating-point standard requires that
2562 // any predicate involving a NaN must return false.
2563
2564 ::std::stringstream val1_ss;
2565 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2566 << val1;
2567
2568 ::std::stringstream val2_ss;
2569 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2570 << val2;
2571
2572 return AssertionFailure()
2573 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2574 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2575 << StringStreamToString(&val2_ss);
2576}
2577
2578} // namespace internal
2579
2580// Asserts that val1 is less than, or almost equal to, val2. Fails
2581// otherwise. In particular, it fails if either val1 or val2 is NaN.
2582AssertionResult FloatLE(const char* expr1, const char* expr2,
2583 float val1, float val2) {
2584 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2585}
2586
2587// Asserts that val1 is less than, or almost equal to, val2. Fails
2588// otherwise. In particular, it fails if either val1 or val2 is NaN.
2589AssertionResult DoubleLE(const char* expr1, const char* expr2,
2590 double val1, double val2) {
2591 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2592}
2593
2594namespace internal {
2595
2596// The helper function for {ASSERT|EXPECT}_EQ with int or enum
2597// arguments.
2598AssertionResult CmpHelperEQ(const char* expected_expression,
2599 const char* actual_expression,
2600 BiggestInt expected,
2601 BiggestInt actual) {
2602 if (expected == actual) {
2603 return AssertionSuccess();
2604 }
2605
2606 return EqFailure(expected_expression,
2607 actual_expression,
2608 FormatForComparisonFailureMessage(expected, actual),
2609 FormatForComparisonFailureMessage(actual, expected),
2610 false);
2611}
2612
2613// A macro for implementing the helper functions needed to implement
2614// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2615// just to avoid copy-and-paste of similar code.
2616#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2617AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2618 BiggestInt val1, BiggestInt val2) {\
2619 if (val1 op val2) {\
2620 return AssertionSuccess();\
2621 } else {\
2622 return AssertionFailure() \
2623 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2624 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2625 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2626 }\
2627}
2628
2629// Implements the helper function for {ASSERT|EXPECT}_NE with int or
2630// enum arguments.
2631GTEST_IMPL_CMP_HELPER_(NE, !=)
2632// Implements the helper function for {ASSERT|EXPECT}_LE with int or
2633// enum arguments.
2634GTEST_IMPL_CMP_HELPER_(LE, <=)
2635// Implements the helper function for {ASSERT|EXPECT}_LT with int or
2636// enum arguments.
2637GTEST_IMPL_CMP_HELPER_(LT, < )
2638// Implements the helper function for {ASSERT|EXPECT}_GE with int or
2639// enum arguments.
2640GTEST_IMPL_CMP_HELPER_(GE, >=)
2641// Implements the helper function for {ASSERT|EXPECT}_GT with int or
2642// enum arguments.
2643GTEST_IMPL_CMP_HELPER_(GT, > )
2644
2645#undef GTEST_IMPL_CMP_HELPER_
2646
2647// The helper function for {ASSERT|EXPECT}_STREQ.
2648AssertionResult CmpHelperSTREQ(const char* expected_expression,
2649 const char* actual_expression,
2650 const char* expected,
2651 const char* actual) {
2652 if (String::CStringEquals(expected, actual)) {
2653 return AssertionSuccess();
2654 }
2655
2656 return EqFailure(expected_expression,
2657 actual_expression,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002658 PrintToString(expected),
2659 PrintToString(actual),
Keir Mierle8ebb0732012-04-30 23:09:08 -07002660 false);
2661}
2662
2663// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2664AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2665 const char* actual_expression,
2666 const char* expected,
2667 const char* actual) {
2668 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2669 return AssertionSuccess();
2670 }
2671
2672 return EqFailure(expected_expression,
2673 actual_expression,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002674 PrintToString(expected),
2675 PrintToString(actual),
Keir Mierle8ebb0732012-04-30 23:09:08 -07002676 true);
2677}
2678
2679// The helper function for {ASSERT|EXPECT}_STRNE.
2680AssertionResult CmpHelperSTRNE(const char* s1_expression,
2681 const char* s2_expression,
2682 const char* s1,
2683 const char* s2) {
2684 if (!String::CStringEquals(s1, s2)) {
2685 return AssertionSuccess();
2686 } else {
2687 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2688 << s2_expression << "), actual: \""
2689 << s1 << "\" vs \"" << s2 << "\"";
2690 }
2691}
2692
2693// The helper function for {ASSERT|EXPECT}_STRCASENE.
2694AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2695 const char* s2_expression,
2696 const char* s1,
2697 const char* s2) {
2698 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2699 return AssertionSuccess();
2700 } else {
2701 return AssertionFailure()
2702 << "Expected: (" << s1_expression << ") != ("
2703 << s2_expression << ") (ignoring case), actual: \""
2704 << s1 << "\" vs \"" << s2 << "\"";
2705 }
2706}
2707
2708} // namespace internal
2709
2710namespace {
2711
2712// Helper functions for implementing IsSubString() and IsNotSubstring().
2713
2714// This group of overloaded functions return true iff needle is a
2715// substring of haystack. NULL is considered a substring of itself
2716// only.
2717
2718bool IsSubstringPred(const char* needle, const char* haystack) {
2719 if (needle == NULL || haystack == NULL)
2720 return needle == haystack;
2721
2722 return strstr(haystack, needle) != NULL;
2723}
2724
2725bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2726 if (needle == NULL || haystack == NULL)
2727 return needle == haystack;
2728
2729 return wcsstr(haystack, needle) != NULL;
2730}
2731
2732// StringType here can be either ::std::string or ::std::wstring.
2733template <typename StringType>
2734bool IsSubstringPred(const StringType& needle,
2735 const StringType& haystack) {
2736 return haystack.find(needle) != StringType::npos;
2737}
2738
2739// This function implements either IsSubstring() or IsNotSubstring(),
2740// depending on the value of the expected_to_be_substring parameter.
2741// StringType here can be const char*, const wchar_t*, ::std::string,
2742// or ::std::wstring.
2743template <typename StringType>
2744AssertionResult IsSubstringImpl(
2745 bool expected_to_be_substring,
2746 const char* needle_expr, const char* haystack_expr,
2747 const StringType& needle, const StringType& haystack) {
2748 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2749 return AssertionSuccess();
2750
2751 const bool is_wide_string = sizeof(needle[0]) > 1;
2752 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2753 return AssertionFailure()
2754 << "Value of: " << needle_expr << "\n"
2755 << " Actual: " << begin_string_quote << needle << "\"\n"
2756 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2757 << "a substring of " << haystack_expr << "\n"
2758 << "Which is: " << begin_string_quote << haystack << "\"";
2759}
2760
2761} // namespace
2762
2763// IsSubstring() and IsNotSubstring() check whether needle is a
2764// substring of haystack (NULL is considered a substring of itself
2765// only), and return an appropriate error message when they fail.
2766
2767AssertionResult IsSubstring(
2768 const char* needle_expr, const char* haystack_expr,
2769 const char* needle, const char* haystack) {
2770 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2771}
2772
2773AssertionResult IsSubstring(
2774 const char* needle_expr, const char* haystack_expr,
2775 const wchar_t* needle, const wchar_t* haystack) {
2776 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2777}
2778
2779AssertionResult IsNotSubstring(
2780 const char* needle_expr, const char* haystack_expr,
2781 const char* needle, const char* haystack) {
2782 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2783}
2784
2785AssertionResult IsNotSubstring(
2786 const char* needle_expr, const char* haystack_expr,
2787 const wchar_t* needle, const wchar_t* haystack) {
2788 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2789}
2790
2791AssertionResult IsSubstring(
2792 const char* needle_expr, const char* haystack_expr,
2793 const ::std::string& needle, const ::std::string& haystack) {
2794 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2795}
2796
2797AssertionResult IsNotSubstring(
2798 const char* needle_expr, const char* haystack_expr,
2799 const ::std::string& needle, const ::std::string& haystack) {
2800 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2801}
2802
2803#if GTEST_HAS_STD_WSTRING
2804AssertionResult IsSubstring(
2805 const char* needle_expr, const char* haystack_expr,
2806 const ::std::wstring& needle, const ::std::wstring& haystack) {
2807 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2808}
2809
2810AssertionResult IsNotSubstring(
2811 const char* needle_expr, const char* haystack_expr,
2812 const ::std::wstring& needle, const ::std::wstring& haystack) {
2813 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2814}
2815#endif // GTEST_HAS_STD_WSTRING
2816
2817namespace internal {
2818
2819#if GTEST_OS_WINDOWS
2820
2821namespace {
2822
2823// Helper function for IsHRESULT{SuccessFailure} predicates
2824AssertionResult HRESULTFailureHelper(const char* expr,
2825 const char* expected,
2826 long hr) { // NOLINT
2827# if GTEST_OS_WINDOWS_MOBILE
2828
2829 // Windows CE doesn't support FormatMessage.
2830 const char error_text[] = "";
2831
2832# else
2833
2834 // Looks up the human-readable system message for the HRESULT code
2835 // and since we're not passing any params to FormatMessage, we don't
2836 // want inserts expanded.
2837 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2838 FORMAT_MESSAGE_IGNORE_INSERTS;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002839 const DWORD kBufSize = 4096;
Keir Mierle8ebb0732012-04-30 23:09:08 -07002840 // Gets the system's human readable message string for this HRESULT.
2841 char error_text[kBufSize] = { '\0' };
2842 DWORD message_length = ::FormatMessageA(kFlags,
2843 0, // no source, we're asking system
2844 hr, // the error
2845 0, // no line width restrictions
2846 error_text, // output buffer
2847 kBufSize, // buf size
2848 NULL); // no arguments for inserts
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002849 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
Keir Mierle8ebb0732012-04-30 23:09:08 -07002850 for (; message_length && IsSpace(error_text[message_length - 1]);
2851 --message_length) {
2852 error_text[message_length - 1] = '\0';
2853 }
2854
2855# endif // GTEST_OS_WINDOWS_MOBILE
2856
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002857 const std::string error_hex("0x" + String::FormatHexInt(hr));
Keir Mierle8ebb0732012-04-30 23:09:08 -07002858 return ::testing::AssertionFailure()
2859 << "Expected: " << expr << " " << expected << ".\n"
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002860 << " Actual: " << error_hex << " " << error_text << "\n";
Keir Mierle8ebb0732012-04-30 23:09:08 -07002861}
2862
2863} // namespace
2864
2865AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2866 if (SUCCEEDED(hr)) {
2867 return AssertionSuccess();
2868 }
2869 return HRESULTFailureHelper(expr, "succeeds", hr);
2870}
2871
2872AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2873 if (FAILED(hr)) {
2874 return AssertionSuccess();
2875 }
2876 return HRESULTFailureHelper(expr, "fails", hr);
2877}
2878
2879#endif // GTEST_OS_WINDOWS
2880
2881// Utility functions for encoding Unicode text (wide strings) in
2882// UTF-8.
2883
2884// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2885// like this:
2886//
2887// Code-point length Encoding
2888// 0 - 7 bits 0xxxxxxx
2889// 8 - 11 bits 110xxxxx 10xxxxxx
2890// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2891// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2892
2893// The maximum code-point a one-byte UTF-8 sequence can represent.
2894const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2895
2896// The maximum code-point a two-byte UTF-8 sequence can represent.
2897const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2898
2899// The maximum code-point a three-byte UTF-8 sequence can represent.
2900const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2901
2902// The maximum code-point a four-byte UTF-8 sequence can represent.
2903const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2904
2905// Chops off the n lowest bits from a bit pattern. Returns the n
2906// lowest bits. As a side effect, the original bit pattern will be
2907// shifted to the right by n bits.
2908inline UInt32 ChopLowBits(UInt32* bits, int n) {
2909 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2910 *bits >>= n;
2911 return low_bits;
2912}
2913
2914// Converts a Unicode code point to a narrow string in UTF-8 encoding.
2915// code_point parameter is of type UInt32 because wchar_t may not be
2916// wide enough to contain a code point.
Keir Mierle8ebb0732012-04-30 23:09:08 -07002917// If the code_point is not a valid Unicode code point
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002918// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2919// to "(Invalid Unicode 0xXXXXXXXX)".
2920std::string CodePointToUtf8(UInt32 code_point) {
2921 if (code_point > kMaxCodePoint4) {
2922 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
2923 }
2924
2925 char str[5]; // Big enough for the largest valid code point.
Keir Mierle8ebb0732012-04-30 23:09:08 -07002926 if (code_point <= kMaxCodePoint1) {
2927 str[1] = '\0';
2928 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2929 } else if (code_point <= kMaxCodePoint2) {
2930 str[2] = '\0';
2931 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2932 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2933 } else if (code_point <= kMaxCodePoint3) {
2934 str[3] = '\0';
2935 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2936 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2937 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002938 } else { // code_point <= kMaxCodePoint4
Keir Mierle8ebb0732012-04-30 23:09:08 -07002939 str[4] = '\0';
2940 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2941 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2942 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2943 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
Keir Mierle8ebb0732012-04-30 23:09:08 -07002944 }
2945 return str;
2946}
2947
2948// The following two functions only make sense if the the system
2949// uses UTF-16 for wide string encoding. All supported systems
2950// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2951
2952// Determines if the arguments constitute UTF-16 surrogate pair
2953// and thus should be combined into a single Unicode code point
2954// using CreateCodePointFromUtf16SurrogatePair.
2955inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2956 return sizeof(wchar_t) == 2 &&
2957 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2958}
2959
2960// Creates a Unicode code point from UTF16 surrogate pair.
2961inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2962 wchar_t second) {
2963 const UInt32 mask = (1 << 10) - 1;
2964 return (sizeof(wchar_t) == 2) ?
2965 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2966 // This function should not be called when the condition is
2967 // false, but we provide a sensible default in case it is.
2968 static_cast<UInt32>(first);
2969}
2970
2971// Converts a wide string to a narrow string in UTF-8 encoding.
2972// The wide string is assumed to have the following encoding:
2973// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2974// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2975// Parameter str points to a null-terminated wide string.
2976// Parameter num_chars may additionally limit the number
2977// of wchar_t characters processed. -1 is used when the entire string
2978// should be processed.
2979// If the string contains code points that are not valid Unicode code points
2980// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2981// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2982// and contains invalid UTF-16 surrogate pairs, values in those pairs
2983// will be encoded as individual Unicode characters from Basic Normal Plane.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07002984std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07002985 if (num_chars == -1)
2986 num_chars = static_cast<int>(wcslen(str));
2987
2988 ::std::stringstream stream;
2989 for (int i = 0; i < num_chars; ++i) {
2990 UInt32 unicode_code_point;
2991
2992 if (str[i] == L'\0') {
2993 break;
2994 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2995 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2996 str[i + 1]);
2997 i++;
2998 } else {
2999 unicode_code_point = static_cast<UInt32>(str[i]);
3000 }
3001
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003002 stream << CodePointToUtf8(unicode_code_point);
Keir Mierle8ebb0732012-04-30 23:09:08 -07003003 }
3004 return StringStreamToString(&stream);
3005}
3006
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003007// Converts a wide C string to an std::string using the UTF-8 encoding.
Keir Mierle8ebb0732012-04-30 23:09:08 -07003008// NULL will be converted to "(null)".
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003009std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3010 if (wide_c_str == NULL) return "(null)";
Keir Mierle8ebb0732012-04-30 23:09:08 -07003011
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003012 return internal::WideStringToUtf8(wide_c_str, -1);
Keir Mierle8ebb0732012-04-30 23:09:08 -07003013}
3014
3015// Compares two wide C strings. Returns true iff they have the same
3016// content.
3017//
3018// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3019// C string is considered different to any non-NULL C string,
3020// including the empty string.
3021bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3022 if (lhs == NULL) return rhs == NULL;
3023
3024 if (rhs == NULL) return false;
3025
3026 return wcscmp(lhs, rhs) == 0;
3027}
3028
3029// Helper function for *_STREQ on wide strings.
3030AssertionResult CmpHelperSTREQ(const char* expected_expression,
3031 const char* actual_expression,
3032 const wchar_t* expected,
3033 const wchar_t* actual) {
3034 if (String::WideCStringEquals(expected, actual)) {
3035 return AssertionSuccess();
3036 }
3037
3038 return EqFailure(expected_expression,
3039 actual_expression,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003040 PrintToString(expected),
3041 PrintToString(actual),
Keir Mierle8ebb0732012-04-30 23:09:08 -07003042 false);
3043}
3044
3045// Helper function for *_STRNE on wide strings.
3046AssertionResult CmpHelperSTRNE(const char* s1_expression,
3047 const char* s2_expression,
3048 const wchar_t* s1,
3049 const wchar_t* s2) {
3050 if (!String::WideCStringEquals(s1, s2)) {
3051 return AssertionSuccess();
3052 }
3053
3054 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3055 << s2_expression << "), actual: "
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003056 << PrintToString(s1)
3057 << " vs " << PrintToString(s2);
Keir Mierle8ebb0732012-04-30 23:09:08 -07003058}
3059
3060// Compares two C strings, ignoring case. Returns true iff they have
3061// the same content.
3062//
3063// Unlike strcasecmp(), this function can handle NULL argument(s). A
3064// NULL C string is considered different to any non-NULL C string,
3065// including the empty string.
3066bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3067 if (lhs == NULL)
3068 return rhs == NULL;
3069 if (rhs == NULL)
3070 return false;
3071 return posix::StrCaseCmp(lhs, rhs) == 0;
3072}
3073
3074 // Compares two wide C strings, ignoring case. Returns true iff they
3075 // have the same content.
3076 //
3077 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3078 // A NULL C string is considered different to any non-NULL wide C string,
3079 // including the empty string.
3080 // NB: The implementations on different platforms slightly differ.
3081 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3082 // environment variable. On GNU platform this method uses wcscasecmp
3083 // which compares according to LC_CTYPE category of the current locale.
3084 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3085 // current locale.
3086bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3087 const wchar_t* rhs) {
3088 if (lhs == NULL) return rhs == NULL;
3089
3090 if (rhs == NULL) return false;
3091
3092#if GTEST_OS_WINDOWS
3093 return _wcsicmp(lhs, rhs) == 0;
3094#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3095 return wcscasecmp(lhs, rhs) == 0;
3096#else
3097 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3098 // Other unknown OSes may not define it either.
3099 wint_t left, right;
3100 do {
3101 left = towlower(*lhs++);
3102 right = towlower(*rhs++);
3103 } while (left && left == right);
3104 return left == right;
3105#endif // OS selector
3106}
3107
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003108// Returns true iff str ends with the given suffix, ignoring case.
3109// Any string is considered to end with an empty suffix.
3110bool String::EndsWithCaseInsensitive(
3111 const std::string& str, const std::string& suffix) {
3112 const size_t str_len = str.length();
3113 const size_t suffix_len = suffix.length();
3114 return (str_len >= suffix_len) &&
3115 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3116 suffix.c_str());
Keir Mierle8ebb0732012-04-30 23:09:08 -07003117}
3118
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003119// Formats an int value as "%02d".
3120std::string String::FormatIntWidth2(int value) {
3121 std::stringstream ss;
3122 ss << std::setfill('0') << std::setw(2) << value;
3123 return ss.str();
Keir Mierle8ebb0732012-04-30 23:09:08 -07003124}
3125
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003126// Formats an int value as "%X".
3127std::string String::FormatHexInt(int value) {
3128 std::stringstream ss;
3129 ss << std::hex << std::uppercase << value;
3130 return ss.str();
Keir Mierle8ebb0732012-04-30 23:09:08 -07003131}
3132
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003133// Formats a byte as "%02X".
3134std::string String::FormatByte(unsigned char value) {
3135 std::stringstream ss;
3136 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3137 << static_cast<unsigned int>(value);
3138 return ss.str();
Keir Mierle8ebb0732012-04-30 23:09:08 -07003139}
3140
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003141// Converts the buffer in a stringstream to an std::string, converting NUL
Keir Mierle8ebb0732012-04-30 23:09:08 -07003142// bytes to "\\0" along the way.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003143std::string StringStreamToString(::std::stringstream* ss) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003144 const ::std::string& str = ss->str();
3145 const char* const start = str.c_str();
3146 const char* const end = start + str.length();
3147
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003148 std::string result;
3149 result.reserve(2 * (end - start));
Keir Mierle8ebb0732012-04-30 23:09:08 -07003150 for (const char* ch = start; ch != end; ++ch) {
3151 if (*ch == '\0') {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003152 result += "\\0"; // Replaces NUL with "\\0";
Keir Mierle8ebb0732012-04-30 23:09:08 -07003153 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003154 result += *ch;
Keir Mierle8ebb0732012-04-30 23:09:08 -07003155 }
3156 }
3157
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003158 return result;
Keir Mierle8ebb0732012-04-30 23:09:08 -07003159}
3160
3161// Appends the user-supplied message to the Google-Test-generated message.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003162std::string AppendUserMessage(const std::string& gtest_msg,
3163 const Message& user_msg) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003164 // Appends the user message if it's non-empty.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003165 const std::string user_msg_string = user_msg.GetString();
Keir Mierle8ebb0732012-04-30 23:09:08 -07003166 if (user_msg_string.empty()) {
3167 return gtest_msg;
3168 }
3169
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003170 return gtest_msg + "\n" + user_msg_string;
Keir Mierle8ebb0732012-04-30 23:09:08 -07003171}
3172
3173} // namespace internal
3174
3175// class TestResult
3176
3177// Creates an empty TestResult.
3178TestResult::TestResult()
3179 : death_test_count_(0),
3180 elapsed_time_(0) {
3181}
3182
3183// D'tor.
3184TestResult::~TestResult() {
3185}
3186
3187// Returns the i-th test part result among all the results. i can
3188// range from 0 to total_part_count() - 1. If i is not in that range,
3189// aborts the program.
3190const TestPartResult& TestResult::GetTestPartResult(int i) const {
3191 if (i < 0 || i >= total_part_count())
3192 internal::posix::Abort();
3193 return test_part_results_.at(i);
3194}
3195
3196// Returns the i-th test property. i can range from 0 to
3197// test_property_count() - 1. If i is not in that range, aborts the
3198// program.
3199const TestProperty& TestResult::GetTestProperty(int i) const {
3200 if (i < 0 || i >= test_property_count())
3201 internal::posix::Abort();
3202 return test_properties_.at(i);
3203}
3204
3205// Clears the test part results.
3206void TestResult::ClearTestPartResults() {
3207 test_part_results_.clear();
3208}
3209
3210// Adds a test part result to the list.
3211void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3212 test_part_results_.push_back(test_part_result);
3213}
3214
3215// Adds a test property to the list. If a property with the same key as the
3216// supplied property is already represented, the value of this test_property
3217// replaces the old value for that key.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003218void TestResult::RecordProperty(const std::string& xml_element,
3219 const TestProperty& test_property) {
3220 if (!ValidateTestProperty(xml_element, test_property)) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003221 return;
3222 }
3223 internal::MutexLock lock(&test_properites_mutex_);
3224 const std::vector<TestProperty>::iterator property_with_matching_key =
3225 std::find_if(test_properties_.begin(), test_properties_.end(),
3226 internal::TestPropertyKeyIs(test_property.key()));
3227 if (property_with_matching_key == test_properties_.end()) {
3228 test_properties_.push_back(test_property);
3229 return;
3230 }
3231 property_with_matching_key->SetValue(test_property.value());
3232}
3233
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003234// The list of reserved attributes used in the <testsuites> element of XML
3235// output.
3236static const char* const kReservedTestSuitesAttributes[] = {
3237 "disabled",
3238 "errors",
3239 "failures",
3240 "name",
3241 "random_seed",
3242 "tests",
3243 "time",
3244 "timestamp"
3245};
3246
3247// The list of reserved attributes used in the <testsuite> element of XML
3248// output.
3249static const char* const kReservedTestSuiteAttributes[] = {
3250 "disabled",
3251 "errors",
3252 "failures",
3253 "name",
3254 "tests",
3255 "time"
3256};
3257
3258// The list of reserved attributes used in the <testcase> element of XML output.
3259static const char* const kReservedTestCaseAttributes[] = {
3260 "classname",
3261 "name",
3262 "status",
3263 "time",
3264 "type_param",
3265 "value_param"
3266};
3267
3268template <int kSize>
3269std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3270 return std::vector<std::string>(array, array + kSize);
3271}
3272
3273static std::vector<std::string> GetReservedAttributesForElement(
3274 const std::string& xml_element) {
3275 if (xml_element == "testsuites") {
3276 return ArrayAsVector(kReservedTestSuitesAttributes);
3277 } else if (xml_element == "testsuite") {
3278 return ArrayAsVector(kReservedTestSuiteAttributes);
3279 } else if (xml_element == "testcase") {
3280 return ArrayAsVector(kReservedTestCaseAttributes);
3281 } else {
3282 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3283 }
3284 // This code is unreachable but some compilers may not realizes that.
3285 return std::vector<std::string>();
3286}
3287
3288static std::string FormatWordList(const std::vector<std::string>& words) {
3289 Message word_list;
3290 for (size_t i = 0; i < words.size(); ++i) {
3291 if (i > 0 && words.size() > 2) {
3292 word_list << ", ";
3293 }
3294 if (i == words.size() - 1) {
3295 word_list << "and ";
3296 }
3297 word_list << "'" << words[i] << "'";
3298 }
3299 return word_list.GetString();
3300}
3301
3302bool ValidateTestPropertyName(const std::string& property_name,
3303 const std::vector<std::string>& reserved_names) {
3304 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3305 reserved_names.end()) {
3306 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3307 << " (" << FormatWordList(reserved_names)
3308 << " are reserved by " << GTEST_NAME_ << ")";
Keir Mierle8ebb0732012-04-30 23:09:08 -07003309 return false;
3310 }
3311 return true;
3312}
3313
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003314// Adds a failure if the key is a reserved attribute of the element named
3315// xml_element. Returns true if the property is valid.
3316bool TestResult::ValidateTestProperty(const std::string& xml_element,
3317 const TestProperty& test_property) {
3318 return ValidateTestPropertyName(test_property.key(),
3319 GetReservedAttributesForElement(xml_element));
3320}
3321
Keir Mierle8ebb0732012-04-30 23:09:08 -07003322// Clears the object.
3323void TestResult::Clear() {
3324 test_part_results_.clear();
3325 test_properties_.clear();
3326 death_test_count_ = 0;
3327 elapsed_time_ = 0;
3328}
3329
3330// Returns true iff the test failed.
3331bool TestResult::Failed() const {
3332 for (int i = 0; i < total_part_count(); ++i) {
3333 if (GetTestPartResult(i).failed())
3334 return true;
3335 }
3336 return false;
3337}
3338
3339// Returns true iff the test part fatally failed.
3340static bool TestPartFatallyFailed(const TestPartResult& result) {
3341 return result.fatally_failed();
3342}
3343
3344// Returns true iff the test fatally failed.
3345bool TestResult::HasFatalFailure() const {
3346 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3347}
3348
3349// Returns true iff the test part non-fatally failed.
3350static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3351 return result.nonfatally_failed();
3352}
3353
3354// Returns true iff the test has a non-fatal failure.
3355bool TestResult::HasNonfatalFailure() const {
3356 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3357}
3358
3359// Gets the number of all test parts. This is the sum of the number
3360// of successful test parts and the number of failed test parts.
3361int TestResult::total_part_count() const {
3362 return static_cast<int>(test_part_results_.size());
3363}
3364
3365// Returns the number of the test properties.
3366int TestResult::test_property_count() const {
3367 return static_cast<int>(test_properties_.size());
3368}
3369
3370// class Test
3371
3372// Creates a Test object.
3373
3374// The c'tor saves the values of all Google Test flags.
3375Test::Test()
3376 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3377}
3378
3379// The d'tor restores the values of all Google Test flags.
3380Test::~Test() {
3381 delete gtest_flag_saver_;
3382}
3383
3384// Sets up the test fixture.
3385//
3386// A sub-class may override this.
3387void Test::SetUp() {
3388}
3389
3390// Tears down the test fixture.
3391//
3392// A sub-class may override this.
3393void Test::TearDown() {
3394}
3395
3396// Allows user supplied key value pairs to be recorded for later output.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003397void Test::RecordProperty(const std::string& key, const std::string& value) {
3398 UnitTest::GetInstance()->RecordProperty(key, value);
Keir Mierle8ebb0732012-04-30 23:09:08 -07003399}
3400
3401// Allows user supplied key value pairs to be recorded for later output.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003402void Test::RecordProperty(const std::string& key, int value) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003403 Message value_message;
3404 value_message << value;
3405 RecordProperty(key, value_message.GetString().c_str());
3406}
3407
3408namespace internal {
3409
3410void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003411 const std::string& message) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003412 // This function is a friend of UnitTest and as such has access to
3413 // AddTestPartResult.
3414 UnitTest::GetInstance()->AddTestPartResult(
3415 result_type,
3416 NULL, // No info about the source file where the exception occurred.
3417 -1, // We have no info on which line caused the exception.
3418 message,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003419 ""); // No stack trace, either.
Keir Mierle8ebb0732012-04-30 23:09:08 -07003420}
3421
3422} // namespace internal
3423
3424// Google Test requires all tests in the same test case to use the same test
3425// fixture class. This function checks if the current test has the
3426// same fixture class as the first test in the current test case. If
3427// yes, it returns true; otherwise it generates a Google Test failure and
3428// returns false.
3429bool Test::HasSameFixtureClass() {
3430 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3431 const TestCase* const test_case = impl->current_test_case();
3432
3433 // Info about the first test in the current test case.
3434 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3435 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3436 const char* const first_test_name = first_test_info->name();
3437
3438 // Info about the current test.
3439 const TestInfo* const this_test_info = impl->current_test_info();
3440 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3441 const char* const this_test_name = this_test_info->name();
3442
3443 if (this_fixture_id != first_fixture_id) {
3444 // Is the first test defined using TEST?
3445 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3446 // Is this test defined using TEST?
3447 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3448
3449 if (first_is_TEST || this_is_TEST) {
3450 // The user mixed TEST and TEST_F in this test case - we'll tell
3451 // him/her how to fix it.
3452
3453 // Gets the name of the TEST and the name of the TEST_F. Note
3454 // that first_is_TEST and this_is_TEST cannot both be true, as
3455 // the fixture IDs are different for the two tests.
3456 const char* const TEST_name =
3457 first_is_TEST ? first_test_name : this_test_name;
3458 const char* const TEST_F_name =
3459 first_is_TEST ? this_test_name : first_test_name;
3460
3461 ADD_FAILURE()
3462 << "All tests in the same test case must use the same test fixture\n"
3463 << "class, so mixing TEST_F and TEST in the same test case is\n"
3464 << "illegal. In test case " << this_test_info->test_case_name()
3465 << ",\n"
3466 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3467 << "test " << TEST_name << " is defined using TEST. You probably\n"
3468 << "want to change the TEST to TEST_F or move it to another test\n"
3469 << "case.";
3470 } else {
3471 // The user defined two fixture classes with the same name in
3472 // two namespaces - we'll tell him/her how to fix it.
3473 ADD_FAILURE()
3474 << "All tests in the same test case must use the same test fixture\n"
3475 << "class. However, in test case "
3476 << this_test_info->test_case_name() << ",\n"
3477 << "you defined test " << first_test_name
3478 << " and test " << this_test_name << "\n"
3479 << "using two different test fixture classes. This can happen if\n"
3480 << "the two classes are from different namespaces or translation\n"
3481 << "units and have the same name. You should probably rename one\n"
3482 << "of the classes to put the tests into different test cases.";
3483 }
3484 return false;
3485 }
3486
3487 return true;
3488}
3489
3490#if GTEST_HAS_SEH
3491
3492// Adds an "exception thrown" fatal failure to the current test. This
3493// function returns its result via an output parameter pointer because VC++
3494// prohibits creation of objects with destructors on stack in functions
3495// using __try (see error C2712).
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003496static std::string* FormatSehExceptionMessage(DWORD exception_code,
3497 const char* location) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003498 Message message;
3499 message << "SEH exception with code 0x" << std::setbase(16) <<
3500 exception_code << std::setbase(10) << " thrown in " << location << ".";
3501
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003502 return new std::string(message.GetString());
Keir Mierle8ebb0732012-04-30 23:09:08 -07003503}
3504
3505#endif // GTEST_HAS_SEH
3506
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003507namespace internal {
3508
Keir Mierle8ebb0732012-04-30 23:09:08 -07003509#if GTEST_HAS_EXCEPTIONS
3510
3511// Adds an "exception thrown" fatal failure to the current test.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003512static std::string FormatCxxExceptionMessage(const char* description,
3513 const char* location) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003514 Message message;
3515 if (description != NULL) {
3516 message << "C++ exception with description \"" << description << "\"";
3517 } else {
3518 message << "Unknown C++ exception";
3519 }
3520 message << " thrown in " << location << ".";
3521
3522 return message.GetString();
3523}
3524
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003525static std::string PrintTestPartResultToString(
Keir Mierle8ebb0732012-04-30 23:09:08 -07003526 const TestPartResult& test_part_result);
3527
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003528GoogleTestFailureException::GoogleTestFailureException(
3529 const TestPartResult& failure)
3530 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3531
Keir Mierle8ebb0732012-04-30 23:09:08 -07003532#endif // GTEST_HAS_EXCEPTIONS
3533
Keir Mierle8ebb0732012-04-30 23:09:08 -07003534// We put these helper functions in the internal namespace as IBM's xlC
3535// compiler rejects the code if they were declared static.
3536
3537// Runs the given method and handles SEH exceptions it throws, when
3538// SEH is supported; returns the 0-value for type Result in case of an
3539// SEH exception. (Microsoft compilers cannot handle SEH and C++
3540// exceptions in the same function. Therefore, we provide a separate
3541// wrapper function for handling SEH exceptions.)
3542template <class T, typename Result>
3543Result HandleSehExceptionsInMethodIfSupported(
3544 T* object, Result (T::*method)(), const char* location) {
3545#if GTEST_HAS_SEH
3546 __try {
3547 return (object->*method)();
3548 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3549 GetExceptionCode())) {
3550 // We create the exception message on the heap because VC++ prohibits
3551 // creation of objects with destructors on stack in functions using __try
3552 // (see error C2712).
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003553 std::string* exception_message = FormatSehExceptionMessage(
Keir Mierle8ebb0732012-04-30 23:09:08 -07003554 GetExceptionCode(), location);
3555 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3556 *exception_message);
3557 delete exception_message;
3558 return static_cast<Result>(0);
3559 }
3560#else
3561 (void)location;
3562 return (object->*method)();
3563#endif // GTEST_HAS_SEH
3564}
3565
3566// Runs the given method and catches and reports C++ and/or SEH-style
3567// exceptions, if they are supported; returns the 0-value for type
3568// Result in case of an SEH exception.
3569template <class T, typename Result>
3570Result HandleExceptionsInMethodIfSupported(
3571 T* object, Result (T::*method)(), const char* location) {
3572 // NOTE: The user code can affect the way in which Google Test handles
3573 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3574 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3575 // after the exception is caught and either report or re-throw the
3576 // exception based on the flag's value:
3577 //
3578 // try {
3579 // // Perform the test method.
3580 // } catch (...) {
3581 // if (GTEST_FLAG(catch_exceptions))
3582 // // Report the exception as failure.
3583 // else
3584 // throw; // Re-throws the original exception.
3585 // }
3586 //
3587 // However, the purpose of this flag is to allow the program to drop into
3588 // the debugger when the exception is thrown. On most platforms, once the
3589 // control enters the catch block, the exception origin information is
3590 // lost and the debugger will stop the program at the point of the
3591 // re-throw in this function -- instead of at the point of the original
3592 // throw statement in the code under test. For this reason, we perform
3593 // the check early, sacrificing the ability to affect Google Test's
3594 // exception handling in the method where the exception is thrown.
3595 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3596#if GTEST_HAS_EXCEPTIONS
3597 try {
3598 return HandleSehExceptionsInMethodIfSupported(object, method, location);
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003599 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3600 // This exception type can only be thrown by a failed Google
3601 // Test assertion with the intention of letting another testing
3602 // framework catch it. Therefore we just re-throw it.
Keir Mierle8ebb0732012-04-30 23:09:08 -07003603 throw;
3604 } catch (const std::exception& e) { // NOLINT
3605 internal::ReportFailureInUnknownLocation(
3606 TestPartResult::kFatalFailure,
3607 FormatCxxExceptionMessage(e.what(), location));
3608 } catch (...) { // NOLINT
3609 internal::ReportFailureInUnknownLocation(
3610 TestPartResult::kFatalFailure,
3611 FormatCxxExceptionMessage(NULL, location));
3612 }
3613 return static_cast<Result>(0);
3614#else
3615 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3616#endif // GTEST_HAS_EXCEPTIONS
3617 } else {
3618 return (object->*method)();
3619 }
3620}
3621
3622} // namespace internal
3623
3624// Runs the test and updates the test result.
3625void Test::Run() {
3626 if (!HasSameFixtureClass()) return;
3627
3628 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3629 impl->os_stack_trace_getter()->UponLeavingGTest();
3630 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3631 // We will run the test only if SetUp() was successful.
3632 if (!HasFatalFailure()) {
3633 impl->os_stack_trace_getter()->UponLeavingGTest();
3634 internal::HandleExceptionsInMethodIfSupported(
3635 this, &Test::TestBody, "the test body");
3636 }
3637
3638 // However, we want to clean up as much as possible. Hence we will
3639 // always call TearDown(), even if SetUp() or the test body has
3640 // failed.
3641 impl->os_stack_trace_getter()->UponLeavingGTest();
3642 internal::HandleExceptionsInMethodIfSupported(
3643 this, &Test::TearDown, "TearDown()");
3644}
3645
3646// Returns true iff the current test has a fatal failure.
3647bool Test::HasFatalFailure() {
3648 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3649}
3650
3651// Returns true iff the current test has a non-fatal failure.
3652bool Test::HasNonfatalFailure() {
3653 return internal::GetUnitTestImpl()->current_test_result()->
3654 HasNonfatalFailure();
3655}
3656
3657// class TestInfo
3658
3659// Constructs a TestInfo object. It assumes ownership of the test factory
3660// object.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003661TestInfo::TestInfo(const std::string& a_test_case_name,
3662 const std::string& a_name,
Keir Mierle8ebb0732012-04-30 23:09:08 -07003663 const char* a_type_param,
3664 const char* a_value_param,
3665 internal::TypeId fixture_class_id,
3666 internal::TestFactoryBase* factory)
3667 : test_case_name_(a_test_case_name),
3668 name_(a_name),
3669 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3670 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3671 fixture_class_id_(fixture_class_id),
3672 should_run_(false),
3673 is_disabled_(false),
3674 matches_filter_(false),
3675 factory_(factory),
3676 result_() {}
3677
3678// Destructs a TestInfo object.
3679TestInfo::~TestInfo() { delete factory_; }
3680
3681namespace internal {
3682
3683// Creates a new TestInfo object and registers it with Google Test;
3684// returns the created object.
3685//
3686// Arguments:
3687//
3688// test_case_name: name of the test case
3689// name: name of the test
3690// type_param: the name of the test's type parameter, or NULL if
3691// this is not a typed or a type-parameterized test.
3692// value_param: text representation of the test's value parameter,
3693// or NULL if this is not a value-parameterized test.
3694// fixture_class_id: ID of the test fixture class
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
3697// factory: pointer to the factory that creates a test object.
3698// The newly created TestInfo instance will assume
3699// ownership of the factory object.
3700TestInfo* MakeAndRegisterTestInfo(
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003701 const char* test_case_name,
3702 const char* name,
Keir Mierle8ebb0732012-04-30 23:09:08 -07003703 const char* type_param,
3704 const char* value_param,
3705 TypeId fixture_class_id,
3706 SetUpTestCaseFunc set_up_tc,
3707 TearDownTestCaseFunc tear_down_tc,
3708 TestFactoryBase* factory) {
3709 TestInfo* const test_info =
3710 new TestInfo(test_case_name, name, type_param, value_param,
3711 fixture_class_id, factory);
3712 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3713 return test_info;
3714}
3715
3716#if GTEST_HAS_PARAM_TEST
3717void ReportInvalidTestCaseType(const char* test_case_name,
3718 const char* file, int line) {
3719 Message errors;
3720 errors
3721 << "Attempted redefinition of test case " << test_case_name << ".\n"
3722 << "All tests in the same test case must use the same test fixture\n"
3723 << "class. However, in test case " << test_case_name << ", you tried\n"
3724 << "to define a test using a fixture class different from the one\n"
3725 << "used earlier. This can happen if the two fixture classes are\n"
3726 << "from different namespaces and have the same name. You should\n"
3727 << "probably rename one of the classes to put the tests into different\n"
3728 << "test cases.";
3729
3730 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3731 errors.GetString().c_str());
3732}
3733#endif // GTEST_HAS_PARAM_TEST
3734
3735} // namespace internal
3736
3737namespace {
3738
3739// A predicate that checks the test name of a TestInfo against a known
3740// value.
3741//
3742// This is used for implementation of the TestCase class only. We put
3743// it in the anonymous namespace to prevent polluting the outer
3744// namespace.
3745//
3746// TestNameIs is copyable.
3747class TestNameIs {
3748 public:
3749 // Constructor.
3750 //
3751 // TestNameIs has NO default constructor.
3752 explicit TestNameIs(const char* name)
3753 : name_(name) {}
3754
3755 // Returns true iff the test name of test_info matches name_.
3756 bool operator()(const TestInfo * test_info) const {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003757 return test_info && test_info->name() == name_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07003758 }
3759
3760 private:
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003761 std::string name_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07003762};
3763
3764} // namespace
3765
3766namespace internal {
3767
3768// This method expands all parameterized tests registered with macros TEST_P
3769// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3770// This will be done just once during the program runtime.
3771void UnitTestImpl::RegisterParameterizedTests() {
3772#if GTEST_HAS_PARAM_TEST
3773 if (!parameterized_tests_registered_) {
3774 parameterized_test_registry_.RegisterTests();
3775 parameterized_tests_registered_ = true;
3776 }
3777#endif
3778}
3779
3780} // namespace internal
3781
3782// Creates the test object, runs it, records its result, and then
3783// deletes it.
3784void TestInfo::Run() {
3785 if (!should_run_) return;
3786
3787 // Tells UnitTest where to store test result.
3788 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3789 impl->set_current_test_info(this);
3790
3791 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3792
3793 // Notifies the unit test event listeners that a test is about to start.
3794 repeater->OnTestStart(*this);
3795
3796 const TimeInMillis start = internal::GetTimeInMillis();
3797
3798 impl->os_stack_trace_getter()->UponLeavingGTest();
3799
3800 // Creates the test object.
3801 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3802 factory_, &internal::TestFactoryBase::CreateTest,
3803 "the test fixture's constructor");
3804
3805 // Runs the test only if the test object was created and its
3806 // constructor didn't generate a fatal failure.
3807 if ((test != NULL) && !Test::HasFatalFailure()) {
3808 // This doesn't throw as all user code that can throw are wrapped into
3809 // exception handling code.
3810 test->Run();
3811 }
3812
3813 // Deletes the test object.
3814 impl->os_stack_trace_getter()->UponLeavingGTest();
3815 internal::HandleExceptionsInMethodIfSupported(
3816 test, &Test::DeleteSelf_, "the test fixture's destructor");
3817
3818 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3819
3820 // Notifies the unit test event listener that a test has just finished.
3821 repeater->OnTestEnd(*this);
3822
3823 // Tells UnitTest to stop associating assertion results to this
3824 // test.
3825 impl->set_current_test_info(NULL);
3826}
3827
3828// class TestCase
3829
3830// Gets the number of successful tests in this test case.
3831int TestCase::successful_test_count() const {
3832 return CountIf(test_info_list_, TestPassed);
3833}
3834
3835// Gets the number of failed tests in this test case.
3836int TestCase::failed_test_count() const {
3837 return CountIf(test_info_list_, TestFailed);
3838}
3839
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003840// Gets the number of disabled tests that will be reported in the XML report.
3841int TestCase::reportable_disabled_test_count() const {
3842 return CountIf(test_info_list_, TestReportableDisabled);
3843}
3844
3845// Gets the number of disabled tests in this test case.
Keir Mierle8ebb0732012-04-30 23:09:08 -07003846int TestCase::disabled_test_count() const {
3847 return CountIf(test_info_list_, TestDisabled);
3848}
3849
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003850// Gets the number of tests to be printed in the XML report.
3851int TestCase::reportable_test_count() const {
3852 return CountIf(test_info_list_, TestReportable);
3853}
3854
Keir Mierle8ebb0732012-04-30 23:09:08 -07003855// Get the number of tests in this test case that should run.
3856int TestCase::test_to_run_count() const {
3857 return CountIf(test_info_list_, ShouldRunTest);
3858}
3859
3860// Gets the number of all tests.
3861int TestCase::total_test_count() const {
3862 return static_cast<int>(test_info_list_.size());
3863}
3864
3865// Creates a TestCase with the given name.
3866//
3867// Arguments:
3868//
3869// name: name of the test case
3870// a_type_param: the name of the test case's type parameter, or NULL if
3871// this is not a typed or a type-parameterized test case.
3872// set_up_tc: pointer to the function that sets up the test case
3873// tear_down_tc: pointer to the function that tears down the test case
3874TestCase::TestCase(const char* a_name, const char* a_type_param,
3875 Test::SetUpTestCaseFunc set_up_tc,
3876 Test::TearDownTestCaseFunc tear_down_tc)
3877 : name_(a_name),
3878 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3879 set_up_tc_(set_up_tc),
3880 tear_down_tc_(tear_down_tc),
3881 should_run_(false),
3882 elapsed_time_(0) {
3883}
3884
3885// Destructor of TestCase.
3886TestCase::~TestCase() {
3887 // Deletes every Test in the collection.
3888 ForEach(test_info_list_, internal::Delete<TestInfo>);
3889}
3890
3891// Returns the i-th test among all the tests. i can range from 0 to
3892// total_test_count() - 1. If i is not in that range, returns NULL.
3893const TestInfo* TestCase::GetTestInfo(int i) const {
3894 const int index = GetElementOr(test_indices_, i, -1);
3895 return index < 0 ? NULL : test_info_list_[index];
3896}
3897
3898// Returns the i-th test among all the tests. i can range from 0 to
3899// total_test_count() - 1. If i is not in that range, returns NULL.
3900TestInfo* TestCase::GetMutableTestInfo(int i) {
3901 const int index = GetElementOr(test_indices_, i, -1);
3902 return index < 0 ? NULL : test_info_list_[index];
3903}
3904
3905// Adds a test to this test case. Will delete the test upon
3906// destruction of the TestCase object.
3907void TestCase::AddTestInfo(TestInfo * test_info) {
3908 test_info_list_.push_back(test_info);
3909 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3910}
3911
3912// Runs every test in this TestCase.
3913void TestCase::Run() {
3914 if (!should_run_) return;
3915
3916 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3917 impl->set_current_test_case(this);
3918
3919 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3920
3921 repeater->OnTestCaseStart(*this);
3922 impl->os_stack_trace_getter()->UponLeavingGTest();
3923 internal::HandleExceptionsInMethodIfSupported(
3924 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3925
3926 const internal::TimeInMillis start = internal::GetTimeInMillis();
3927 for (int i = 0; i < total_test_count(); i++) {
3928 GetMutableTestInfo(i)->Run();
3929 }
3930 elapsed_time_ = internal::GetTimeInMillis() - start;
3931
3932 impl->os_stack_trace_getter()->UponLeavingGTest();
3933 internal::HandleExceptionsInMethodIfSupported(
3934 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3935
3936 repeater->OnTestCaseEnd(*this);
3937 impl->set_current_test_case(NULL);
3938}
3939
3940// Clears the results of all tests in this test case.
3941void TestCase::ClearResult() {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003942 ad_hoc_test_result_.Clear();
Keir Mierle8ebb0732012-04-30 23:09:08 -07003943 ForEach(test_info_list_, TestInfo::ClearTestResult);
3944}
3945
3946// Shuffles the tests in this test case.
3947void TestCase::ShuffleTests(internal::Random* random) {
3948 Shuffle(random, &test_indices_);
3949}
3950
3951// Restores the test order to before the first shuffle.
3952void TestCase::UnshuffleTests() {
3953 for (size_t i = 0; i < test_indices_.size(); i++) {
3954 test_indices_[i] = static_cast<int>(i);
3955 }
3956}
3957
3958// Formats a countable noun. Depending on its quantity, either the
3959// singular form or the plural form is used. e.g.
3960//
3961// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3962// FormatCountableNoun(5, "book", "books") returns "5 books".
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003963static std::string FormatCountableNoun(int count,
3964 const char * singular_form,
3965 const char * plural_form) {
3966 return internal::StreamableToString(count) + " " +
3967 (count == 1 ? singular_form : plural_form);
Keir Mierle8ebb0732012-04-30 23:09:08 -07003968}
3969
3970// Formats the count of tests.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003971static std::string FormatTestCount(int test_count) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003972 return FormatCountableNoun(test_count, "test", "tests");
3973}
3974
3975// Formats the count of test cases.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07003976static std::string FormatTestCaseCount(int test_case_count) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07003977 return FormatCountableNoun(test_case_count, "test case", "test cases");
3978}
3979
3980// Converts a TestPartResult::Type enum to human-friendly string
3981// representation. Both kNonFatalFailure and kFatalFailure are translated
3982// to "Failure", as the user usually doesn't care about the difference
3983// between the two when viewing the test result.
3984static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3985 switch (type) {
3986 case TestPartResult::kSuccess:
3987 return "Success";
3988
3989 case TestPartResult::kNonFatalFailure:
3990 case TestPartResult::kFatalFailure:
3991#ifdef _MSC_VER
3992 return "error: ";
3993#else
3994 return "Failure\n";
3995#endif
3996 default:
3997 return "Unknown result type";
3998 }
3999}
4000
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004001namespace internal {
4002
4003// Prints a TestPartResult to an std::string.
4004static std::string PrintTestPartResultToString(
Keir Mierle8ebb0732012-04-30 23:09:08 -07004005 const TestPartResult& test_part_result) {
4006 return (Message()
4007 << internal::FormatFileLocation(test_part_result.file_name(),
4008 test_part_result.line_number())
4009 << " " << TestPartResultTypeToString(test_part_result.type())
4010 << test_part_result.message()).GetString();
4011}
4012
4013// Prints a TestPartResult.
4014static void PrintTestPartResult(const TestPartResult& test_part_result) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004015 const std::string& result =
Keir Mierle8ebb0732012-04-30 23:09:08 -07004016 PrintTestPartResultToString(test_part_result);
4017 printf("%s\n", result.c_str());
4018 fflush(stdout);
4019 // If the test program runs in Visual Studio or a debugger, the
4020 // following statements add the test part result message to the Output
4021 // window such that the user can double-click on it to jump to the
4022 // corresponding source code location; otherwise they do nothing.
4023#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4024 // We don't call OutputDebugString*() on Windows Mobile, as printing
4025 // to stdout is done by OutputDebugString() there already - we don't
4026 // want the same message printed twice.
4027 ::OutputDebugStringA(result.c_str());
4028 ::OutputDebugStringA("\n");
4029#endif
4030}
4031
4032// class PrettyUnitTestResultPrinter
4033
Keir Mierle8ebb0732012-04-30 23:09:08 -07004034enum GTestColor {
4035 COLOR_DEFAULT,
4036 COLOR_RED,
4037 COLOR_GREEN,
4038 COLOR_YELLOW
4039};
4040
4041#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4042
4043// Returns the character attribute for the given color.
4044WORD GetColorAttribute(GTestColor color) {
4045 switch (color) {
4046 case COLOR_RED: return FOREGROUND_RED;
4047 case COLOR_GREEN: return FOREGROUND_GREEN;
4048 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4049 default: return 0;
4050 }
4051}
4052
4053#else
4054
4055// Returns the ANSI color code for the given color. COLOR_DEFAULT is
4056// an invalid input.
4057const char* GetAnsiColorCode(GTestColor color) {
4058 switch (color) {
4059 case COLOR_RED: return "1";
4060 case COLOR_GREEN: return "2";
4061 case COLOR_YELLOW: return "3";
4062 default: return NULL;
4063 };
4064}
4065
4066#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4067
4068// Returns true iff Google Test should use colors in the output.
4069bool ShouldUseColor(bool stdout_is_tty) {
4070 const char* const gtest_color = GTEST_FLAG(color).c_str();
4071
4072 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4073#if GTEST_OS_WINDOWS
4074 // On Windows the TERM variable is usually not set, but the
4075 // console there does support colors.
4076 return stdout_is_tty;
4077#else
4078 // On non-Windows platforms, we rely on the TERM variable.
4079 const char* const term = posix::GetEnv("TERM");
4080 const bool term_supports_color =
4081 String::CStringEquals(term, "xterm") ||
4082 String::CStringEquals(term, "xterm-color") ||
4083 String::CStringEquals(term, "xterm-256color") ||
4084 String::CStringEquals(term, "screen") ||
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004085 String::CStringEquals(term, "screen-256color") ||
Keir Mierle8ebb0732012-04-30 23:09:08 -07004086 String::CStringEquals(term, "linux") ||
4087 String::CStringEquals(term, "cygwin");
4088 return stdout_is_tty && term_supports_color;
4089#endif // GTEST_OS_WINDOWS
4090 }
4091
4092 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4093 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4094 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4095 String::CStringEquals(gtest_color, "1");
4096 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4097 // value is neither one of these nor "auto", we treat it as "no" to
4098 // be conservative.
4099}
4100
4101// Helpers for printing colored strings to stdout. Note that on Windows, we
4102// cannot simply emit special characters and have the terminal change colors.
4103// This routine must actually emit the characters rather than return a string
4104// that would be colored when printed, as can be done on Linux.
4105void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4106 va_list args;
4107 va_start(args, fmt);
4108
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004109#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
Keir Mierle8ebb0732012-04-30 23:09:08 -07004110 const bool use_color = false;
4111#else
4112 static const bool in_color_mode =
4113 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4114 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4115#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4116 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4117
4118 if (!use_color) {
4119 vprintf(fmt, args);
4120 va_end(args);
4121 return;
4122 }
4123
4124#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4125 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4126
4127 // Gets the current text color.
4128 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4129 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4130 const WORD old_color_attrs = buffer_info.wAttributes;
4131
4132 // We need to flush the stream buffers into the console before each
4133 // SetConsoleTextAttribute call lest it affect the text that is already
4134 // printed but has not yet reached the console.
4135 fflush(stdout);
4136 SetConsoleTextAttribute(stdout_handle,
4137 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4138 vprintf(fmt, args);
4139
4140 fflush(stdout);
4141 // Restores the text color.
4142 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4143#else
4144 printf("\033[0;3%sm", GetAnsiColorCode(color));
4145 vprintf(fmt, args);
4146 printf("\033[m"); // Resets the terminal to default.
4147#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4148 va_end(args);
4149}
4150
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004151// Text printed in Google Test's text output and --gunit_list_tests
4152// output to label the type parameter and value parameter for a test.
4153static const char kTypeParamLabel[] = "TypeParam";
4154static const char kValueParamLabel[] = "GetParam()";
4155
Keir Mierle8ebb0732012-04-30 23:09:08 -07004156void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4157 const char* const type_param = test_info.type_param();
4158 const char* const value_param = test_info.value_param();
4159
4160 if (type_param != NULL || value_param != NULL) {
4161 printf(", where ");
4162 if (type_param != NULL) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004163 printf("%s = %s", kTypeParamLabel, type_param);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004164 if (value_param != NULL)
4165 printf(" and ");
4166 }
4167 if (value_param != NULL) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004168 printf("%s = %s", kValueParamLabel, value_param);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004169 }
4170 }
4171}
4172
4173// This class implements the TestEventListener interface.
4174//
4175// Class PrettyUnitTestResultPrinter is copyable.
4176class PrettyUnitTestResultPrinter : public TestEventListener {
4177 public:
4178 PrettyUnitTestResultPrinter() {}
4179 static void PrintTestName(const char * test_case, const char * test) {
4180 printf("%s.%s", test_case, test);
4181 }
4182
4183 // The following methods override what's in the TestEventListener class.
4184 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4185 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4186 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4187 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4188 virtual void OnTestCaseStart(const TestCase& test_case);
4189 virtual void OnTestStart(const TestInfo& test_info);
4190 virtual void OnTestPartResult(const TestPartResult& result);
4191 virtual void OnTestEnd(const TestInfo& test_info);
4192 virtual void OnTestCaseEnd(const TestCase& test_case);
4193 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4194 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4195 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4196 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4197
4198 private:
4199 static void PrintFailedTests(const UnitTest& unit_test);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004200};
4201
4202 // Fired before each iteration of tests starts.
4203void PrettyUnitTestResultPrinter::OnTestIterationStart(
4204 const UnitTest& unit_test, int iteration) {
4205 if (GTEST_FLAG(repeat) != 1)
4206 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4207
4208 const char* const filter = GTEST_FLAG(filter).c_str();
4209
4210 // Prints the filter if it's not *. This reminds the user that some
4211 // tests may be skipped.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004212 if (!String::CStringEquals(filter, kUniversalFilter)) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004213 ColoredPrintf(COLOR_YELLOW,
4214 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4215 }
4216
4217 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4218 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4219 ColoredPrintf(COLOR_YELLOW,
4220 "Note: This is test shard %d of %s.\n",
4221 static_cast<int>(shard_index) + 1,
4222 internal::posix::GetEnv(kTestTotalShards));
4223 }
4224
4225 if (GTEST_FLAG(shuffle)) {
4226 ColoredPrintf(COLOR_YELLOW,
4227 "Note: Randomizing tests' orders with a seed of %d .\n",
4228 unit_test.random_seed());
4229 }
4230
4231 ColoredPrintf(COLOR_GREEN, "[==========] ");
4232 printf("Running %s from %s.\n",
4233 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4234 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4235 fflush(stdout);
4236}
4237
4238void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4239 const UnitTest& /*unit_test*/) {
4240 ColoredPrintf(COLOR_GREEN, "[----------] ");
4241 printf("Global test environment set-up.\n");
4242 fflush(stdout);
4243}
4244
4245void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004246 const std::string counts =
Keir Mierle8ebb0732012-04-30 23:09:08 -07004247 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4248 ColoredPrintf(COLOR_GREEN, "[----------] ");
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004249 printf("%s from %s", counts.c_str(), test_case.name());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004250 if (test_case.type_param() == NULL) {
4251 printf("\n");
4252 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004253 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004254 }
4255 fflush(stdout);
4256}
4257
4258void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4259 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004260 PrintTestName(test_info.test_case_name(), test_info.name());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004261 printf("\n");
4262 fflush(stdout);
4263}
4264
4265// Called after an assertion failure.
4266void PrettyUnitTestResultPrinter::OnTestPartResult(
4267 const TestPartResult& result) {
4268 // If the test part succeeded, we don't need to do anything.
4269 if (result.type() == TestPartResult::kSuccess)
4270 return;
4271
4272 // Print failure message from the assertion (e.g. expected this and got that).
4273 PrintTestPartResult(result);
4274 fflush(stdout);
4275}
4276
4277void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4278 if (test_info.result()->Passed()) {
4279 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4280 } else {
4281 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4282 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004283 PrintTestName(test_info.test_case_name(), test_info.name());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004284 if (test_info.result()->Failed())
4285 PrintFullTestCommentIfPresent(test_info);
4286
4287 if (GTEST_FLAG(print_time)) {
4288 printf(" (%s ms)\n", internal::StreamableToString(
4289 test_info.result()->elapsed_time()).c_str());
4290 } else {
4291 printf("\n");
4292 }
4293 fflush(stdout);
4294}
4295
4296void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4297 if (!GTEST_FLAG(print_time)) return;
4298
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004299 const std::string counts =
Keir Mierle8ebb0732012-04-30 23:09:08 -07004300 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4301 ColoredPrintf(COLOR_GREEN, "[----------] ");
4302 printf("%s from %s (%s ms total)\n\n",
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004303 counts.c_str(), test_case.name(),
Keir Mierle8ebb0732012-04-30 23:09:08 -07004304 internal::StreamableToString(test_case.elapsed_time()).c_str());
4305 fflush(stdout);
4306}
4307
4308void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4309 const UnitTest& /*unit_test*/) {
4310 ColoredPrintf(COLOR_GREEN, "[----------] ");
4311 printf("Global test environment tear-down\n");
4312 fflush(stdout);
4313}
4314
4315// Internal helper for printing the list of failed tests.
4316void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4317 const int failed_test_count = unit_test.failed_test_count();
4318 if (failed_test_count == 0) {
4319 return;
4320 }
4321
4322 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4323 const TestCase& test_case = *unit_test.GetTestCase(i);
4324 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4325 continue;
4326 }
4327 for (int j = 0; j < test_case.total_test_count(); ++j) {
4328 const TestInfo& test_info = *test_case.GetTestInfo(j);
4329 if (!test_info.should_run() || test_info.result()->Passed()) {
4330 continue;
4331 }
4332 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4333 printf("%s.%s", test_case.name(), test_info.name());
4334 PrintFullTestCommentIfPresent(test_info);
4335 printf("\n");
4336 }
4337 }
4338}
4339
4340void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4341 int /*iteration*/) {
4342 ColoredPrintf(COLOR_GREEN, "[==========] ");
4343 printf("%s from %s ran.",
4344 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4345 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4346 if (GTEST_FLAG(print_time)) {
4347 printf(" (%s ms total)",
4348 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4349 }
4350 printf("\n");
4351 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4352 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4353
4354 int num_failures = unit_test.failed_test_count();
4355 if (!unit_test.Passed()) {
4356 const int failed_test_count = unit_test.failed_test_count();
4357 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4358 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4359 PrintFailedTests(unit_test);
4360 printf("\n%2d FAILED %s\n", num_failures,
4361 num_failures == 1 ? "TEST" : "TESTS");
4362 }
4363
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004364 int num_disabled = unit_test.reportable_disabled_test_count();
Keir Mierle8ebb0732012-04-30 23:09:08 -07004365 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4366 if (!num_failures) {
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -07004367 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
Keir Mierle8ebb0732012-04-30 23:09:08 -07004368 }
4369 ColoredPrintf(COLOR_YELLOW,
4370 " YOU HAVE %d DISABLED %s\n\n",
4371 num_disabled,
4372 num_disabled == 1 ? "TEST" : "TESTS");
4373 }
4374 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4375 fflush(stdout);
4376}
4377
4378// End PrettyUnitTestResultPrinter
4379
4380// class TestEventRepeater
4381//
4382// This class forwards events to other event listeners.
4383class TestEventRepeater : public TestEventListener {
4384 public:
4385 TestEventRepeater() : forwarding_enabled_(true) {}
4386 virtual ~TestEventRepeater();
4387 void Append(TestEventListener *listener);
4388 TestEventListener* Release(TestEventListener* listener);
4389
4390 // Controls whether events will be forwarded to listeners_. Set to false
4391 // in death test child processes.
4392 bool forwarding_enabled() const { return forwarding_enabled_; }
4393 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4394
4395 virtual void OnTestProgramStart(const UnitTest& unit_test);
4396 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4397 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4398 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4399 virtual void OnTestCaseStart(const TestCase& test_case);
4400 virtual void OnTestStart(const TestInfo& test_info);
4401 virtual void OnTestPartResult(const TestPartResult& result);
4402 virtual void OnTestEnd(const TestInfo& test_info);
4403 virtual void OnTestCaseEnd(const TestCase& test_case);
4404 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4405 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4406 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4407 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4408
4409 private:
4410 // Controls whether events will be forwarded to listeners_. Set to false
4411 // in death test child processes.
4412 bool forwarding_enabled_;
4413 // The list of listeners that receive events.
4414 std::vector<TestEventListener*> listeners_;
4415
4416 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4417};
4418
4419TestEventRepeater::~TestEventRepeater() {
4420 ForEach(listeners_, Delete<TestEventListener>);
4421}
4422
4423void TestEventRepeater::Append(TestEventListener *listener) {
4424 listeners_.push_back(listener);
4425}
4426
4427// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4428TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4429 for (size_t i = 0; i < listeners_.size(); ++i) {
4430 if (listeners_[i] == listener) {
4431 listeners_.erase(listeners_.begin() + i);
4432 return listener;
4433 }
4434 }
4435
4436 return NULL;
4437}
4438
4439// Since most methods are very similar, use macros to reduce boilerplate.
4440// This defines a member that forwards the call to all listeners.
4441#define GTEST_REPEATER_METHOD_(Name, Type) \
4442void TestEventRepeater::Name(const Type& parameter) { \
4443 if (forwarding_enabled_) { \
4444 for (size_t i = 0; i < listeners_.size(); i++) { \
4445 listeners_[i]->Name(parameter); \
4446 } \
4447 } \
4448}
4449// This defines a member that forwards the call to all listeners in reverse
4450// order.
4451#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4452void TestEventRepeater::Name(const Type& parameter) { \
4453 if (forwarding_enabled_) { \
4454 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4455 listeners_[i]->Name(parameter); \
4456 } \
4457 } \
4458}
4459
4460GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4461GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4462GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4463GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4464GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4465GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4466GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4467GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4468GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4469GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4470GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4471
4472#undef GTEST_REPEATER_METHOD_
4473#undef GTEST_REVERSE_REPEATER_METHOD_
4474
4475void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4476 int iteration) {
4477 if (forwarding_enabled_) {
4478 for (size_t i = 0; i < listeners_.size(); i++) {
4479 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4480 }
4481 }
4482}
4483
4484void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4485 int iteration) {
4486 if (forwarding_enabled_) {
4487 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4488 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4489 }
4490 }
4491}
4492
4493// End TestEventRepeater
4494
4495// This class generates an XML output file.
4496class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4497 public:
4498 explicit XmlUnitTestResultPrinter(const char* output_file);
4499
4500 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4501
4502 private:
4503 // Is c a whitespace character that is normalized to a space character
4504 // when it appears in an XML attribute value?
4505 static bool IsNormalizableWhitespace(char c) {
4506 return c == 0x9 || c == 0xA || c == 0xD;
4507 }
4508
4509 // May c appear in a well-formed XML document?
4510 static bool IsValidXmlCharacter(char c) {
4511 return IsNormalizableWhitespace(c) || c >= 0x20;
4512 }
4513
4514 // Returns an XML-escaped copy of the input string str. If
4515 // is_attribute is true, the text is meant to appear as an attribute
4516 // value, and normalizable whitespace is preserved by replacing it
4517 // with character references.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004518 static std::string EscapeXml(const std::string& str, bool is_attribute);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004519
4520 // Returns the given string with all characters invalid in XML removed.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004521 static std::string RemoveInvalidXmlCharacters(const std::string& str);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004522
4523 // Convenience wrapper around EscapeXml when str is an attribute value.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004524 static std::string EscapeXmlAttribute(const std::string& str) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004525 return EscapeXml(str, true);
4526 }
4527
4528 // Convenience wrapper around EscapeXml when str is not an attribute value.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004529 static std::string EscapeXmlText(const char* str) {
4530 return EscapeXml(str, false);
4531 }
4532
4533 // Verifies that the given attribute belongs to the given element and
4534 // streams the attribute as XML.
4535 static void OutputXmlAttribute(std::ostream* stream,
4536 const std::string& element_name,
4537 const std::string& name,
4538 const std::string& value);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004539
4540 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4541 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4542
4543 // Streams an XML representation of a TestInfo object.
4544 static void OutputXmlTestInfo(::std::ostream* stream,
4545 const char* test_case_name,
4546 const TestInfo& test_info);
4547
4548 // Prints an XML representation of a TestCase object
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004549 static void PrintXmlTestCase(::std::ostream* stream,
4550 const TestCase& test_case);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004551
4552 // Prints an XML summary of unit_test to output stream out.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004553 static void PrintXmlUnitTest(::std::ostream* stream,
4554 const UnitTest& unit_test);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004555
4556 // Produces a string representing the test properties in a result as space
4557 // delimited XML attributes based on the property key="value" pairs.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004558 // When the std::string is not empty, it includes a space at the beginning,
Keir Mierle8ebb0732012-04-30 23:09:08 -07004559 // to delimit this attribute from prior attributes.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004560 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004561
4562 // The output file.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004563 const std::string output_file_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07004564
4565 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4566};
4567
4568// Creates a new XmlUnitTestResultPrinter.
4569XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4570 : output_file_(output_file) {
4571 if (output_file_.c_str() == NULL || output_file_.empty()) {
4572 fprintf(stderr, "XML output file may not be null\n");
4573 fflush(stderr);
4574 exit(EXIT_FAILURE);
4575 }
4576}
4577
4578// Called after the unit test ends.
4579void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4580 int /*iteration*/) {
4581 FILE* xmlout = NULL;
4582 FilePath output_file(output_file_);
4583 FilePath output_dir(output_file.RemoveFileName());
4584
4585 if (output_dir.CreateDirectoriesRecursively()) {
4586 xmlout = posix::FOpen(output_file_.c_str(), "w");
4587 }
4588 if (xmlout == NULL) {
4589 // TODO(wan): report the reason of the failure.
4590 //
4591 // We don't do it for now as:
4592 //
4593 // 1. There is no urgent need for it.
4594 // 2. It's a bit involved to make the errno variable thread-safe on
4595 // all three operating systems (Linux, Windows, and Mac OS).
4596 // 3. To interpret the meaning of errno in a thread-safe way,
4597 // we need the strerror_r() function, which is not available on
4598 // Windows.
4599 fprintf(stderr,
4600 "Unable to open file \"%s\"\n",
4601 output_file_.c_str());
4602 fflush(stderr);
4603 exit(EXIT_FAILURE);
4604 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004605 std::stringstream stream;
4606 PrintXmlUnitTest(&stream, unit_test);
4607 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004608 fclose(xmlout);
4609}
4610
4611// Returns an XML-escaped copy of the input string str. If is_attribute
4612// is true, the text is meant to appear as an attribute value, and
4613// normalizable whitespace is preserved by replacing it with character
4614// references.
4615//
4616// Invalid XML characters in str, if any, are stripped from the output.
4617// It is expected that most, if not all, of the text processed by this
4618// module will consist of ordinary English text.
4619// If this module is ever modified to produce version 1.1 XML output,
4620// most invalid characters can be retained using character references.
4621// TODO(wan): It might be nice to have a minimally invasive, human-readable
4622// escaping scheme for invalid characters, rather than dropping them.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004623std::string XmlUnitTestResultPrinter::EscapeXml(
4624 const std::string& str, bool is_attribute) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004625 Message m;
4626
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004627 for (size_t i = 0; i < str.size(); ++i) {
4628 const char ch = str[i];
4629 switch (ch) {
4630 case '<':
4631 m << "&lt;";
4632 break;
4633 case '>':
4634 m << "&gt;";
4635 break;
4636 case '&':
4637 m << "&amp;";
4638 break;
4639 case '\'':
4640 if (is_attribute)
4641 m << "&apos;";
4642 else
4643 m << '\'';
4644 break;
4645 case '"':
4646 if (is_attribute)
4647 m << "&quot;";
4648 else
4649 m << '"';
4650 break;
4651 default:
4652 if (IsValidXmlCharacter(ch)) {
4653 if (is_attribute && IsNormalizableWhitespace(ch))
4654 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4655 << ";";
Keir Mierle8ebb0732012-04-30 23:09:08 -07004656 else
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004657 m << ch;
4658 }
4659 break;
Keir Mierle8ebb0732012-04-30 23:09:08 -07004660 }
4661 }
4662
4663 return m.GetString();
4664}
4665
4666// Returns the given string with all characters invalid in XML removed.
4667// Currently invalid characters are dropped from the string. An
4668// alternative is to replace them with certain characters such as . or ?.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004669std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4670 const std::string& str) {
4671 std::string output;
Keir Mierle8ebb0732012-04-30 23:09:08 -07004672 output.reserve(str.size());
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004673 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
Keir Mierle8ebb0732012-04-30 23:09:08 -07004674 if (IsValidXmlCharacter(*it))
4675 output.push_back(*it);
4676
4677 return output;
4678}
4679
4680// The following routines generate an XML representation of a UnitTest
4681// object.
4682//
4683// This is how Google Test concepts map to the DTD:
4684//
4685// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4686// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4687// <testcase name="test-name"> <-- corresponds to a TestInfo object
4688// <failure message="...">...</failure>
4689// <failure message="...">...</failure>
4690// <failure message="...">...</failure>
4691// <-- individual assertion failures
4692// </testcase>
4693// </testsuite>
4694// </testsuites>
4695
4696// Formats the given time in milliseconds as seconds.
4697std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4698 ::std::stringstream ss;
4699 ss << ms/1000.0;
4700 return ss.str();
4701}
4702
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004703// Converts the given epoch time in milliseconds to a date string in the ISO
4704// 8601 format, without the timezone information.
4705std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4706 // Using non-reentrant version as localtime_r is not portable.
4707 time_t seconds = static_cast<time_t>(ms / 1000);
4708#ifdef _MSC_VER
4709# pragma warning(push) // Saves the current warning state.
4710# pragma warning(disable:4996) // Temporarily disables warning 4996
4711 // (function or variable may be unsafe).
4712 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4713# pragma warning(pop) // Restores the warning state again.
4714#else
4715 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4716#endif
4717 if (time_struct == NULL)
4718 return ""; // Invalid ms value
4719
4720 // YYYY-MM-DDThh:mm:ss
4721 return StreamableToString(time_struct->tm_year + 1900) + "-" +
4722 String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4723 String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4724 String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4725 String::FormatIntWidth2(time_struct->tm_min) + ":" +
4726 String::FormatIntWidth2(time_struct->tm_sec);
4727}
4728
Keir Mierle8ebb0732012-04-30 23:09:08 -07004729// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4730void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4731 const char* data) {
4732 const char* segment = data;
4733 *stream << "<![CDATA[";
4734 for (;;) {
4735 const char* const next_segment = strstr(segment, "]]>");
4736 if (next_segment != NULL) {
4737 stream->write(
4738 segment, static_cast<std::streamsize>(next_segment - segment));
4739 *stream << "]]>]]&gt;<![CDATA[";
4740 segment = next_segment + strlen("]]>");
4741 } else {
4742 *stream << segment;
4743 break;
4744 }
4745 }
4746 *stream << "]]>";
4747}
4748
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004749void XmlUnitTestResultPrinter::OutputXmlAttribute(
4750 std::ostream* stream,
4751 const std::string& element_name,
4752 const std::string& name,
4753 const std::string& value) {
4754 const std::vector<std::string>& allowed_names =
4755 GetReservedAttributesForElement(element_name);
4756
4757 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4758 allowed_names.end())
4759 << "Attribute " << name << " is not allowed for element <" << element_name
4760 << ">.";
4761
4762 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4763}
4764
Keir Mierle8ebb0732012-04-30 23:09:08 -07004765// Prints an XML representation of a TestInfo object.
4766// TODO(wan): There is also value in printing properties with the plain printer.
4767void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4768 const char* test_case_name,
4769 const TestInfo& test_info) {
4770 const TestResult& result = *test_info.result();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004771 const std::string kTestcase = "testcase";
4772
4773 *stream << " <testcase";
4774 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004775
4776 if (test_info.value_param() != NULL) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004777 OutputXmlAttribute(stream, kTestcase, "value_param",
4778 test_info.value_param());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004779 }
4780 if (test_info.type_param() != NULL) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004781 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004782 }
4783
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004784 OutputXmlAttribute(stream, kTestcase, "status",
4785 test_info.should_run() ? "run" : "notrun");
4786 OutputXmlAttribute(stream, kTestcase, "time",
4787 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4788 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4789 *stream << TestPropertiesAsXmlAttributes(result);
Keir Mierle8ebb0732012-04-30 23:09:08 -07004790
4791 int failures = 0;
4792 for (int i = 0; i < result.total_part_count(); ++i) {
4793 const TestPartResult& part = result.GetTestPartResult(i);
4794 if (part.failed()) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004795 if (++failures == 1) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004796 *stream << ">\n";
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004797 }
Keir Mierle8ebb0732012-04-30 23:09:08 -07004798 const string location = internal::FormatCompilerIndependentFileLocation(
4799 part.file_name(), part.line_number());
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004800 const string summary = location + "\n" + part.summary();
4801 *stream << " <failure message=\""
4802 << EscapeXmlAttribute(summary.c_str())
4803 << "\" type=\"\">";
4804 const string detail = location + "\n" + part.message();
4805 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
Keir Mierle8ebb0732012-04-30 23:09:08 -07004806 *stream << "</failure>\n";
4807 }
4808 }
4809
4810 if (failures == 0)
4811 *stream << " />\n";
4812 else
4813 *stream << " </testcase>\n";
4814}
4815
4816// Prints an XML representation of a TestCase object
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004817void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
Keir Mierle8ebb0732012-04-30 23:09:08 -07004818 const TestCase& test_case) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004819 const std::string kTestsuite = "testsuite";
4820 *stream << " <" << kTestsuite;
4821 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4822 OutputXmlAttribute(stream, kTestsuite, "tests",
4823 StreamableToString(test_case.reportable_test_count()));
4824 OutputXmlAttribute(stream, kTestsuite, "failures",
4825 StreamableToString(test_case.failed_test_count()));
4826 OutputXmlAttribute(
4827 stream, kTestsuite, "disabled",
4828 StreamableToString(test_case.reportable_disabled_test_count()));
4829 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4830 OutputXmlAttribute(stream, kTestsuite, "time",
4831 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
4832 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4833 << ">\n";
4834
Keir Mierle8ebb0732012-04-30 23:09:08 -07004835 for (int i = 0; i < test_case.total_test_count(); ++i) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004836 if (test_case.GetTestInfo(i)->is_reportable())
4837 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
Keir Mierle8ebb0732012-04-30 23:09:08 -07004838 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004839 *stream << " </" << kTestsuite << ">\n";
Keir Mierle8ebb0732012-04-30 23:09:08 -07004840}
4841
4842// Prints an XML summary of unit_test to output stream out.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004843void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
Keir Mierle8ebb0732012-04-30 23:09:08 -07004844 const UnitTest& unit_test) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004845 const std::string kTestsuites = "testsuites";
4846
4847 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4848 *stream << "<" << kTestsuites;
4849
4850 OutputXmlAttribute(stream, kTestsuites, "tests",
4851 StreamableToString(unit_test.reportable_test_count()));
4852 OutputXmlAttribute(stream, kTestsuites, "failures",
4853 StreamableToString(unit_test.failed_test_count()));
4854 OutputXmlAttribute(
4855 stream, kTestsuites, "disabled",
4856 StreamableToString(unit_test.reportable_disabled_test_count()));
4857 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4858 OutputXmlAttribute(
4859 stream, kTestsuites, "timestamp",
4860 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4861 OutputXmlAttribute(stream, kTestsuites, "time",
4862 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4863
Keir Mierle8ebb0732012-04-30 23:09:08 -07004864 if (GTEST_FLAG(shuffle)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004865 OutputXmlAttribute(stream, kTestsuites, "random_seed",
4866 StreamableToString(unit_test.random_seed()));
Keir Mierle8ebb0732012-04-30 23:09:08 -07004867 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004868
4869 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4870
4871 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4872 *stream << ">\n";
4873
4874 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4875 if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
4876 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4877 }
4878 *stream << "</" << kTestsuites << ">\n";
Keir Mierle8ebb0732012-04-30 23:09:08 -07004879}
4880
4881// Produces a string representing the test properties in a result as space
4882// delimited XML attributes based on the property key="value" pairs.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004883std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
Keir Mierle8ebb0732012-04-30 23:09:08 -07004884 const TestResult& result) {
4885 Message attributes;
4886 for (int i = 0; i < result.test_property_count(); ++i) {
4887 const TestProperty& property = result.GetTestProperty(i);
4888 attributes << " " << property.key() << "="
4889 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4890 }
4891 return attributes.GetString();
4892}
4893
4894// End XmlUnitTestResultPrinter
4895
4896#if GTEST_CAN_STREAM_RESULTS_
4897
Keir Mierle8ebb0732012-04-30 23:09:08 -07004898// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4899// replaces them by "%xx" where xx is their hexadecimal value. For
4900// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4901// in both time and space -- important as the input str may contain an
4902// arbitrarily long test failure message and stack trace.
4903string StreamingListener::UrlEncode(const char* str) {
4904 string result;
4905 result.reserve(strlen(str) + 1);
4906 for (char ch = *str; ch != '\0'; ch = *++str) {
4907 switch (ch) {
4908 case '%':
4909 case '=':
4910 case '&':
4911 case '\n':
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004912 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
Keir Mierle8ebb0732012-04-30 23:09:08 -07004913 break;
4914 default:
4915 result.push_back(ch);
4916 break;
4917 }
4918 }
4919 return result;
4920}
4921
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004922void StreamingListener::SocketWriter::MakeConnection() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004923 GTEST_CHECK_(sockfd_ == -1)
4924 << "MakeConnection() can't be called when there is already a connection.";
4925
4926 addrinfo hints;
4927 memset(&hints, 0, sizeof(hints));
4928 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4929 hints.ai_socktype = SOCK_STREAM;
4930 addrinfo* servinfo = NULL;
4931
4932 // Use the getaddrinfo() to get a linked list of IP addresses for
4933 // the given host name.
4934 const int error_num = getaddrinfo(
4935 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4936 if (error_num != 0) {
4937 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4938 << gai_strerror(error_num);
4939 }
4940
4941 // Loop through all the results and connect to the first we can.
4942 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4943 cur_addr = cur_addr->ai_next) {
4944 sockfd_ = socket(
4945 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4946 if (sockfd_ != -1) {
4947 // Connect the client socket to the server socket.
4948 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4949 close(sockfd_);
4950 sockfd_ = -1;
4951 }
4952 }
4953 }
4954
4955 freeaddrinfo(servinfo); // all done with this structure
4956
4957 if (sockfd_ == -1) {
4958 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4959 << host_name_ << ":" << port_num_;
4960 }
4961}
4962
4963// End of class Streaming Listener
4964#endif // GTEST_CAN_STREAM_RESULTS__
4965
4966// Class ScopedTrace
4967
4968// Pushes the given source file location and message onto a per-thread
4969// trace stack maintained by Google Test.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004970ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4971 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004972 TraceInfo trace;
4973 trace.file = file;
4974 trace.line = line;
4975 trace.message = message.GetString();
4976
4977 UnitTest::GetInstance()->PushGTestTrace(trace);
4978}
4979
4980// Pops the info pushed by the c'tor.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004981ScopedTrace::~ScopedTrace()
4982 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07004983 UnitTest::GetInstance()->PopGTestTrace();
4984}
4985
4986
4987// class OsStackTraceGetter
4988
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004989// Returns the current OS stack trace as an std::string. Parameters:
Keir Mierle8ebb0732012-04-30 23:09:08 -07004990//
4991// max_depth - the maximum number of stack frames to be included
4992// in the trace.
4993// skip_count - the number of top frames to be skipped; doesn't count
4994// against max_depth.
4995//
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07004996string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4997 int /* skip_count */)
4998 GTEST_LOCK_EXCLUDED_(mutex_) {
4999 return "";
Keir Mierle8ebb0732012-04-30 23:09:08 -07005000}
5001
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005002void OsStackTraceGetter::UponLeavingGTest()
5003 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005004}
5005
5006const char* const
5007OsStackTraceGetter::kElidedFramesMarker =
5008 "... " GTEST_NAME_ " internal frames ...";
5009
Sameer Agarwal4894a842013-09-19 10:21:56 -07005010// A helper class that creates the premature-exit file in its
5011// constructor and deletes the file in its destructor.
5012class ScopedPrematureExitFile {
5013 public:
5014 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5015 : premature_exit_filepath_(premature_exit_filepath) {
5016 // If a path to the premature-exit file is specified...
5017 if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5018 // create the file with a single "0" character in it. I/O
5019 // errors are ignored as there's nothing better we can do and we
5020 // don't want to fail the test because of this.
5021 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5022 fwrite("0", 1, 1, pfile);
5023 fclose(pfile);
5024 }
5025 }
5026
5027 ~ScopedPrematureExitFile() {
5028 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5029 remove(premature_exit_filepath_);
5030 }
5031 }
5032
5033 private:
5034 const char* const premature_exit_filepath_;
5035
5036 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5037};
5038
Keir Mierle8ebb0732012-04-30 23:09:08 -07005039} // namespace internal
5040
5041// class TestEventListeners
5042
5043TestEventListeners::TestEventListeners()
5044 : repeater_(new internal::TestEventRepeater()),
5045 default_result_printer_(NULL),
5046 default_xml_generator_(NULL) {
5047}
5048
5049TestEventListeners::~TestEventListeners() { delete repeater_; }
5050
5051// Returns the standard listener responsible for the default console
5052// output. Can be removed from the listeners list to shut down default
5053// console output. Note that removing this object from the listener list
5054// with Release transfers its ownership to the user.
5055void TestEventListeners::Append(TestEventListener* listener) {
5056 repeater_->Append(listener);
5057}
5058
5059// Removes the given event listener from the list and returns it. It then
5060// becomes the caller's responsibility to delete the listener. Returns
5061// NULL if the listener is not found in the list.
5062TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5063 if (listener == default_result_printer_)
5064 default_result_printer_ = NULL;
5065 else if (listener == default_xml_generator_)
5066 default_xml_generator_ = NULL;
5067 return repeater_->Release(listener);
5068}
5069
5070// Returns repeater that broadcasts the TestEventListener events to all
5071// subscribers.
5072TestEventListener* TestEventListeners::repeater() { return repeater_; }
5073
5074// Sets the default_result_printer attribute to the provided listener.
5075// The listener is also added to the listener list and previous
5076// default_result_printer is removed from it and deleted. The listener can
5077// also be NULL in which case it will not be added to the list. Does
5078// nothing if the previous and the current listener objects are the same.
5079void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5080 if (default_result_printer_ != listener) {
5081 // It is an error to pass this method a listener that is already in the
5082 // list.
5083 delete Release(default_result_printer_);
5084 default_result_printer_ = listener;
5085 if (listener != NULL)
5086 Append(listener);
5087 }
5088}
5089
5090// Sets the default_xml_generator attribute to the provided listener. The
5091// listener is also added to the listener list and previous
5092// default_xml_generator is removed from it and deleted. The listener can
5093// also be NULL in which case it will not be added to the list. Does
5094// nothing if the previous and the current listener objects are the same.
5095void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5096 if (default_xml_generator_ != listener) {
5097 // It is an error to pass this method a listener that is already in the
5098 // list.
5099 delete Release(default_xml_generator_);
5100 default_xml_generator_ = listener;
5101 if (listener != NULL)
5102 Append(listener);
5103 }
5104}
5105
5106// Controls whether events will be forwarded by the repeater to the
5107// listeners in the list.
5108bool TestEventListeners::EventForwardingEnabled() const {
5109 return repeater_->forwarding_enabled();
5110}
5111
5112void TestEventListeners::SuppressEventForwarding() {
5113 repeater_->set_forwarding_enabled(false);
5114}
5115
5116// class UnitTest
5117
5118// Gets the singleton UnitTest object. The first time this method is
5119// called, a UnitTest object is constructed and returned. Consecutive
5120// calls will return the same object.
5121//
5122// We don't protect this under mutex_ as a user is not supposed to
5123// call this before main() starts, from which point on the return
5124// value will never change.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005125UnitTest* UnitTest::GetInstance() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005126 // When compiled with MSVC 7.1 in optimized mode, destroying the
5127 // UnitTest object upon exiting the program messes up the exit code,
5128 // causing successful tests to appear failed. We have to use a
5129 // different implementation in this case to bypass the compiler bug.
5130 // This implementation makes the compiler happy, at the cost of
5131 // leaking the UnitTest object.
5132
5133 // CodeGear C++Builder insists on a public destructor for the
5134 // default implementation. Use this implementation to keep good OO
5135 // design with private destructor.
5136
5137#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5138 static UnitTest* const instance = new UnitTest;
5139 return instance;
5140#else
5141 static UnitTest instance;
5142 return &instance;
5143#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5144}
5145
5146// Gets the number of successful test cases.
5147int UnitTest::successful_test_case_count() const {
5148 return impl()->successful_test_case_count();
5149}
5150
5151// Gets the number of failed test cases.
5152int UnitTest::failed_test_case_count() const {
5153 return impl()->failed_test_case_count();
5154}
5155
5156// Gets the number of all test cases.
5157int UnitTest::total_test_case_count() const {
5158 return impl()->total_test_case_count();
5159}
5160
5161// Gets the number of all test cases that contain at least one test
5162// that should run.
5163int UnitTest::test_case_to_run_count() const {
5164 return impl()->test_case_to_run_count();
5165}
5166
5167// Gets the number of successful tests.
5168int UnitTest::successful_test_count() const {
5169 return impl()->successful_test_count();
5170}
5171
5172// Gets the number of failed tests.
5173int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5174
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005175// Gets the number of disabled tests that will be reported in the XML report.
5176int UnitTest::reportable_disabled_test_count() const {
5177 return impl()->reportable_disabled_test_count();
5178}
5179
Keir Mierle8ebb0732012-04-30 23:09:08 -07005180// Gets the number of disabled tests.
5181int UnitTest::disabled_test_count() const {
5182 return impl()->disabled_test_count();
5183}
5184
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005185// Gets the number of tests to be printed in the XML report.
5186int UnitTest::reportable_test_count() const {
5187 return impl()->reportable_test_count();
5188}
5189
Keir Mierle8ebb0732012-04-30 23:09:08 -07005190// Gets the number of all tests.
5191int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5192
5193// Gets the number of tests that should run.
5194int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5195
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005196// Gets the time of the test program start, in ms from the start of the
5197// UNIX epoch.
5198internal::TimeInMillis UnitTest::start_timestamp() const {
5199 return impl()->start_timestamp();
5200}
5201
Keir Mierle8ebb0732012-04-30 23:09:08 -07005202// Gets the elapsed time, in milliseconds.
5203internal::TimeInMillis UnitTest::elapsed_time() const {
5204 return impl()->elapsed_time();
5205}
5206
5207// Returns true iff the unit test passed (i.e. all test cases passed).
5208bool UnitTest::Passed() const { return impl()->Passed(); }
5209
5210// Returns true iff the unit test failed (i.e. some test case failed
5211// or something outside of all tests failed).
5212bool UnitTest::Failed() const { return impl()->Failed(); }
5213
5214// Gets the i-th test case among all the test cases. i can range from 0 to
5215// total_test_case_count() - 1. If i is not in that range, returns NULL.
5216const TestCase* UnitTest::GetTestCase(int i) const {
5217 return impl()->GetTestCase(i);
5218}
5219
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005220// Returns the TestResult containing information on test failures and
5221// properties logged outside of individual test cases.
5222const TestResult& UnitTest::ad_hoc_test_result() const {
5223 return *impl()->ad_hoc_test_result();
5224}
5225
Keir Mierle8ebb0732012-04-30 23:09:08 -07005226// Gets the i-th test case among all the test cases. i can range from 0 to
5227// total_test_case_count() - 1. If i is not in that range, returns NULL.
5228TestCase* UnitTest::GetMutableTestCase(int i) {
5229 return impl()->GetMutableTestCase(i);
5230}
5231
5232// Returns the list of event listeners that can be used to track events
5233// inside Google Test.
5234TestEventListeners& UnitTest::listeners() {
5235 return *impl()->listeners();
5236}
5237
5238// Registers and returns a global test environment. When a test
5239// program is run, all global test environments will be set-up in the
5240// order they were registered. After all tests in the program have
5241// finished, all global test environments will be torn-down in the
5242// *reverse* order they were registered.
5243//
5244// The UnitTest object takes ownership of the given environment.
5245//
5246// We don't protect this under mutex_, as we only support calling it
5247// from the main thread.
5248Environment* UnitTest::AddEnvironment(Environment* env) {
5249 if (env == NULL) {
5250 return NULL;
5251 }
5252
5253 impl_->environments().push_back(env);
5254 return env;
5255}
5256
5257// Adds a TestPartResult to the current TestResult object. All Google Test
5258// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5259// this to report their results. The user code should use the
5260// assertion macros instead of calling this directly.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005261void UnitTest::AddTestPartResult(
5262 TestPartResult::Type result_type,
5263 const char* file_name,
5264 int line_number,
5265 const std::string& message,
5266 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005267 Message msg;
5268 msg << message;
5269
5270 internal::MutexLock lock(&mutex_);
5271 if (impl_->gtest_trace_stack().size() > 0) {
5272 msg << "\n" << GTEST_NAME_ << " trace:";
5273
5274 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5275 i > 0; --i) {
5276 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5277 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5278 << " " << trace.message;
5279 }
5280 }
5281
5282 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5283 msg << internal::kStackTraceMarker << os_stack_trace;
5284 }
5285
5286 const TestPartResult result =
5287 TestPartResult(result_type, file_name, line_number,
5288 msg.GetString().c_str());
5289 impl_->GetTestPartResultReporterForCurrentThread()->
5290 ReportTestPartResult(result);
5291
5292 if (result_type != TestPartResult::kSuccess) {
5293 // gtest_break_on_failure takes precedence over
5294 // gtest_throw_on_failure. This allows a user to set the latter
5295 // in the code (perhaps in order to use Google Test assertions
5296 // with another testing framework) and specify the former on the
5297 // command line for debugging.
5298 if (GTEST_FLAG(break_on_failure)) {
5299#if GTEST_OS_WINDOWS
5300 // Using DebugBreak on Windows allows gtest to still break into a debugger
5301 // when a failure happens and both the --gtest_break_on_failure and
5302 // the --gtest_catch_exceptions flags are specified.
5303 DebugBreak();
5304#else
5305 // Dereference NULL through a volatile pointer to prevent the compiler
5306 // from removing. We use this rather than abort() or __builtin_trap() for
5307 // portability: Symbian doesn't implement abort() well, and some debuggers
5308 // don't correctly trap abort().
5309 *static_cast<volatile int*>(NULL) = 1;
5310#endif // GTEST_OS_WINDOWS
5311 } else if (GTEST_FLAG(throw_on_failure)) {
5312#if GTEST_HAS_EXCEPTIONS
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005313 throw internal::GoogleTestFailureException(result);
Keir Mierle8ebb0732012-04-30 23:09:08 -07005314#else
5315 // We cannot call abort() as it generates a pop-up in debug mode
5316 // that cannot be suppressed in VC 7.1 or below.
5317 exit(1);
5318#endif
5319 }
5320 }
5321}
5322
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005323// Adds a TestProperty to the current TestResult object when invoked from
5324// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5325// from SetUpTestCase or TearDownTestCase, or to the global property set
5326// when invoked elsewhere. If the result already contains a property with
5327// the same key, the value will be updated.
5328void UnitTest::RecordProperty(const std::string& key,
5329 const std::string& value) {
5330 impl_->RecordProperty(TestProperty(key, value));
Keir Mierle8ebb0732012-04-30 23:09:08 -07005331}
5332
5333// Runs all tests in this UnitTest object and prints the result.
5334// Returns 0 if successful, or 1 otherwise.
5335//
5336// We don't protect this under mutex_, as we only support calling it
5337// from the main thread.
5338int UnitTest::Run() {
Sameer Agarwal4894a842013-09-19 10:21:56 -07005339 const bool in_death_test_child_process =
5340 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5341
5342 // Google Test implements this protocol for catching that a test
5343 // program exits before returning control to Google Test:
5344 //
5345 // 1. Upon start, Google Test creates a file whose absolute path
5346 // is specified by the environment variable
5347 // TEST_PREMATURE_EXIT_FILE.
5348 // 2. When Google Test has finished its work, it deletes the file.
5349 //
5350 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5351 // running a Google-Test-based test program and check the existence
5352 // of the file at the end of the test execution to see if it has
5353 // exited prematurely.
5354
5355 // If we are in the child process of a death test, don't
5356 // create/delete the premature exit file, as doing so is unnecessary
5357 // and will confuse the parent process. Otherwise, create/delete
5358 // the file upon entering/leaving this function. If the program
5359 // somehow exits before this function has a chance to return, the
5360 // premature-exit file will be left undeleted, causing a test runner
5361 // that understands the premature-exit-file protocol to report the
5362 // test as having failed.
5363 const internal::ScopedPrematureExitFile premature_exit_file(
5364 in_death_test_child_process ?
5365 NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5366
Keir Mierle8ebb0732012-04-30 23:09:08 -07005367 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5368 // used for the duration of the program.
5369 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5370
5371#if GTEST_HAS_SEH
Keir Mierle8ebb0732012-04-30 23:09:08 -07005372 // Either the user wants Google Test to catch exceptions thrown by the
5373 // tests or this is executing in the context of death test child
5374 // process. In either case the user does not want to see pop-up dialogs
5375 // about crashes - they are expected.
5376 if (impl()->catch_exceptions() || in_death_test_child_process) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005377# if !GTEST_OS_WINDOWS_MOBILE
5378 // SetErrorMode doesn't exist on CE.
5379 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5380 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5381# endif // !GTEST_OS_WINDOWS_MOBILE
5382
5383# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5384 // Death test children can be terminated with _abort(). On Windows,
5385 // _abort() can show a dialog with a warning message. This forces the
5386 // abort message to go to stderr instead.
5387 _set_error_mode(_OUT_TO_STDERR);
5388# endif
5389
5390# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5391 // In the debug version, Visual Studio pops up a separate dialog
5392 // offering a choice to debug the aborted program. We need to suppress
5393 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5394 // executed. Google Test will notify the user of any unexpected
5395 // failure via stderr.
5396 //
5397 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5398 // Users of prior VC versions shall suffer the agony and pain of
5399 // clicking through the countless debug dialogs.
5400 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5401 // debug mode when compiled with VC 7.1 or lower.
5402 if (!GTEST_FLAG(break_on_failure))
5403 _set_abort_behavior(
5404 0x0, // Clear the following flags:
5405 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5406# endif
Keir Mierle8ebb0732012-04-30 23:09:08 -07005407 }
5408#endif // GTEST_HAS_SEH
5409
5410 return internal::HandleExceptionsInMethodIfSupported(
5411 impl(),
5412 &internal::UnitTestImpl::RunAllTests,
5413 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5414}
5415
5416// Returns the working directory when the first TEST() or TEST_F() was
5417// executed.
5418const char* UnitTest::original_working_dir() const {
5419 return impl_->original_working_dir_.c_str();
5420}
5421
5422// Returns the TestCase object for the test that's currently running,
5423// or NULL if no test is running.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005424const TestCase* UnitTest::current_test_case() const
5425 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005426 internal::MutexLock lock(&mutex_);
5427 return impl_->current_test_case();
5428}
5429
5430// Returns the TestInfo object for the test that's currently running,
5431// or NULL if no test is running.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005432const TestInfo* UnitTest::current_test_info() const
5433 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005434 internal::MutexLock lock(&mutex_);
5435 return impl_->current_test_info();
5436}
5437
5438// Returns the random seed used at the start of the current test run.
5439int UnitTest::random_seed() const { return impl_->random_seed(); }
5440
5441#if GTEST_HAS_PARAM_TEST
5442// Returns ParameterizedTestCaseRegistry object used to keep track of
5443// value-parameterized tests and instantiate and register them.
Keir Mierle8ebb0732012-04-30 23:09:08 -07005444internal::ParameterizedTestCaseRegistry&
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005445 UnitTest::parameterized_test_registry()
5446 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005447 return impl_->parameterized_test_registry();
5448}
5449#endif // GTEST_HAS_PARAM_TEST
5450
5451// Creates an empty UnitTest.
5452UnitTest::UnitTest() {
5453 impl_ = new internal::UnitTestImpl(this);
5454}
5455
5456// Destructor of UnitTest.
5457UnitTest::~UnitTest() {
5458 delete impl_;
5459}
5460
5461// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5462// Google Test trace stack.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005463void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5464 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005465 internal::MutexLock lock(&mutex_);
5466 impl_->gtest_trace_stack().push_back(trace);
5467}
5468
5469// Pops a trace from the per-thread Google Test trace stack.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005470void UnitTest::PopGTestTrace()
5471 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005472 internal::MutexLock lock(&mutex_);
5473 impl_->gtest_trace_stack().pop_back();
5474}
5475
5476namespace internal {
5477
5478UnitTestImpl::UnitTestImpl(UnitTest* parent)
5479 : parent_(parent),
5480#ifdef _MSC_VER
5481# pragma warning(push) // Saves the current warning state.
5482# pragma warning(disable:4355) // Temporarily disables warning 4355
5483 // (using this in initializer).
5484 default_global_test_part_result_reporter_(this),
5485 default_per_thread_test_part_result_reporter_(this),
5486# pragma warning(pop) // Restores the warning state again.
5487#else
5488 default_global_test_part_result_reporter_(this),
5489 default_per_thread_test_part_result_reporter_(this),
5490#endif // _MSC_VER
5491 global_test_part_result_repoter_(
5492 &default_global_test_part_result_reporter_),
5493 per_thread_test_part_result_reporter_(
5494 &default_per_thread_test_part_result_reporter_),
5495#if GTEST_HAS_PARAM_TEST
5496 parameterized_test_registry_(),
5497 parameterized_tests_registered_(false),
5498#endif // GTEST_HAS_PARAM_TEST
5499 last_death_test_case_(-1),
5500 current_test_case_(NULL),
5501 current_test_info_(NULL),
5502 ad_hoc_test_result_(),
5503 os_stack_trace_getter_(NULL),
5504 post_flag_parse_init_performed_(false),
5505 random_seed_(0), // Will be overridden by the flag before first use.
5506 random_(0), // Will be reseeded before first use.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005507 start_timestamp_(0),
Keir Mierle8ebb0732012-04-30 23:09:08 -07005508 elapsed_time_(0),
5509#if GTEST_HAS_DEATH_TEST
Keir Mierle8ebb0732012-04-30 23:09:08 -07005510 death_test_factory_(new DefaultDeathTestFactory),
5511#endif
5512 // Will be overridden by the flag before first use.
5513 catch_exceptions_(false) {
5514 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5515}
5516
5517UnitTestImpl::~UnitTestImpl() {
5518 // Deletes every TestCase.
5519 ForEach(test_cases_, internal::Delete<TestCase>);
5520
5521 // Deletes every Environment.
5522 ForEach(environments_, internal::Delete<Environment>);
5523
5524 delete os_stack_trace_getter_;
5525}
5526
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005527// Adds a TestProperty to the current TestResult object when invoked in a
5528// context of a test, to current test case's ad_hoc_test_result when invoke
5529// from SetUpTestCase/TearDownTestCase, or to the global property set
5530// otherwise. If the result already contains a property with the same key,
5531// the value will be updated.
5532void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5533 std::string xml_element;
5534 TestResult* test_result; // TestResult appropriate for property recording.
5535
5536 if (current_test_info_ != NULL) {
5537 xml_element = "testcase";
5538 test_result = &(current_test_info_->result_);
5539 } else if (current_test_case_ != NULL) {
5540 xml_element = "testsuite";
5541 test_result = &(current_test_case_->ad_hoc_test_result_);
5542 } else {
5543 xml_element = "testsuites";
5544 test_result = &ad_hoc_test_result_;
5545 }
5546 test_result->RecordProperty(xml_element, test_property);
5547}
5548
Keir Mierle8ebb0732012-04-30 23:09:08 -07005549#if GTEST_HAS_DEATH_TEST
5550// Disables event forwarding if the control is currently in a death test
5551// subprocess. Must not be called before InitGoogleTest.
5552void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5553 if (internal_run_death_test_flag_.get() != NULL)
5554 listeners()->SuppressEventForwarding();
5555}
5556#endif // GTEST_HAS_DEATH_TEST
5557
5558// Initializes event listeners performing XML output as specified by
5559// UnitTestOptions. Must not be called before InitGoogleTest.
5560void UnitTestImpl::ConfigureXmlOutput() {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005561 const std::string& output_format = UnitTestOptions::GetOutputFormat();
Keir Mierle8ebb0732012-04-30 23:09:08 -07005562 if (output_format == "xml") {
5563 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5564 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5565 } else if (output_format != "") {
5566 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5567 output_format.c_str());
5568 fflush(stdout);
5569 }
5570}
5571
5572#if GTEST_CAN_STREAM_RESULTS_
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005573// Initializes event listeners for streaming test results in string form.
Keir Mierle8ebb0732012-04-30 23:09:08 -07005574// Must not be called before InitGoogleTest.
5575void UnitTestImpl::ConfigureStreamingOutput() {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005576 const std::string& target = GTEST_FLAG(stream_result_to);
Keir Mierle8ebb0732012-04-30 23:09:08 -07005577 if (!target.empty()) {
5578 const size_t pos = target.find(':');
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005579 if (pos != std::string::npos) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07005580 listeners()->Append(new StreamingListener(target.substr(0, pos),
5581 target.substr(pos+1)));
5582 } else {
5583 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5584 target.c_str());
5585 fflush(stdout);
5586 }
5587 }
5588}
5589#endif // GTEST_CAN_STREAM_RESULTS_
5590
5591// Performs initialization dependent upon flag values obtained in
5592// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5593// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5594// this function is also called from RunAllTests. Since this function can be
5595// called more than once, it has to be idempotent.
5596void UnitTestImpl::PostFlagParsingInit() {
5597 // Ensures that this function does not execute more than once.
5598 if (!post_flag_parse_init_performed_) {
5599 post_flag_parse_init_performed_ = true;
5600
5601#if GTEST_HAS_DEATH_TEST
5602 InitDeathTestSubprocessControlInfo();
5603 SuppressTestEventsIfInSubprocess();
5604#endif // GTEST_HAS_DEATH_TEST
5605
5606 // Registers parameterized tests. This makes parameterized tests
5607 // available to the UnitTest reflection API without running
5608 // RUN_ALL_TESTS.
5609 RegisterParameterizedTests();
5610
5611 // Configures listeners for XML output. This makes it possible for users
5612 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5613 ConfigureXmlOutput();
5614
5615#if GTEST_CAN_STREAM_RESULTS_
5616 // Configures listeners for streaming test results to the specified server.
5617 ConfigureStreamingOutput();
5618#endif // GTEST_CAN_STREAM_RESULTS_
5619 }
5620}
5621
5622// A predicate that checks the name of a TestCase against a known
5623// value.
5624//
5625// This is used for implementation of the UnitTest class only. We put
5626// it in the anonymous namespace to prevent polluting the outer
5627// namespace.
5628//
5629// TestCaseNameIs is copyable.
5630class TestCaseNameIs {
5631 public:
5632 // Constructor.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005633 explicit TestCaseNameIs(const std::string& name)
Keir Mierle8ebb0732012-04-30 23:09:08 -07005634 : name_(name) {}
5635
5636 // Returns true iff the name of test_case matches name_.
5637 bool operator()(const TestCase* test_case) const {
5638 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5639 }
5640
5641 private:
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005642 std::string name_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07005643};
5644
5645// Finds and returns a TestCase with the given name. If one doesn't
5646// exist, creates one and returns it. It's the CALLER'S
5647// RESPONSIBILITY to ensure that this function is only called WHEN THE
5648// TESTS ARE NOT SHUFFLED.
5649//
5650// Arguments:
5651//
5652// test_case_name: name of the test case
5653// type_param: the name of the test case's type parameter, or NULL if
5654// this is not a typed or a type-parameterized test case.
5655// set_up_tc: pointer to the function that sets up the test case
5656// tear_down_tc: pointer to the function that tears down the test case
5657TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5658 const char* type_param,
5659 Test::SetUpTestCaseFunc set_up_tc,
5660 Test::TearDownTestCaseFunc tear_down_tc) {
5661 // Can we find a TestCase with the given name?
5662 const std::vector<TestCase*>::const_iterator test_case =
5663 std::find_if(test_cases_.begin(), test_cases_.end(),
5664 TestCaseNameIs(test_case_name));
5665
5666 if (test_case != test_cases_.end())
5667 return *test_case;
5668
5669 // No. Let's create one.
5670 TestCase* const new_test_case =
5671 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5672
5673 // Is this a death test case?
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005674 if (internal::UnitTestOptions::MatchesFilter(test_case_name,
Keir Mierle8ebb0732012-04-30 23:09:08 -07005675 kDeathTestCaseFilter)) {
5676 // Yes. Inserts the test case after the last death test case
5677 // defined so far. This only works when the test cases haven't
5678 // been shuffled. Otherwise we may end up running a death test
5679 // after a non-death test.
5680 ++last_death_test_case_;
5681 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5682 new_test_case);
5683 } else {
5684 // No. Appends to the end of the list.
5685 test_cases_.push_back(new_test_case);
5686 }
5687
5688 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5689 return new_test_case;
5690}
5691
5692// Helpers for setting up / tearing down the given environment. They
5693// are for use in the ForEach() function.
5694static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5695static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5696
5697// Runs all tests in this UnitTest object, prints the result, and
5698// returns true if all tests are successful. If any exception is
5699// thrown during a test, the test is considered to be failed, but the
5700// rest of the tests will still be run.
5701//
5702// When parameterized tests are enabled, it expands and registers
5703// parameterized tests first in RegisterParameterizedTests().
5704// All other functions called from RunAllTests() may safely assume that
5705// parameterized tests are ready to be counted and run.
5706bool UnitTestImpl::RunAllTests() {
5707 // Makes sure InitGoogleTest() was called.
5708 if (!GTestIsInitialized()) {
5709 printf("%s",
5710 "\nThis test program did NOT call ::testing::InitGoogleTest "
5711 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5712 return false;
5713 }
5714
5715 // Do not run any test if the --help flag was specified.
5716 if (g_help_flag)
5717 return true;
5718
5719 // Repeats the call to the post-flag parsing initialization in case the
5720 // user didn't call InitGoogleTest.
5721 PostFlagParsingInit();
5722
5723 // Even if sharding is not on, test runners may want to use the
5724 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5725 // protocol.
5726 internal::WriteToShardStatusFileIfNeeded();
5727
5728 // True iff we are in a subprocess for running a thread-safe-style
5729 // death test.
5730 bool in_subprocess_for_death_test = false;
5731
5732#if GTEST_HAS_DEATH_TEST
5733 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5734#endif // GTEST_HAS_DEATH_TEST
5735
5736 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5737 in_subprocess_for_death_test);
5738
5739 // Compares the full test names with the filter to decide which
5740 // tests to run.
5741 const bool has_tests_to_run = FilterTests(should_shard
5742 ? HONOR_SHARDING_PROTOCOL
5743 : IGNORE_SHARDING_PROTOCOL) > 0;
5744
5745 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5746 if (GTEST_FLAG(list_tests)) {
5747 // This must be called *after* FilterTests() has been called.
5748 ListTestsMatchingFilter();
5749 return true;
5750 }
5751
5752 random_seed_ = GTEST_FLAG(shuffle) ?
5753 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5754
5755 // True iff at least one test has failed.
5756 bool failed = false;
5757
5758 TestEventListener* repeater = listeners()->repeater();
5759
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005760 start_timestamp_ = GetTimeInMillis();
Keir Mierle8ebb0732012-04-30 23:09:08 -07005761 repeater->OnTestProgramStart(*parent_);
5762
5763 // How many times to repeat the tests? We don't want to repeat them
5764 // when we are inside the subprocess of a death test.
5765 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5766 // Repeats forever if the repeat count is negative.
5767 const bool forever = repeat < 0;
5768 for (int i = 0; forever || i != repeat; i++) {
5769 // We want to preserve failures generated by ad-hoc test
5770 // assertions executed before RUN_ALL_TESTS().
5771 ClearNonAdHocTestResult();
5772
5773 const TimeInMillis start = GetTimeInMillis();
5774
5775 // Shuffles test cases and tests if requested.
5776 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5777 random()->Reseed(random_seed_);
5778 // This should be done before calling OnTestIterationStart(),
5779 // such that a test event listener can see the actual test order
5780 // in the event.
5781 ShuffleTests();
5782 }
5783
5784 // Tells the unit test event listeners that the tests are about to start.
5785 repeater->OnTestIterationStart(*parent_, i);
5786
5787 // Runs each test case if there is at least one test to run.
5788 if (has_tests_to_run) {
5789 // Sets up all environments beforehand.
5790 repeater->OnEnvironmentsSetUpStart(*parent_);
5791 ForEach(environments_, SetUpEnvironment);
5792 repeater->OnEnvironmentsSetUpEnd(*parent_);
5793
5794 // Runs the tests only if there was no fatal failure during global
5795 // set-up.
5796 if (!Test::HasFatalFailure()) {
5797 for (int test_index = 0; test_index < total_test_case_count();
5798 test_index++) {
5799 GetMutableTestCase(test_index)->Run();
5800 }
5801 }
5802
5803 // Tears down all environments in reverse order afterwards.
5804 repeater->OnEnvironmentsTearDownStart(*parent_);
5805 std::for_each(environments_.rbegin(), environments_.rend(),
5806 TearDownEnvironment);
5807 repeater->OnEnvironmentsTearDownEnd(*parent_);
5808 }
5809
5810 elapsed_time_ = GetTimeInMillis() - start;
5811
5812 // Tells the unit test event listener that the tests have just finished.
5813 repeater->OnTestIterationEnd(*parent_, i);
5814
5815 // Gets the result and clears it.
5816 if (!Passed()) {
5817 failed = true;
5818 }
5819
5820 // Restores the original test order after the iteration. This
5821 // allows the user to quickly repro a failure that happens in the
5822 // N-th iteration without repeating the first (N - 1) iterations.
5823 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5824 // case the user somehow changes the value of the flag somewhere
5825 // (it's always safe to unshuffle the tests).
5826 UnshuffleTests();
5827
5828 if (GTEST_FLAG(shuffle)) {
5829 // Picks a new random seed for each iteration.
5830 random_seed_ = GetNextRandomSeed(random_seed_);
5831 }
5832 }
5833
5834 repeater->OnTestProgramEnd(*parent_);
5835
5836 return !failed;
5837}
5838
5839// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5840// if the variable is present. If a file already exists at this location, this
5841// function will write over it. If the variable is present, but the file cannot
5842// be created, prints an error and exits.
5843void WriteToShardStatusFileIfNeeded() {
5844 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5845 if (test_shard_file != NULL) {
5846 FILE* const file = posix::FOpen(test_shard_file, "w");
5847 if (file == NULL) {
5848 ColoredPrintf(COLOR_RED,
5849 "Could not write to the test shard status file \"%s\" "
5850 "specified by the %s environment variable.\n",
5851 test_shard_file, kTestShardStatusFile);
5852 fflush(stdout);
5853 exit(EXIT_FAILURE);
5854 }
5855 fclose(file);
5856 }
5857}
5858
5859// Checks whether sharding is enabled by examining the relevant
5860// environment variable values. If the variables are present,
5861// but inconsistent (i.e., shard_index >= total_shards), prints
5862// an error and exits. If in_subprocess_for_death_test, sharding is
5863// disabled because it must only be applied to the original test
5864// process. Otherwise, we could filter out death tests we intended to execute.
5865bool ShouldShard(const char* total_shards_env,
5866 const char* shard_index_env,
5867 bool in_subprocess_for_death_test) {
5868 if (in_subprocess_for_death_test) {
5869 return false;
5870 }
5871
5872 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5873 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5874
5875 if (total_shards == -1 && shard_index == -1) {
5876 return false;
5877 } else if (total_shards == -1 && shard_index != -1) {
5878 const Message msg = Message()
5879 << "Invalid environment variables: you have "
5880 << kTestShardIndex << " = " << shard_index
5881 << ", but have left " << kTestTotalShards << " unset.\n";
5882 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5883 fflush(stdout);
5884 exit(EXIT_FAILURE);
5885 } else if (total_shards != -1 && shard_index == -1) {
5886 const Message msg = Message()
5887 << "Invalid environment variables: you have "
5888 << kTestTotalShards << " = " << total_shards
5889 << ", but have left " << kTestShardIndex << " unset.\n";
5890 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5891 fflush(stdout);
5892 exit(EXIT_FAILURE);
5893 } else if (shard_index < 0 || shard_index >= total_shards) {
5894 const Message msg = Message()
5895 << "Invalid environment variables: we require 0 <= "
5896 << kTestShardIndex << " < " << kTestTotalShards
5897 << ", but you have " << kTestShardIndex << "=" << shard_index
5898 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5899 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5900 fflush(stdout);
5901 exit(EXIT_FAILURE);
5902 }
5903
5904 return total_shards > 1;
5905}
5906
5907// Parses the environment variable var as an Int32. If it is unset,
5908// returns default_val. If it is not an Int32, prints an error
5909// and aborts.
5910Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5911 const char* str_val = posix::GetEnv(var);
5912 if (str_val == NULL) {
5913 return default_val;
5914 }
5915
5916 Int32 result;
5917 if (!ParseInt32(Message() << "The value of environment variable " << var,
5918 str_val, &result)) {
5919 exit(EXIT_FAILURE);
5920 }
5921 return result;
5922}
5923
5924// Given the total number of shards, the shard index, and the test id,
5925// returns true iff the test should be run on this shard. The test id is
5926// some arbitrary but unique non-negative integer assigned to each test
5927// method. Assumes that 0 <= shard_index < total_shards.
5928bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5929 return (test_id % total_shards) == shard_index;
5930}
5931
5932// Compares the name of each test with the user-specified filter to
5933// decide whether the test should be run, then records the result in
5934// each TestCase and TestInfo object.
5935// If shard_tests == true, further filters tests based on sharding
5936// variables in the environment - see
5937// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5938// Returns the number of tests that should run.
5939int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5940 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5941 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5942 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5943 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5944
5945 // num_runnable_tests are the number of tests that will
5946 // run across all shards (i.e., match filter and are not disabled).
5947 // num_selected_tests are the number of tests to be run on
5948 // this shard.
5949 int num_runnable_tests = 0;
5950 int num_selected_tests = 0;
5951 for (size_t i = 0; i < test_cases_.size(); i++) {
5952 TestCase* const test_case = test_cases_[i];
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005953 const std::string &test_case_name = test_case->name();
Keir Mierle8ebb0732012-04-30 23:09:08 -07005954 test_case->set_should_run(false);
5955
5956 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5957 TestInfo* const test_info = test_case->test_info_list()[j];
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005958 const std::string test_name(test_info->name());
Keir Mierle8ebb0732012-04-30 23:09:08 -07005959 // A test is disabled if test case name or test name matches
5960 // kDisableTestFilter.
5961 const bool is_disabled =
5962 internal::UnitTestOptions::MatchesFilter(test_case_name,
5963 kDisableTestFilter) ||
5964 internal::UnitTestOptions::MatchesFilter(test_name,
5965 kDisableTestFilter);
5966 test_info->is_disabled_ = is_disabled;
5967
5968 const bool matches_filter =
5969 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5970 test_name);
5971 test_info->matches_filter_ = matches_filter;
5972
5973 const bool is_runnable =
5974 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5975 matches_filter;
5976
5977 const bool is_selected = is_runnable &&
5978 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5979 ShouldRunTestOnShard(total_shards, shard_index,
5980 num_runnable_tests));
5981
5982 num_runnable_tests += is_runnable;
5983 num_selected_tests += is_selected;
5984
5985 test_info->should_run_ = is_selected;
5986 test_case->set_should_run(test_case->should_run() || is_selected);
5987 }
5988 }
5989 return num_selected_tests;
5990}
5991
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07005992// Prints the given C-string on a single line by replacing all '\n'
5993// characters with string "\\n". If the output takes more than
5994// max_length characters, only prints the first max_length characters
5995// and "...".
5996static void PrintOnOneLine(const char* str, int max_length) {
5997 if (str != NULL) {
5998 for (int i = 0; *str != '\0'; ++str) {
5999 if (i >= max_length) {
6000 printf("...");
6001 break;
6002 }
6003 if (*str == '\n') {
6004 printf("\\n");
6005 i += 2;
6006 } else {
6007 printf("%c", *str);
6008 ++i;
6009 }
6010 }
6011 }
6012}
6013
Keir Mierle8ebb0732012-04-30 23:09:08 -07006014// Prints the names of the tests matching the user-specified filter flag.
6015void UnitTestImpl::ListTestsMatchingFilter() {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006016 // Print at most this many characters for each type/value parameter.
6017 const int kMaxParamLength = 250;
6018
Keir Mierle8ebb0732012-04-30 23:09:08 -07006019 for (size_t i = 0; i < test_cases_.size(); i++) {
6020 const TestCase* const test_case = test_cases_[i];
6021 bool printed_test_case_name = false;
6022
6023 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6024 const TestInfo* const test_info =
6025 test_case->test_info_list()[j];
6026 if (test_info->matches_filter_) {
6027 if (!printed_test_case_name) {
6028 printed_test_case_name = true;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006029 printf("%s.", test_case->name());
6030 if (test_case->type_param() != NULL) {
6031 printf(" # %s = ", kTypeParamLabel);
6032 // We print the type parameter on a single line to make
6033 // the output easy to parse by a program.
6034 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6035 }
6036 printf("\n");
Keir Mierle8ebb0732012-04-30 23:09:08 -07006037 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006038 printf(" %s", test_info->name());
6039 if (test_info->value_param() != NULL) {
6040 printf(" # %s = ", kValueParamLabel);
6041 // We print the value parameter on a single line to make the
6042 // output easy to parse by a program.
6043 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6044 }
6045 printf("\n");
Keir Mierle8ebb0732012-04-30 23:09:08 -07006046 }
6047 }
6048 }
6049 fflush(stdout);
6050}
6051
6052// Sets the OS stack trace getter.
6053//
6054// Does nothing if the input and the current OS stack trace getter are
6055// the same; otherwise, deletes the old getter and makes the input the
6056// current getter.
6057void UnitTestImpl::set_os_stack_trace_getter(
6058 OsStackTraceGetterInterface* getter) {
6059 if (os_stack_trace_getter_ != getter) {
6060 delete os_stack_trace_getter_;
6061 os_stack_trace_getter_ = getter;
6062 }
6063}
6064
6065// Returns the current OS stack trace getter if it is not NULL;
6066// otherwise, creates an OsStackTraceGetter, makes it the current
6067// getter, and returns it.
6068OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6069 if (os_stack_trace_getter_ == NULL) {
6070 os_stack_trace_getter_ = new OsStackTraceGetter;
6071 }
6072
6073 return os_stack_trace_getter_;
6074}
6075
6076// Returns the TestResult for the test that's currently running, or
6077// the TestResult for the ad hoc test if no test is running.
6078TestResult* UnitTestImpl::current_test_result() {
6079 return current_test_info_ ?
6080 &(current_test_info_->result_) : &ad_hoc_test_result_;
6081}
6082
6083// Shuffles all test cases, and the tests within each test case,
6084// making sure that death tests are still run first.
6085void UnitTestImpl::ShuffleTests() {
6086 // Shuffles the death test cases.
6087 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6088
6089 // Shuffles the non-death test cases.
6090 ShuffleRange(random(), last_death_test_case_ + 1,
6091 static_cast<int>(test_cases_.size()), &test_case_indices_);
6092
6093 // Shuffles the tests inside each test case.
6094 for (size_t i = 0; i < test_cases_.size(); i++) {
6095 test_cases_[i]->ShuffleTests(random());
6096 }
6097}
6098
6099// Restores the test cases and tests to their order before the first shuffle.
6100void UnitTestImpl::UnshuffleTests() {
6101 for (size_t i = 0; i < test_cases_.size(); i++) {
6102 // Unshuffles the tests in each test case.
6103 test_cases_[i]->UnshuffleTests();
6104 // Resets the index of each test case.
6105 test_case_indices_[i] = static_cast<int>(i);
6106 }
6107}
6108
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006109// Returns the current OS stack trace as an std::string.
Keir Mierle8ebb0732012-04-30 23:09:08 -07006110//
6111// The maximum number of stack frames to be included is specified by
6112// the gtest_stack_trace_depth flag. The skip_count parameter
6113// specifies the number of top frames to be skipped, which doesn't
6114// count against the number of frames to be included.
6115//
6116// For example, if Foo() calls Bar(), which in turn calls
6117// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6118// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006119std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6120 int skip_count) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006121 // We pass skip_count + 1 to skip this wrapper function in addition
6122 // to what the user really wants to skip.
6123 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6124}
6125
6126// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6127// suppress unreachable code warnings.
6128namespace {
6129class ClassUniqueToAlwaysTrue {};
6130}
6131
6132bool IsTrue(bool condition) { return condition; }
6133
6134bool AlwaysTrue() {
6135#if GTEST_HAS_EXCEPTIONS
6136 // This condition is always false so AlwaysTrue() never actually throws,
6137 // but it makes the compiler think that it may throw.
6138 if (IsTrue(false))
6139 throw ClassUniqueToAlwaysTrue();
6140#endif // GTEST_HAS_EXCEPTIONS
6141 return true;
6142}
6143
6144// If *pstr starts with the given prefix, modifies *pstr to be right
6145// past the prefix and returns true; otherwise leaves *pstr unchanged
6146// and returns false. None of pstr, *pstr, and prefix can be NULL.
6147bool SkipPrefix(const char* prefix, const char** pstr) {
6148 const size_t prefix_len = strlen(prefix);
6149 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6150 *pstr += prefix_len;
6151 return true;
6152 }
6153 return false;
6154}
6155
6156// Parses a string as a command line flag. The string should have
6157// the format "--flag=value". When def_optional is true, the "=value"
6158// part can be omitted.
6159//
6160// Returns the value of the flag, or NULL if the parsing failed.
6161const char* ParseFlagValue(const char* str,
6162 const char* flag,
6163 bool def_optional) {
6164 // str and flag must not be NULL.
6165 if (str == NULL || flag == NULL) return NULL;
6166
6167 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006168 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
Keir Mierle8ebb0732012-04-30 23:09:08 -07006169 const size_t flag_len = flag_str.length();
6170 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6171
6172 // Skips the flag name.
6173 const char* flag_end = str + flag_len;
6174
6175 // When def_optional is true, it's OK to not have a "=value" part.
6176 if (def_optional && (flag_end[0] == '\0')) {
6177 return flag_end;
6178 }
6179
6180 // If def_optional is true and there are more characters after the
6181 // flag name, or if def_optional is false, there must be a '=' after
6182 // the flag name.
6183 if (flag_end[0] != '=') return NULL;
6184
6185 // Returns the string after "=".
6186 return flag_end + 1;
6187}
6188
6189// Parses a string for a bool flag, in the form of either
6190// "--flag=value" or "--flag".
6191//
6192// In the former case, the value is taken as true as long as it does
6193// not start with '0', 'f', or 'F'.
6194//
6195// In the latter case, the value is taken as true.
6196//
6197// On success, stores the value of the flag in *value, and returns
6198// true. On failure, returns false without changing *value.
6199bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6200 // Gets the value of the flag as a string.
6201 const char* const value_str = ParseFlagValue(str, flag, true);
6202
6203 // Aborts if the parsing failed.
6204 if (value_str == NULL) return false;
6205
6206 // Converts the string value to a bool.
6207 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6208 return true;
6209}
6210
6211// Parses a string for an Int32 flag, in the form of
6212// "--flag=value".
6213//
6214// On success, stores the value of the flag in *value, and returns
6215// true. On failure, returns false without changing *value.
6216bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6217 // Gets the value of the flag as a string.
6218 const char* const value_str = ParseFlagValue(str, flag, false);
6219
6220 // Aborts if the parsing failed.
6221 if (value_str == NULL) return false;
6222
6223 // Sets *value to the value of the flag.
6224 return ParseInt32(Message() << "The value of flag --" << flag,
6225 value_str, value);
6226}
6227
6228// Parses a string for a string flag, in the form of
6229// "--flag=value".
6230//
6231// On success, stores the value of the flag in *value, and returns
6232// true. On failure, returns false without changing *value.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006233bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006234 // Gets the value of the flag as a string.
6235 const char* const value_str = ParseFlagValue(str, flag, false);
6236
6237 // Aborts if the parsing failed.
6238 if (value_str == NULL) return false;
6239
6240 // Sets *value to the value of the flag.
6241 *value = value_str;
6242 return true;
6243}
6244
6245// Determines whether a string has a prefix that Google Test uses for its
6246// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6247// If Google Test detects that a command line flag has its prefix but is not
6248// recognized, it will print its help message. Flags starting with
6249// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6250// internal flags and do not trigger the help message.
6251static bool HasGoogleTestFlagPrefix(const char* str) {
6252 return (SkipPrefix("--", &str) ||
6253 SkipPrefix("-", &str) ||
6254 SkipPrefix("/", &str)) &&
6255 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6256 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6257 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6258}
6259
6260// Prints a string containing code-encoded text. The following escape
6261// sequences can be used in the string to control the text color:
6262//
6263// @@ prints a single '@' character.
6264// @R changes the color to red.
6265// @G changes the color to green.
6266// @Y changes the color to yellow.
6267// @D changes to the default terminal text color.
6268//
6269// TODO(wan@google.com): Write tests for this once we add stdout
6270// capturing to Google Test.
6271static void PrintColorEncoded(const char* str) {
6272 GTestColor color = COLOR_DEFAULT; // The current color.
6273
6274 // Conceptually, we split the string into segments divided by escape
6275 // sequences. Then we print one segment at a time. At the end of
6276 // each iteration, the str pointer advances to the beginning of the
6277 // next segment.
6278 for (;;) {
6279 const char* p = strchr(str, '@');
6280 if (p == NULL) {
6281 ColoredPrintf(color, "%s", str);
6282 return;
6283 }
6284
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006285 ColoredPrintf(color, "%s", std::string(str, p).c_str());
Keir Mierle8ebb0732012-04-30 23:09:08 -07006286
6287 const char ch = p[1];
6288 str = p + 2;
6289 if (ch == '@') {
6290 ColoredPrintf(color, "@");
6291 } else if (ch == 'D') {
6292 color = COLOR_DEFAULT;
6293 } else if (ch == 'R') {
6294 color = COLOR_RED;
6295 } else if (ch == 'G') {
6296 color = COLOR_GREEN;
6297 } else if (ch == 'Y') {
6298 color = COLOR_YELLOW;
6299 } else {
6300 --str;
6301 }
6302 }
6303}
6304
6305static const char kColorEncodedHelpMessage[] =
6306"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6307"following command line flags to control its behavior:\n"
6308"\n"
6309"Test Selection:\n"
6310" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6311" List the names of all tests instead of running them. The name of\n"
6312" TEST(Foo, Bar) is \"Foo.Bar\".\n"
6313" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6314 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6315" Run only the tests whose name matches one of the positive patterns but\n"
6316" none of the negative patterns. '?' matches any single character; '*'\n"
6317" matches any substring; ':' separates two patterns.\n"
6318" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6319" Run all disabled tests too.\n"
6320"\n"
6321"Test Execution:\n"
6322" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6323" Run the tests repeatedly; use a negative count to repeat forever.\n"
6324" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6325" Randomize tests' orders on every iteration.\n"
6326" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6327" Random number seed to use for shuffling test orders (between 1 and\n"
6328" 99999, or 0 to use a seed based on the current time).\n"
6329"\n"
6330"Test Output:\n"
6331" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6332" Enable/disable colored output. The default is @Gauto@D.\n"
6333" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6334" Don't print the elapsed time of each test.\n"
6335" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6336 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6337" Generate an XML report in the given directory or with the given file\n"
6338" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6339#if GTEST_CAN_STREAM_RESULTS_
6340" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6341" Stream test results to the given server.\n"
6342#endif // GTEST_CAN_STREAM_RESULTS_
6343"\n"
6344"Assertion Behavior:\n"
6345#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6346" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6347" Set the default death test style.\n"
6348#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6349" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6350" Turn assertion failures into debugger break-points.\n"
6351" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6352" Turn assertion failures into C++ exceptions.\n"
6353" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6354" Do not report exceptions as test failures. Instead, allow them\n"
6355" to crash the program or throw a pop-up (on Windows).\n"
6356"\n"
6357"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6358 "the corresponding\n"
6359"environment variable of a flag (all letters in upper-case). For example, to\n"
6360"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6361 "color=no@D or set\n"
6362"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6363"\n"
6364"For more information, please read the " GTEST_NAME_ " documentation at\n"
6365"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6366"(not one in your own code or tests), please report it to\n"
6367"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6368
6369// Parses the command line for Google Test flags, without initializing
6370// other parts of Google Test. The type parameter CharType can be
6371// instantiated to either char or wchar_t.
6372template <typename CharType>
6373void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6374 for (int i = 1; i < *argc; i++) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006375 const std::string arg_string = StreamableToString(argv[i]);
Keir Mierle8ebb0732012-04-30 23:09:08 -07006376 const char* const arg = arg_string.c_str();
6377
6378 using internal::ParseBoolFlag;
6379 using internal::ParseInt32Flag;
6380 using internal::ParseStringFlag;
6381
6382 // Do we see a Google Test flag?
6383 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6384 &GTEST_FLAG(also_run_disabled_tests)) ||
6385 ParseBoolFlag(arg, kBreakOnFailureFlag,
6386 &GTEST_FLAG(break_on_failure)) ||
6387 ParseBoolFlag(arg, kCatchExceptionsFlag,
6388 &GTEST_FLAG(catch_exceptions)) ||
6389 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6390 ParseStringFlag(arg, kDeathTestStyleFlag,
6391 &GTEST_FLAG(death_test_style)) ||
6392 ParseBoolFlag(arg, kDeathTestUseFork,
6393 &GTEST_FLAG(death_test_use_fork)) ||
6394 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6395 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6396 &GTEST_FLAG(internal_run_death_test)) ||
6397 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6398 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6399 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6400 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6401 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6402 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6403 ParseInt32Flag(arg, kStackTraceDepthFlag,
6404 &GTEST_FLAG(stack_trace_depth)) ||
6405 ParseStringFlag(arg, kStreamResultToFlag,
6406 &GTEST_FLAG(stream_result_to)) ||
6407 ParseBoolFlag(arg, kThrowOnFailureFlag,
6408 &GTEST_FLAG(throw_on_failure))
6409 ) {
6410 // Yes. Shift the remainder of the argv list left by one. Note
6411 // that argv has (*argc + 1) elements, the last one always being
6412 // NULL. The following loop moves the trailing NULL element as
6413 // well.
6414 for (int j = i; j != *argc; j++) {
6415 argv[j] = argv[j + 1];
6416 }
6417
6418 // Decrements the argument count.
6419 (*argc)--;
6420
6421 // We also need to decrement the iterator as we just removed
6422 // an element.
6423 i--;
6424 } else if (arg_string == "--help" || arg_string == "-h" ||
6425 arg_string == "-?" || arg_string == "/?" ||
6426 HasGoogleTestFlagPrefix(arg)) {
6427 // Both help flag and unrecognized Google Test flags (excluding
6428 // internal ones) trigger help display.
6429 g_help_flag = true;
6430 }
6431 }
6432
6433 if (g_help_flag) {
6434 // We print the help here instead of in RUN_ALL_TESTS(), as the
6435 // latter may not be called at all if the user is using Google
6436 // Test with another testing framework.
6437 PrintColorEncoded(kColorEncodedHelpMessage);
6438 }
6439}
6440
6441// Parses the command line for Google Test flags, without initializing
6442// other parts of Google Test.
6443void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6444 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6445}
6446void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6447 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6448}
6449
6450// The internal implementation of InitGoogleTest().
6451//
6452// The type parameter CharType can be instantiated to either char or
6453// wchar_t.
6454template <typename CharType>
6455void InitGoogleTestImpl(int* argc, CharType** argv) {
6456 g_init_gtest_count++;
6457
6458 // We don't want to run the initialization code twice.
6459 if (g_init_gtest_count != 1) return;
6460
6461 if (*argc <= 0) return;
6462
6463 internal::g_executable_path = internal::StreamableToString(argv[0]);
6464
6465#if GTEST_HAS_DEATH_TEST
6466
6467 g_argvs.clear();
6468 for (int i = 0; i != *argc; i++) {
6469 g_argvs.push_back(StreamableToString(argv[i]));
6470 }
6471
6472#endif // GTEST_HAS_DEATH_TEST
6473
6474 ParseGoogleTestFlagsOnly(argc, argv);
6475 GetUnitTestImpl()->PostFlagParsingInit();
6476}
6477
6478} // namespace internal
6479
6480// Initializes Google Test. This must be called before calling
6481// RUN_ALL_TESTS(). In particular, it parses a command line for the
6482// flags that Google Test recognizes. Whenever a Google Test flag is
6483// seen, it is removed from argv, and *argc is decremented.
6484//
6485// No value is returned. Instead, the Google Test flag variables are
6486// updated.
6487//
6488// Calling the function for the second time has no user-visible effect.
6489void InitGoogleTest(int* argc, char** argv) {
6490 internal::InitGoogleTestImpl(argc, argv);
6491}
6492
6493// This overloaded version can be used in Windows programs compiled in
6494// UNICODE mode.
6495void InitGoogleTest(int* argc, wchar_t** argv) {
6496 internal::InitGoogleTestImpl(argc, argv);
6497}
6498
6499} // namespace testing
6500// Copyright 2005, Google Inc.
6501// All rights reserved.
6502//
6503// Redistribution and use in source and binary forms, with or without
6504// modification, are permitted provided that the following conditions are
6505// met:
6506//
6507// * Redistributions of source code must retain the above copyright
6508// notice, this list of conditions and the following disclaimer.
6509// * Redistributions in binary form must reproduce the above
6510// copyright notice, this list of conditions and the following disclaimer
6511// in the documentation and/or other materials provided with the
6512// distribution.
6513// * Neither the name of Google Inc. nor the names of its
6514// contributors may be used to endorse or promote products derived from
6515// this software without specific prior written permission.
6516//
6517// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6518// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6519// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6520// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6521// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6522// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6523// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6524// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6525// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6526// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6527// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6528//
6529// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6530//
6531// This file implements death tests.
6532
6533
6534#if GTEST_HAS_DEATH_TEST
6535
6536# if GTEST_OS_MAC
6537# include <crt_externs.h>
6538# endif // GTEST_OS_MAC
6539
6540# include <errno.h>
6541# include <fcntl.h>
6542# include <limits.h>
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006543
6544# if GTEST_OS_LINUX
6545# include <signal.h>
6546# endif // GTEST_OS_LINUX
6547
Keir Mierle8ebb0732012-04-30 23:09:08 -07006548# include <stdarg.h>
6549
6550# if GTEST_OS_WINDOWS
6551# include <windows.h>
6552# else
6553# include <sys/mman.h>
6554# include <sys/wait.h>
6555# endif // GTEST_OS_WINDOWS
6556
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006557# if GTEST_OS_QNX
6558# include <spawn.h>
6559# endif // GTEST_OS_QNX
6560
Keir Mierle8ebb0732012-04-30 23:09:08 -07006561#endif // GTEST_HAS_DEATH_TEST
6562
6563
6564// Indicates that this translation unit is part of Google Test's
6565// implementation. It must come before gtest-internal-inl.h is
6566// included, or there will be a compiler error. This trick is to
6567// prevent a user from accidentally including gtest-internal-inl.h in
6568// his code.
6569#define GTEST_IMPLEMENTATION_ 1
6570#undef GTEST_IMPLEMENTATION_
6571
6572namespace testing {
6573
6574// Constants.
6575
6576// The default death test style.
6577static const char kDefaultDeathTestStyle[] = "fast";
6578
6579GTEST_DEFINE_string_(
6580 death_test_style,
6581 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6582 "Indicates how to run a death test in a forked child process: "
6583 "\"threadsafe\" (child process re-executes the test binary "
6584 "from the beginning, running only the specific death test) or "
6585 "\"fast\" (child process runs the death test immediately "
6586 "after forking).");
6587
6588GTEST_DEFINE_bool_(
6589 death_test_use_fork,
6590 internal::BoolFromGTestEnv("death_test_use_fork", false),
6591 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6592 "Ignored and always uses fork() on POSIX systems where clone() is not "
6593 "implemented. Useful when running under valgrind or similar tools if "
6594 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6595 "it sees an unsupported combination of clone() flags. "
6596 "It is not recommended to use this flag w/o valgrind though it will "
6597 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6598 "most likely be removed.");
6599
6600namespace internal {
6601GTEST_DEFINE_string_(
6602 internal_run_death_test, "",
6603 "Indicates the file, line number, temporal index of "
6604 "the single death test to run, and a file descriptor to "
6605 "which a success code may be sent, all separated by "
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006606 "the '|' characters. This flag is specified if and only if the current "
Keir Mierle8ebb0732012-04-30 23:09:08 -07006607 "process is a sub-process launched for running a thread-safe "
6608 "death test. FOR INTERNAL USE ONLY.");
6609} // namespace internal
6610
6611#if GTEST_HAS_DEATH_TEST
6612
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006613namespace internal {
6614
6615// Valid only for fast death tests. Indicates the code is running in the
6616// child process of a fast style death test.
6617static bool g_in_fast_death_test_child = false;
6618
6619// Returns a Boolean value indicating whether the caller is currently
6620// executing in the context of the death test child process. Tools such as
6621// Valgrind heap checkers may need this to modify their behavior in death
6622// tests. IMPORTANT: This is an internal utility. Using it may break the
6623// implementation of death tests. User code MUST NOT use it.
6624bool InDeathTestChild() {
6625# if GTEST_OS_WINDOWS
6626
6627 // On Windows, death tests are thread-safe regardless of the value of the
6628 // death_test_style flag.
6629 return !GTEST_FLAG(internal_run_death_test).empty();
6630
6631# else
6632
6633 if (GTEST_FLAG(death_test_style) == "threadsafe")
6634 return !GTEST_FLAG(internal_run_death_test).empty();
6635 else
6636 return g_in_fast_death_test_child;
6637#endif
6638}
6639
6640} // namespace internal
6641
Keir Mierle8ebb0732012-04-30 23:09:08 -07006642// ExitedWithCode constructor.
6643ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6644}
6645
6646// ExitedWithCode function-call operator.
6647bool ExitedWithCode::operator()(int exit_status) const {
6648# if GTEST_OS_WINDOWS
6649
6650 return exit_status == exit_code_;
6651
6652# else
6653
6654 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6655
6656# endif // GTEST_OS_WINDOWS
6657}
6658
6659# if !GTEST_OS_WINDOWS
6660// KilledBySignal constructor.
6661KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6662}
6663
6664// KilledBySignal function-call operator.
6665bool KilledBySignal::operator()(int exit_status) const {
6666 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6667}
6668# endif // !GTEST_OS_WINDOWS
6669
6670namespace internal {
6671
6672// Utilities needed for death tests.
6673
6674// Generates a textual description of a given exit code, in the format
6675// specified by wait(2).
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006676static std::string ExitSummary(int exit_code) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006677 Message m;
6678
6679# if GTEST_OS_WINDOWS
6680
6681 m << "Exited with exit status " << exit_code;
6682
6683# else
6684
6685 if (WIFEXITED(exit_code)) {
6686 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6687 } else if (WIFSIGNALED(exit_code)) {
6688 m << "Terminated by signal " << WTERMSIG(exit_code);
6689 }
6690# ifdef WCOREDUMP
6691 if (WCOREDUMP(exit_code)) {
6692 m << " (core dumped)";
6693 }
6694# endif
6695# endif // GTEST_OS_WINDOWS
6696
6697 return m.GetString();
6698}
6699
6700// Returns true if exit_status describes a process that was terminated
6701// by a signal, or exited normally with a nonzero exit code.
6702bool ExitedUnsuccessfully(int exit_status) {
6703 return !ExitedWithCode(0)(exit_status);
6704}
6705
6706# if !GTEST_OS_WINDOWS
6707// Generates a textual failure message when a death test finds more than
6708// one thread running, or cannot determine the number of threads, prior
6709// to executing the given statement. It is the responsibility of the
6710// caller not to pass a thread_count of 1.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006711static std::string DeathTestThreadWarning(size_t thread_count) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006712 Message msg;
6713 msg << "Death tests use fork(), which is unsafe particularly"
6714 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6715 if (thread_count == 0)
6716 msg << "couldn't detect the number of threads.";
6717 else
6718 msg << "detected " << thread_count << " threads.";
6719 return msg.GetString();
6720}
6721# endif // !GTEST_OS_WINDOWS
6722
6723// Flag characters for reporting a death test that did not die.
6724static const char kDeathTestLived = 'L';
6725static const char kDeathTestReturned = 'R';
6726static const char kDeathTestThrew = 'T';
6727static const char kDeathTestInternalError = 'I';
6728
6729// An enumeration describing all of the possible ways that a death test can
6730// conclude. DIED means that the process died while executing the test
6731// code; LIVED means that process lived beyond the end of the test code;
6732// RETURNED means that the test statement attempted to execute a return
6733// statement, which is not allowed; THREW means that the test statement
6734// returned control by throwing an exception. IN_PROGRESS means the test
6735// has not yet concluded.
6736// TODO(vladl@google.com): Unify names and possibly values for
6737// AbortReason, DeathTestOutcome, and flag characters above.
6738enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6739
6740// Routine for aborting the program which is safe to call from an
6741// exec-style death test child process, in which case the error
6742// message is propagated back to the parent process. Otherwise, the
6743// message is simply printed to stderr. In either case, the program
6744// then exits with status 1.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006745void DeathTestAbort(const std::string& message) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006746 // On a POSIX system, this function may be called from a threadsafe-style
6747 // death test child process, which operates on a very small stack. Use
6748 // the heap for any additional non-minuscule memory requirements.
6749 const InternalRunDeathTestFlag* const flag =
6750 GetUnitTestImpl()->internal_run_death_test_flag();
6751 if (flag != NULL) {
6752 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6753 fputc(kDeathTestInternalError, parent);
6754 fprintf(parent, "%s", message.c_str());
6755 fflush(parent);
6756 _exit(1);
6757 } else {
6758 fprintf(stderr, "%s", message.c_str());
6759 fflush(stderr);
6760 posix::Abort();
6761 }
6762}
6763
6764// A replacement for CHECK that calls DeathTestAbort if the assertion
6765// fails.
6766# define GTEST_DEATH_TEST_CHECK_(expression) \
6767 do { \
6768 if (!::testing::internal::IsTrue(expression)) { \
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006769 DeathTestAbort( \
6770 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6771 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6772 + #expression); \
Keir Mierle8ebb0732012-04-30 23:09:08 -07006773 } \
6774 } while (::testing::internal::AlwaysFalse())
6775
6776// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6777// evaluating any system call that fulfills two conditions: it must return
6778// -1 on failure, and set errno to EINTR when it is interrupted and
6779// should be tried again. The macro expands to a loop that repeatedly
6780// evaluates the expression as long as it evaluates to -1 and sets
6781// errno to EINTR. If the expression evaluates to -1 but errno is
6782// something other than EINTR, DeathTestAbort is called.
6783# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6784 do { \
6785 int gtest_retval; \
6786 do { \
6787 gtest_retval = (expression); \
6788 } while (gtest_retval == -1 && errno == EINTR); \
6789 if (gtest_retval == -1) { \
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006790 DeathTestAbort( \
6791 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6792 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6793 + #expression + " != -1"); \
Keir Mierle8ebb0732012-04-30 23:09:08 -07006794 } \
6795 } while (::testing::internal::AlwaysFalse())
6796
6797// Returns the message describing the last system error in errno.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006798std::string GetLastErrnoDescription() {
6799 return errno == 0 ? "" : posix::StrError(errno);
Keir Mierle8ebb0732012-04-30 23:09:08 -07006800}
6801
6802// This is called from a death test parent process to read a failure
6803// message from the death test child process and log it with the FATAL
6804// severity. On Windows, the message is read from a pipe handle. On other
6805// platforms, it is read from a file descriptor.
6806static void FailFromInternalError(int fd) {
6807 Message error;
6808 char buffer[256];
6809 int num_read;
6810
6811 do {
6812 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6813 buffer[num_read] = '\0';
6814 error << buffer;
6815 }
6816 } while (num_read == -1 && errno == EINTR);
6817
6818 if (num_read == 0) {
6819 GTEST_LOG_(FATAL) << error.GetString();
6820 } else {
6821 const int last_error = errno;
6822 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6823 << GetLastErrnoDescription() << " [" << last_error << "]";
6824 }
6825}
6826
6827// Death test constructor. Increments the running death test count
6828// for the current test.
6829DeathTest::DeathTest() {
6830 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6831 if (info == NULL) {
6832 DeathTestAbort("Cannot run a death test outside of a TEST or "
6833 "TEST_F construct");
6834 }
6835}
6836
6837// Creates and returns a death test by dispatching to the current
6838// death test factory.
6839bool DeathTest::Create(const char* statement, const RE* regex,
6840 const char* file, int line, DeathTest** test) {
6841 return GetUnitTestImpl()->death_test_factory()->Create(
6842 statement, regex, file, line, test);
6843}
6844
6845const char* DeathTest::LastMessage() {
6846 return last_death_test_message_.c_str();
6847}
6848
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006849void DeathTest::set_last_death_test_message(const std::string& message) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07006850 last_death_test_message_ = message;
6851}
6852
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07006853std::string DeathTest::last_death_test_message_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07006854
6855// Provides cross platform implementation for some death functionality.
6856class DeathTestImpl : public DeathTest {
6857 protected:
6858 DeathTestImpl(const char* a_statement, const RE* a_regex)
6859 : statement_(a_statement),
6860 regex_(a_regex),
6861 spawned_(false),
6862 status_(-1),
6863 outcome_(IN_PROGRESS),
6864 read_fd_(-1),
6865 write_fd_(-1) {}
6866
6867 // read_fd_ is expected to be closed and cleared by a derived class.
6868 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6869
6870 void Abort(AbortReason reason);
6871 virtual bool Passed(bool status_ok);
6872
6873 const char* statement() const { return statement_; }
6874 const RE* regex() const { return regex_; }
6875 bool spawned() const { return spawned_; }
6876 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6877 int status() const { return status_; }
6878 void set_status(int a_status) { status_ = a_status; }
6879 DeathTestOutcome outcome() const { return outcome_; }
6880 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6881 int read_fd() const { return read_fd_; }
6882 void set_read_fd(int fd) { read_fd_ = fd; }
6883 int write_fd() const { return write_fd_; }
6884 void set_write_fd(int fd) { write_fd_ = fd; }
6885
6886 // Called in the parent process only. Reads the result code of the death
6887 // test child process via a pipe, interprets it to set the outcome_
6888 // member, and closes read_fd_. Outputs diagnostics and terminates in
6889 // case of unexpected codes.
6890 void ReadAndInterpretStatusByte();
6891
6892 private:
6893 // The textual content of the code this object is testing. This class
6894 // doesn't own this string and should not attempt to delete it.
6895 const char* const statement_;
6896 // The regular expression which test output must match. DeathTestImpl
6897 // doesn't own this object and should not attempt to delete it.
6898 const RE* const regex_;
6899 // True if the death test child process has been successfully spawned.
6900 bool spawned_;
6901 // The exit status of the child process.
6902 int status_;
6903 // How the death test concluded.
6904 DeathTestOutcome outcome_;
6905 // Descriptor to the read end of the pipe to the child process. It is
6906 // always -1 in the child process. The child keeps its write end of the
6907 // pipe in write_fd_.
6908 int read_fd_;
6909 // Descriptor to the child's write end of the pipe to the parent process.
6910 // It is always -1 in the parent process. The parent keeps its end of the
6911 // pipe in read_fd_.
6912 int write_fd_;
6913};
6914
6915// Called in the parent process only. Reads the result code of the death
6916// test child process via a pipe, interprets it to set the outcome_
6917// member, and closes read_fd_. Outputs diagnostics and terminates in
6918// case of unexpected codes.
6919void DeathTestImpl::ReadAndInterpretStatusByte() {
6920 char flag;
6921 int bytes_read;
6922
6923 // The read() here blocks until data is available (signifying the
6924 // failure of the death test) or until the pipe is closed (signifying
6925 // its success), so it's okay to call this in the parent before
6926 // the child process has exited.
6927 do {
6928 bytes_read = posix::Read(read_fd(), &flag, 1);
6929 } while (bytes_read == -1 && errno == EINTR);
6930
6931 if (bytes_read == 0) {
6932 set_outcome(DIED);
6933 } else if (bytes_read == 1) {
6934 switch (flag) {
6935 case kDeathTestReturned:
6936 set_outcome(RETURNED);
6937 break;
6938 case kDeathTestThrew:
6939 set_outcome(THREW);
6940 break;
6941 case kDeathTestLived:
6942 set_outcome(LIVED);
6943 break;
6944 case kDeathTestInternalError:
6945 FailFromInternalError(read_fd()); // Does not return.
6946 break;
6947 default:
6948 GTEST_LOG_(FATAL) << "Death test child process reported "
6949 << "unexpected status byte ("
6950 << static_cast<unsigned int>(flag) << ")";
6951 }
6952 } else {
6953 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6954 << GetLastErrnoDescription();
6955 }
6956 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6957 set_read_fd(-1);
6958}
6959
6960// Signals that the death test code which should have exited, didn't.
6961// Should be called only in a death test child process.
6962// Writes a status byte to the child's status file descriptor, then
6963// calls _exit(1).
6964void DeathTestImpl::Abort(AbortReason reason) {
6965 // The parent process considers the death test to be a failure if
6966 // it finds any data in our pipe. So, here we write a single flag byte
6967 // to the pipe, then exit.
6968 const char status_ch =
6969 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6970 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6971
6972 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6973 // We are leaking the descriptor here because on some platforms (i.e.,
6974 // when built as Windows DLL), destructors of global objects will still
6975 // run after calling _exit(). On such systems, write_fd_ will be
6976 // indirectly closed from the destructor of UnitTestImpl, causing double
6977 // close if it is also closed here. On debug configurations, double close
6978 // may assert. As there are no in-process buffers to flush here, we are
6979 // relying on the OS to close the descriptor after the process terminates
6980 // when the destructors are not run.
6981 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6982}
6983
6984// Returns an indented copy of stderr output for a death test.
6985// This makes distinguishing death test output lines from regular log lines
6986// much easier.
6987static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6988 ::std::string ret;
6989 for (size_t at = 0; ; ) {
6990 const size_t line_end = output.find('\n', at);
6991 ret += "[ DEATH ] ";
6992 if (line_end == ::std::string::npos) {
6993 ret += output.substr(at);
6994 break;
6995 }
6996 ret += output.substr(at, line_end + 1 - at);
6997 at = line_end + 1;
6998 }
6999 return ret;
7000}
7001
7002// Assesses the success or failure of a death test, using both private
7003// members which have previously been set, and one argument:
7004//
7005// Private data members:
7006// outcome: An enumeration describing how the death test
7007// concluded: DIED, LIVED, THREW, or RETURNED. The death test
7008// fails in the latter three cases.
7009// status: The exit status of the child process. On *nix, it is in the
7010// in the format specified by wait(2). On Windows, this is the
7011// value supplied to the ExitProcess() API or a numeric code
7012// of the exception that terminated the program.
7013// regex: A regular expression object to be applied to
7014// the test's captured standard error output; the death test
7015// fails if it does not match.
7016//
7017// Argument:
7018// status_ok: true if exit_status is acceptable in the context of
7019// this particular death test, which fails if it is false
7020//
7021// Returns true iff all of the above conditions are met. Otherwise, the
7022// first failing condition, in the order given above, is the one that is
7023// reported. Also sets the last death test message string.
7024bool DeathTestImpl::Passed(bool status_ok) {
7025 if (!spawned())
7026 return false;
7027
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007028 const std::string error_message = GetCapturedStderr();
Keir Mierle8ebb0732012-04-30 23:09:08 -07007029
7030 bool success = false;
7031 Message buffer;
7032
7033 buffer << "Death test: " << statement() << "\n";
7034 switch (outcome()) {
7035 case LIVED:
7036 buffer << " Result: failed to die.\n"
7037 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7038 break;
7039 case THREW:
7040 buffer << " Result: threw an exception.\n"
7041 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7042 break;
7043 case RETURNED:
7044 buffer << " Result: illegal return in test statement.\n"
7045 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7046 break;
7047 case DIED:
7048 if (status_ok) {
7049 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7050 if (matched) {
7051 success = true;
7052 } else {
7053 buffer << " Result: died but not with expected error.\n"
7054 << " Expected: " << regex()->pattern() << "\n"
7055 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7056 }
7057 } else {
7058 buffer << " Result: died but not with expected exit code:\n"
7059 << " " << ExitSummary(status()) << "\n"
7060 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7061 }
7062 break;
7063 case IN_PROGRESS:
7064 default:
7065 GTEST_LOG_(FATAL)
7066 << "DeathTest::Passed somehow called before conclusion of test";
7067 }
7068
7069 DeathTest::set_last_death_test_message(buffer.GetString());
7070 return success;
7071}
7072
7073# if GTEST_OS_WINDOWS
7074// WindowsDeathTest implements death tests on Windows. Due to the
7075// specifics of starting new processes on Windows, death tests there are
7076// always threadsafe, and Google Test considers the
7077// --gtest_death_test_style=fast setting to be equivalent to
7078// --gtest_death_test_style=threadsafe there.
7079//
7080// A few implementation notes: Like the Linux version, the Windows
7081// implementation uses pipes for child-to-parent communication. But due to
7082// the specifics of pipes on Windows, some extra steps are required:
7083//
7084// 1. The parent creates a communication pipe and stores handles to both
7085// ends of it.
7086// 2. The parent starts the child and provides it with the information
7087// necessary to acquire the handle to the write end of the pipe.
7088// 3. The child acquires the write end of the pipe and signals the parent
7089// using a Windows event.
7090// 4. Now the parent can release the write end of the pipe on its side. If
7091// this is done before step 3, the object's reference count goes down to
7092// 0 and it is destroyed, preventing the child from acquiring it. The
7093// parent now has to release it, or read operations on the read end of
7094// the pipe will not return when the child terminates.
7095// 5. The parent reads child's output through the pipe (outcome code and
7096// any possible error messages) from the pipe, and its stderr and then
7097// determines whether to fail the test.
7098//
7099// Note: to distinguish Win32 API calls from the local method and function
7100// calls, the former are explicitly resolved in the global namespace.
7101//
7102class WindowsDeathTest : public DeathTestImpl {
7103 public:
7104 WindowsDeathTest(const char* a_statement,
7105 const RE* a_regex,
7106 const char* file,
7107 int line)
7108 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7109
7110 // All of these virtual functions are inherited from DeathTest.
7111 virtual int Wait();
7112 virtual TestRole AssumeRole();
7113
7114 private:
7115 // The name of the file in which the death test is located.
7116 const char* const file_;
7117 // The line number on which the death test is located.
7118 const int line_;
7119 // Handle to the write end of the pipe to the child process.
7120 AutoHandle write_handle_;
7121 // Child process handle.
7122 AutoHandle child_handle_;
7123 // Event the child process uses to signal the parent that it has
7124 // acquired the handle to the write end of the pipe. After seeing this
7125 // event the parent can release its own handles to make sure its
7126 // ReadFile() calls return when the child terminates.
7127 AutoHandle event_handle_;
7128};
7129
7130// Waits for the child in a death test to exit, returning its exit
7131// status, or 0 if no child process exists. As a side effect, sets the
7132// outcome data member.
7133int WindowsDeathTest::Wait() {
7134 if (!spawned())
7135 return 0;
7136
7137 // Wait until the child either signals that it has acquired the write end
7138 // of the pipe or it dies.
7139 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7140 switch (::WaitForMultipleObjects(2,
7141 wait_handles,
7142 FALSE, // Waits for any of the handles.
7143 INFINITE)) {
7144 case WAIT_OBJECT_0:
7145 case WAIT_OBJECT_0 + 1:
7146 break;
7147 default:
7148 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7149 }
7150
7151 // The child has acquired the write end of the pipe or exited.
7152 // We release the handle on our side and continue.
7153 write_handle_.Reset();
7154 event_handle_.Reset();
7155
7156 ReadAndInterpretStatusByte();
7157
7158 // Waits for the child process to exit if it haven't already. This
7159 // returns immediately if the child has already exited, regardless of
7160 // whether previous calls to WaitForMultipleObjects synchronized on this
7161 // handle or not.
7162 GTEST_DEATH_TEST_CHECK_(
7163 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7164 INFINITE));
7165 DWORD status_code;
7166 GTEST_DEATH_TEST_CHECK_(
7167 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7168 child_handle_.Reset();
7169 set_status(static_cast<int>(status_code));
7170 return status();
7171}
7172
7173// The AssumeRole process for a Windows death test. It creates a child
7174// process with the same executable as the current process to run the
7175// death test. The child process is given the --gtest_filter and
7176// --gtest_internal_run_death_test flags such that it knows to run the
7177// current death test only.
7178DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7179 const UnitTestImpl* const impl = GetUnitTestImpl();
7180 const InternalRunDeathTestFlag* const flag =
7181 impl->internal_run_death_test_flag();
7182 const TestInfo* const info = impl->current_test_info();
7183 const int death_test_index = info->result()->death_test_count();
7184
7185 if (flag != NULL) {
7186 // ParseInternalRunDeathTestFlag() has performed all the necessary
7187 // processing.
7188 set_write_fd(flag->write_fd());
7189 return EXECUTE_TEST;
7190 }
7191
7192 // WindowsDeathTest uses an anonymous pipe to communicate results of
7193 // a death test.
7194 SECURITY_ATTRIBUTES handles_are_inheritable = {
7195 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7196 HANDLE read_handle, write_handle;
7197 GTEST_DEATH_TEST_CHECK_(
7198 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7199 0) // Default buffer size.
7200 != FALSE);
7201 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7202 O_RDONLY));
7203 write_handle_.Reset(write_handle);
7204 event_handle_.Reset(::CreateEvent(
7205 &handles_are_inheritable,
7206 TRUE, // The event will automatically reset to non-signaled state.
7207 FALSE, // The initial state is non-signalled.
7208 NULL)); // The even is unnamed.
7209 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007210 const std::string filter_flag =
7211 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7212 info->test_case_name() + "." + info->name();
7213 const std::string internal_flag =
7214 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7215 "=" + file_ + "|" + StreamableToString(line_) + "|" +
7216 StreamableToString(death_test_index) + "|" +
7217 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7218 // size_t has the same width as pointers on both 32-bit and 64-bit
Keir Mierle8ebb0732012-04-30 23:09:08 -07007219 // Windows platforms.
7220 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007221 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7222 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007223
7224 char executable_path[_MAX_PATH + 1]; // NOLINT
7225 GTEST_DEATH_TEST_CHECK_(
7226 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7227 executable_path,
7228 _MAX_PATH));
7229
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007230 std::string command_line =
7231 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7232 internal_flag + "\"";
Keir Mierle8ebb0732012-04-30 23:09:08 -07007233
7234 DeathTest::set_last_death_test_message("");
7235
7236 CaptureStderr();
7237 // Flush the log buffers since the log streams are shared with the child.
7238 FlushInfoLog();
7239
7240 // The child process will share the standard handles with the parent.
7241 STARTUPINFOA startup_info;
7242 memset(&startup_info, 0, sizeof(STARTUPINFO));
7243 startup_info.dwFlags = STARTF_USESTDHANDLES;
7244 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7245 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7246 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7247
7248 PROCESS_INFORMATION process_info;
7249 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7250 executable_path,
7251 const_cast<char*>(command_line.c_str()),
7252 NULL, // Retuned process handle is not inheritable.
7253 NULL, // Retuned thread handle is not inheritable.
7254 TRUE, // Child inherits all inheritable handles (for write_handle_).
7255 0x0, // Default creation flags.
7256 NULL, // Inherit the parent's environment.
7257 UnitTest::GetInstance()->original_working_dir(),
7258 &startup_info,
7259 &process_info) != FALSE);
7260 child_handle_.Reset(process_info.hProcess);
7261 ::CloseHandle(process_info.hThread);
7262 set_spawned(true);
7263 return OVERSEE_TEST;
7264}
7265# else // We are not on Windows.
7266
7267// ForkingDeathTest provides implementations for most of the abstract
7268// methods of the DeathTest interface. Only the AssumeRole method is
7269// left undefined.
7270class ForkingDeathTest : public DeathTestImpl {
7271 public:
7272 ForkingDeathTest(const char* statement, const RE* regex);
7273
7274 // All of these virtual functions are inherited from DeathTest.
7275 virtual int Wait();
7276
7277 protected:
7278 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7279
7280 private:
7281 // PID of child process during death test; 0 in the child process itself.
7282 pid_t child_pid_;
7283};
7284
7285// Constructs a ForkingDeathTest.
7286ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7287 : DeathTestImpl(a_statement, a_regex),
7288 child_pid_(-1) {}
7289
7290// Waits for the child in a death test to exit, returning its exit
7291// status, or 0 if no child process exists. As a side effect, sets the
7292// outcome data member.
7293int ForkingDeathTest::Wait() {
7294 if (!spawned())
7295 return 0;
7296
7297 ReadAndInterpretStatusByte();
7298
7299 int status_value;
7300 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7301 set_status(status_value);
7302 return status_value;
7303}
7304
7305// A concrete death test class that forks, then immediately runs the test
7306// in the child process.
7307class NoExecDeathTest : public ForkingDeathTest {
7308 public:
7309 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7310 ForkingDeathTest(a_statement, a_regex) { }
7311 virtual TestRole AssumeRole();
7312};
7313
7314// The AssumeRole process for a fork-and-run death test. It implements a
7315// straightforward fork, with a simple pipe to transmit the status byte.
7316DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7317 const size_t thread_count = GetThreadCount();
7318 if (thread_count != 1) {
7319 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7320 }
7321
7322 int pipe_fd[2];
7323 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7324
7325 DeathTest::set_last_death_test_message("");
7326 CaptureStderr();
7327 // When we fork the process below, the log file buffers are copied, but the
7328 // file descriptors are shared. We flush all log files here so that closing
7329 // the file descriptors in the child process doesn't throw off the
7330 // synchronization between descriptors and buffers in the parent process.
7331 // This is as close to the fork as possible to avoid a race condition in case
7332 // there are multiple threads running before the death test, and another
7333 // thread writes to the log file.
7334 FlushInfoLog();
7335
7336 const pid_t child_pid = fork();
7337 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7338 set_child_pid(child_pid);
7339 if (child_pid == 0) {
7340 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7341 set_write_fd(pipe_fd[1]);
7342 // Redirects all logging to stderr in the child process to prevent
7343 // concurrent writes to the log files. We capture stderr in the parent
7344 // process and append the child process' output to a log.
7345 LogToStderr();
7346 // Event forwarding to the listeners of event listener API mush be shut
7347 // down in death test subprocesses.
7348 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007349 g_in_fast_death_test_child = true;
Keir Mierle8ebb0732012-04-30 23:09:08 -07007350 return EXECUTE_TEST;
7351 } else {
7352 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7353 set_read_fd(pipe_fd[0]);
7354 set_spawned(true);
7355 return OVERSEE_TEST;
7356 }
7357}
7358
7359// A concrete death test class that forks and re-executes the main
7360// program from the beginning, with command-line flags set that cause
7361// only this specific death test to be run.
7362class ExecDeathTest : public ForkingDeathTest {
7363 public:
7364 ExecDeathTest(const char* a_statement, const RE* a_regex,
7365 const char* file, int line) :
7366 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7367 virtual TestRole AssumeRole();
7368 private:
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007369 static ::std::vector<testing::internal::string>
7370 GetArgvsForDeathTestChildProcess() {
7371 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7372 return args;
7373 }
Keir Mierle8ebb0732012-04-30 23:09:08 -07007374 // The name of the file in which the death test is located.
7375 const char* const file_;
7376 // The line number on which the death test is located.
7377 const int line_;
7378};
7379
7380// Utility class for accumulating command-line arguments.
7381class Arguments {
7382 public:
7383 Arguments() {
7384 args_.push_back(NULL);
7385 }
7386
7387 ~Arguments() {
7388 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7389 ++i) {
7390 free(*i);
7391 }
7392 }
7393 void AddArgument(const char* argument) {
7394 args_.insert(args_.end() - 1, posix::StrDup(argument));
7395 }
7396
7397 template <typename Str>
7398 void AddArguments(const ::std::vector<Str>& arguments) {
7399 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7400 i != arguments.end();
7401 ++i) {
7402 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7403 }
7404 }
7405 char* const* Argv() {
7406 return &args_[0];
7407 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007408
Keir Mierle8ebb0732012-04-30 23:09:08 -07007409 private:
7410 std::vector<char*> args_;
7411};
7412
7413// A struct that encompasses the arguments to the child process of a
7414// threadsafe-style death test process.
7415struct ExecDeathTestArgs {
7416 char* const* argv; // Command-line arguments for the child's call to exec
7417 int close_fd; // File descriptor to close; the read end of a pipe
7418};
7419
7420# if GTEST_OS_MAC
7421inline char** GetEnviron() {
7422 // When Google Test is built as a framework on MacOS X, the environ variable
7423 // is unavailable. Apple's documentation (man environ) recommends using
7424 // _NSGetEnviron() instead.
7425 return *_NSGetEnviron();
7426}
7427# else
7428// Some POSIX platforms expect you to declare environ. extern "C" makes
7429// it reside in the global namespace.
7430extern "C" char** environ;
7431inline char** GetEnviron() { return environ; }
7432# endif // GTEST_OS_MAC
7433
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007434# if !GTEST_OS_QNX
Keir Mierle8ebb0732012-04-30 23:09:08 -07007435// The main function for a threadsafe-style death test child process.
7436// This function is called in a clone()-ed process and thus must avoid
7437// any potentially unsafe operations like malloc or libc functions.
7438static int ExecDeathTestChildMain(void* child_arg) {
7439 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7441
7442 // We need to execute the test program in the same environment where
7443 // it was originally invoked. Therefore we change to the original
7444 // working directory first.
7445 const char* const original_dir =
7446 UnitTest::GetInstance()->original_working_dir();
7447 // We can safely call chdir() as it's a direct system call.
7448 if (chdir(original_dir) != 0) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007449 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7450 GetLastErrnoDescription());
Keir Mierle8ebb0732012-04-30 23:09:08 -07007451 return EXIT_FAILURE;
7452 }
7453
7454 // We can safely call execve() as it's a direct system call. We
7455 // cannot use execvp() as it's a libc function and thus potentially
7456 // unsafe. Since execve() doesn't search the PATH, the user must
7457 // invoke the test program via a valid path that contains at least
7458 // one path separator.
7459 execve(args->argv[0], args->argv, GetEnviron());
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007460 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7461 original_dir + " failed: " +
7462 GetLastErrnoDescription());
Keir Mierle8ebb0732012-04-30 23:09:08 -07007463 return EXIT_FAILURE;
7464}
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007465# endif // !GTEST_OS_QNX
Keir Mierle8ebb0732012-04-30 23:09:08 -07007466
7467// Two utility routines that together determine the direction the stack
7468// grows.
7469// This could be accomplished more elegantly by a single recursive
7470// function, but we want to guard against the unlikely possibility of
7471// a smart compiler optimizing the recursion away.
7472//
7473// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7474// StackLowerThanAddress into StackGrowsDown, which then doesn't give
7475// correct answer.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007476void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7477void StackLowerThanAddress(const void* ptr, bool* result) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07007478 int dummy;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007479 *result = (&dummy < ptr);
Keir Mierle8ebb0732012-04-30 23:09:08 -07007480}
7481
7482bool StackGrowsDown() {
7483 int dummy;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007484 bool result;
7485 StackLowerThanAddress(&dummy, &result);
7486 return result;
Keir Mierle8ebb0732012-04-30 23:09:08 -07007487}
7488
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007489// Spawns a child process with the same executable as the current process in
7490// a thread-safe manner and instructs it to run the death test. The
7491// implementation uses fork(2) + exec. On systems where clone(2) is
7492// available, it is used instead, being slightly more thread-safe. On QNX,
7493// fork supports only single-threaded environments, so this function uses
7494// spawn(2) there instead. The function dies with an error message if
7495// anything goes wrong.
7496static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07007497 ExecDeathTestArgs args = { argv, close_fd };
7498 pid_t child_pid = -1;
7499
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007500# if GTEST_OS_QNX
7501 // Obtains the current directory and sets it to be closed in the child
7502 // process.
7503 const int cwd_fd = open(".", O_RDONLY);
7504 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7505 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7506 // We need to execute the test program in the same environment where
7507 // it was originally invoked. Therefore we change to the original
7508 // working directory first.
7509 const char* const original_dir =
7510 UnitTest::GetInstance()->original_working_dir();
7511 // We can safely call chdir() as it's a direct system call.
7512 if (chdir(original_dir) != 0) {
7513 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7514 GetLastErrnoDescription());
7515 return EXIT_FAILURE;
7516 }
7517
7518 int fd_flags;
7519 // Set close_fd to be closed after spawn.
7520 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7521 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7522 fd_flags | FD_CLOEXEC));
7523 struct inheritance inherit = {0};
7524 // spawn is a system call.
7525 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7526 // Restores the current working directory.
7527 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7528 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7529
7530# else // GTEST_OS_QNX
7531# if GTEST_OS_LINUX
7532 // When a SIGPROF signal is received while fork() or clone() are executing,
7533 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7534 // it after the call to fork()/clone() is complete.
7535 struct sigaction saved_sigprof_action;
7536 struct sigaction ignore_sigprof_action;
7537 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7538 sigemptyset(&ignore_sigprof_action.sa_mask);
7539 ignore_sigprof_action.sa_handler = SIG_IGN;
7540 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7541 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7542# endif // GTEST_OS_LINUX
7543
7544# if GTEST_HAS_CLONE
Keir Mierle8ebb0732012-04-30 23:09:08 -07007545 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7546
7547 if (!use_fork) {
7548 static const bool stack_grows_down = StackGrowsDown();
7549 const size_t stack_size = getpagesize();
7550 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7551 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7552 MAP_ANON | MAP_PRIVATE, -1, 0);
7553 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007554
7555 // Maximum stack alignment in bytes: For a downward-growing stack, this
7556 // amount is subtracted from size of the stack space to get an address
7557 // that is within the stack space and is aligned on all systems we care
7558 // about. As far as I know there is no ABI with stack alignment greater
7559 // than 64. We assume stack and stack_size already have alignment of
7560 // kMaxStackAlignment.
7561 const size_t kMaxStackAlignment = 64;
Keir Mierle8ebb0732012-04-30 23:09:08 -07007562 void* const stack_top =
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007563 static_cast<char*>(stack) +
7564 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7565 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7566 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
Keir Mierle8ebb0732012-04-30 23:09:08 -07007567
7568 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7569
7570 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7571 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007572# else
Keir Mierle8ebb0732012-04-30 23:09:08 -07007573 const bool use_fork = true;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007574# endif // GTEST_HAS_CLONE
Keir Mierle8ebb0732012-04-30 23:09:08 -07007575
7576 if (use_fork && (child_pid = fork()) == 0) {
7577 ExecDeathTestChildMain(&args);
7578 _exit(0);
7579 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007580# endif // GTEST_OS_QNX
7581# if GTEST_OS_LINUX
7582 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7583 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7584# endif // GTEST_OS_LINUX
Keir Mierle8ebb0732012-04-30 23:09:08 -07007585
7586 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7587 return child_pid;
7588}
7589
7590// The AssumeRole process for a fork-and-exec death test. It re-executes the
7591// main program from the beginning, setting the --gtest_filter
7592// and --gtest_internal_run_death_test flags to cause only the current
7593// death test to be re-run.
7594DeathTest::TestRole ExecDeathTest::AssumeRole() {
7595 const UnitTestImpl* const impl = GetUnitTestImpl();
7596 const InternalRunDeathTestFlag* const flag =
7597 impl->internal_run_death_test_flag();
7598 const TestInfo* const info = impl->current_test_info();
7599 const int death_test_index = info->result()->death_test_count();
7600
7601 if (flag != NULL) {
7602 set_write_fd(flag->write_fd());
7603 return EXECUTE_TEST;
7604 }
7605
7606 int pipe_fd[2];
7607 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7608 // Clear the close-on-exec flag on the write end of the pipe, lest
7609 // it be closed when the child process does an exec:
7610 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7611
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007612 const std::string filter_flag =
7613 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7614 + info->test_case_name() + "." + info->name();
7615 const std::string internal_flag =
7616 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7617 + file_ + "|" + StreamableToString(line_) + "|"
7618 + StreamableToString(death_test_index) + "|"
7619 + StreamableToString(pipe_fd[1]);
Keir Mierle8ebb0732012-04-30 23:09:08 -07007620 Arguments args;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007621 args.AddArguments(GetArgvsForDeathTestChildProcess());
Keir Mierle8ebb0732012-04-30 23:09:08 -07007622 args.AddArgument(filter_flag.c_str());
7623 args.AddArgument(internal_flag.c_str());
7624
7625 DeathTest::set_last_death_test_message("");
7626
7627 CaptureStderr();
7628 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7629 // is necessary.
7630 FlushInfoLog();
7631
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007632 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
Keir Mierle8ebb0732012-04-30 23:09:08 -07007633 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7634 set_child_pid(child_pid);
7635 set_read_fd(pipe_fd[0]);
7636 set_spawned(true);
7637 return OVERSEE_TEST;
7638}
7639
7640# endif // !GTEST_OS_WINDOWS
7641
7642// Creates a concrete DeathTest-derived class that depends on the
7643// --gtest_death_test_style flag, and sets the pointer pointed to
7644// by the "test" argument to its address. If the test should be
7645// skipped, sets that pointer to NULL. Returns true, unless the
7646// flag is set to an invalid value.
7647bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7648 const char* file, int line,
7649 DeathTest** test) {
7650 UnitTestImpl* const impl = GetUnitTestImpl();
7651 const InternalRunDeathTestFlag* const flag =
7652 impl->internal_run_death_test_flag();
7653 const int death_test_index = impl->current_test_info()
7654 ->increment_death_test_count();
7655
7656 if (flag != NULL) {
7657 if (death_test_index > flag->index()) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007658 DeathTest::set_last_death_test_message(
7659 "Death test count (" + StreamableToString(death_test_index)
7660 + ") somehow exceeded expected maximum ("
7661 + StreamableToString(flag->index()) + ")");
Keir Mierle8ebb0732012-04-30 23:09:08 -07007662 return false;
7663 }
7664
7665 if (!(flag->file() == file && flag->line() == line &&
7666 flag->index() == death_test_index)) {
7667 *test = NULL;
7668 return true;
7669 }
7670 }
7671
7672# if GTEST_OS_WINDOWS
7673
7674 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7675 GTEST_FLAG(death_test_style) == "fast") {
7676 *test = new WindowsDeathTest(statement, regex, file, line);
7677 }
7678
7679# else
7680
7681 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7682 *test = new ExecDeathTest(statement, regex, file, line);
7683 } else if (GTEST_FLAG(death_test_style) == "fast") {
7684 *test = new NoExecDeathTest(statement, regex);
7685 }
7686
7687# endif // GTEST_OS_WINDOWS
7688
7689 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007690 DeathTest::set_last_death_test_message(
7691 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
7692 + "\" encountered");
Keir Mierle8ebb0732012-04-30 23:09:08 -07007693 return false;
7694 }
7695
7696 return true;
7697}
7698
7699// Splits a given string on a given delimiter, populating a given
7700// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7701// ::std::string, so we can use it here.
7702static void SplitString(const ::std::string& str, char delimiter,
7703 ::std::vector< ::std::string>* dest) {
7704 ::std::vector< ::std::string> parsed;
7705 ::std::string::size_type pos = 0;
7706 while (::testing::internal::AlwaysTrue()) {
7707 const ::std::string::size_type colon = str.find(delimiter, pos);
7708 if (colon == ::std::string::npos) {
7709 parsed.push_back(str.substr(pos));
7710 break;
7711 } else {
7712 parsed.push_back(str.substr(pos, colon - pos));
7713 pos = colon + 1;
7714 }
7715 }
7716 dest->swap(parsed);
7717}
7718
7719# if GTEST_OS_WINDOWS
7720// Recreates the pipe and event handles from the provided parameters,
7721// signals the event, and returns a file descriptor wrapped around the pipe
7722// handle. This function is called in the child process only.
7723int GetStatusFileDescriptor(unsigned int parent_process_id,
7724 size_t write_handle_as_size_t,
7725 size_t event_handle_as_size_t) {
7726 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7727 FALSE, // Non-inheritable.
7728 parent_process_id));
7729 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007730 DeathTestAbort("Unable to open parent process " +
7731 StreamableToString(parent_process_id));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007732 }
7733
7734 // TODO(vladl@google.com): Replace the following check with a
7735 // compile-time assertion when available.
7736 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7737
7738 const HANDLE write_handle =
7739 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7740 HANDLE dup_write_handle;
7741
7742 // The newly initialized handle is accessible only in in the parent
7743 // process. To obtain one accessible within the child, we need to use
7744 // DuplicateHandle.
7745 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7746 ::GetCurrentProcess(), &dup_write_handle,
7747 0x0, // Requested privileges ignored since
7748 // DUPLICATE_SAME_ACCESS is used.
7749 FALSE, // Request non-inheritable handler.
7750 DUPLICATE_SAME_ACCESS)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007751 DeathTestAbort("Unable to duplicate the pipe handle " +
7752 StreamableToString(write_handle_as_size_t) +
7753 " from the parent process " +
7754 StreamableToString(parent_process_id));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007755 }
7756
7757 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7758 HANDLE dup_event_handle;
7759
7760 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7761 ::GetCurrentProcess(), &dup_event_handle,
7762 0x0,
7763 FALSE,
7764 DUPLICATE_SAME_ACCESS)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007765 DeathTestAbort("Unable to duplicate the event handle " +
7766 StreamableToString(event_handle_as_size_t) +
7767 " from the parent process " +
7768 StreamableToString(parent_process_id));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007769 }
7770
7771 const int write_fd =
7772 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7773 if (write_fd == -1) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007774 DeathTestAbort("Unable to convert pipe handle " +
7775 StreamableToString(write_handle_as_size_t) +
7776 " to a file descriptor");
Keir Mierle8ebb0732012-04-30 23:09:08 -07007777 }
7778
7779 // Signals the parent that the write end of the pipe has been acquired
7780 // so the parent can release its own write end.
7781 ::SetEvent(dup_event_handle);
7782
7783 return write_fd;
7784}
7785# endif // GTEST_OS_WINDOWS
7786
7787// Returns a newly created InternalRunDeathTestFlag object with fields
7788// initialized from the GTEST_FLAG(internal_run_death_test) flag if
7789// the flag is specified; otherwise returns NULL.
7790InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7791 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7792
7793 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7794 // can use it here.
7795 int line = -1;
7796 int index = -1;
7797 ::std::vector< ::std::string> fields;
7798 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7799 int write_fd = -1;
7800
7801# if GTEST_OS_WINDOWS
7802
7803 unsigned int parent_process_id = 0;
7804 size_t write_handle_as_size_t = 0;
7805 size_t event_handle_as_size_t = 0;
7806
7807 if (fields.size() != 6
7808 || !ParseNaturalNumber(fields[1], &line)
7809 || !ParseNaturalNumber(fields[2], &index)
7810 || !ParseNaturalNumber(fields[3], &parent_process_id)
7811 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7812 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007813 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7814 GTEST_FLAG(internal_run_death_test));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007815 }
7816 write_fd = GetStatusFileDescriptor(parent_process_id,
7817 write_handle_as_size_t,
7818 event_handle_as_size_t);
7819# else
7820
7821 if (fields.size() != 4
7822 || !ParseNaturalNumber(fields[1], &line)
7823 || !ParseNaturalNumber(fields[2], &index)
7824 || !ParseNaturalNumber(fields[3], &write_fd)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007825 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
7826 + GTEST_FLAG(internal_run_death_test));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007827 }
7828
7829# endif // GTEST_OS_WINDOWS
7830
7831 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7832}
7833
7834} // namespace internal
7835
7836#endif // GTEST_HAS_DEATH_TEST
7837
7838} // namespace testing
7839// Copyright 2008, Google Inc.
7840// All rights reserved.
7841//
7842// Redistribution and use in source and binary forms, with or without
7843// modification, are permitted provided that the following conditions are
7844// met:
7845//
7846// * Redistributions of source code must retain the above copyright
7847// notice, this list of conditions and the following disclaimer.
7848// * Redistributions in binary form must reproduce the above
7849// copyright notice, this list of conditions and the following disclaimer
7850// in the documentation and/or other materials provided with the
7851// distribution.
7852// * Neither the name of Google Inc. nor the names of its
7853// contributors may be used to endorse or promote products derived from
7854// this software without specific prior written permission.
7855//
7856// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7857// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7858// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7859// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7860// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7861// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7862// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7863// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7864// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7865// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7866// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7867//
7868// Authors: keith.ray@gmail.com (Keith Ray)
7869
7870
7871#include <stdlib.h>
7872
7873#if GTEST_OS_WINDOWS_MOBILE
7874# include <windows.h>
7875#elif GTEST_OS_WINDOWS
7876# include <direct.h>
7877# include <io.h>
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007878#elif GTEST_OS_SYMBIAN
7879// Symbian OpenC has PATH_MAX in sys/syslimits.h
Keir Mierle8ebb0732012-04-30 23:09:08 -07007880# include <sys/syslimits.h>
7881#else
7882# include <limits.h>
7883# include <climits> // Some Linux distributions define PATH_MAX here.
7884#endif // GTEST_OS_WINDOWS_MOBILE
7885
7886#if GTEST_OS_WINDOWS
7887# define GTEST_PATH_MAX_ _MAX_PATH
7888#elif defined(PATH_MAX)
7889# define GTEST_PATH_MAX_ PATH_MAX
7890#elif defined(_XOPEN_PATH_MAX)
7891# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7892#else
7893# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7894#endif // GTEST_OS_WINDOWS
7895
7896
7897namespace testing {
7898namespace internal {
7899
7900#if GTEST_OS_WINDOWS
7901// On Windows, '\\' is the standard path separator, but many tools and the
7902// Windows API also accept '/' as an alternate path separator. Unless otherwise
7903// noted, a file path can contain either kind of path separators, or a mixture
7904// of them.
7905const char kPathSeparator = '\\';
7906const char kAlternatePathSeparator = '/';
Keir Mierle8ebb0732012-04-30 23:09:08 -07007907const char kAlternatePathSeparatorString[] = "/";
7908# if GTEST_OS_WINDOWS_MOBILE
7909// Windows CE doesn't have a current directory. You should not use
7910// the current directory in tests on Windows CE, but this at least
7911// provides a reasonable fallback.
7912const char kCurrentDirectoryString[] = "\\";
7913// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7914const DWORD kInvalidFileAttributes = 0xffffffff;
7915# else
7916const char kCurrentDirectoryString[] = ".\\";
7917# endif // GTEST_OS_WINDOWS_MOBILE
7918#else
7919const char kPathSeparator = '/';
Keir Mierle8ebb0732012-04-30 23:09:08 -07007920const char kCurrentDirectoryString[] = "./";
7921#endif // GTEST_OS_WINDOWS
7922
7923// Returns whether the given character is a valid path separator.
7924static bool IsPathSeparator(char c) {
7925#if GTEST_HAS_ALT_PATH_SEP_
7926 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7927#else
7928 return c == kPathSeparator;
7929#endif
7930}
7931
7932// Returns the current working directory, or "" if unsuccessful.
7933FilePath FilePath::GetCurrentDir() {
7934#if GTEST_OS_WINDOWS_MOBILE
7935 // Windows CE doesn't have a current directory, so we just return
7936 // something reasonable.
7937 return FilePath(kCurrentDirectoryString);
7938#elif GTEST_OS_WINDOWS
7939 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7940 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7941#else
7942 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7943 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7944#endif // GTEST_OS_WINDOWS_MOBILE
7945}
7946
7947// Returns a copy of the FilePath with the case-insensitive extension removed.
7948// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7949// FilePath("dir/file"). If a case-insensitive extension is not
7950// found, returns a copy of the original FilePath.
7951FilePath FilePath::RemoveExtension(const char* extension) const {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007952 const std::string dot_extension = std::string(".") + extension;
7953 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7954 return FilePath(pathname_.substr(
7955 0, pathname_.length() - dot_extension.length()));
Keir Mierle8ebb0732012-04-30 23:09:08 -07007956 }
7957 return *this;
7958}
7959
7960// Returns a pointer to the last occurence of a valid path separator in
7961// the FilePath. On Windows, for example, both '/' and '\' are valid path
7962// separators. Returns NULL if no path separator was found.
7963const char* FilePath::FindLastPathSeparator() const {
7964 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7965#if GTEST_HAS_ALT_PATH_SEP_
7966 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7967 // Comparing two pointers of which only one is NULL is undefined.
7968 if (last_alt_sep != NULL &&
7969 (last_sep == NULL || last_alt_sep > last_sep)) {
7970 return last_alt_sep;
7971 }
7972#endif
7973 return last_sep;
7974}
7975
7976// Returns a copy of the FilePath with the directory part removed.
7977// Example: FilePath("path/to/file").RemoveDirectoryName() returns
7978// FilePath("file"). If there is no directory part ("just_a_file"), it returns
7979// the FilePath unmodified. If there is no file part ("just_a_dir/") it
7980// returns an empty FilePath ("").
7981// On Windows platform, '\' is the path separator, otherwise it is '/'.
7982FilePath FilePath::RemoveDirectoryName() const {
7983 const char* const last_sep = FindLastPathSeparator();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007984 return last_sep ? FilePath(last_sep + 1) : *this;
Keir Mierle8ebb0732012-04-30 23:09:08 -07007985}
7986
7987// RemoveFileName returns the directory path with the filename removed.
7988// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7989// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7990// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7991// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7992// On Windows platform, '\' is the path separator, otherwise it is '/'.
7993FilePath FilePath::RemoveFileName() const {
7994 const char* const last_sep = FindLastPathSeparator();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007995 std::string dir;
Keir Mierle8ebb0732012-04-30 23:09:08 -07007996 if (last_sep) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07007997 dir = std::string(c_str(), last_sep + 1 - c_str());
Keir Mierle8ebb0732012-04-30 23:09:08 -07007998 } else {
7999 dir = kCurrentDirectoryString;
8000 }
8001 return FilePath(dir);
8002}
8003
8004// Helper functions for naming files in a directory for xml output.
8005
8006// Given directory = "dir", base_name = "test", number = 0,
8007// extension = "xml", returns "dir/test.xml". If number is greater
8008// than zero (e.g., 12), returns "dir/test_12.xml".
8009// On Windows platform, uses \ as the separator rather than /.
8010FilePath FilePath::MakeFileName(const FilePath& directory,
8011 const FilePath& base_name,
8012 int number,
8013 const char* extension) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008014 std::string file;
Keir Mierle8ebb0732012-04-30 23:09:08 -07008015 if (number == 0) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008016 file = base_name.string() + "." + extension;
Keir Mierle8ebb0732012-04-30 23:09:08 -07008017 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008018 file = base_name.string() + "_" + StreamableToString(number)
8019 + "." + extension;
Keir Mierle8ebb0732012-04-30 23:09:08 -07008020 }
8021 return ConcatPaths(directory, FilePath(file));
8022}
8023
8024// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8025// On Windows, uses \ as the separator rather than /.
8026FilePath FilePath::ConcatPaths(const FilePath& directory,
8027 const FilePath& relative_path) {
8028 if (directory.IsEmpty())
8029 return relative_path;
8030 const FilePath dir(directory.RemoveTrailingPathSeparator());
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008031 return FilePath(dir.string() + kPathSeparator + relative_path.string());
Keir Mierle8ebb0732012-04-30 23:09:08 -07008032}
8033
8034// Returns true if pathname describes something findable in the file-system,
8035// either a file, directory, or whatever.
8036bool FilePath::FileOrDirectoryExists() const {
8037#if GTEST_OS_WINDOWS_MOBILE
8038 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8039 const DWORD attributes = GetFileAttributes(unicode);
8040 delete [] unicode;
8041 return attributes != kInvalidFileAttributes;
8042#else
8043 posix::StatStruct file_stat;
8044 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8045#endif // GTEST_OS_WINDOWS_MOBILE
8046}
8047
8048// Returns true if pathname describes a directory in the file-system
8049// that exists.
8050bool FilePath::DirectoryExists() const {
8051 bool result = false;
8052#if GTEST_OS_WINDOWS
8053 // Don't strip off trailing separator if path is a root directory on
8054 // Windows (like "C:\\").
8055 const FilePath& path(IsRootDirectory() ? *this :
8056 RemoveTrailingPathSeparator());
8057#else
8058 const FilePath& path(*this);
8059#endif
8060
8061#if GTEST_OS_WINDOWS_MOBILE
8062 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8063 const DWORD attributes = GetFileAttributes(unicode);
8064 delete [] unicode;
8065 if ((attributes != kInvalidFileAttributes) &&
8066 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8067 result = true;
8068 }
8069#else
8070 posix::StatStruct file_stat;
8071 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8072 posix::IsDir(file_stat);
8073#endif // GTEST_OS_WINDOWS_MOBILE
8074
8075 return result;
8076}
8077
8078// Returns true if pathname describes a root directory. (Windows has one
8079// root directory per disk drive.)
8080bool FilePath::IsRootDirectory() const {
8081#if GTEST_OS_WINDOWS
8082 // TODO(wan@google.com): on Windows a network share like
8083 // \\server\share can be a root directory, although it cannot be the
8084 // current directory. Handle this properly.
8085 return pathname_.length() == 3 && IsAbsolutePath();
8086#else
8087 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8088#endif
8089}
8090
8091// Returns true if pathname describes an absolute path.
8092bool FilePath::IsAbsolutePath() const {
8093 const char* const name = pathname_.c_str();
8094#if GTEST_OS_WINDOWS
8095 return pathname_.length() >= 3 &&
8096 ((name[0] >= 'a' && name[0] <= 'z') ||
8097 (name[0] >= 'A' && name[0] <= 'Z')) &&
8098 name[1] == ':' &&
8099 IsPathSeparator(name[2]);
8100#else
8101 return IsPathSeparator(name[0]);
8102#endif
8103}
8104
8105// Returns a pathname for a file that does not currently exist. The pathname
8106// will be directory/base_name.extension or
8107// directory/base_name_<number>.extension if directory/base_name.extension
8108// already exists. The number will be incremented until a pathname is found
8109// that does not already exist.
8110// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8111// There could be a race condition if two or more processes are calling this
8112// function at the same time -- they could both pick the same filename.
8113FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8114 const FilePath& base_name,
8115 const char* extension) {
8116 FilePath full_pathname;
8117 int number = 0;
8118 do {
8119 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8120 } while (full_pathname.FileOrDirectoryExists());
8121 return full_pathname;
8122}
8123
8124// Returns true if FilePath ends with a path separator, which indicates that
8125// it is intended to represent a directory. Returns false otherwise.
8126// This does NOT check that a directory (or file) actually exists.
8127bool FilePath::IsDirectory() const {
8128 return !pathname_.empty() &&
8129 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8130}
8131
8132// Create directories so that path exists. Returns true if successful or if
8133// the directories already exist; returns false if unable to create directories
8134// for any reason.
8135bool FilePath::CreateDirectoriesRecursively() const {
8136 if (!this->IsDirectory()) {
8137 return false;
8138 }
8139
8140 if (pathname_.length() == 0 || this->DirectoryExists()) {
8141 return true;
8142 }
8143
8144 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8145 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8146}
8147
8148// Create the directory so that path exists. Returns true if successful or
8149// if the directory already exists; returns false if unable to create the
8150// directory for any reason, including if the parent directory does not
8151// exist. Not named "CreateDirectory" because that's a macro on Windows.
8152bool FilePath::CreateFolder() const {
8153#if GTEST_OS_WINDOWS_MOBILE
8154 FilePath removed_sep(this->RemoveTrailingPathSeparator());
8155 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8156 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8157 delete [] unicode;
8158#elif GTEST_OS_WINDOWS
8159 int result = _mkdir(pathname_.c_str());
8160#else
8161 int result = mkdir(pathname_.c_str(), 0777);
8162#endif // GTEST_OS_WINDOWS_MOBILE
8163
8164 if (result == -1) {
8165 return this->DirectoryExists(); // An error is OK if the directory exists.
8166 }
8167 return true; // No error.
8168}
8169
8170// If input name has a trailing separator character, remove it and return the
8171// name, otherwise return the name string unmodified.
8172// On Windows platform, uses \ as the separator, other platforms use /.
8173FilePath FilePath::RemoveTrailingPathSeparator() const {
8174 return IsDirectory()
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008175 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
Keir Mierle8ebb0732012-04-30 23:09:08 -07008176 : *this;
8177}
8178
8179// Removes any redundant separators that might be in the pathname.
8180// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8181// redundancies that might be in a pathname involving "." or "..".
8182// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8183void FilePath::Normalize() {
8184 if (pathname_.c_str() == NULL) {
8185 pathname_ = "";
8186 return;
8187 }
8188 const char* src = pathname_.c_str();
8189 char* const dest = new char[pathname_.length() + 1];
8190 char* dest_ptr = dest;
8191 memset(dest_ptr, 0, pathname_.length() + 1);
8192
8193 while (*src != '\0') {
8194 *dest_ptr = *src;
8195 if (!IsPathSeparator(*src)) {
8196 src++;
8197 } else {
8198#if GTEST_HAS_ALT_PATH_SEP_
8199 if (*dest_ptr == kAlternatePathSeparator) {
8200 *dest_ptr = kPathSeparator;
8201 }
8202#endif
8203 while (IsPathSeparator(*src))
8204 src++;
8205 }
8206 dest_ptr++;
8207 }
8208 *dest_ptr = '\0';
8209 pathname_ = dest;
8210 delete[] dest;
8211}
8212
8213} // namespace internal
8214} // namespace testing
8215// Copyright 2008, Google Inc.
8216// All rights reserved.
8217//
8218// Redistribution and use in source and binary forms, with or without
8219// modification, are permitted provided that the following conditions are
8220// met:
8221//
8222// * Redistributions of source code must retain the above copyright
8223// notice, this list of conditions and the following disclaimer.
8224// * Redistributions in binary form must reproduce the above
8225// copyright notice, this list of conditions and the following disclaimer
8226// in the documentation and/or other materials provided with the
8227// distribution.
8228// * Neither the name of Google Inc. nor the names of its
8229// contributors may be used to endorse or promote products derived from
8230// this software without specific prior written permission.
8231//
8232// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8233// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8234// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8235// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8236// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8237// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8238// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8239// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8240// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8241// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8242// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8243//
8244// Author: wan@google.com (Zhanyong Wan)
8245
8246
8247#include <limits.h>
8248#include <stdlib.h>
8249#include <stdio.h>
8250#include <string.h>
8251
8252#if GTEST_OS_WINDOWS_MOBILE
8253# include <windows.h> // For TerminateProcess()
8254#elif GTEST_OS_WINDOWS
8255# include <io.h>
8256# include <sys/stat.h>
8257#else
8258# include <unistd.h>
8259#endif // GTEST_OS_WINDOWS_MOBILE
8260
8261#if GTEST_OS_MAC
8262# include <mach/mach_init.h>
8263# include <mach/task.h>
8264# include <mach/vm_map.h>
8265#endif // GTEST_OS_MAC
8266
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008267#if GTEST_OS_QNX
8268# include <devctl.h>
8269# include <sys/procfs.h>
8270#endif // GTEST_OS_QNX
8271
Keir Mierle8ebb0732012-04-30 23:09:08 -07008272
8273// Indicates that this translation unit is part of Google Test's
8274// implementation. It must come before gtest-internal-inl.h is
8275// included, or there will be a compiler error. This trick is to
8276// prevent a user from accidentally including gtest-internal-inl.h in
8277// his code.
8278#define GTEST_IMPLEMENTATION_ 1
8279#undef GTEST_IMPLEMENTATION_
8280
8281namespace testing {
8282namespace internal {
8283
8284#if defined(_MSC_VER) || defined(__BORLANDC__)
8285// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8286const int kStdOutFileno = 1;
8287const int kStdErrFileno = 2;
8288#else
8289const int kStdOutFileno = STDOUT_FILENO;
8290const int kStdErrFileno = STDERR_FILENO;
8291#endif // _MSC_VER
8292
8293#if GTEST_OS_MAC
8294
8295// Returns the number of threads running in the process, or 0 to indicate that
8296// we cannot detect it.
8297size_t GetThreadCount() {
8298 const task_t task = mach_task_self();
8299 mach_msg_type_number_t thread_count;
8300 thread_act_array_t thread_list;
8301 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8302 if (status == KERN_SUCCESS) {
8303 // task_threads allocates resources in thread_list and we need to free them
8304 // to avoid leaks.
8305 vm_deallocate(task,
8306 reinterpret_cast<vm_address_t>(thread_list),
8307 sizeof(thread_t) * thread_count);
8308 return static_cast<size_t>(thread_count);
8309 } else {
8310 return 0;
8311 }
8312}
8313
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008314#elif GTEST_OS_QNX
8315
8316// Returns the number of threads running in the process, or 0 to indicate that
8317// we cannot detect it.
8318size_t GetThreadCount() {
8319 const int fd = open("/proc/self/as", O_RDONLY);
8320 if (fd < 0) {
8321 return 0;
8322 }
8323 procfs_info process_info;
8324 const int status =
8325 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8326 close(fd);
8327 if (status == EOK) {
8328 return static_cast<size_t>(process_info.num_threads);
8329 } else {
8330 return 0;
8331 }
8332}
8333
Keir Mierle8ebb0732012-04-30 23:09:08 -07008334#else
8335
8336size_t GetThreadCount() {
8337 // There's no portable way to detect the number of threads, so we just
8338 // return 0 to indicate that we cannot detect it.
8339 return 0;
8340}
8341
8342#endif // GTEST_OS_MAC
8343
8344#if GTEST_USES_POSIX_RE
8345
8346// Implements RE. Currently only needed for death tests.
8347
8348RE::~RE() {
8349 if (is_valid_) {
8350 // regfree'ing an invalid regex might crash because the content
8351 // of the regex is undefined. Since the regex's are essentially
8352 // the same, one cannot be valid (or invalid) without the other
8353 // being so too.
8354 regfree(&partial_regex_);
8355 regfree(&full_regex_);
8356 }
8357 free(const_cast<char*>(pattern_));
8358}
8359
8360// Returns true iff regular expression re matches the entire str.
8361bool RE::FullMatch(const char* str, const RE& re) {
8362 if (!re.is_valid_) return false;
8363
8364 regmatch_t match;
8365 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8366}
8367
8368// Returns true iff regular expression re matches a substring of str
8369// (including str itself).
8370bool RE::PartialMatch(const char* str, const RE& re) {
8371 if (!re.is_valid_) return false;
8372
8373 regmatch_t match;
8374 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8375}
8376
8377// Initializes an RE from its string representation.
8378void RE::Init(const char* regex) {
8379 pattern_ = posix::StrDup(regex);
8380
8381 // Reserves enough bytes to hold the regular expression used for a
8382 // full match.
8383 const size_t full_regex_len = strlen(regex) + 10;
8384 char* const full_pattern = new char[full_regex_len];
8385
8386 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8387 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8388 // We want to call regcomp(&partial_regex_, ...) even if the
8389 // previous expression returns false. Otherwise partial_regex_ may
8390 // not be properly initialized can may cause trouble when it's
8391 // freed.
8392 //
8393 // Some implementation of POSIX regex (e.g. on at least some
8394 // versions of Cygwin) doesn't accept the empty string as a valid
8395 // regex. We change it to an equivalent form "()" to be safe.
8396 if (is_valid_) {
8397 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8398 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8399 }
8400 EXPECT_TRUE(is_valid_)
8401 << "Regular expression \"" << regex
8402 << "\" is not a valid POSIX Extended regular expression.";
8403
8404 delete[] full_pattern;
8405}
8406
8407#elif GTEST_USES_SIMPLE_RE
8408
8409// Returns true iff ch appears anywhere in str (excluding the
8410// terminating '\0' character).
8411bool IsInSet(char ch, const char* str) {
8412 return ch != '\0' && strchr(str, ch) != NULL;
8413}
8414
8415// Returns true iff ch belongs to the given classification. Unlike
8416// similar functions in <ctype.h>, these aren't affected by the
8417// current locale.
8418bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
8419bool IsAsciiPunct(char ch) {
8420 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8421}
8422bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
8423bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
8424bool IsAsciiWordChar(char ch) {
8425 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8426 ('0' <= ch && ch <= '9') || ch == '_';
8427}
8428
8429// Returns true iff "\\c" is a supported escape sequence.
8430bool IsValidEscape(char c) {
8431 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8432}
8433
8434// Returns true iff the given atom (specified by escaped and pattern)
8435// matches ch. The result is undefined if the atom is invalid.
8436bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8437 if (escaped) { // "\\p" where p is pattern_char.
8438 switch (pattern_char) {
8439 case 'd': return IsAsciiDigit(ch);
8440 case 'D': return !IsAsciiDigit(ch);
8441 case 'f': return ch == '\f';
8442 case 'n': return ch == '\n';
8443 case 'r': return ch == '\r';
8444 case 's': return IsAsciiWhiteSpace(ch);
8445 case 'S': return !IsAsciiWhiteSpace(ch);
8446 case 't': return ch == '\t';
8447 case 'v': return ch == '\v';
8448 case 'w': return IsAsciiWordChar(ch);
8449 case 'W': return !IsAsciiWordChar(ch);
8450 }
8451 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8452 }
8453
8454 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8455}
8456
8457// Helper function used by ValidateRegex() to format error messages.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008458std::string FormatRegexSyntaxError(const char* regex, int index) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07008459 return (Message() << "Syntax error at index " << index
8460 << " in simple regular expression \"" << regex << "\": ").GetString();
8461}
8462
8463// Generates non-fatal failures and returns false if regex is invalid;
8464// otherwise returns true.
8465bool ValidateRegex(const char* regex) {
8466 if (regex == NULL) {
8467 // TODO(wan@google.com): fix the source file location in the
8468 // assertion failures to match where the regex is used in user
8469 // code.
8470 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8471 return false;
8472 }
8473
8474 bool is_valid = true;
8475
8476 // True iff ?, *, or + can follow the previous atom.
8477 bool prev_repeatable = false;
8478 for (int i = 0; regex[i]; i++) {
8479 if (regex[i] == '\\') { // An escape sequence
8480 i++;
8481 if (regex[i] == '\0') {
8482 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8483 << "'\\' cannot appear at the end.";
8484 return false;
8485 }
8486
8487 if (!IsValidEscape(regex[i])) {
8488 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8489 << "invalid escape sequence \"\\" << regex[i] << "\".";
8490 is_valid = false;
8491 }
8492 prev_repeatable = true;
8493 } else { // Not an escape sequence.
8494 const char ch = regex[i];
8495
8496 if (ch == '^' && i > 0) {
8497 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8498 << "'^' can only appear at the beginning.";
8499 is_valid = false;
8500 } else if (ch == '$' && regex[i + 1] != '\0') {
8501 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8502 << "'$' can only appear at the end.";
8503 is_valid = false;
8504 } else if (IsInSet(ch, "()[]{}|")) {
8505 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8506 << "'" << ch << "' is unsupported.";
8507 is_valid = false;
8508 } else if (IsRepeat(ch) && !prev_repeatable) {
8509 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8510 << "'" << ch << "' can only follow a repeatable token.";
8511 is_valid = false;
8512 }
8513
8514 prev_repeatable = !IsInSet(ch, "^$?*+");
8515 }
8516 }
8517
8518 return is_valid;
8519}
8520
8521// Matches a repeated regex atom followed by a valid simple regular
8522// expression. The regex atom is defined as c if escaped is false,
8523// or \c otherwise. repeat is the repetition meta character (?, *,
8524// or +). The behavior is undefined if str contains too many
8525// characters to be indexable by size_t, in which case the test will
8526// probably time out anyway. We are fine with this limitation as
8527// std::string has it too.
8528bool MatchRepetitionAndRegexAtHead(
8529 bool escaped, char c, char repeat, const char* regex,
8530 const char* str) {
8531 const size_t min_count = (repeat == '+') ? 1 : 0;
8532 const size_t max_count = (repeat == '?') ? 1 :
8533 static_cast<size_t>(-1) - 1;
8534 // We cannot call numeric_limits::max() as it conflicts with the
8535 // max() macro on Windows.
8536
8537 for (size_t i = 0; i <= max_count; ++i) {
8538 // We know that the atom matches each of the first i characters in str.
8539 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8540 // We have enough matches at the head, and the tail matches too.
8541 // Since we only care about *whether* the pattern matches str
8542 // (as opposed to *how* it matches), there is no need to find a
8543 // greedy match.
8544 return true;
8545 }
8546 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8547 return false;
8548 }
8549 return false;
8550}
8551
8552// Returns true iff regex matches a prefix of str. regex must be a
8553// valid simple regular expression and not start with "^", or the
8554// result is undefined.
8555bool MatchRegexAtHead(const char* regex, const char* str) {
8556 if (*regex == '\0') // An empty regex matches a prefix of anything.
8557 return true;
8558
8559 // "$" only matches the end of a string. Note that regex being
8560 // valid guarantees that there's nothing after "$" in it.
8561 if (*regex == '$')
8562 return *str == '\0';
8563
8564 // Is the first thing in regex an escape sequence?
8565 const bool escaped = *regex == '\\';
8566 if (escaped)
8567 ++regex;
8568 if (IsRepeat(regex[1])) {
8569 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8570 // here's an indirect recursion. It terminates as the regex gets
8571 // shorter in each recursion.
8572 return MatchRepetitionAndRegexAtHead(
8573 escaped, regex[0], regex[1], regex + 2, str);
8574 } else {
8575 // regex isn't empty, isn't "$", and doesn't start with a
8576 // repetition. We match the first atom of regex with the first
8577 // character of str and recurse.
8578 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8579 MatchRegexAtHead(regex + 1, str + 1);
8580 }
8581}
8582
8583// Returns true iff regex matches any substring of str. regex must be
8584// a valid simple regular expression, or the result is undefined.
8585//
8586// The algorithm is recursive, but the recursion depth doesn't exceed
8587// the regex length, so we won't need to worry about running out of
8588// stack space normally. In rare cases the time complexity can be
8589// exponential with respect to the regex length + the string length,
8590// but usually it's must faster (often close to linear).
8591bool MatchRegexAnywhere(const char* regex, const char* str) {
8592 if (regex == NULL || str == NULL)
8593 return false;
8594
8595 if (*regex == '^')
8596 return MatchRegexAtHead(regex + 1, str);
8597
8598 // A successful match can be anywhere in str.
8599 do {
8600 if (MatchRegexAtHead(regex, str))
8601 return true;
8602 } while (*str++ != '\0');
8603 return false;
8604}
8605
8606// Implements the RE class.
8607
8608RE::~RE() {
8609 free(const_cast<char*>(pattern_));
8610 free(const_cast<char*>(full_pattern_));
8611}
8612
8613// Returns true iff regular expression re matches the entire str.
8614bool RE::FullMatch(const char* str, const RE& re) {
8615 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8616}
8617
8618// Returns true iff regular expression re matches a substring of str
8619// (including str itself).
8620bool RE::PartialMatch(const char* str, const RE& re) {
8621 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8622}
8623
8624// Initializes an RE from its string representation.
8625void RE::Init(const char* regex) {
8626 pattern_ = full_pattern_ = NULL;
8627 if (regex != NULL) {
8628 pattern_ = posix::StrDup(regex);
8629 }
8630
8631 is_valid_ = ValidateRegex(regex);
8632 if (!is_valid_) {
8633 // No need to calculate the full pattern when the regex is invalid.
8634 return;
8635 }
8636
8637 const size_t len = strlen(regex);
8638 // Reserves enough bytes to hold the regular expression used for a
8639 // full match: we need space to prepend a '^', append a '$', and
8640 // terminate the string with '\0'.
8641 char* buffer = static_cast<char*>(malloc(len + 3));
8642 full_pattern_ = buffer;
8643
8644 if (*regex != '^')
8645 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8646
8647 // We don't use snprintf or strncpy, as they trigger a warning when
8648 // compiled with VC++ 8.0.
8649 memcpy(buffer, regex, len);
8650 buffer += len;
8651
8652 if (len == 0 || regex[len - 1] != '$')
8653 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8654
8655 *buffer = '\0';
8656}
8657
8658#endif // GTEST_USES_POSIX_RE
8659
8660const char kUnknownFile[] = "unknown file";
8661
8662// Formats a source file path and a line number as they would appear
8663// in an error message from the compiler used to compile this code.
8664GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008665 const std::string file_name(file == NULL ? kUnknownFile : file);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008666
8667 if (line < 0) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008668 return file_name + ":";
Keir Mierle8ebb0732012-04-30 23:09:08 -07008669 }
8670#ifdef _MSC_VER
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008671 return file_name + "(" + StreamableToString(line) + "):";
Keir Mierle8ebb0732012-04-30 23:09:08 -07008672#else
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008673 return file_name + ":" + StreamableToString(line) + ":";
Keir Mierle8ebb0732012-04-30 23:09:08 -07008674#endif // _MSC_VER
8675}
8676
8677// Formats a file location for compiler-independent XML output.
8678// Although this function is not platform dependent, we put it next to
8679// FormatFileLocation in order to contrast the two functions.
8680// Note that FormatCompilerIndependentFileLocation() does NOT append colon
8681// to the file location it produces, unlike FormatFileLocation().
8682GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8683 const char* file, int line) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008684 const std::string file_name(file == NULL ? kUnknownFile : file);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008685
8686 if (line < 0)
8687 return file_name;
8688 else
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008689 return file_name + ":" + StreamableToString(line);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008690}
8691
8692
8693GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8694 : severity_(severity) {
8695 const char* const marker =
8696 severity == GTEST_INFO ? "[ INFO ]" :
8697 severity == GTEST_WARNING ? "[WARNING]" :
8698 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8699 GetStream() << ::std::endl << marker << " "
8700 << FormatFileLocation(file, line).c_str() << ": ";
8701}
8702
8703// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8704GTestLog::~GTestLog() {
8705 GetStream() << ::std::endl;
8706 if (severity_ == GTEST_FATAL) {
8707 fflush(stderr);
8708 posix::Abort();
8709 }
8710}
8711// Disable Microsoft deprecation warnings for POSIX functions called from
8712// this class (creat, dup, dup2, and close)
8713#ifdef _MSC_VER
8714# pragma warning(push)
8715# pragma warning(disable: 4996)
8716#endif // _MSC_VER
8717
8718#if GTEST_HAS_STREAM_REDIRECTION
8719
8720// Object that captures an output stream (stdout/stderr).
8721class CapturedStream {
8722 public:
8723 // The ctor redirects the stream to a temporary file.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008724 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07008725# if GTEST_OS_WINDOWS
8726 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8727 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8728
8729 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8730 const UINT success = ::GetTempFileNameA(temp_dir_path,
8731 "gtest_redir",
8732 0, // Generate unique file name.
8733 temp_file_path);
8734 GTEST_CHECK_(success != 0)
8735 << "Unable to create a temporary file in " << temp_dir_path;
8736 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8737 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8738 << temp_file_path;
8739 filename_ = temp_file_path;
8740# else
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008741 // There's no guarantee that a test has write access to the current
8742 // directory, so we create the temporary file in the /tmp directory
8743 // instead. We use /tmp on most systems, and /sdcard on Android.
8744 // That's because Android doesn't have /tmp.
8745# if GTEST_OS_LINUX_ANDROID
8746 // Note: Android applications are expected to call the framework's
8747 // Context.getExternalStorageDirectory() method through JNI to get
8748 // the location of the world-writable SD Card directory. However,
8749 // this requires a Context handle, which cannot be retrieved
8750 // globally from native code. Doing so also precludes running the
8751 // code as part of a regular standalone executable, which doesn't
8752 // run in a Dalvik process (e.g. when running it through 'adb shell').
8753 //
8754 // The location /sdcard is directly accessible from native code
8755 // and is the only location (unofficially) supported by the Android
8756 // team. It's generally a symlink to the real SD Card mount point
8757 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8758 // other OEM-customized locations. Never rely on these, and always
8759 // use /sdcard.
8760 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8761# else
Keir Mierle8ebb0732012-04-30 23:09:08 -07008762 char name_template[] = "/tmp/captured_stream.XXXXXX";
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008763# endif // GTEST_OS_LINUX_ANDROID
Keir Mierle8ebb0732012-04-30 23:09:08 -07008764 const int captured_fd = mkstemp(name_template);
8765 filename_ = name_template;
8766# endif // GTEST_OS_WINDOWS
8767 fflush(NULL);
8768 dup2(captured_fd, fd_);
8769 close(captured_fd);
8770 }
8771
8772 ~CapturedStream() {
8773 remove(filename_.c_str());
8774 }
8775
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008776 std::string GetCapturedString() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07008777 if (uncaptured_fd_ != -1) {
8778 // Restores the original stream.
8779 fflush(NULL);
8780 dup2(uncaptured_fd_, fd_);
8781 close(uncaptured_fd_);
8782 uncaptured_fd_ = -1;
8783 }
8784
8785 FILE* const file = posix::FOpen(filename_.c_str(), "r");
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008786 const std::string content = ReadEntireFile(file);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008787 posix::FClose(file);
8788 return content;
8789 }
8790
8791 private:
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008792 // Reads the entire content of a file as an std::string.
8793 static std::string ReadEntireFile(FILE* file);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008794
8795 // Returns the size (in bytes) of a file.
8796 static size_t GetFileSize(FILE* file);
8797
8798 const int fd_; // A stream to capture.
8799 int uncaptured_fd_;
8800 // Name of the temporary file holding the stderr output.
8801 ::std::string filename_;
8802
8803 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8804};
8805
8806// Returns the size (in bytes) of a file.
8807size_t CapturedStream::GetFileSize(FILE* file) {
8808 fseek(file, 0, SEEK_END);
8809 return static_cast<size_t>(ftell(file));
8810}
8811
8812// Reads the entire content of a file as a string.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008813std::string CapturedStream::ReadEntireFile(FILE* file) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07008814 const size_t file_size = GetFileSize(file);
8815 char* const buffer = new char[file_size];
8816
8817 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8818 size_t bytes_read = 0; // # of bytes read so far
8819
8820 fseek(file, 0, SEEK_SET);
8821
8822 // Keeps reading the file until we cannot read further or the
8823 // pre-determined file size is reached.
8824 do {
8825 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8826 bytes_read += bytes_last_read;
8827 } while (bytes_last_read > 0 && bytes_read < file_size);
8828
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008829 const std::string content(buffer, bytes_read);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008830 delete[] buffer;
8831
8832 return content;
8833}
8834
8835# ifdef _MSC_VER
8836# pragma warning(pop)
8837# endif // _MSC_VER
8838
8839static CapturedStream* g_captured_stderr = NULL;
8840static CapturedStream* g_captured_stdout = NULL;
8841
8842// Starts capturing an output stream (stdout/stderr).
8843void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8844 if (*stream != NULL) {
8845 GTEST_LOG_(FATAL) << "Only one " << stream_name
8846 << " capturer can exist at a time.";
8847 }
8848 *stream = new CapturedStream(fd);
8849}
8850
8851// Stops capturing the output stream and returns the captured string.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008852std::string GetCapturedStream(CapturedStream** captured_stream) {
8853 const std::string content = (*captured_stream)->GetCapturedString();
Keir Mierle8ebb0732012-04-30 23:09:08 -07008854
8855 delete *captured_stream;
8856 *captured_stream = NULL;
8857
8858 return content;
8859}
8860
8861// Starts capturing stdout.
8862void CaptureStdout() {
8863 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8864}
8865
8866// Starts capturing stderr.
8867void CaptureStderr() {
8868 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8869}
8870
8871// Stops capturing stdout and returns the captured string.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008872std::string GetCapturedStdout() {
8873 return GetCapturedStream(&g_captured_stdout);
8874}
Keir Mierle8ebb0732012-04-30 23:09:08 -07008875
8876// Stops capturing stderr and returns the captured string.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008877std::string GetCapturedStderr() {
8878 return GetCapturedStream(&g_captured_stderr);
8879}
Keir Mierle8ebb0732012-04-30 23:09:08 -07008880
8881#endif // GTEST_HAS_STREAM_REDIRECTION
8882
8883#if GTEST_HAS_DEATH_TEST
8884
8885// A copy of all command line arguments. Set by InitGoogleTest().
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008886::std::vector<testing::internal::string> g_argvs;
Keir Mierle8ebb0732012-04-30 23:09:08 -07008887
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008888static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8889 NULL; // Owned.
Keir Mierle8ebb0732012-04-30 23:09:08 -07008890
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008891void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8892 if (g_injected_test_argvs != argvs)
8893 delete g_injected_test_argvs;
8894 g_injected_test_argvs = argvs;
8895}
8896
8897const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8898 if (g_injected_test_argvs != NULL) {
8899 return *g_injected_test_argvs;
8900 }
8901 return g_argvs;
8902}
Keir Mierle8ebb0732012-04-30 23:09:08 -07008903#endif // GTEST_HAS_DEATH_TEST
8904
8905#if GTEST_OS_WINDOWS_MOBILE
8906namespace posix {
8907void Abort() {
8908 DebugBreak();
8909 TerminateProcess(GetCurrentProcess(), 1);
8910}
8911} // namespace posix
8912#endif // GTEST_OS_WINDOWS_MOBILE
8913
8914// Returns the name of the environment variable corresponding to the
8915// given flag. For example, FlagToEnvVar("foo") will return
8916// "GTEST_FOO" in the open-source version.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008917static std::string FlagToEnvVar(const char* flag) {
8918 const std::string full_flag =
Keir Mierle8ebb0732012-04-30 23:09:08 -07008919 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8920
8921 Message env_var;
8922 for (size_t i = 0; i != full_flag.length(); i++) {
8923 env_var << ToUpper(full_flag.c_str()[i]);
8924 }
8925
8926 return env_var.GetString();
8927}
8928
8929// Parses 'str' for a 32-bit signed integer. If successful, writes
8930// the result to *value and returns true; otherwise leaves *value
8931// unchanged and returns false.
8932bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8933 // Parses the environment variable as a decimal integer.
8934 char* end = NULL;
8935 const long long_value = strtol(str, &end, 10); // NOLINT
8936
8937 // Has strtol() consumed all characters in the string?
8938 if (*end != '\0') {
8939 // No - an invalid character was encountered.
8940 Message msg;
8941 msg << "WARNING: " << src_text
8942 << " is expected to be a 32-bit integer, but actually"
8943 << " has value \"" << str << "\".\n";
8944 printf("%s", msg.GetString().c_str());
8945 fflush(stdout);
8946 return false;
8947 }
8948
8949 // Is the parsed value in the range of an Int32?
8950 const Int32 result = static_cast<Int32>(long_value);
8951 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8952 // The parsed value overflows as a long. (strtol() returns
8953 // LONG_MAX or LONG_MIN when the input overflows.)
8954 result != long_value
8955 // The parsed value overflows as an Int32.
8956 ) {
8957 Message msg;
8958 msg << "WARNING: " << src_text
8959 << " is expected to be a 32-bit integer, but actually"
8960 << " has value " << str << ", which overflows.\n";
8961 printf("%s", msg.GetString().c_str());
8962 fflush(stdout);
8963 return false;
8964 }
8965
8966 *value = result;
8967 return true;
8968}
8969
8970// Reads and returns the Boolean environment variable corresponding to
8971// the given flag; if it's not set, returns default_value.
8972//
8973// The value is considered true iff it's not "0".
8974bool BoolFromGTestEnv(const char* flag, bool default_value) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008975 const std::string env_var = FlagToEnvVar(flag);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008976 const char* const string_value = posix::GetEnv(env_var.c_str());
8977 return string_value == NULL ?
8978 default_value : strcmp(string_value, "0") != 0;
8979}
8980
8981// Reads and returns a 32-bit integer stored in the environment
8982// variable corresponding to the given flag; if it isn't set or
8983// doesn't represent a valid 32-bit integer, returns default_value.
8984Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07008985 const std::string env_var = FlagToEnvVar(flag);
Keir Mierle8ebb0732012-04-30 23:09:08 -07008986 const char* const string_value = posix::GetEnv(env_var.c_str());
8987 if (string_value == NULL) {
8988 // The environment variable is not set.
8989 return default_value;
8990 }
8991
8992 Int32 result = default_value;
8993 if (!ParseInt32(Message() << "Environment variable " << env_var,
8994 string_value, &result)) {
8995 printf("The default value %s is used.\n",
8996 (Message() << default_value).GetString().c_str());
8997 fflush(stdout);
8998 return default_value;
8999 }
9000
9001 return result;
9002}
9003
9004// Reads and returns the string environment variable corresponding to
9005// the given flag; if it's not set, returns default_value.
9006const char* StringFromGTestEnv(const char* flag, const char* default_value) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009007 const std::string env_var = FlagToEnvVar(flag);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009008 const char* const value = posix::GetEnv(env_var.c_str());
9009 return value == NULL ? default_value : value;
9010}
9011
9012} // namespace internal
9013} // namespace testing
9014// Copyright 2007, Google Inc.
9015// All rights reserved.
9016//
9017// Redistribution and use in source and binary forms, with or without
9018// modification, are permitted provided that the following conditions are
9019// met:
9020//
9021// * Redistributions of source code must retain the above copyright
9022// notice, this list of conditions and the following disclaimer.
9023// * Redistributions in binary form must reproduce the above
9024// copyright notice, this list of conditions and the following disclaimer
9025// in the documentation and/or other materials provided with the
9026// distribution.
9027// * Neither the name of Google Inc. nor the names of its
9028// contributors may be used to endorse or promote products derived from
9029// this software without specific prior written permission.
9030//
9031// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9032// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9033// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9034// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9035// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9036// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9037// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9038// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9039// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9040// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9041// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9042//
9043// Author: wan@google.com (Zhanyong Wan)
9044
9045// Google Test - The Google C++ Testing Framework
9046//
9047// This file implements a universal value printer that can print a
9048// value of any type T:
9049//
9050// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9051//
9052// It uses the << operator when possible, and prints the bytes in the
9053// object otherwise. A user can override its behavior for a class
9054// type Foo by defining either operator<<(::std::ostream&, const Foo&)
9055// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9056// defines Foo.
9057
9058#include <ctype.h>
9059#include <stdio.h>
9060#include <ostream> // NOLINT
9061#include <string>
9062
9063namespace testing {
9064
9065namespace {
9066
9067using ::std::ostream;
9068
Keir Mierle8ebb0732012-04-30 23:09:08 -07009069// Prints a segment of bytes in the given object.
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -07009070GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9071GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
Keir Mierle8ebb0732012-04-30 23:09:08 -07009072void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9073 size_t count, ostream* os) {
9074 char text[5] = "";
9075 for (size_t i = 0; i != count; i++) {
9076 const size_t j = start + i;
9077 if (i != 0) {
9078 // Organizes the bytes into groups of 2 for easy parsing by
9079 // human.
9080 if ((j % 2) == 0)
9081 *os << ' ';
9082 else
9083 *os << '-';
9084 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009085 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009086 *os << text;
9087 }
9088}
9089
9090// Prints the bytes in the given value to the given ostream.
9091void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9092 ostream* os) {
9093 // Tells the user how big the object is.
9094 *os << count << "-byte object <";
9095
9096 const size_t kThreshold = 132;
9097 const size_t kChunkSize = 64;
9098 // If the object size is bigger than kThreshold, we'll have to omit
9099 // some details by printing only the first and the last kChunkSize
9100 // bytes.
9101 // TODO(wan): let the user control the threshold using a flag.
9102 if (count < kThreshold) {
9103 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9104 } else {
9105 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9106 *os << " ... ";
9107 // Rounds up to 2-byte boundary.
9108 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9109 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9110 }
9111 *os << ">";
9112}
9113
9114} // namespace
9115
9116namespace internal2 {
9117
9118// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9119// given object. The delegation simplifies the implementation, which
9120// uses the << operator and thus is easier done outside of the
9121// ::testing::internal namespace, which contains a << operator that
9122// sometimes conflicts with the one in STL.
9123void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9124 ostream* os) {
9125 PrintBytesInObjectToImpl(obj_bytes, count, os);
9126}
9127
9128} // namespace internal2
9129
9130namespace internal {
9131
9132// Depending on the value of a char (or wchar_t), we print it in one
9133// of three formats:
9134// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9135// - as a hexidecimal escape sequence (e.g. '\x7F'), or
9136// - as a special escape sequence (e.g. '\r', '\n').
9137enum CharFormat {
9138 kAsIs,
9139 kHexEscape,
9140 kSpecialEscape
9141};
9142
9143// Returns true if c is a printable ASCII character. We test the
9144// value of c directly instead of calling isprint(), which is buggy on
9145// Windows Mobile.
9146inline bool IsPrintableAscii(wchar_t c) {
9147 return 0x20 <= c && c <= 0x7E;
9148}
9149
9150// Prints a wide or narrow char c as a character literal without the
9151// quotes, escaping it when necessary; returns how c was formatted.
9152// The template argument UnsignedChar is the unsigned version of Char,
9153// which is the type of c.
9154template <typename UnsignedChar, typename Char>
9155static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9156 switch (static_cast<wchar_t>(c)) {
9157 case L'\0':
9158 *os << "\\0";
9159 break;
9160 case L'\'':
9161 *os << "\\'";
9162 break;
9163 case L'\\':
9164 *os << "\\\\";
9165 break;
9166 case L'\a':
9167 *os << "\\a";
9168 break;
9169 case L'\b':
9170 *os << "\\b";
9171 break;
9172 case L'\f':
9173 *os << "\\f";
9174 break;
9175 case L'\n':
9176 *os << "\\n";
9177 break;
9178 case L'\r':
9179 *os << "\\r";
9180 break;
9181 case L'\t':
9182 *os << "\\t";
9183 break;
9184 case L'\v':
9185 *os << "\\v";
9186 break;
9187 default:
9188 if (IsPrintableAscii(c)) {
9189 *os << static_cast<char>(c);
9190 return kAsIs;
9191 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009192 *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
Keir Mierle8ebb0732012-04-30 23:09:08 -07009193 return kHexEscape;
9194 }
9195 }
9196 return kSpecialEscape;
9197}
9198
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009199// Prints a wchar_t c as if it's part of a string literal, escaping it when
Keir Mierle8ebb0732012-04-30 23:09:08 -07009200// necessary; returns how c was formatted.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009201static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009202 switch (c) {
9203 case L'\'':
9204 *os << "'";
9205 return kAsIs;
9206 case L'"':
9207 *os << "\\\"";
9208 return kSpecialEscape;
9209 default:
9210 return PrintAsCharLiteralTo<wchar_t>(c, os);
9211 }
9212}
9213
9214// Prints a char c as if it's part of a string literal, escaping it when
9215// necessary; returns how c was formatted.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009216static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9217 return PrintAsStringLiteralTo(
9218 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009219}
9220
9221// Prints a wide or narrow character c and its code. '\0' is printed
9222// as "'\\0'", other unprintable characters are also properly escaped
9223// using the standard C++ escape sequence. The template argument
9224// UnsignedChar is the unsigned version of Char, which is the type of c.
9225template <typename UnsignedChar, typename Char>
9226void PrintCharAndCodeTo(Char c, ostream* os) {
9227 // First, print c as a literal in the most readable form we can find.
9228 *os << ((sizeof(c) > 1) ? "L'" : "'");
9229 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9230 *os << "'";
9231
9232 // To aid user debugging, we also print c's code in decimal, unless
9233 // it's 0 (in which case c was printed as '\\0', making the code
9234 // obvious).
9235 if (c == 0)
9236 return;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009237 *os << " (" << static_cast<int>(c);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009238
9239 // For more convenience, we print c's code again in hexidecimal,
9240 // unless c was already printed in the form '\x##' or the code is in
9241 // [1, 9].
9242 if (format == kHexEscape || (1 <= c && c <= 9)) {
9243 // Do nothing.
9244 } else {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009245 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
Keir Mierle8ebb0732012-04-30 23:09:08 -07009246 }
9247 *os << ")";
9248}
9249
9250void PrintTo(unsigned char c, ::std::ostream* os) {
9251 PrintCharAndCodeTo<unsigned char>(c, os);
9252}
9253void PrintTo(signed char c, ::std::ostream* os) {
9254 PrintCharAndCodeTo<unsigned char>(c, os);
9255}
9256
9257// Prints a wchar_t as a symbol if it is printable or as its internal
9258// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9259void PrintTo(wchar_t wc, ostream* os) {
9260 PrintCharAndCodeTo<wchar_t>(wc, os);
9261}
9262
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009263// Prints the given array of characters to the ostream. CharType must be either
9264// char or wchar_t.
9265// The array starts at begin, the length is len, it may include '\0' characters
9266// and may not be NUL-terminated.
9267template <typename CharType>
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -07009268GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9269GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009270static void PrintCharsAsStringTo(
9271 const CharType* begin, size_t len, ostream* os) {
9272 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9273 *os << kQuoteBegin;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009274 bool is_previous_hex = false;
9275 for (size_t index = 0; index < len; ++index) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009276 const CharType cur = begin[index];
Keir Mierle8ebb0732012-04-30 23:09:08 -07009277 if (is_previous_hex && IsXDigit(cur)) {
9278 // Previous character is of '\x..' form and this character can be
9279 // interpreted as another hexadecimal digit in its number. Break string to
9280 // disambiguate.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009281 *os << "\" " << kQuoteBegin;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009282 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009283 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009284 }
9285 *os << "\"";
9286}
9287
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009288// Prints a (const) char/wchar_t array of 'len' elements, starting at address
9289// 'begin'. CharType must be either char or wchar_t.
9290template <typename CharType>
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -07009291GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9292GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009293static void UniversalPrintCharArray(
9294 const CharType* begin, size_t len, ostream* os) {
9295 // The code
9296 // const char kFoo[] = "foo";
9297 // generates an array of 4, not 3, elements, with the last one being '\0'.
9298 //
9299 // Therefore when printing a char array, we don't print the last element if
9300 // it's '\0', such that the output matches the string literal as it's
9301 // written in the source code.
9302 if (len > 0 && begin[len - 1] == '\0') {
9303 PrintCharsAsStringTo(begin, len - 1, os);
9304 return;
9305 }
9306
9307 // If, however, the last element in the array is not '\0', e.g.
9308 // const char kFoo[] = { 'f', 'o', 'o' };
9309 // we must print the entire array. We also print a message to indicate
9310 // that the array is not NUL-terminated.
9311 PrintCharsAsStringTo(begin, len, os);
9312 *os << " (no terminating NUL)";
9313}
9314
Keir Mierle8ebb0732012-04-30 23:09:08 -07009315// Prints a (const) char array of 'len' elements, starting at address 'begin'.
9316void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009317 UniversalPrintCharArray(begin, len, os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009318}
9319
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009320// Prints a (const) wchar_t array of 'len' elements, starting at address
9321// 'begin'.
9322void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9323 UniversalPrintCharArray(begin, len, os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009324}
9325
9326// Prints the given C string to the ostream.
9327void PrintTo(const char* s, ostream* os) {
9328 if (s == NULL) {
9329 *os << "NULL";
9330 } else {
9331 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9332 PrintCharsAsStringTo(s, strlen(s), os);
9333 }
9334}
9335
9336// MSVC compiler can be configured to define whar_t as a typedef
9337// of unsigned short. Defining an overload for const wchar_t* in that case
9338// would cause pointers to unsigned shorts be printed as wide strings,
9339// possibly accessing more memory than intended and causing invalid
9340// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9341// wchar_t is implemented as a native type.
9342#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9343// Prints the given wide C string to the ostream.
9344void PrintTo(const wchar_t* s, ostream* os) {
9345 if (s == NULL) {
9346 *os << "NULL";
9347 } else {
9348 *os << ImplicitCast_<const void*>(s) << " pointing to ";
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009349 PrintCharsAsStringTo(s, wcslen(s), os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009350 }
9351}
9352#endif // wchar_t is native
9353
9354// Prints a ::string object.
9355#if GTEST_HAS_GLOBAL_STRING
9356void PrintStringTo(const ::string& s, ostream* os) {
9357 PrintCharsAsStringTo(s.data(), s.size(), os);
9358}
9359#endif // GTEST_HAS_GLOBAL_STRING
9360
9361void PrintStringTo(const ::std::string& s, ostream* os) {
9362 PrintCharsAsStringTo(s.data(), s.size(), os);
9363}
9364
9365// Prints a ::wstring object.
9366#if GTEST_HAS_GLOBAL_WSTRING
9367void PrintWideStringTo(const ::wstring& s, ostream* os) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009368 PrintCharsAsStringTo(s.data(), s.size(), os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009369}
9370#endif // GTEST_HAS_GLOBAL_WSTRING
9371
9372#if GTEST_HAS_STD_WSTRING
9373void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009374 PrintCharsAsStringTo(s.data(), s.size(), os);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009375}
9376#endif // GTEST_HAS_STD_WSTRING
9377
9378} // namespace internal
9379
9380} // namespace testing
9381// Copyright 2008, Google Inc.
9382// All rights reserved.
9383//
9384// Redistribution and use in source and binary forms, with or without
9385// modification, are permitted provided that the following conditions are
9386// met:
9387//
9388// * Redistributions of source code must retain the above copyright
9389// notice, this list of conditions and the following disclaimer.
9390// * Redistributions in binary form must reproduce the above
9391// copyright notice, this list of conditions and the following disclaimer
9392// in the documentation and/or other materials provided with the
9393// distribution.
9394// * Neither the name of Google Inc. nor the names of its
9395// contributors may be used to endorse or promote products derived from
9396// this software without specific prior written permission.
9397//
9398// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9399// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9400// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9401// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9402// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9403// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9404// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9405// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9406// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9407// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9408// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9409//
9410// Author: mheule@google.com (Markus Heule)
9411//
9412// The Google C++ Testing Framework (Google Test)
9413
9414
9415// Indicates that this translation unit is part of Google Test's
9416// implementation. It must come before gtest-internal-inl.h is
9417// included, or there will be a compiler error. This trick is to
9418// prevent a user from accidentally including gtest-internal-inl.h in
9419// his code.
9420#define GTEST_IMPLEMENTATION_ 1
9421#undef GTEST_IMPLEMENTATION_
9422
9423namespace testing {
9424
9425using internal::GetUnitTestImpl;
9426
9427// Gets the summary of the failure message by omitting the stack trace
9428// in it.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009429std::string TestPartResult::ExtractSummary(const char* message) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009430 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009431 return stack_trace == NULL ? message :
9432 std::string(message, stack_trace);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009433}
9434
9435// Prints a TestPartResult object.
9436std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9437 return os
9438 << result.file_name() << ":" << result.line_number() << ": "
9439 << (result.type() == TestPartResult::kSuccess ? "Success" :
9440 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
9441 "Non-fatal failure") << ":\n"
9442 << result.message() << std::endl;
9443}
9444
9445// Appends a TestPartResult to the array.
9446void TestPartResultArray::Append(const TestPartResult& result) {
9447 array_.push_back(result);
9448}
9449
9450// Returns the TestPartResult at the given index (0-based).
9451const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9452 if (index < 0 || index >= size()) {
9453 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9454 internal::posix::Abort();
9455 }
9456
9457 return array_[index];
9458}
9459
9460// Returns the number of TestPartResult objects in the array.
9461int TestPartResultArray::size() const {
9462 return static_cast<int>(array_.size());
9463}
9464
9465namespace internal {
9466
9467HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9468 : has_new_fatal_failure_(false),
9469 original_reporter_(GetUnitTestImpl()->
9470 GetTestPartResultReporterForCurrentThread()) {
9471 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9472}
9473
9474HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9475 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9476 original_reporter_);
9477}
9478
9479void HasNewFatalFailureHelper::ReportTestPartResult(
9480 const TestPartResult& result) {
9481 if (result.fatally_failed())
9482 has_new_fatal_failure_ = true;
9483 original_reporter_->ReportTestPartResult(result);
9484}
9485
9486} // namespace internal
9487
9488} // namespace testing
9489// Copyright 2008 Google Inc.
9490// All Rights Reserved.
9491//
9492// Redistribution and use in source and binary forms, with or without
9493// modification, are permitted provided that the following conditions are
9494// met:
9495//
9496// * Redistributions of source code must retain the above copyright
9497// notice, this list of conditions and the following disclaimer.
9498// * Redistributions in binary form must reproduce the above
9499// copyright notice, this list of conditions and the following disclaimer
9500// in the documentation and/or other materials provided with the
9501// distribution.
9502// * Neither the name of Google Inc. nor the names of its
9503// contributors may be used to endorse or promote products derived from
9504// this software without specific prior written permission.
9505//
9506// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9507// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9508// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9509// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9510// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9511// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9512// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9513// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9514// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9515// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9516// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9517//
9518// Author: wan@google.com (Zhanyong Wan)
9519
9520
9521namespace testing {
9522namespace internal {
9523
9524#if GTEST_HAS_TYPED_TEST_P
9525
9526// Skips to the first non-space char in str. Returns an empty string if str
9527// contains only whitespace characters.
9528static const char* SkipSpaces(const char* str) {
9529 while (IsSpace(*str))
9530 str++;
9531 return str;
9532}
9533
9534// Verifies that registered_tests match the test names in
9535// defined_test_names_; returns registered_tests if successful, or
9536// aborts the program otherwise.
9537const char* TypedTestCasePState::VerifyRegisteredTestNames(
9538 const char* file, int line, const char* registered_tests) {
9539 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9540 registered_ = true;
9541
9542 // Skip initial whitespace in registered_tests since some
9543 // preprocessors prefix stringizied literals with whitespace.
9544 registered_tests = SkipSpaces(registered_tests);
9545
9546 Message errors;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009547 ::std::set<std::string> tests;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009548 for (const char* names = registered_tests; names != NULL;
9549 names = SkipComma(names)) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009550 const std::string name = GetPrefixUntilComma(names);
Keir Mierle8ebb0732012-04-30 23:09:08 -07009551 if (tests.count(name) != 0) {
9552 errors << "Test " << name << " is listed more than once.\n";
9553 continue;
9554 }
9555
9556 bool found = false;
9557 for (DefinedTestIter it = defined_test_names_.begin();
9558 it != defined_test_names_.end();
9559 ++it) {
9560 if (name == *it) {
9561 found = true;
9562 break;
9563 }
9564 }
9565
9566 if (found) {
9567 tests.insert(name);
9568 } else {
9569 errors << "No test named " << name
9570 << " can be found in this test case.\n";
9571 }
9572 }
9573
9574 for (DefinedTestIter it = defined_test_names_.begin();
9575 it != defined_test_names_.end();
9576 ++it) {
9577 if (tests.count(*it) == 0) {
9578 errors << "You forgot to list test " << *it << ".\n";
9579 }
9580 }
9581
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009582 const std::string& errors_str = errors.GetString();
Keir Mierle8ebb0732012-04-30 23:09:08 -07009583 if (errors_str != "") {
9584 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9585 errors_str.c_str());
9586 fflush(stderr);
9587 posix::Abort();
9588 }
9589
9590 return registered_tests;
9591}
9592
9593#endif // GTEST_HAS_TYPED_TEST_P
9594
9595} // namespace internal
9596} // namespace testing
9597// Copyright 2008, Google Inc.
9598// All rights reserved.
9599//
9600// Redistribution and use in source and binary forms, with or without
9601// modification, are permitted provided that the following conditions are
9602// met:
9603//
9604// * Redistributions of source code must retain the above copyright
9605// notice, this list of conditions and the following disclaimer.
9606// * Redistributions in binary form must reproduce the above
9607// copyright notice, this list of conditions and the following disclaimer
9608// in the documentation and/or other materials provided with the
9609// distribution.
9610// * Neither the name of Google Inc. nor the names of its
9611// contributors may be used to endorse or promote products derived from
9612// this software without specific prior written permission.
9613//
9614// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9615// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9616// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9617// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9618// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9619// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9620// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9621// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9622// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9623// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9624// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9625//
9626// Author: wan@google.com (Zhanyong Wan)
9627//
9628// Google C++ Mocking Framework (Google Mock)
9629//
9630// This file #includes all Google Mock implementation .cc files. The
9631// purpose is to allow a user to build Google Mock by compiling this
9632// file alone.
9633
9634// This line ensures that gmock.h can be compiled on its own, even
9635// when it's fused.
9636#include "gmock/gmock.h"
9637
9638// The following lines pull in the real gmock *.cc files.
9639// Copyright 2007, Google Inc.
9640// All rights reserved.
9641//
9642// Redistribution and use in source and binary forms, with or without
9643// modification, are permitted provided that the following conditions are
9644// met:
9645//
9646// * Redistributions of source code must retain the above copyright
9647// notice, this list of conditions and the following disclaimer.
9648// * Redistributions in binary form must reproduce the above
9649// copyright notice, this list of conditions and the following disclaimer
9650// in the documentation and/or other materials provided with the
9651// distribution.
9652// * Neither the name of Google Inc. nor the names of its
9653// contributors may be used to endorse or promote products derived from
9654// this software without specific prior written permission.
9655//
9656// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9657// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9658// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9659// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9660// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9661// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9662// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9663// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9664// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9665// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9666// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9667//
9668// Author: wan@google.com (Zhanyong Wan)
9669
9670// Google Mock - a framework for writing C++ mock classes.
9671//
9672// This file implements cardinalities.
9673
9674
9675#include <limits.h>
9676#include <ostream> // NOLINT
9677#include <sstream>
9678#include <string>
9679
9680namespace testing {
9681
9682namespace {
9683
9684// Implements the Between(m, n) cardinality.
9685class BetweenCardinalityImpl : public CardinalityInterface {
9686 public:
9687 BetweenCardinalityImpl(int min, int max)
9688 : min_(min >= 0 ? min : 0),
9689 max_(max >= min_ ? max : min_) {
9690 std::stringstream ss;
9691 if (min < 0) {
9692 ss << "The invocation lower bound must be >= 0, "
9693 << "but is actually " << min << ".";
9694 internal::Expect(false, __FILE__, __LINE__, ss.str());
9695 } else if (max < 0) {
9696 ss << "The invocation upper bound must be >= 0, "
9697 << "but is actually " << max << ".";
9698 internal::Expect(false, __FILE__, __LINE__, ss.str());
9699 } else if (min > max) {
9700 ss << "The invocation upper bound (" << max
9701 << ") must be >= the invocation lower bound (" << min
9702 << ").";
9703 internal::Expect(false, __FILE__, __LINE__, ss.str());
9704 }
9705 }
9706
9707 // Conservative estimate on the lower/upper bound of the number of
9708 // calls allowed.
9709 virtual int ConservativeLowerBound() const { return min_; }
9710 virtual int ConservativeUpperBound() const { return max_; }
9711
9712 virtual bool IsSatisfiedByCallCount(int call_count) const {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009713 return min_ <= call_count && call_count <= max_;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009714 }
9715
9716 virtual bool IsSaturatedByCallCount(int call_count) const {
9717 return call_count >= max_;
9718 }
9719
9720 virtual void DescribeTo(::std::ostream* os) const;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009721
Keir Mierle8ebb0732012-04-30 23:09:08 -07009722 private:
9723 const int min_;
9724 const int max_;
9725
9726 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
9727};
9728
9729// Formats "n times" in a human-friendly way.
9730inline internal::string FormatTimes(int n) {
9731 if (n == 1) {
9732 return "once";
9733 } else if (n == 2) {
9734 return "twice";
9735 } else {
9736 std::stringstream ss;
9737 ss << n << " times";
9738 return ss.str();
9739 }
9740}
9741
9742// Describes the Between(m, n) cardinality in human-friendly text.
9743void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
9744 if (min_ == 0) {
9745 if (max_ == 0) {
9746 *os << "never called";
9747 } else if (max_ == INT_MAX) {
9748 *os << "called any number of times";
9749 } else {
9750 *os << "called at most " << FormatTimes(max_);
9751 }
9752 } else if (min_ == max_) {
9753 *os << "called " << FormatTimes(min_);
9754 } else if (max_ == INT_MAX) {
9755 *os << "called at least " << FormatTimes(min_);
9756 } else {
9757 // 0 < min_ < max_ < INT_MAX
9758 *os << "called between " << min_ << " and " << max_ << " times";
9759 }
9760}
9761
9762} // Unnamed namespace
9763
9764// Describes the given call count to an ostream.
9765void Cardinality::DescribeActualCallCountTo(int actual_call_count,
9766 ::std::ostream* os) {
9767 if (actual_call_count > 0) {
9768 *os << "called " << FormatTimes(actual_call_count);
9769 } else {
9770 *os << "never called";
9771 }
9772}
9773
9774// Creates a cardinality that allows at least n calls.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009775GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
Keir Mierle8ebb0732012-04-30 23:09:08 -07009776
9777// Creates a cardinality that allows at most n calls.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009778GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
Keir Mierle8ebb0732012-04-30 23:09:08 -07009779
9780// Creates a cardinality that allows any number of calls.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009781GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
Keir Mierle8ebb0732012-04-30 23:09:08 -07009782
9783// Creates a cardinality that allows between min and max calls.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009784GTEST_API_ Cardinality Between(int min, int max) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009785 return Cardinality(new BetweenCardinalityImpl(min, max));
9786}
9787
9788// Creates a cardinality that allows exactly n calls.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009789GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
Keir Mierle8ebb0732012-04-30 23:09:08 -07009790
9791} // namespace testing
9792// Copyright 2007, Google Inc.
9793// All rights reserved.
9794//
9795// Redistribution and use in source and binary forms, with or without
9796// modification, are permitted provided that the following conditions are
9797// met:
9798//
9799// * Redistributions of source code must retain the above copyright
9800// notice, this list of conditions and the following disclaimer.
9801// * Redistributions in binary form must reproduce the above
9802// copyright notice, this list of conditions and the following disclaimer
9803// in the documentation and/or other materials provided with the
9804// distribution.
9805// * Neither the name of Google Inc. nor the names of its
9806// contributors may be used to endorse or promote products derived from
9807// this software without specific prior written permission.
9808//
9809// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9810// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9811// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9812// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9813// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9814// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9815// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9816// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9817// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9818// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9819// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9820//
9821// Author: wan@google.com (Zhanyong Wan)
9822
9823// Google Mock - a framework for writing C++ mock classes.
9824//
9825// This file defines some utilities useful for implementing Google
9826// Mock. They are subject to change without notice, so please DO NOT
9827// USE THEM IN USER CODE.
9828
9829
9830#include <ctype.h>
9831#include <ostream> // NOLINT
9832#include <string>
9833
9834namespace testing {
9835namespace internal {
9836
9837// Converts an identifier name to a space-separated list of lower-case
9838// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9839// treated as one word. For example, both "FooBar123" and
9840// "foo_bar_123" are converted to "foo bar 123".
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009841GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009842 string result;
9843 char prev_char = '\0';
9844 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
9845 // We don't care about the current locale as the input is
9846 // guaranteed to be a valid C++ identifier name.
9847 const bool starts_new_word = IsUpper(*p) ||
9848 (!IsAlpha(prev_char) && IsLower(*p)) ||
9849 (!IsDigit(prev_char) && IsDigit(*p));
9850
9851 if (IsAlNum(*p)) {
9852 if (starts_new_word && result != "")
9853 result += ' ';
9854 result += ToLower(*p);
9855 }
9856 }
9857 return result;
9858}
9859
9860// This class reports Google Mock failures as Google Test failures. A
9861// user can define another class in a similar fashion if he intends to
9862// use Google Mock with a testing framework other than Google Test.
9863class GoogleTestFailureReporter : public FailureReporterInterface {
9864 public:
9865 virtual void ReportFailure(FailureType type, const char* file, int line,
9866 const string& message) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009867 AssertHelper(type == kFatal ?
Keir Mierle8ebb0732012-04-30 23:09:08 -07009868 TestPartResult::kFatalFailure :
9869 TestPartResult::kNonFatalFailure,
9870 file,
9871 line,
9872 message.c_str()) = Message();
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009873 if (type == kFatal) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009874 posix::Abort();
9875 }
9876 }
9877};
9878
9879// Returns the global failure reporter. Will create a
9880// GoogleTestFailureReporter and return it the first time called.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009881GTEST_API_ FailureReporterInterface* GetFailureReporter() {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009882 // Points to the global failure reporter used by Google Mock. gcc
9883 // guarantees that the following use of failure_reporter is
9884 // thread-safe. We may need to add additional synchronization to
9885 // protect failure_reporter if we port Google Mock to other
9886 // compilers.
9887 static FailureReporterInterface* const failure_reporter =
9888 new GoogleTestFailureReporter();
9889 return failure_reporter;
9890}
9891
9892// Protects global resources (stdout in particular) used by Log().
9893static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
9894
9895// Returns true iff a log with the given severity is visible according
9896// to the --gmock_verbose flag.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009897GTEST_API_ bool LogIsVisible(LogSeverity severity) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009898 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
9899 // Always show the log if --gmock_verbose=info.
9900 return true;
9901 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
9902 // Always hide it if --gmock_verbose=error.
9903 return false;
9904 } else {
9905 // If --gmock_verbose is neither "info" nor "error", we treat it
9906 // as "warning" (its default value).
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009907 return severity == kWarning;
Keir Mierle8ebb0732012-04-30 23:09:08 -07009908 }
9909}
9910
9911// Prints the given message to stdout iff 'severity' >= the level
9912// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
9913// 0, also prints the stack trace excluding the top
9914// stack_frames_to_skip frames. In opt mode, any positive
9915// stack_frames_to_skip is treated as 0, since we don't know which
9916// function calls will be inlined by the compiler and need to be
9917// conservative.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009918GTEST_API_ void Log(LogSeverity severity,
9919 const string& message,
9920 int stack_frames_to_skip) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009921 if (!LogIsVisible(severity))
9922 return;
9923
9924 // Ensures that logs from different threads don't interleave.
9925 MutexLock l(&g_log_mutex);
9926
9927 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9928 // macro.
9929
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -07009930 if (severity == kWarning) {
Keir Mierle8ebb0732012-04-30 23:09:08 -07009931 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9932 std::cout << "\nGMOCK WARNING:";
9933 }
9934 // Pre-pends a new-line to message if it doesn't start with one.
9935 if (message.empty() || message[0] != '\n') {
9936 std::cout << "\n";
9937 }
9938 std::cout << message;
9939 if (stack_frames_to_skip >= 0) {
9940#ifdef NDEBUG
9941 // In opt mode, we have to be conservative and skip no stack frame.
9942 const int actual_to_skip = 0;
9943#else
9944 // In dbg mode, we can do what the caller tell us to do (plus one
9945 // for skipping this function's stack frame).
9946 const int actual_to_skip = stack_frames_to_skip + 1;
9947#endif // NDEBUG
9948
9949 // Appends a new-line to message if it doesn't end with one.
9950 if (!message.empty() && *message.rbegin() != '\n') {
9951 std::cout << "\n";
9952 }
9953 std::cout << "Stack trace:\n"
9954 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
9955 ::testing::UnitTest::GetInstance(), actual_to_skip);
9956 }
9957 std::cout << ::std::flush;
9958}
9959
9960} // namespace internal
9961} // namespace testing
9962// Copyright 2007, Google Inc.
9963// All rights reserved.
9964//
9965// Redistribution and use in source and binary forms, with or without
9966// modification, are permitted provided that the following conditions are
9967// met:
9968//
9969// * Redistributions of source code must retain the above copyright
9970// notice, this list of conditions and the following disclaimer.
9971// * Redistributions in binary form must reproduce the above
9972// copyright notice, this list of conditions and the following disclaimer
9973// in the documentation and/or other materials provided with the
9974// distribution.
9975// * Neither the name of Google Inc. nor the names of its
9976// contributors may be used to endorse or promote products derived from
9977// this software without specific prior written permission.
9978//
9979// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9980// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9981// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9982// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9983// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9984// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9985// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9986// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9987// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9988// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9989// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9990//
9991// Author: wan@google.com (Zhanyong Wan)
9992
9993// Google Mock - a framework for writing C++ mock classes.
9994//
9995// This file implements Matcher<const string&>, Matcher<string>, and
9996// utilities for defining matchers.
9997
9998
9999#include <string.h>
10000#include <sstream>
10001#include <string>
10002
10003namespace testing {
10004
10005// Constructs a matcher that matches a const string& whose value is
10006// equal to s.
10007Matcher<const internal::string&>::Matcher(const internal::string& s) {
10008 *this = Eq(s);
10009}
10010
10011// Constructs a matcher that matches a const string& whose value is
10012// equal to s.
10013Matcher<const internal::string&>::Matcher(const char* s) {
10014 *this = Eq(internal::string(s));
10015}
10016
10017// Constructs a matcher that matches a string whose value is equal to s.
10018Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
10019
10020// Constructs a matcher that matches a string whose value is equal to s.
10021Matcher<internal::string>::Matcher(const char* s) {
10022 *this = Eq(internal::string(s));
10023}
10024
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010025#if GTEST_HAS_STRING_PIECE_
10026// Constructs a matcher that matches a const StringPiece& whose value is
10027// equal to s.
10028Matcher<const StringPiece&>::Matcher(const internal::string& s) {
10029 *this = Eq(s);
10030}
10031
10032// Constructs a matcher that matches a const StringPiece& whose value is
10033// equal to s.
10034Matcher<const StringPiece&>::Matcher(const char* s) {
10035 *this = Eq(internal::string(s));
10036}
10037
10038// Constructs a matcher that matches a const StringPiece& whose value is
10039// equal to s.
10040Matcher<const StringPiece&>::Matcher(StringPiece s) {
10041 *this = Eq(s.ToString());
10042}
10043
10044// Constructs a matcher that matches a StringPiece whose value is equal to s.
10045Matcher<StringPiece>::Matcher(const internal::string& s) {
10046 *this = Eq(s);
10047}
10048
10049// Constructs a matcher that matches a StringPiece whose value is equal to s.
10050Matcher<StringPiece>::Matcher(const char* s) {
10051 *this = Eq(internal::string(s));
10052}
10053
10054// Constructs a matcher that matches a StringPiece whose value is equal to s.
10055Matcher<StringPiece>::Matcher(StringPiece s) {
10056 *this = Eq(s.ToString());
10057}
10058#endif // GTEST_HAS_STRING_PIECE_
10059
Keir Mierle8ebb0732012-04-30 23:09:08 -070010060namespace internal {
10061
10062// Joins a vector of strings as if they are fields of a tuple; returns
10063// the joined string.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010064GTEST_API_ string JoinAsTuple(const Strings& fields) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010065 switch (fields.size()) {
10066 case 0:
10067 return "";
10068 case 1:
10069 return fields[0];
10070 default:
10071 string result = "(" + fields[0];
10072 for (size_t i = 1; i < fields.size(); i++) {
10073 result += ", ";
10074 result += fields[i];
10075 }
10076 result += ")";
10077 return result;
10078 }
10079}
10080
10081// Returns the description for a matcher defined using the MATCHER*()
10082// macro where the user-supplied description string is "", if
10083// 'negation' is false; otherwise returns the description of the
10084// negation of the matcher. 'param_values' contains a list of strings
10085// that are the print-out of the matcher's parameters.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010086GTEST_API_ string FormatMatcherDescription(bool negation,
10087 const char* matcher_name,
10088 const Strings& param_values) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010089 string result = ConvertIdentifierNameToWords(matcher_name);
10090 if (param_values.size() >= 1)
10091 result += " " + JoinAsTuple(param_values);
10092 return negation ? "not (" + result + ")" : result;
10093}
10094
Sameer Agarwal4894a842013-09-19 10:21:56 -070010095// FindMaxBipartiteMatching and its helper class.
10096//
10097// Uses the well-known Ford-Fulkerson max flow method to find a maximum
10098// bipartite matching. Flow is considered to be from left to right.
10099// There is an implicit source node that is connected to all of the left
10100// nodes, and an implicit sink node that is connected to all of the
10101// right nodes. All edges have unit capacity.
10102//
10103// Neither the flow graph nor the residual flow graph are represented
10104// explicitly. Instead, they are implied by the information in 'graph' and
10105// a vector<int> called 'left_' whose elements are initialized to the
10106// value kUnused. This represents the initial state of the algorithm,
10107// where the flow graph is empty, and the residual flow graph has the
10108// following edges:
10109// - An edge from source to each left_ node
10110// - An edge from each right_ node to sink
10111// - An edge from each left_ node to each right_ node, if the
10112// corresponding edge exists in 'graph'.
10113//
10114// When the TryAugment() method adds a flow, it sets left_[l] = r for some
10115// nodes l and r. This induces the following changes:
10116// - The edges (source, l), (l, r), and (r, sink) are added to the
10117// flow graph.
10118// - The same three edges are removed from the residual flow graph.
10119// - The reverse edges (l, source), (r, l), and (sink, r) are added
10120// to the residual flow graph, which is a directional graph
10121// representing unused flow capacity.
10122//
10123// When the method augments a flow (moving left_[l] from some r1 to some
10124// other r2), this can be thought of as "undoing" the above steps with
10125// respect to r1 and "redoing" them with respect to r2.
10126//
10127// It bears repeating that the flow graph and residual flow graph are
10128// never represented explicitly, but can be derived by looking at the
10129// information in 'graph' and in left_.
10130//
10131// As an optimization, there is a second vector<int> called right_ which
10132// does not provide any new information. Instead, it enables more
10133// efficient queries about edges entering or leaving the right-side nodes
10134// of the flow or residual flow graphs. The following invariants are
10135// maintained:
10136//
10137// left[l] == kUnused or right[left[l]] == l
10138// right[r] == kUnused or left[right[r]] == r
10139//
10140// . [ source ] .
10141// . ||| .
10142// . ||| .
10143// . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
10144// . || | | .
10145// . |\---> left[1]=-1 \--> right[1]=0 ---\| .
10146// . | || .
10147// . \----> left[2]=2 ------> right[2]=2 --\|| .
10148// . ||| .
10149// . elements matchers vvv .
10150// . [ sink ] .
10151//
10152// See Also:
10153// [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
10154// "Introduction to Algorithms (Second ed.)", pp. 651–664.
10155// [2] "Ford–Fulkerson algorithm", Wikipedia,
10156// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
10157class MaxBipartiteMatchState {
10158 public:
10159 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
10160 : graph_(&graph),
10161 left_(graph_->LhsSize(), kUnused),
10162 right_(graph_->RhsSize(), kUnused) {
10163 }
10164
10165 // Returns the edges of a maximal match, each in the form {left, right}.
10166 ElementMatcherPairs Compute() {
10167 // 'seen' is used for path finding { 0: unseen, 1: seen }.
10168 ::std::vector<char> seen;
10169 // Searches the residual flow graph for a path from each left node to
10170 // the sink in the residual flow graph, and if one is found, add flow
10171 // to the graph. It's okay to search through the left nodes once. The
10172 // edge from the implicit source node to each previously-visited left
10173 // node will have flow if that left node has any path to the sink
10174 // whatsoever. Subsequent augmentations can only add flow to the
10175 // network, and cannot take away that previous flow unit from the source.
10176 // Since the source-to-left edge can only carry one flow unit (or,
10177 // each element can be matched to only one matcher), there is no need
10178 // to visit the left nodes more than once looking for augmented paths.
10179 // The flow is known to be possible or impossible by looking at the
10180 // node once.
10181 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
10182 // Reset the path-marking vector and try to find a path from
10183 // source to sink starting at the left_[ilhs] node.
10184 GTEST_CHECK_(left_[ilhs] == kUnused)
10185 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
10186 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
10187 seen.assign(graph_->RhsSize(), 0);
10188 TryAugment(ilhs, &seen);
10189 }
10190 ElementMatcherPairs result;
10191 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10192 size_t irhs = left_[ilhs];
10193 if (irhs == kUnused) continue;
10194 result.push_back(ElementMatcherPair(ilhs, irhs));
10195 }
10196 return result;
10197 }
10198
10199 private:
10200 static const size_t kUnused = static_cast<size_t>(-1);
10201
10202 // Perform a depth-first search from left node ilhs to the sink. If a
10203 // path is found, flow is added to the network by linking the left and
10204 // right vector elements corresponding each segment of the path.
10205 // Returns true if a path to sink was found, which means that a unit of
10206 // flow was added to the network. The 'seen' vector elements correspond
10207 // to right nodes and are marked to eliminate cycles from the search.
10208 //
10209 // Left nodes will only be explored at most once because they
10210 // are accessible from at most one right node in the residual flow
10211 // graph.
10212 //
10213 // Note that left_[ilhs] is the only element of left_ that TryAugment will
10214 // potentially transition from kUnused to another value. Any other
10215 // left_ element holding kUnused before TryAugment will be holding it
10216 // when TryAugment returns.
10217 //
10218 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
10219 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
10220 if ((*seen)[irhs])
10221 continue;
10222 if (!graph_->HasEdge(ilhs, irhs))
10223 continue;
10224 // There's an available edge from ilhs to irhs.
10225 (*seen)[irhs] = 1;
10226 // Next a search is performed to determine whether
10227 // this edge is a dead end or leads to the sink.
10228 //
10229 // right_[irhs] == kUnused means that there is residual flow from
10230 // right node irhs to the sink, so we can use that to finish this
10231 // flow path and return success.
10232 //
10233 // Otherwise there is residual flow to some ilhs. We push flow
10234 // along that path and call ourselves recursively to see if this
10235 // ultimately leads to sink.
10236 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
10237 // Add flow from left_[ilhs] to right_[irhs].
10238 left_[ilhs] = irhs;
10239 right_[irhs] = ilhs;
10240 return true;
10241 }
10242 }
10243 return false;
10244 }
10245
10246 const MatchMatrix* graph_; // not owned
10247 // Each element of the left_ vector represents a left hand side node
10248 // (i.e. an element) and each element of right_ is a right hand side
10249 // node (i.e. a matcher). The values in the left_ vector indicate
10250 // outflow from that node to a node on the the right_ side. The values
10251 // in the right_ indicate inflow, and specify which left_ node is
10252 // feeding that right_ node, if any. For example, left_[3] == 1 means
10253 // there's a flow from element #3 to matcher #1. Such a flow would also
10254 // be redundantly represented in the right_ vector as right_[1] == 3.
10255 // Elements of left_ and right_ are either kUnused or mutually
10256 // referent. Mutually referent means that left_[right_[i]] = i and
10257 // right_[left_[i]] = i.
10258 ::std::vector<size_t> left_;
10259 ::std::vector<size_t> right_;
10260
10261 GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
10262};
10263
10264const size_t MaxBipartiteMatchState::kUnused;
10265
10266GTEST_API_ ElementMatcherPairs
10267FindMaxBipartiteMatching(const MatchMatrix& g) {
10268 return MaxBipartiteMatchState(g).Compute();
10269}
10270
10271static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
10272 ::std::ostream* stream) {
10273 typedef ElementMatcherPairs::const_iterator Iter;
10274 ::std::ostream& os = *stream;
10275 os << "{";
10276 const char *sep = "";
10277 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
10278 os << sep << "\n ("
10279 << "element #" << it->first << ", "
10280 << "matcher #" << it->second << ")";
10281 sep = ",";
10282 }
10283 os << "\n}";
10284}
10285
10286// Tries to find a pairing, and explains the result.
10287GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
10288 MatchResultListener* listener) {
10289 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
10290
10291 size_t max_flow = matches.size();
10292 bool result = (max_flow == matrix.RhsSize());
10293
10294 if (!result) {
10295 if (listener->IsInterested()) {
10296 *listener << "where no permutation of the elements can "
10297 "satisfy all matchers, and the closest match is "
10298 << max_flow << " of " << matrix.RhsSize()
10299 << " matchers with the pairings:\n";
10300 LogElementMatcherPairVec(matches, listener->stream());
10301 }
10302 return false;
10303 }
10304
10305 if (matches.size() > 1) {
10306 if (listener->IsInterested()) {
10307 const char *sep = "where:\n";
10308 for (size_t mi = 0; mi < matches.size(); ++mi) {
10309 *listener << sep << " - element #" << matches[mi].first
10310 << " is matched by matcher #" << matches[mi].second;
10311 sep = ",\n";
10312 }
10313 }
10314 }
10315 return true;
10316}
10317
10318bool MatchMatrix::NextGraph() {
10319 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10320 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10321 char& b = matched_[SpaceIndex(ilhs, irhs)];
10322 if (!b) {
10323 b = 1;
10324 return true;
10325 }
10326 b = 0;
10327 }
10328 }
10329 return false;
10330}
10331
10332void MatchMatrix::Randomize() {
10333 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10334 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10335 char& b = matched_[SpaceIndex(ilhs, irhs)];
10336 b = static_cast<char>(rand() & 1); // NOLINT
10337 }
10338 }
10339}
10340
10341string MatchMatrix::DebugString() const {
10342 ::std::stringstream ss;
10343 const char *sep = "";
10344 for (size_t i = 0; i < LhsSize(); ++i) {
10345 ss << sep;
10346 for (size_t j = 0; j < RhsSize(); ++j) {
10347 ss << HasEdge(i, j);
10348 }
10349 sep = ";";
10350 }
10351 return ss.str();
10352}
10353
10354void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
10355 ::std::ostream* os) const {
10356 if (matcher_describers_.empty()) {
10357 *os << "is empty";
10358 return;
10359 }
10360 if (matcher_describers_.size() == 1) {
10361 *os << "has " << Elements(1) << " and that element ";
10362 matcher_describers_[0]->DescribeTo(os);
10363 return;
10364 }
10365 *os << "has " << Elements(matcher_describers_.size())
10366 << " and there exists some permutation of elements such that:\n";
10367 const char* sep = "";
10368 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10369 *os << sep << " - element #" << i << " ";
10370 matcher_describers_[i]->DescribeTo(os);
10371 sep = ", and\n";
10372 }
10373}
10374
10375void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
10376 ::std::ostream* os) const {
10377 if (matcher_describers_.empty()) {
10378 *os << "isn't empty";
10379 return;
10380 }
10381 if (matcher_describers_.size() == 1) {
10382 *os << "doesn't have " << Elements(1)
10383 << ", or has " << Elements(1) << " that ";
10384 matcher_describers_[0]->DescribeNegationTo(os);
10385 return;
10386 }
10387 *os << "doesn't have " << Elements(matcher_describers_.size())
10388 << ", or there exists no permutation of elements such that:\n";
10389 const char* sep = "";
10390 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10391 *os << sep << " - element #" << i << " ";
10392 matcher_describers_[i]->DescribeTo(os);
10393 sep = ", and\n";
10394 }
10395}
10396
10397// Checks that all matchers match at least one element, and that all
10398// elements match at least one matcher. This enables faster matching
10399// and better error reporting.
10400// Returns false, writing an explanation to 'listener', if and only
10401// if the success criteria are not met.
10402bool UnorderedElementsAreMatcherImplBase::
10403VerifyAllElementsAndMatchersAreMatched(
10404 const ::std::vector<string>& element_printouts,
10405 const MatchMatrix& matrix,
10406 MatchResultListener* listener) const {
10407 bool result = true;
10408 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
10409 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
10410
10411 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
10412 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
10413 char matched = matrix.HasEdge(ilhs, irhs);
10414 element_matched[ilhs] |= matched;
10415 matcher_matched[irhs] |= matched;
10416 }
10417 }
10418
10419 {
10420 const char* sep =
10421 "where the following matchers don't match any elements:\n";
10422 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
10423 if (matcher_matched[mi])
10424 continue;
10425 result = false;
10426 if (listener->IsInterested()) {
10427 *listener << sep << "matcher #" << mi << ": ";
10428 matcher_describers_[mi]->DescribeTo(listener->stream());
10429 sep = ",\n";
10430 }
10431 }
10432 }
10433
10434 {
10435 const char* sep =
10436 "where the following elements don't match any matchers:\n";
10437 const char* outer_sep = "";
10438 if (!result) {
10439 outer_sep = "\nand ";
10440 }
10441 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
10442 if (element_matched[ei])
10443 continue;
10444 result = false;
10445 if (listener->IsInterested()) {
10446 *listener << outer_sep << sep << "element #" << ei << ": "
10447 << element_printouts[ei];
10448 sep = ",\n";
10449 outer_sep = "";
10450 }
10451 }
10452 }
10453 return result;
10454}
10455
Keir Mierle8ebb0732012-04-30 23:09:08 -070010456} // namespace internal
10457} // namespace testing
10458// Copyright 2007, Google Inc.
10459// All rights reserved.
10460//
10461// Redistribution and use in source and binary forms, with or without
10462// modification, are permitted provided that the following conditions are
10463// met:
10464//
10465// * Redistributions of source code must retain the above copyright
10466// notice, this list of conditions and the following disclaimer.
10467// * Redistributions in binary form must reproduce the above
10468// copyright notice, this list of conditions and the following disclaimer
10469// in the documentation and/or other materials provided with the
10470// distribution.
10471// * Neither the name of Google Inc. nor the names of its
10472// contributors may be used to endorse or promote products derived from
10473// this software without specific prior written permission.
10474//
10475// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10476// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10477// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10478// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10479// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10480// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10481// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10482// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10483// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10484// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10485// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10486//
10487// Author: wan@google.com (Zhanyong Wan)
10488
10489// Google Mock - a framework for writing C++ mock classes.
10490//
10491// This file implements the spec builder syntax (ON_CALL and
10492// EXPECT_CALL).
10493
10494
10495#include <stdlib.h>
10496#include <iostream> // NOLINT
10497#include <map>
10498#include <set>
10499#include <string>
10500
10501#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
10502# include <unistd.h> // NOLINT
10503#endif
10504
10505namespace testing {
10506namespace internal {
10507
10508// Protects the mock object registry (in class Mock), all function
10509// mockers, and all expectations.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010510GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
Keir Mierle8ebb0732012-04-30 23:09:08 -070010511
10512// Logs a message including file and line number information.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010513GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
10514 const char* file, int line,
10515 const string& message) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010516 ::std::ostringstream s;
10517 s << file << ":" << line << ": " << message << ::std::endl;
10518 Log(severity, s.str(), 0);
10519}
10520
10521// Constructs an ExpectationBase object.
10522ExpectationBase::ExpectationBase(const char* a_file,
10523 int a_line,
10524 const string& a_source_text)
10525 : file_(a_file),
10526 line_(a_line),
10527 source_text_(a_source_text),
10528 cardinality_specified_(false),
10529 cardinality_(Exactly(1)),
10530 call_count_(0),
10531 retired_(false),
10532 extra_matcher_specified_(false),
10533 repeated_action_specified_(false),
10534 retires_on_saturation_(false),
10535 last_clause_(kNone),
10536 action_count_checked_(false) {}
10537
10538// Destructs an ExpectationBase object.
10539ExpectationBase::~ExpectationBase() {}
10540
10541// Explicitly specifies the cardinality of this expectation. Used by
10542// the subclasses to implement the .Times() clause.
10543void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
10544 cardinality_specified_ = true;
10545 cardinality_ = a_cardinality;
10546}
10547
10548// Retires all pre-requisites of this expectation.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010549void ExpectationBase::RetireAllPreRequisites()
10550 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010551 if (is_retired()) {
10552 // We can take this short-cut as we never retire an expectation
10553 // until we have retired all its pre-requisites.
10554 return;
10555 }
10556
10557 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10558 it != immediate_prerequisites_.end(); ++it) {
10559 ExpectationBase* const prerequisite = it->expectation_base().get();
10560 if (!prerequisite->is_retired()) {
10561 prerequisite->RetireAllPreRequisites();
10562 prerequisite->Retire();
10563 }
10564 }
10565}
10566
10567// Returns true iff all pre-requisites of this expectation have been
10568// satisfied.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010569bool ExpectationBase::AllPrerequisitesAreSatisfied() const
10570 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010571 g_gmock_mutex.AssertHeld();
10572 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10573 it != immediate_prerequisites_.end(); ++it) {
10574 if (!(it->expectation_base()->IsSatisfied()) ||
10575 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
10576 return false;
10577 }
10578 return true;
10579}
10580
10581// Adds unsatisfied pre-requisites of this expectation to 'result'.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010582void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
10583 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010584 g_gmock_mutex.AssertHeld();
10585 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10586 it != immediate_prerequisites_.end(); ++it) {
10587 if (it->expectation_base()->IsSatisfied()) {
10588 // If *it is satisfied and has a call count of 0, some of its
10589 // pre-requisites may not be satisfied yet.
10590 if (it->expectation_base()->call_count_ == 0) {
10591 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
10592 }
10593 } else {
10594 // Now that we know *it is unsatisfied, we are not so interested
10595 // in whether its pre-requisites are satisfied. Therefore we
10596 // don't recursively call FindUnsatisfiedPrerequisites() here.
10597 *result += *it;
10598 }
10599 }
10600}
10601
10602// Describes how many times a function call matching this
10603// expectation has occurred.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010604void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
10605 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010606 g_gmock_mutex.AssertHeld();
10607
10608 // Describes how many times the function is expected to be called.
10609 *os << " Expected: to be ";
10610 cardinality().DescribeTo(os);
10611 *os << "\n Actual: ";
10612 Cardinality::DescribeActualCallCountTo(call_count(), os);
10613
10614 // Describes the state of the expectation (e.g. is it satisfied?
10615 // is it active?).
10616 *os << " - " << (IsOverSaturated() ? "over-saturated" :
10617 IsSaturated() ? "saturated" :
10618 IsSatisfied() ? "satisfied" : "unsatisfied")
10619 << " and "
10620 << (is_retired() ? "retired" : "active");
10621}
10622
10623// Checks the action count (i.e. the number of WillOnce() and
10624// WillRepeatedly() clauses) against the cardinality if this hasn't
10625// been done before. Prints a warning if there are too many or too
10626// few actions.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010627void ExpectationBase::CheckActionCountIfNotDone() const
10628 GTEST_LOCK_EXCLUDED_(mutex_) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010629 bool should_check = false;
10630 {
10631 MutexLock l(&mutex_);
10632 if (!action_count_checked_) {
10633 action_count_checked_ = true;
10634 should_check = true;
10635 }
10636 }
10637
10638 if (should_check) {
10639 if (!cardinality_specified_) {
10640 // The cardinality was inferred - no need to check the action
10641 // count against it.
10642 return;
10643 }
10644
10645 // The cardinality was explicitly specified.
10646 const int action_count = static_cast<int>(untyped_actions_.size());
10647 const int upper_bound = cardinality().ConservativeUpperBound();
10648 const int lower_bound = cardinality().ConservativeLowerBound();
10649 bool too_many; // True if there are too many actions, or false
10650 // if there are too few.
10651 if (action_count > upper_bound ||
10652 (action_count == upper_bound && repeated_action_specified_)) {
10653 too_many = true;
10654 } else if (0 < action_count && action_count < lower_bound &&
10655 !repeated_action_specified_) {
10656 too_many = false;
10657 } else {
10658 return;
10659 }
10660
10661 ::std::stringstream ss;
10662 DescribeLocationTo(&ss);
10663 ss << "Too " << (too_many ? "many" : "few")
10664 << " actions specified in " << source_text() << "...\n"
10665 << "Expected to be ";
10666 cardinality().DescribeTo(&ss);
10667 ss << ", but has " << (too_many ? "" : "only ")
10668 << action_count << " WillOnce()"
10669 << (action_count == 1 ? "" : "s");
10670 if (repeated_action_specified_) {
10671 ss << " and a WillRepeatedly()";
10672 }
10673 ss << ".";
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010674 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
Keir Mierle8ebb0732012-04-30 23:09:08 -070010675 }
10676}
10677
10678// Implements the .Times() clause.
10679void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
10680 if (last_clause_ == kTimes) {
10681 ExpectSpecProperty(false,
10682 ".Times() cannot appear "
10683 "more than once in an EXPECT_CALL().");
10684 } else {
10685 ExpectSpecProperty(last_clause_ < kTimes,
10686 ".Times() cannot appear after "
10687 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
10688 "or .RetiresOnSaturation().");
10689 }
10690 last_clause_ = kTimes;
10691
10692 SpecifyCardinality(a_cardinality);
10693}
10694
10695// Points to the implicit sequence introduced by a living InSequence
10696// object (if any) in the current thread or NULL.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010697GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
Keir Mierle8ebb0732012-04-30 23:09:08 -070010698
10699// Reports an uninteresting call (whose description is in msg) in the
10700// manner specified by 'reaction'.
10701void ReportUninterestingCall(CallReaction reaction, const string& msg) {
10702 switch (reaction) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010703 case kAllow:
10704 Log(kInfo, msg, 3);
Keir Mierle8ebb0732012-04-30 23:09:08 -070010705 break;
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010706 case kWarn:
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -070010707 Log(kWarning,
10708 msg +
10709 "\nNOTE: You can safely ignore the above warning unless this "
10710 "call should not happen. Do not suppress it by blindly adding "
10711 "an EXPECT_CALL() if you don't mean to enforce the call. "
10712 "See http://code.google.com/p/googlemock/wiki/CookBook#"
10713 "Knowing_When_to_Expect for details.",
10714 3);
Keir Mierle8ebb0732012-04-30 23:09:08 -070010715 break;
10716 default: // FAIL
10717 Expect(false, NULL, -1, msg);
10718 }
10719}
10720
10721UntypedFunctionMockerBase::UntypedFunctionMockerBase()
10722 : mock_obj_(NULL), name_("") {}
10723
10724UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
10725
10726// Sets the mock object this mock method belongs to, and registers
10727// this information in the global mock registry. Will be called
10728// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
10729// method.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010730void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
10731 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010732 {
10733 MutexLock l(&g_gmock_mutex);
10734 mock_obj_ = mock_obj;
10735 }
10736 Mock::Register(mock_obj, this);
10737}
10738
10739// Sets the mock object this mock method belongs to, and sets the name
10740// of the mock function. Will be called upon each invocation of this
10741// mock function.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010742void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
10743 const char* name)
10744 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010745 // We protect name_ under g_gmock_mutex in case this mock function
10746 // is called from two threads concurrently.
10747 MutexLock l(&g_gmock_mutex);
10748 mock_obj_ = mock_obj;
10749 name_ = name;
10750}
10751
10752// Returns the name of the function being mocked. Must be called
10753// after RegisterOwner() or SetOwnerAndName() has been called.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010754const void* UntypedFunctionMockerBase::MockObject() const
10755 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010756 const void* mock_obj;
10757 {
10758 // We protect mock_obj_ under g_gmock_mutex in case this mock
10759 // function is called from two threads concurrently.
10760 MutexLock l(&g_gmock_mutex);
10761 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
10762 "MockObject() must not be called before RegisterOwner() or "
10763 "SetOwnerAndName() has been called.");
10764 mock_obj = mock_obj_;
10765 }
10766 return mock_obj;
10767}
10768
10769// Returns the name of this mock method. Must be called after
10770// SetOwnerAndName() has been called.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010771const char* UntypedFunctionMockerBase::Name() const
10772 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010773 const char* name;
10774 {
10775 // We protect name_ under g_gmock_mutex in case this mock
10776 // function is called from two threads concurrently.
10777 MutexLock l(&g_gmock_mutex);
10778 Assert(name_ != NULL, __FILE__, __LINE__,
10779 "Name() must not be called before SetOwnerAndName() has "
10780 "been called.");
10781 name = name_;
10782 }
10783 return name;
10784}
10785
10786// Calculates the result of invoking this mock function with the given
10787// arguments, prints it, and returns it. The caller is responsible
10788// for deleting the result.
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -070010789UntypedActionResultHolderBase*
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010790UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
10791 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010792 if (untyped_expectations_.size() == 0) {
10793 // No expectation is set on this mock method - we have an
10794 // uninteresting call.
10795
10796 // We must get Google Mock's reaction on uninteresting calls
10797 // made on this mock object BEFORE performing the action,
10798 // because the action may DELETE the mock object and make the
10799 // following expression meaningless.
10800 const CallReaction reaction =
10801 Mock::GetReactionOnUninterestingCalls(MockObject());
10802
10803 // True iff we need to print this call's arguments and return
10804 // value. This definition must be kept in sync with
10805 // the behavior of ReportUninterestingCall().
10806 const bool need_to_report_uninteresting_call =
10807 // If the user allows this uninteresting call, we print it
10808 // only when he wants informational messages.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010809 reaction == kAllow ? LogIsVisible(kInfo) :
Keir Mierle8ebb0732012-04-30 23:09:08 -070010810 // If the user wants this to be a warning, we print it only
10811 // when he wants to see warnings.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010812 reaction == kWarn ? LogIsVisible(kWarning) :
Keir Mierle8ebb0732012-04-30 23:09:08 -070010813 // Otherwise, the user wants this to be an error, and we
10814 // should always print detailed information in the error.
10815 true;
10816
10817 if (!need_to_report_uninteresting_call) {
10818 // Perform the action without printing the call information.
10819 return this->UntypedPerformDefaultAction(untyped_args, "");
10820 }
10821
10822 // Warns about the uninteresting call.
10823 ::std::stringstream ss;
10824 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
10825
10826 // Calculates the function result.
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -070010827 UntypedActionResultHolderBase* const result =
Keir Mierle8ebb0732012-04-30 23:09:08 -070010828 this->UntypedPerformDefaultAction(untyped_args, ss.str());
10829
10830 // Prints the function result.
10831 if (result != NULL)
10832 result->PrintAsActionResult(&ss);
10833
10834 ReportUninterestingCall(reaction, ss.str());
10835 return result;
10836 }
10837
10838 bool is_excessive = false;
10839 ::std::stringstream ss;
10840 ::std::stringstream why;
10841 ::std::stringstream loc;
10842 const void* untyped_action = NULL;
10843
10844 // The UntypedFindMatchingExpectation() function acquires and
10845 // releases g_gmock_mutex.
10846 const ExpectationBase* const untyped_expectation =
10847 this->UntypedFindMatchingExpectation(
10848 untyped_args, &untyped_action, &is_excessive,
10849 &ss, &why);
10850 const bool found = untyped_expectation != NULL;
10851
10852 // True iff we need to print the call's arguments and return value.
10853 // This definition must be kept in sync with the uses of Expect()
10854 // and Log() in this function.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010855 const bool need_to_report_call =
10856 !found || is_excessive || LogIsVisible(kInfo);
Keir Mierle8ebb0732012-04-30 23:09:08 -070010857 if (!need_to_report_call) {
10858 // Perform the action without printing the call information.
10859 return
10860 untyped_action == NULL ?
10861 this->UntypedPerformDefaultAction(untyped_args, "") :
10862 this->UntypedPerformAction(untyped_action, untyped_args);
10863 }
10864
10865 ss << " Function call: " << Name();
10866 this->UntypedPrintArgs(untyped_args, &ss);
10867
10868 // In case the action deletes a piece of the expectation, we
10869 // generate the message beforehand.
10870 if (found && !is_excessive) {
10871 untyped_expectation->DescribeLocationTo(&loc);
10872 }
10873
Sameer Agarwal7b3ffe52014-03-11 10:48:40 -070010874 UntypedActionResultHolderBase* const result =
Keir Mierle8ebb0732012-04-30 23:09:08 -070010875 untyped_action == NULL ?
10876 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
10877 this->UntypedPerformAction(untyped_action, untyped_args);
10878 if (result != NULL)
10879 result->PrintAsActionResult(&ss);
10880 ss << "\n" << why.str();
10881
10882 if (!found) {
10883 // No expectation matches this call - reports a failure.
10884 Expect(false, NULL, -1, ss.str());
10885 } else if (is_excessive) {
10886 // We had an upper-bound violation and the failure message is in ss.
10887 Expect(false, untyped_expectation->file(),
10888 untyped_expectation->line(), ss.str());
10889 } else {
10890 // We had an expected call and the matching expectation is
10891 // described in ss.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010892 Log(kInfo, loc.str() + ss.str(), 2);
Keir Mierle8ebb0732012-04-30 23:09:08 -070010893 }
10894
10895 return result;
10896}
10897
10898// Returns an Expectation object that references and co-owns exp,
10899// which must be an expectation on this mock function.
10900Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
10901 for (UntypedExpectations::const_iterator it =
10902 untyped_expectations_.begin();
10903 it != untyped_expectations_.end(); ++it) {
10904 if (it->get() == exp) {
10905 return Expectation(*it);
10906 }
10907 }
10908
10909 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
10910 return Expectation();
10911 // The above statement is just to make the code compile, and will
10912 // never be executed.
10913}
10914
10915// Verifies that all expectations on this mock function have been
10916// satisfied. Reports one or more Google Test non-fatal failures
10917// and returns false if not.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010918bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
10919 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070010920 g_gmock_mutex.AssertHeld();
10921 bool expectations_met = true;
10922 for (UntypedExpectations::const_iterator it =
10923 untyped_expectations_.begin();
10924 it != untyped_expectations_.end(); ++it) {
10925 ExpectationBase* const untyped_expectation = it->get();
10926 if (untyped_expectation->IsOverSaturated()) {
10927 // There was an upper-bound violation. Since the error was
10928 // already reported when it occurred, there is no need to do
10929 // anything here.
10930 expectations_met = false;
10931 } else if (!untyped_expectation->IsSatisfied()) {
10932 expectations_met = false;
10933 ::std::stringstream ss;
10934 ss << "Actual function call count doesn't match "
10935 << untyped_expectation->source_text() << "...\n";
10936 // No need to show the source file location of the expectation
10937 // in the description, as the Expect() call that follows already
10938 // takes care of it.
10939 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
10940 untyped_expectation->DescribeCallCountTo(&ss);
10941 Expect(false, untyped_expectation->file(),
10942 untyped_expectation->line(), ss.str());
10943 }
10944 }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070010945
10946 // Deleting our expectations may trigger other mock objects to be deleted, for
10947 // example if an action contains a reference counted smart pointer to that
10948 // mock object, and that is the last reference. So if we delete our
10949 // expectations within the context of the global mutex we may deadlock when
10950 // this method is called again. Instead, make a copy of the set of
10951 // expectations to delete, clear our set within the mutex, and then clear the
10952 // copied set outside of it.
10953 UntypedExpectations expectations_to_delete;
10954 untyped_expectations_.swap(expectations_to_delete);
10955
10956 g_gmock_mutex.Unlock();
10957 expectations_to_delete.clear();
10958 g_gmock_mutex.Lock();
10959
Keir Mierle8ebb0732012-04-30 23:09:08 -070010960 return expectations_met;
10961}
10962
10963} // namespace internal
10964
10965// Class Mock.
10966
10967namespace {
10968
10969typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10970
10971// The current state of a mock object. Such information is needed for
10972// detecting leaked mock objects and explicitly verifying a mock's
10973// expectations.
10974struct MockObjectState {
10975 MockObjectState()
10976 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
10977
10978 // Where in the source file an ON_CALL or EXPECT_CALL is first
10979 // invoked on this mock object.
10980 const char* first_used_file;
10981 int first_used_line;
10982 ::std::string first_used_test_case;
10983 ::std::string first_used_test;
10984 bool leakable; // true iff it's OK to leak the object.
10985 FunctionMockers function_mockers; // All registered methods of the object.
10986};
10987
10988// A global registry holding the state of all mock objects that are
10989// alive. A mock object is added to this registry the first time
10990// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
10991// is removed from the registry in the mock object's destructor.
10992class MockObjectRegistry {
10993 public:
10994 // Maps a mock object (identified by its address) to its state.
10995 typedef std::map<const void*, MockObjectState> StateMap;
10996
10997 // This destructor will be called when a program exits, after all
10998 // tests in it have been run. By then, there should be no mock
10999 // object alive. Therefore we report any living object as test
11000 // failure, unless the user explicitly asked us to ignore it.
11001 ~MockObjectRegistry() {
11002 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
11003 // a macro.
11004
11005 if (!GMOCK_FLAG(catch_leaked_mocks))
11006 return;
11007
11008 int leaked_count = 0;
11009 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
11010 ++it) {
11011 if (it->second.leakable) // The user said it's fine to leak this object.
11012 continue;
11013
11014 // TODO(wan@google.com): Print the type of the leaked object.
11015 // This can help the user identify the leaked object.
11016 std::cout << "\n";
11017 const MockObjectState& state = it->second;
11018 std::cout << internal::FormatFileLocation(state.first_used_file,
11019 state.first_used_line);
11020 std::cout << " ERROR: this mock object";
11021 if (state.first_used_test != "") {
11022 std::cout << " (used in test " << state.first_used_test_case << "."
11023 << state.first_used_test << ")";
11024 }
11025 std::cout << " should be deleted but never is. Its address is @"
11026 << it->first << ".";
11027 leaked_count++;
11028 }
11029 if (leaked_count > 0) {
11030 std::cout << "\nERROR: " << leaked_count
11031 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
11032 << " found at program exit.\n";
11033 std::cout.flush();
11034 ::std::cerr.flush();
11035 // RUN_ALL_TESTS() has already returned when this destructor is
11036 // called. Therefore we cannot use the normal Google Test
11037 // failure reporting mechanism.
11038 _exit(1); // We cannot call exit() as it is not reentrant and
11039 // may already have been called.
11040 }
11041 }
11042
11043 StateMap& states() { return states_; }
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011044
Keir Mierle8ebb0732012-04-30 23:09:08 -070011045 private:
11046 StateMap states_;
11047};
11048
11049// Protected by g_gmock_mutex.
11050MockObjectRegistry g_mock_object_registry;
11051
11052// Maps a mock object to the reaction Google Mock should have when an
11053// uninteresting method is called. Protected by g_gmock_mutex.
11054std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11055
11056// Sets the reaction Google Mock should have when an uninteresting
11057// method of the given mock object is called.
Keir Mierle8ebb0732012-04-30 23:09:08 -070011058void SetReactionOnUninterestingCalls(const void* mock_obj,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011059 internal::CallReaction reaction)
11060 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011061 internal::MutexLock l(&internal::g_gmock_mutex);
11062 g_uninteresting_call_reaction[mock_obj] = reaction;
11063}
11064
11065} // namespace
11066
11067// Tells Google Mock to allow uninteresting calls on the given mock
11068// object.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011069void Mock::AllowUninterestingCalls(const void* mock_obj)
11070 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11071 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
Keir Mierle8ebb0732012-04-30 23:09:08 -070011072}
11073
11074// Tells Google Mock to warn the user about uninteresting calls on the
11075// given mock object.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011076void Mock::WarnUninterestingCalls(const void* mock_obj)
11077 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11078 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
Keir Mierle8ebb0732012-04-30 23:09:08 -070011079}
11080
11081// Tells Google Mock to fail uninteresting calls on the given mock
11082// object.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011083void Mock::FailUninterestingCalls(const void* mock_obj)
11084 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11085 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
Keir Mierle8ebb0732012-04-30 23:09:08 -070011086}
11087
11088// Tells Google Mock the given mock object is being destroyed and its
11089// entry in the call-reaction table should be removed.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011090void Mock::UnregisterCallReaction(const void* mock_obj)
11091 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011092 internal::MutexLock l(&internal::g_gmock_mutex);
11093 g_uninteresting_call_reaction.erase(mock_obj);
11094}
11095
11096// Returns the reaction Google Mock will have on uninteresting calls
11097// made on the given mock object.
Keir Mierle8ebb0732012-04-30 23:09:08 -070011098internal::CallReaction Mock::GetReactionOnUninterestingCalls(
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011099 const void* mock_obj)
11100 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011101 internal::MutexLock l(&internal::g_gmock_mutex);
11102 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011103 internal::kDefault : g_uninteresting_call_reaction[mock_obj];
Keir Mierle8ebb0732012-04-30 23:09:08 -070011104}
11105
11106// Tells Google Mock to ignore mock_obj when checking for leaked mock
11107// objects.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011108void Mock::AllowLeak(const void* mock_obj)
11109 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011110 internal::MutexLock l(&internal::g_gmock_mutex);
11111 g_mock_object_registry.states()[mock_obj].leakable = true;
11112}
11113
11114// Verifies and clears all expectations on the given mock object. If
11115// the expectations aren't satisfied, generates one or more Google
11116// Test non-fatal failures and returns false.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011117bool Mock::VerifyAndClearExpectations(void* mock_obj)
11118 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011119 internal::MutexLock l(&internal::g_gmock_mutex);
11120 return VerifyAndClearExpectationsLocked(mock_obj);
11121}
11122
11123// Verifies all expectations on the given mock object and clears its
11124// default actions and expectations. Returns true iff the
11125// verification was successful.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011126bool Mock::VerifyAndClear(void* mock_obj)
11127 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011128 internal::MutexLock l(&internal::g_gmock_mutex);
11129 ClearDefaultActionsLocked(mock_obj);
11130 return VerifyAndClearExpectationsLocked(mock_obj);
11131}
11132
11133// Verifies and clears all expectations on the given mock object. If
11134// the expectations aren't satisfied, generates one or more Google
11135// Test non-fatal failures and returns false.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011136bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
11137 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011138 internal::g_gmock_mutex.AssertHeld();
11139 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11140 // No EXPECT_CALL() was set on the given mock object.
11141 return true;
11142 }
11143
11144 // Verifies and clears the expectations on each mock method in the
11145 // given mock object.
11146 bool expectations_met = true;
11147 FunctionMockers& mockers =
11148 g_mock_object_registry.states()[mock_obj].function_mockers;
11149 for (FunctionMockers::const_iterator it = mockers.begin();
11150 it != mockers.end(); ++it) {
11151 if (!(*it)->VerifyAndClearExpectationsLocked()) {
11152 expectations_met = false;
11153 }
11154 }
11155
11156 // We don't clear the content of mockers, as they may still be
11157 // needed by ClearDefaultActionsLocked().
11158 return expectations_met;
11159}
11160
11161// Registers a mock object and a mock method it owns.
Keir Mierle8ebb0732012-04-30 23:09:08 -070011162void Mock::Register(const void* mock_obj,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011163 internal::UntypedFunctionMockerBase* mocker)
11164 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011165 internal::MutexLock l(&internal::g_gmock_mutex);
11166 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11167}
11168
11169// Tells Google Mock where in the source code mock_obj is used in an
11170// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
11171// information helps the user identify which object it is.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011172void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
11173 const char* file, int line)
11174 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011175 internal::MutexLock l(&internal::g_gmock_mutex);
11176 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
11177 if (state.first_used_file == NULL) {
11178 state.first_used_file = file;
11179 state.first_used_line = line;
11180 const TestInfo* const test_info =
11181 UnitTest::GetInstance()->current_test_info();
11182 if (test_info != NULL) {
11183 // TODO(wan@google.com): record the test case name when the
11184 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
11185 // TearDownTestCase().
11186 state.first_used_test_case = test_info->test_case_name();
11187 state.first_used_test = test_info->name();
11188 }
11189 }
11190}
11191
11192// Unregisters a mock method; removes the owning mock object from the
11193// registry when the last mock method associated with it has been
11194// unregistered. This is called only in the destructor of
11195// FunctionMockerBase.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011196void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
11197 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011198 internal::g_gmock_mutex.AssertHeld();
11199 for (MockObjectRegistry::StateMap::iterator it =
11200 g_mock_object_registry.states().begin();
11201 it != g_mock_object_registry.states().end(); ++it) {
11202 FunctionMockers& mockers = it->second.function_mockers;
11203 if (mockers.erase(mocker) > 0) {
11204 // mocker was in mockers and has been just removed.
11205 if (mockers.empty()) {
11206 g_mock_object_registry.states().erase(it);
11207 }
11208 return;
11209 }
11210 }
11211}
11212
11213// Clears all ON_CALL()s set on the given mock object.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011214void Mock::ClearDefaultActionsLocked(void* mock_obj)
11215 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011216 internal::g_gmock_mutex.AssertHeld();
11217
11218 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11219 // No ON_CALL() was set on the given mock object.
11220 return;
11221 }
11222
11223 // Clears the default actions for each mock method in the given mock
11224 // object.
11225 FunctionMockers& mockers =
11226 g_mock_object_registry.states()[mock_obj].function_mockers;
11227 for (FunctionMockers::const_iterator it = mockers.begin();
11228 it != mockers.end(); ++it) {
11229 (*it)->ClearDefaultActionsLocked();
11230 }
11231
11232 // We don't clear the content of mockers, as they may still be
11233 // needed by VerifyAndClearExpectationsLocked().
11234}
11235
11236Expectation::Expectation() {}
11237
11238Expectation::Expectation(
11239 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
11240 : expectation_base_(an_expectation_base) {}
11241
11242Expectation::~Expectation() {}
11243
11244// Adds an expectation to a sequence.
11245void Sequence::AddExpectation(const Expectation& expectation) const {
11246 if (*last_expectation_ != expectation) {
11247 if (last_expectation_->expectation_base() != NULL) {
11248 expectation.expectation_base()->immediate_prerequisites_
11249 += *last_expectation_;
11250 }
11251 *last_expectation_ = expectation;
11252 }
11253}
11254
11255// Creates the implicit sequence if there isn't one.
11256InSequence::InSequence() {
11257 if (internal::g_gmock_implicit_sequence.get() == NULL) {
11258 internal::g_gmock_implicit_sequence.set(new Sequence);
11259 sequence_created_ = true;
11260 } else {
11261 sequence_created_ = false;
11262 }
11263}
11264
11265// Deletes the implicit sequence if it was created by the constructor
11266// of this object.
11267InSequence::~InSequence() {
11268 if (sequence_created_) {
11269 delete internal::g_gmock_implicit_sequence.get();
11270 internal::g_gmock_implicit_sequence.set(NULL);
11271 }
11272}
11273
11274} // namespace testing
11275// Copyright 2008, Google Inc.
11276// All rights reserved.
11277//
11278// Redistribution and use in source and binary forms, with or without
11279// modification, are permitted provided that the following conditions are
11280// met:
11281//
11282// * Redistributions of source code must retain the above copyright
11283// notice, this list of conditions and the following disclaimer.
11284// * Redistributions in binary form must reproduce the above
11285// copyright notice, this list of conditions and the following disclaimer
11286// in the documentation and/or other materials provided with the
11287// distribution.
11288// * Neither the name of Google Inc. nor the names of its
11289// contributors may be used to endorse or promote products derived from
11290// this software without specific prior written permission.
11291//
11292// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11293// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11294// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11295// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11296// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11297// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11298// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11299// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11300// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11301// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11302// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11303//
11304// Author: wan@google.com (Zhanyong Wan)
11305
11306
11307namespace testing {
11308
11309// TODO(wan@google.com): support using environment variables to
11310// control the flag values, like what Google Test does.
11311
11312GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
11313 "true iff Google Mock should report leaked mock objects "
11314 "as failures.");
11315
11316GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
11317 "Controls how verbose Google Mock's output is."
11318 " Valid values:\n"
11319 " info - prints all messages.\n"
11320 " warning - prints warnings and errors.\n"
11321 " error - prints errors only.");
11322
11323namespace internal {
11324
11325// Parses a string as a command line flag. The string should have the
11326// format "--gmock_flag=value". When def_optional is true, the
11327// "=value" part can be omitted.
11328//
11329// Returns the value of the flag, or NULL if the parsing failed.
11330static const char* ParseGoogleMockFlagValue(const char* str,
11331 const char* flag,
11332 bool def_optional) {
11333 // str and flag must not be NULL.
11334 if (str == NULL || flag == NULL) return NULL;
11335
11336 // The flag must start with "--gmock_".
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011337 const std::string flag_str = std::string("--gmock_") + flag;
Keir Mierle8ebb0732012-04-30 23:09:08 -070011338 const size_t flag_len = flag_str.length();
11339 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
11340
11341 // Skips the flag name.
11342 const char* flag_end = str + flag_len;
11343
11344 // When def_optional is true, it's OK to not have a "=value" part.
11345 if (def_optional && (flag_end[0] == '\0')) {
11346 return flag_end;
11347 }
11348
11349 // If def_optional is true and there are more characters after the
11350 // flag name, or if def_optional is false, there must be a '=' after
11351 // the flag name.
11352 if (flag_end[0] != '=') return NULL;
11353
11354 // Returns the string after "=".
11355 return flag_end + 1;
11356}
11357
11358// Parses a string for a Google Mock bool flag, in the form of
11359// "--gmock_flag=value".
11360//
11361// On success, stores the value of the flag in *value, and returns
11362// true. On failure, returns false without changing *value.
11363static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
11364 bool* value) {
11365 // Gets the value of the flag as a string.
11366 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
11367
11368 // Aborts if the parsing failed.
11369 if (value_str == NULL) return false;
11370
11371 // Converts the string value to a bool.
11372 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
11373 return true;
11374}
11375
11376// Parses a string for a Google Mock string flag, in the form of
11377// "--gmock_flag=value".
11378//
11379// On success, stores the value of the flag in *value, and returns
11380// true. On failure, returns false without changing *value.
11381static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011382 std::string* value) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011383 // Gets the value of the flag as a string.
11384 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
11385
11386 // Aborts if the parsing failed.
11387 if (value_str == NULL) return false;
11388
11389 // Sets *value to the value of the flag.
11390 *value = value_str;
11391 return true;
11392}
11393
11394// The internal implementation of InitGoogleMock().
11395//
11396// The type parameter CharType can be instantiated to either char or
11397// wchar_t.
11398template <typename CharType>
11399void InitGoogleMockImpl(int* argc, CharType** argv) {
11400 // Makes sure Google Test is initialized. InitGoogleTest() is
11401 // idempotent, so it's fine if the user has already called it.
11402 InitGoogleTest(argc, argv);
11403 if (*argc <= 0) return;
11404
11405 for (int i = 1; i != *argc; i++) {
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011406 const std::string arg_string = StreamableToString(argv[i]);
Keir Mierle8ebb0732012-04-30 23:09:08 -070011407 const char* const arg = arg_string.c_str();
11408
11409 // Do we see a Google Mock flag?
11410 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
11411 &GMOCK_FLAG(catch_leaked_mocks)) ||
11412 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
11413 // Yes. Shift the remainder of the argv list left by one. Note
11414 // that argv has (*argc + 1) elements, the last one always being
11415 // NULL. The following loop moves the trailing NULL element as
11416 // well.
11417 for (int j = i; j != *argc; j++) {
11418 argv[j] = argv[j + 1];
11419 }
11420
11421 // Decrements the argument count.
11422 (*argc)--;
11423
11424 // We also need to decrement the iterator as we just removed
11425 // an element.
11426 i--;
11427 }
11428 }
11429}
11430
11431} // namespace internal
11432
11433// Initializes Google Mock. This must be called before running the
11434// tests. In particular, it parses a command line for the flags that
11435// Google Mock recognizes. Whenever a Google Mock flag is seen, it is
11436// removed from argv, and *argc is decremented.
11437//
11438// No value is returned. Instead, the Google Mock flag variables are
11439// updated.
11440//
11441// Since Google Test is needed for Google Mock to work, this function
11442// also initializes Google Test and parses its flags, if that hasn't
11443// been done.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011444GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011445 internal::InitGoogleMockImpl(argc, argv);
11446}
11447
11448// This overloaded version can be used in Windows programs compiled in
11449// UNICODE mode.
Sameer Agarwal1ab7fde2013-07-08 10:03:49 -070011450GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070011451 internal::InitGoogleMockImpl(argc, argv);
11452}
11453
11454} // namespace testing