1 // Copyright 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 //
31 // The Google C++ Testing and Mocking Framework (Google Test)
32 //
33 // This header file defines the public API for Google Test.  It should be
34 // included by any test program that uses Google Test.
35 //
36 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
37 // leave some internal implementation details in this header file.
38 // They are clearly marked by comments like this:
39 //
40 //   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
41 //
42 // Such code is NOT meant to be used by a user directly, and is subject
43 // to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
44 // program!
45 //
46 // Acknowledgment: Google Test borrowed the idea of automatic test
47 // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
48 // easyUnit framework.
49 
50 // GOOGLETEST_CM0001 DO NOT DELETE
51 
52 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
53 #define GTEST_INCLUDE_GTEST_GTEST_H_
54 
55 #include <cstddef>
56 #include <limits>
57 #include <memory>
58 #include <ostream>
59 #include <type_traits>
60 #include <vector>
61 
62 #include "gtest/internal/gtest-internal.h"
63 #include "gtest/internal/gtest-string.h"
64 #include "gtest/gtest-death-test.h"
65 #include "gtest/gtest-matchers.h"
66 #include "gtest/gtest-message.h"
67 #include "gtest/gtest-param-test.h"
68 #include "gtest/gtest-printers.h"
69 #include "gtest/gtest_prod.h"
70 #include "gtest/gtest-test-part.h"
71 #include "gtest/gtest-typed-test.h"
72 
73 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
74 /* class A needs to have dll-interface to be used by clients of class B */)
75 
76 namespace testing {
77 
78 // Silence C4100 (unreferenced formal parameter) and 4805
79 // unsafe mix of type 'const int' and type 'const bool'
80 #ifdef _MSC_VER
81 # pragma warning(push)
82 # pragma warning(disable:4805)
83 # pragma warning(disable:4100)
84 #endif
85 
86 
87 // Declares the flags.
88 
89 // This flag temporary enables the disabled tests.
90 GTEST_DECLARE_bool_(also_run_disabled_tests);
91 
92 // This flag brings the debugger on an assertion failure.
93 GTEST_DECLARE_bool_(break_on_failure);
94 
95 // This flag controls whether Google Test catches all test-thrown exceptions
96 // and logs them as failures.
97 GTEST_DECLARE_bool_(catch_exceptions);
98 
99 // This flag enables using colors in terminal output. Available values are
100 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
101 // to let Google Test decide.
102 GTEST_DECLARE_string_(color);
103 
104 // This flag sets up the filter to select by name using a glob pattern
105 // the tests to run. If the filter is not given all tests are executed.
106 GTEST_DECLARE_string_(filter);
107 
108 // This flag controls whether Google Test installs a signal handler that dumps
109 // debugging information when fatal signals are raised.
110 GTEST_DECLARE_bool_(install_failure_signal_handler);
111 
112 // This flag causes the Google Test to list tests. None of the tests listed
113 // are actually run if the flag is provided.
114 GTEST_DECLARE_bool_(list_tests);
115 
116 // This flag controls whether Google Test emits a detailed XML report to a file
117 // in addition to its normal textual output.
118 GTEST_DECLARE_string_(output);
119 
120 // This flags control whether Google Test prints the elapsed time for each
121 // test.
122 GTEST_DECLARE_bool_(print_time);
123 
124 // This flags control whether Google Test prints UTF8 characters as text.
125 GTEST_DECLARE_bool_(print_utf8);
126 
127 // This flag specifies the random number seed.
128 GTEST_DECLARE_int32_(random_seed);
129 
130 // This flag sets how many times the tests are repeated. The default value
131 // is 1. If the value is -1 the tests are repeating forever.
132 GTEST_DECLARE_int32_(repeat);
133 
134 // This flag controls whether Google Test includes Google Test internal
135 // stack frames in failure stack traces.
136 GTEST_DECLARE_bool_(show_internal_stack_frames);
137 
138 // When this flag is specified, tests' order is randomized on every iteration.
139 GTEST_DECLARE_bool_(shuffle);
140 
141 // This flag specifies the maximum number of stack frames to be
142 // printed in a failure message.
143 GTEST_DECLARE_int32_(stack_trace_depth);
144 
145 // When this flag is specified, a failed assertion will throw an
146 // exception if exceptions are enabled, or exit the program with a
147 // non-zero code otherwise. For use with an external test framework.
148 GTEST_DECLARE_bool_(throw_on_failure);
149 
150 // When this flag is set with a "host:port" string, on supported
151 // platforms test results are streamed to the specified port on
152 // the specified host machine.
153 GTEST_DECLARE_string_(stream_result_to);
154 
155 #if GTEST_USE_OWN_FLAGFILE_FLAG_
156 GTEST_DECLARE_string_(flagfile);
157 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
158 
159 // The upper limit for valid stack trace depths.
160 const int kMaxStackTraceDepth = 100;
161 
162 namespace internal {
163 
164 class AssertHelper;
165 class DefaultGlobalTestPartResultReporter;
166 class ExecDeathTest;
167 class NoExecDeathTest;
168 class FinalSuccessChecker;
169 class GTestFlagSaver;
170 class StreamingListenerTest;
171 class TestResultAccessor;
172 class TestEventListenersAccessor;
173 class TestEventRepeater;
174 class UnitTestRecordPropertyTestHelper;
175 class WindowsDeathTest;
176 class FuchsiaDeathTest;
177 class UnitTestImpl* GetUnitTestImpl();
178 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
179                                     const std::string& message);
180 
181 }  // namespace internal
182 
183 // The friend relationship of some of these classes is cyclic.
184 // If we don't forward declare them the compiler might confuse the classes
185 // in friendship clauses with same named classes on the scope.
186 class Test;
187 class TestSuite;
188 
189 // Old API is still available but deprecated
190 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
191 using TestCase = TestSuite;
192 #endif
193 class TestInfo;
194 class UnitTest;
195 
196 // A class for indicating whether an assertion was successful.  When
197 // the assertion wasn't successful, the AssertionResult object
198 // remembers a non-empty message that describes how it failed.
199 //
200 // To create an instance of this class, use one of the factory functions
201 // (AssertionSuccess() and AssertionFailure()).
202 //
203 // This class is useful for two purposes:
204 //   1. Defining predicate functions to be used with Boolean test assertions
205 //      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
206 //   2. Defining predicate-format functions to be
207 //      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
208 //
209 // For example, if you define IsEven predicate:
210 //
211 //   testing::AssertionResult IsEven(int n) {
212 //     if ((n % 2) == 0)
213 //       return testing::AssertionSuccess();
214 //     else
215 //       return testing::AssertionFailure() << n << " is odd";
216 //   }
217 //
218 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
219 // will print the message
220 //
221 //   Value of: IsEven(Fib(5))
222 //     Actual: false (5 is odd)
223 //   Expected: true
224 //
225 // instead of a more opaque
226 //
227 //   Value of: IsEven(Fib(5))
228 //     Actual: false
229 //   Expected: true
230 //
231 // in case IsEven is a simple Boolean predicate.
232 //
233 // If you expect your predicate to be reused and want to support informative
234 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
235 // about half as often as positive ones in our tests), supply messages for
236 // both success and failure cases:
237 //
238 //   testing::AssertionResult IsEven(int n) {
239 //     if ((n % 2) == 0)
240 //       return testing::AssertionSuccess() << n << " is even";
241 //     else
242 //       return testing::AssertionFailure() << n << " is odd";
243 //   }
244 //
245 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
246 //
247 //   Value of: IsEven(Fib(6))
248 //     Actual: true (8 is even)
249 //   Expected: false
250 //
251 // NB: Predicates that support negative Boolean assertions have reduced
252 // performance in positive ones so be careful not to use them in tests
253 // that have lots (tens of thousands) of positive Boolean assertions.
254 //
255 // To use this class with EXPECT_PRED_FORMAT assertions such as:
256 //
257 //   // Verifies that Foo() returns an even number.
258 //   EXPECT_PRED_FORMAT1(IsEven, Foo());
259 //
260 // you need to define:
261 //
262 //   testing::AssertionResult IsEven(const char* expr, int n) {
263 //     if ((n % 2) == 0)
264 //       return testing::AssertionSuccess();
265 //     else
266 //       return testing::AssertionFailure()
267 //         << "Expected: " << expr << " is even\n  Actual: it's " << n;
268 //   }
269 //
270 // If Foo() returns 5, you will see the following message:
271 //
272 //   Expected: Foo() is even
273 //     Actual: it's 5
274 //
275 class GTEST_API_ AssertionResult {
276  public:
277   // Copy constructor.
278   // Used in EXPECT_TRUE/FALSE(assertion_result).
279   AssertionResult(const AssertionResult& other);
280 
281 #if defined(_MSC_VER) && _MSC_VER < 1910
282   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
283 #endif
284 
285   // Used in the EXPECT_TRUE/FALSE(bool_expression).
286   //
287   // T must be contextually convertible to bool.
288   //
289   // The second parameter prevents this overload from being considered if
290   // the argument is implicitly convertible to AssertionResult. In that case
291   // we want AssertionResult's copy constructor to be used.
292   template <typename T>
293   explicit AssertionResult(
294       const T& success,
295       typename std::enable_if<
296           !std::is_convertible<T, AssertionResult>::value>::type*
297       /*enabler*/
298       = nullptr)
success_(success)299       : success_(success) {}
300 
301 #if defined(_MSC_VER) && _MSC_VER < 1910
GTEST_DISABLE_MSC_WARNINGS_POP_()302   GTEST_DISABLE_MSC_WARNINGS_POP_()
303 #endif
304 
305   // Assignment operator.
306   AssertionResult& operator=(AssertionResult other) {
307     swap(other);
308     return *this;
309   }
310 
311   // Returns true if and only if the assertion succeeded.
312   operator bool() const { return success_; }  // NOLINT
313 
314   // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
315   AssertionResult operator!() const;
316 
317   // Returns the text streamed into this AssertionResult. Test assertions
318   // use it when they fail (i.e., the predicate's outcome doesn't match the
319   // assertion's expectation). When nothing has been streamed into the
320   // object, returns an empty string.
message()321   const char* message() const {
322     return message_.get() != nullptr ? message_->c_str() : "";
323   }
324   // Deprecated; please use message() instead.
failure_message()325   const char* failure_message() const { return message(); }
326 
327   // Streams a custom failure message into this object.
328   template <typename T> AssertionResult& operator<<(const T& value) {
329     AppendMessage(Message() << value);
330     return *this;
331   }
332 
333   // Allows streaming basic output manipulators such as endl or flush into
334   // this object.
335   AssertionResult& operator<<(
336       ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
337     AppendMessage(Message() << basic_manipulator);
338     return *this;
339   }
340 
341  private:
342   // Appends the contents of message to message_.
AppendMessage(const Message & a_message)343   void AppendMessage(const Message& a_message) {
344     if (message_.get() == nullptr) message_.reset(new ::std::string);
345     message_->append(a_message.GetString().c_str());
346   }
347 
348   // Swap the contents of this AssertionResult with other.
349   void swap(AssertionResult& other);
350 
351   // Stores result of the assertion predicate.
352   bool success_;
353   // Stores the message describing the condition in case the expectation
354   // construct is not satisfied with the predicate's outcome.
355   // Referenced via a pointer to avoid taking too much stack frame space
356   // with test assertions.
357   std::unique_ptr< ::std::string> message_;
358 };
359 
360 // Makes a successful assertion result.
361 GTEST_API_ AssertionResult AssertionSuccess();
362 
363 // Makes a failed assertion result.
364 GTEST_API_ AssertionResult AssertionFailure();
365 
366 // Makes a failed assertion result with the given failure message.
367 // Deprecated; use AssertionFailure() << msg.
368 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
369 
370 }  // namespace testing
371 
372 // Includes the auto-generated header that implements a family of generic
373 // predicate assertion macros. This include comes late because it relies on
374 // APIs declared above.
375 #include "gtest/gtest_pred_impl.h"
376 
377 namespace testing {
378 
379 // The abstract class that all tests inherit from.
380 //
381 // In Google Test, a unit test program contains one or many TestSuites, and
382 // each TestSuite contains one or many Tests.
383 //
384 // When you define a test using the TEST macro, you don't need to
385 // explicitly derive from Test - the TEST macro automatically does
386 // this for you.
387 //
388 // The only time you derive from Test is when defining a test fixture
389 // to be used in a TEST_F.  For example:
390 //
391 //   class FooTest : public testing::Test {
392 //    protected:
393 //     void SetUp() override { ... }
394 //     void TearDown() override { ... }
395 //     ...
396 //   };
397 //
398 //   TEST_F(FooTest, Bar) { ... }
399 //   TEST_F(FooTest, Baz) { ... }
400 //
401 // Test is not copyable.
402 class GTEST_API_ Test {
403  public:
404   friend class TestInfo;
405 
406   // The d'tor is virtual as we intend to inherit from Test.
407   virtual ~Test();
408 
409   // Sets up the stuff shared by all tests in this test case.
410   //
411   // Google Test will call Foo::SetUpTestSuite() before running the first
412   // test in test case Foo.  Hence a sub-class can define its own
413   // SetUpTestSuite() method to shadow the one defined in the super
414   // class.
415   // Failures that happen during SetUpTestSuite are logged but otherwise
416   // ignored.
SetUpTestSuite()417   static void SetUpTestSuite() {}
418 
419   // Tears down the stuff shared by all tests in this test suite.
420   //
421   // Google Test will call Foo::TearDownTestSuite() after running the last
422   // test in test case Foo.  Hence a sub-class can define its own
423   // TearDownTestSuite() method to shadow the one defined in the super
424   // class.
425   // Failures that happen during TearDownTestSuite are logged but otherwise
426   // ignored.
TearDownTestSuite()427   static void TearDownTestSuite() {}
428 
429   // Legacy API is deprecated but still available
430 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
TearDownTestCase()431   static void TearDownTestCase() {}
SetUpTestCase()432   static void SetUpTestCase() {}
433 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
434 
435   // Returns true if and only if the current test has a fatal failure.
436   static bool HasFatalFailure();
437 
438   // Returns true if and only if the current test has a non-fatal failure.
439   static bool HasNonfatalFailure();
440 
441   // Returns true if and only if the current test was skipped.
442   static bool IsSkipped();
443 
444   // Returns true if and only if the current test has a (either fatal or
445   // non-fatal) failure.
HasFailure()446   static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
447 
448   // Logs a property for the current test, test suite, or for the entire
449   // invocation of the test program when used outside of the context of a
450   // test suite.  Only the last value for a given key is remembered.  These
451   // are public static so they can be called from utility functions that are
452   // not members of the test fixture.  Calls to RecordProperty made during
453   // lifespan of the test (from the moment its constructor starts to the
454   // moment its destructor finishes) will be output in XML as attributes of
455   // the <testcase> element.  Properties recorded from fixture's
456   // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
457   // corresponding <testsuite> element.  Calls to RecordProperty made in the
458   // global context (before or after invocation of RUN_ALL_TESTS and from
459   // SetUp/TearDown method of Environment objects registered with Google
460   // Test) will be output as attributes of the <testsuites> element.
461   static void RecordProperty(const std::string& key, const std::string& value);
462   static void RecordProperty(const std::string& key, int value);
463 
464  protected:
465   // Creates a Test object.
466   Test();
467 
468   // Sets up the test fixture.
469   virtual void SetUp();
470 
471   // Tears down the test fixture.
472   virtual void TearDown();
473 
474  private:
475   // Returns true if and only if the current test has the same fixture class
476   // as the first test in the current test suite.
477   static bool HasSameFixtureClass();
478 
479   // Runs the test after the test fixture has been set up.
480   //
481   // A sub-class must implement this to define the test logic.
482   //
483   // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
484   // Instead, use the TEST or TEST_F macro.
485   virtual void TestBody() = 0;
486 
487   // Sets up, executes, and tears down the test.
488   void Run();
489 
490   // Deletes self.  We deliberately pick an unusual name for this
491   // internal method to avoid clashing with names used in user TESTs.
DeleteSelf_()492   void DeleteSelf_() { delete this; }
493 
494   const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
495 
496   // Often a user misspells SetUp() as Setup() and spends a long time
497   // wondering why it is never called by Google Test.  The declaration of
498   // the following method is solely for catching such an error at
499   // compile time:
500   //
501   //   - The return type is deliberately chosen to be not void, so it
502   //   will be a conflict if void Setup() is declared in the user's
503   //   test fixture.
504   //
505   //   - This method is private, so it will be another compiler error
506   //   if the method is called from the user's test fixture.
507   //
508   // DO NOT OVERRIDE THIS FUNCTION.
509   //
510   // If you see an error about overriding the following function or
511   // about it being private, you have mis-spelled SetUp() as Setup().
512   struct Setup_should_be_spelled_SetUp {};
Setup()513   virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
514 
515   // We disallow copying Tests.
516   GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
517 };
518 
519 typedef internal::TimeInMillis TimeInMillis;
520 
521 // A copyable object representing a user specified test property which can be
522 // output as a key/value string pair.
523 //
524 // Don't inherit from TestProperty as its destructor is not virtual.
525 class TestProperty {
526  public:
527   // C'tor.  TestProperty does NOT have a default constructor.
528   // Always use this constructor (with parameters) to create a
529   // TestProperty object.
TestProperty(const std::string & a_key,const std::string & a_value)530   TestProperty(const std::string& a_key, const std::string& a_value) :
531     key_(a_key), value_(a_value) {
532   }
533 
534   // Gets the user supplied key.
key()535   const char* key() const {
536     return key_.c_str();
537   }
538 
539   // Gets the user supplied value.
value()540   const char* value() const {
541     return value_.c_str();
542   }
543 
544   // Sets a new value, overriding the one supplied in the constructor.
SetValue(const std::string & new_value)545   void SetValue(const std::string& new_value) {
546     value_ = new_value;
547   }
548 
549  private:
550   // The key supplied by the user.
551   std::string key_;
552   // The value supplied by the user.
553   std::string value_;
554 };
555 
556 // The result of a single Test.  This includes a list of
557 // TestPartResults, a list of TestProperties, a count of how many
558 // death tests there are in the Test, and how much time it took to run
559 // the Test.
560 //
561 // TestResult is not copyable.
562 class GTEST_API_ TestResult {
563  public:
564   // Creates an empty TestResult.
565   TestResult();
566 
567   // D'tor.  Do not inherit from TestResult.
568   ~TestResult();
569 
570   // Gets the number of all test parts.  This is the sum of the number
571   // of successful test parts and the number of failed test parts.
572   int total_part_count() const;
573 
574   // Returns the number of the test properties.
575   int test_property_count() const;
576 
577   // Returns true if and only if the test passed (i.e. no test part failed).
Passed()578   bool Passed() const { return !Skipped() && !Failed(); }
579 
580   // Returns true if and only if the test was skipped.
581   bool Skipped() const;
582 
583   // Returns true if and only if the test failed.
584   bool Failed() const;
585 
586   // Returns true if and only if the test fatally failed.
587   bool HasFatalFailure() const;
588 
589   // Returns true if and only if the test has a non-fatal failure.
590   bool HasNonfatalFailure() const;
591 
592   // Returns the elapsed time, in milliseconds.
elapsed_time()593   TimeInMillis elapsed_time() const { return elapsed_time_; }
594 
595   // Gets the time of the test case start, in ms from the start of the
596   // UNIX epoch.
start_timestamp()597   TimeInMillis start_timestamp() const { return start_timestamp_; }
598 
599   // Returns the i-th test part result among all the results. i can range from 0
600   // to total_part_count() - 1. If i is not in that range, aborts the program.
601   const TestPartResult& GetTestPartResult(int i) const;
602 
603   // Returns the i-th test property. i can range from 0 to
604   // test_property_count() - 1. If i is not in that range, aborts the
605   // program.
606   const TestProperty& GetTestProperty(int i) const;
607 
608  private:
609   friend class TestInfo;
610   friend class TestSuite;
611   friend class UnitTest;
612   friend class internal::DefaultGlobalTestPartResultReporter;
613   friend class internal::ExecDeathTest;
614   friend class internal::TestResultAccessor;
615   friend class internal::UnitTestImpl;
616   friend class internal::WindowsDeathTest;
617   friend class internal::FuchsiaDeathTest;
618 
619   // Gets the vector of TestPartResults.
test_part_results()620   const std::vector<TestPartResult>& test_part_results() const {
621     return test_part_results_;
622   }
623 
624   // Gets the vector of TestProperties.
test_properties()625   const std::vector<TestProperty>& test_properties() const {
626     return test_properties_;
627   }
628 
629   // Sets the start time.
set_start_timestamp(TimeInMillis start)630   void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
631 
632   // Sets the elapsed time.
set_elapsed_time(TimeInMillis elapsed)633   void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
634 
635   // Adds a test property to the list. The property is validated and may add
636   // a non-fatal failure if invalid (e.g., if it conflicts with reserved
637   // key names). If a property is already recorded for the same key, the
638   // value will be updated, rather than storing multiple values for the same
639   // key.  xml_element specifies the element for which the property is being
640   // recorded and is used for validation.
641   void RecordProperty(const std::string& xml_element,
642                       const TestProperty& test_property);
643 
644   // Adds a failure if the key is a reserved attribute of Google Test
645   // testsuite tags.  Returns true if the property is valid.
646   // FIXME: Validate attribute names are legal and human readable.
647   static bool ValidateTestProperty(const std::string& xml_element,
648                                    const TestProperty& test_property);
649 
650   // Adds a test part result to the list.
651   void AddTestPartResult(const TestPartResult& test_part_result);
652 
653   // Returns the death test count.
death_test_count()654   int death_test_count() const { return death_test_count_; }
655 
656   // Increments the death test count, returning the new count.
increment_death_test_count()657   int increment_death_test_count() { return ++death_test_count_; }
658 
659   // Clears the test part results.
660   void ClearTestPartResults();
661 
662   // Clears the object.
663   void Clear();
664 
665   // Protects mutable state of the property vector and of owned
666   // properties, whose values may be updated.
667   internal::Mutex test_properites_mutex_;
668 
669   // The vector of TestPartResults
670   std::vector<TestPartResult> test_part_results_;
671   // The vector of TestProperties
672   std::vector<TestProperty> test_properties_;
673   // Running count of death tests.
674   int death_test_count_;
675   // The start time, in milliseconds since UNIX Epoch.
676   TimeInMillis start_timestamp_;
677   // The elapsed time, in milliseconds.
678   TimeInMillis elapsed_time_;
679 
680   // We disallow copying TestResult.
681   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
682 };  // class TestResult
683 
684 // A TestInfo object stores the following information about a test:
685 //
686 //   Test suite name
687 //   Test name
688 //   Whether the test should be run
689 //   A function pointer that creates the test object when invoked
690 //   Test result
691 //
692 // The constructor of TestInfo registers itself with the UnitTest
693 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
694 // run.
695 class GTEST_API_ TestInfo {
696  public:
697   // Destructs a TestInfo object.  This function is not virtual, so
698   // don't inherit from TestInfo.
699   ~TestInfo();
700 
701   // Returns the test suite name.
test_suite_name()702   const char* test_suite_name() const { return test_suite_name_.c_str(); }
703 
704 // Legacy API is deprecated but still available
705 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
test_case_name()706   const char* test_case_name() const { return test_suite_name(); }
707 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
708 
709   // Returns the test name.
name()710   const char* name() const { return name_.c_str(); }
711 
712   // Returns the name of the parameter type, or NULL if this is not a typed
713   // or a type-parameterized test.
type_param()714   const char* type_param() const {
715     if (type_param_.get() != nullptr) return type_param_->c_str();
716     return nullptr;
717   }
718 
719   // Returns the text representation of the value parameter, or NULL if this
720   // is not a value-parameterized test.
value_param()721   const char* value_param() const {
722     if (value_param_.get() != nullptr) return value_param_->c_str();
723     return nullptr;
724   }
725 
726   // Returns the file name where this test is defined.
file()727   const char* file() const { return location_.file.c_str(); }
728 
729   // Returns the line where this test is defined.
line()730   int line() const { return location_.line; }
731 
732   // Return true if this test should not be run because it's in another shard.
is_in_another_shard()733   bool is_in_another_shard() const { return is_in_another_shard_; }
734 
735   // Returns true if this test should run, that is if the test is not
736   // disabled (or it is disabled but the also_run_disabled_tests flag has
737   // been specified) and its full name matches the user-specified filter.
738   //
739   // Google Test allows the user to filter the tests by their full names.
740   // The full name of a test Bar in test suite Foo is defined as
741   // "Foo.Bar".  Only the tests that match the filter will run.
742   //
743   // A filter is a colon-separated list of glob (not regex) patterns,
744   // optionally followed by a '-' and a colon-separated list of
745   // negative patterns (tests to exclude).  A test is run if it
746   // matches one of the positive patterns and does not match any of
747   // the negative patterns.
748   //
749   // For example, *A*:Foo.* is a filter that matches any string that
750   // contains the character 'A' or starts with "Foo.".
should_run()751   bool should_run() const { return should_run_; }
752 
753   // Returns true if and only if this test will appear in the XML report.
is_reportable()754   bool is_reportable() const {
755     // The XML report includes tests matching the filter, excluding those
756     // run in other shards.
757     return matches_filter_ && !is_in_another_shard_;
758   }
759 
760   // Returns the result of the test.
result()761   const TestResult* result() const { return &result_; }
762 
763  private:
764 #if GTEST_HAS_DEATH_TEST
765   friend class internal::DefaultDeathTestFactory;
766 #endif  // GTEST_HAS_DEATH_TEST
767   friend class Test;
768   friend class TestSuite;
769   friend class internal::UnitTestImpl;
770   friend class internal::StreamingListenerTest;
771   friend TestInfo* internal::MakeAndRegisterTestInfo(
772       const char* test_suite_name, const char* name, const char* type_param,
773       const char* value_param, internal::CodeLocation code_location,
774       internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
775       internal::TearDownTestSuiteFunc tear_down_tc,
776       internal::TestFactoryBase* factory);
777 
778   // Constructs a TestInfo object. The newly constructed instance assumes
779   // ownership of the factory object.
780   TestInfo(const std::string& test_suite_name, const std::string& name,
781            const char* a_type_param,   // NULL if not a type-parameterized test
782            const char* a_value_param,  // NULL if not a value-parameterized test
783            internal::CodeLocation a_code_location,
784            internal::TypeId fixture_class_id,
785            internal::TestFactoryBase* factory);
786 
787   // Increments the number of death tests encountered in this test so
788   // far.
increment_death_test_count()789   int increment_death_test_count() {
790     return result_.increment_death_test_count();
791   }
792 
793   // Creates the test object, runs it, records its result, and then
794   // deletes it.
795   void Run();
796 
ClearTestResult(TestInfo * test_info)797   static void ClearTestResult(TestInfo* test_info) {
798     test_info->result_.Clear();
799   }
800 
801   // These fields are immutable properties of the test.
802   const std::string test_suite_name_;    // test suite name
803   const std::string name_;               // Test name
804   // Name of the parameter type, or NULL if this is not a typed or a
805   // type-parameterized test.
806   const std::unique_ptr<const ::std::string> type_param_;
807   // Text representation of the value parameter, or NULL if this is not a
808   // value-parameterized test.
809   const std::unique_ptr<const ::std::string> value_param_;
810   internal::CodeLocation location_;
811   const internal::TypeId fixture_class_id_;  // ID of the test fixture class
812   bool should_run_;           // True if and only if this test should run
813   bool is_disabled_;          // True if and only if this test is disabled
814   bool matches_filter_;       // True if this test matches the
815                               // user-specified filter.
816   bool is_in_another_shard_;  // Will be run in another shard.
817   internal::TestFactoryBase* const factory_;  // The factory that creates
818                                               // the test object
819 
820   // This field is mutable and needs to be reset before running the
821   // test for the second time.
822   TestResult result_;
823 
824   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
825 };
826 
827 // A test suite, which consists of a vector of TestInfos.
828 //
829 // TestSuite is not copyable.
830 class GTEST_API_ TestSuite {
831  public:
832   // Creates a TestSuite with the given name.
833   //
834   // TestSuite does NOT have a default constructor.  Always use this
835   // constructor to create a TestSuite object.
836   //
837   // Arguments:
838   //
839   //   name:         name of the test suite
840   //   a_type_param: the name of the test's type parameter, or NULL if
841   //                 this is not a type-parameterized test.
842   //   set_up_tc:    pointer to the function that sets up the test suite
843   //   tear_down_tc: pointer to the function that tears down the test suite
844   TestSuite(const char* name, const char* a_type_param,
845             internal::SetUpTestSuiteFunc set_up_tc,
846             internal::TearDownTestSuiteFunc tear_down_tc);
847 
848   // Destructor of TestSuite.
849   virtual ~TestSuite();
850 
851   // Gets the name of the TestSuite.
name()852   const char* name() const { return name_.c_str(); }
853 
854   // Returns the name of the parameter type, or NULL if this is not a
855   // type-parameterized test suite.
type_param()856   const char* type_param() const {
857     if (type_param_.get() != nullptr) return type_param_->c_str();
858     return nullptr;
859   }
860 
861   // Returns true if any test in this test suite should run.
should_run()862   bool should_run() const { return should_run_; }
863 
864   // Gets the number of successful tests in this test suite.
865   int successful_test_count() const;
866 
867   // Gets the number of skipped tests in this test suite.
868   int skipped_test_count() const;
869 
870   // Gets the number of failed tests in this test suite.
871   int failed_test_count() const;
872 
873   // Gets the number of disabled tests that will be reported in the XML report.
874   int reportable_disabled_test_count() const;
875 
876   // Gets the number of disabled tests in this test suite.
877   int disabled_test_count() const;
878 
879   // Gets the number of tests to be printed in the XML report.
880   int reportable_test_count() const;
881 
882   // Get the number of tests in this test suite that should run.
883   int test_to_run_count() const;
884 
885   // Gets the number of all tests in this test suite.
886   int total_test_count() const;
887 
888   // Returns true if and only if the test suite passed.
Passed()889   bool Passed() const { return !Failed(); }
890 
891   // Returns true if and only if the test suite failed.
Failed()892   bool Failed() const { return failed_test_count() > 0; }
893 
894   // Returns the elapsed time, in milliseconds.
elapsed_time()895   TimeInMillis elapsed_time() const { return elapsed_time_; }
896 
897   // Gets the time of the test suite start, in ms from the start of the
898   // UNIX epoch.
start_timestamp()899   TimeInMillis start_timestamp() const { return start_timestamp_; }
900 
901   // Returns the i-th test among all the tests. i can range from 0 to
902   // total_test_count() - 1. If i is not in that range, returns NULL.
903   const TestInfo* GetTestInfo(int i) const;
904 
905   // Returns the TestResult that holds test properties recorded during
906   // execution of SetUpTestSuite and TearDownTestSuite.
ad_hoc_test_result()907   const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
908 
909  private:
910   friend class Test;
911   friend class internal::UnitTestImpl;
912 
913   // Gets the (mutable) vector of TestInfos in this TestSuite.
test_info_list()914   std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
915 
916   // Gets the (immutable) vector of TestInfos in this TestSuite.
test_info_list()917   const std::vector<TestInfo*>& test_info_list() const {
918     return test_info_list_;
919   }
920 
921   // Returns the i-th test among all the tests. i can range from 0 to
922   // total_test_count() - 1. If i is not in that range, returns NULL.
923   TestInfo* GetMutableTestInfo(int i);
924 
925   // Sets the should_run member.
set_should_run(bool should)926   void set_should_run(bool should) { should_run_ = should; }
927 
928   // Adds a TestInfo to this test suite.  Will delete the TestInfo upon
929   // destruction of the TestSuite object.
930   void AddTestInfo(TestInfo * test_info);
931 
932   // Clears the results of all tests in this test suite.
933   void ClearResult();
934 
935   // Clears the results of all tests in the given test suite.
ClearTestSuiteResult(TestSuite * test_suite)936   static void ClearTestSuiteResult(TestSuite* test_suite) {
937     test_suite->ClearResult();
938   }
939 
940   // Runs every test in this TestSuite.
941   void Run();
942 
943   // Runs SetUpTestSuite() for this TestSuite.  This wrapper is needed
944   // for catching exceptions thrown from SetUpTestSuite().
RunSetUpTestSuite()945   void RunSetUpTestSuite() {
946     if (set_up_tc_ != nullptr) {
947       (*set_up_tc_)();
948     }
949   }
950 
951   // Runs TearDownTestSuite() for this TestSuite.  This wrapper is
952   // needed for catching exceptions thrown from TearDownTestSuite().
RunTearDownTestSuite()953   void RunTearDownTestSuite() {
954     if (tear_down_tc_ != nullptr) {
955       (*tear_down_tc_)();
956     }
957   }
958 
959   // Returns true if and only if test passed.
TestPassed(const TestInfo * test_info)960   static bool TestPassed(const TestInfo* test_info) {
961     return test_info->should_run() && test_info->result()->Passed();
962   }
963 
964   // Returns true if and only if test skipped.
TestSkipped(const TestInfo * test_info)965   static bool TestSkipped(const TestInfo* test_info) {
966     return test_info->should_run() && test_info->result()->Skipped();
967   }
968 
969   // Returns true if and only if test failed.
TestFailed(const TestInfo * test_info)970   static bool TestFailed(const TestInfo* test_info) {
971     return test_info->should_run() && test_info->result()->Failed();
972   }
973 
974   // Returns true if and only if the test is disabled and will be reported in
975   // the XML report.
TestReportableDisabled(const TestInfo * test_info)976   static bool TestReportableDisabled(const TestInfo* test_info) {
977     return test_info->is_reportable() && test_info->is_disabled_;
978   }
979 
980   // Returns true if and only if test is disabled.
TestDisabled(const TestInfo * test_info)981   static bool TestDisabled(const TestInfo* test_info) {
982     return test_info->is_disabled_;
983   }
984 
985   // Returns true if and only if this test will appear in the XML report.
TestReportable(const TestInfo * test_info)986   static bool TestReportable(const TestInfo* test_info) {
987     return test_info->is_reportable();
988   }
989 
990   // Returns true if the given test should run.
ShouldRunTest(const TestInfo * test_info)991   static bool ShouldRunTest(const TestInfo* test_info) {
992     return test_info->should_run();
993   }
994 
995   // Shuffles the tests in this test suite.
996   void ShuffleTests(internal::Random* random);
997 
998   // Restores the test order to before the first shuffle.
999   void UnshuffleTests();
1000 
1001   // Name of the test suite.
1002   std::string name_;
1003   // Name of the parameter type, or NULL if this is not a typed or a
1004   // type-parameterized test.
1005   const std::unique_ptr<const ::std::string> type_param_;
1006   // The vector of TestInfos in their original order.  It owns the
1007   // elements in the vector.
1008   std::vector<TestInfo*> test_info_list_;
1009   // Provides a level of indirection for the test list to allow easy
1010   // shuffling and restoring the test order.  The i-th element in this
1011   // vector is the index of the i-th test in the shuffled test list.
1012   std::vector<int> test_indices_;
1013   // Pointer to the function that sets up the test suite.
1014   internal::SetUpTestSuiteFunc set_up_tc_;
1015   // Pointer to the function that tears down the test suite.
1016   internal::TearDownTestSuiteFunc tear_down_tc_;
1017   // True if and only if any test in this test suite should run.
1018   bool should_run_;
1019   // The start time, in milliseconds since UNIX Epoch.
1020   TimeInMillis start_timestamp_;
1021   // Elapsed time, in milliseconds.
1022   TimeInMillis elapsed_time_;
1023   // Holds test properties recorded during execution of SetUpTestSuite and
1024   // TearDownTestSuite.
1025   TestResult ad_hoc_test_result_;
1026 
1027   // We disallow copying TestSuites.
1028   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
1029 };
1030 
1031 // An Environment object is capable of setting up and tearing down an
1032 // environment.  You should subclass this to define your own
1033 // environment(s).
1034 //
1035 // An Environment object does the set-up and tear-down in virtual
1036 // methods SetUp() and TearDown() instead of the constructor and the
1037 // destructor, as:
1038 //
1039 //   1. You cannot safely throw from a destructor.  This is a problem
1040 //      as in some cases Google Test is used where exceptions are enabled, and
1041 //      we may want to implement ASSERT_* using exceptions where they are
1042 //      available.
1043 //   2. You cannot use ASSERT_* directly in a constructor or
1044 //      destructor.
1045 class Environment {
1046  public:
1047   // The d'tor is virtual as we need to subclass Environment.
~Environment()1048   virtual ~Environment() {}
1049 
1050   // Override this to define how to set up the environment.
SetUp()1051   virtual void SetUp() {}
1052 
1053   // Override this to define how to tear down the environment.
TearDown()1054   virtual void TearDown() {}
1055  private:
1056   // If you see an error about overriding the following function or
1057   // about it being private, you have mis-spelled SetUp() as Setup().
1058   struct Setup_should_be_spelled_SetUp {};
Setup()1059   virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
1060 };
1061 
1062 #if GTEST_HAS_EXCEPTIONS
1063 
1064 // Exception which can be thrown from TestEventListener::OnTestPartResult.
1065 class GTEST_API_ AssertionException
1066     : public internal::GoogleTestFailureException {
1067  public:
AssertionException(const TestPartResult & result)1068   explicit AssertionException(const TestPartResult& result)
1069       : GoogleTestFailureException(result) {}
1070 };
1071 
1072 #endif  // GTEST_HAS_EXCEPTIONS
1073 
1074 // The interface for tracing execution of tests. The methods are organized in
1075 // the order the corresponding events are fired.
1076 class TestEventListener {
1077  public:
~TestEventListener()1078   virtual ~TestEventListener() {}
1079 
1080   // Fired before any test activity starts.
1081   virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
1082 
1083   // Fired before each iteration of tests starts.  There may be more than
1084   // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
1085   // index, starting from 0.
1086   virtual void OnTestIterationStart(const UnitTest& unit_test,
1087                                     int iteration) = 0;
1088 
1089   // Fired before environment set-up for each iteration of tests starts.
1090   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
1091 
1092   // Fired after environment set-up for each iteration of tests ends.
1093   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
1094 
1095   // Fired before the test suite starts.
OnTestSuiteStart(const TestSuite &)1096   virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
1097 
1098   //  Legacy API is deprecated but still available
1099 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseStart(const TestCase &)1100   virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
1101 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1102 
1103   // Fired before the test starts.
1104   virtual void OnTestStart(const TestInfo& test_info) = 0;
1105 
1106   // Fired after a failed assertion or a SUCCEED() invocation.
1107   // If you want to throw an exception from this function to skip to the next
1108   // TEST, it must be AssertionException defined above, or inherited from it.
1109   virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
1110 
1111   // Fired after the test ends.
1112   virtual void OnTestEnd(const TestInfo& test_info) = 0;
1113 
1114   // Fired after the test suite ends.
OnTestSuiteEnd(const TestSuite &)1115   virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
1116 
1117 //  Legacy API is deprecated but still available
1118 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseEnd(const TestCase &)1119   virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
1120 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1121 
1122   // Fired before environment tear-down for each iteration of tests starts.
1123   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
1124 
1125   // Fired after environment tear-down for each iteration of tests ends.
1126   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
1127 
1128   // Fired after each iteration of tests finishes.
1129   virtual void OnTestIterationEnd(const UnitTest& unit_test,
1130                                   int iteration) = 0;
1131 
1132   // Fired after all test activities have ended.
1133   virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
1134 };
1135 
1136 // The convenience class for users who need to override just one or two
1137 // methods and are not concerned that a possible change to a signature of
1138 // the methods they override will not be caught during the build.  For
1139 // comments about each method please see the definition of TestEventListener
1140 // above.
1141 class EmptyTestEventListener : public TestEventListener {
1142  public:
OnTestProgramStart(const UnitTest &)1143   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
OnTestIterationStart(const UnitTest &,int)1144   void OnTestIterationStart(const UnitTest& /*unit_test*/,
1145                             int /*iteration*/) override {}
OnEnvironmentsSetUpStart(const UnitTest &)1146   void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
OnEnvironmentsSetUpEnd(const UnitTest &)1147   void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
OnTestSuiteStart(const TestSuite &)1148   void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
1149 //  Legacy API is deprecated but still available
1150 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseStart(const TestCase &)1151   void OnTestCaseStart(const TestCase& /*test_case*/) override {}
1152 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1153 
OnTestStart(const TestInfo &)1154   void OnTestStart(const TestInfo& /*test_info*/) override {}
OnTestPartResult(const TestPartResult &)1155   void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
OnTestEnd(const TestInfo &)1156   void OnTestEnd(const TestInfo& /*test_info*/) override {}
OnTestSuiteEnd(const TestSuite &)1157   void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
1158 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseEnd(const TestCase &)1159   void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
1160 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1161 
OnEnvironmentsTearDownStart(const UnitTest &)1162   void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
OnEnvironmentsTearDownEnd(const UnitTest &)1163   void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
OnTestIterationEnd(const UnitTest &,int)1164   void OnTestIterationEnd(const UnitTest& /*unit_test*/,
1165                           int /*iteration*/) override {}
OnTestProgramEnd(const UnitTest &)1166   void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
1167 };
1168 
1169 // TestEventListeners lets users add listeners to track events in Google Test.
1170 class GTEST_API_ TestEventListeners {
1171  public:
1172   TestEventListeners();
1173   ~TestEventListeners();
1174 
1175   // Appends an event listener to the end of the list. Google Test assumes
1176   // the ownership of the listener (i.e. it will delete the listener when
1177   // the test program finishes).
1178   void Append(TestEventListener* listener);
1179 
1180   // Removes the given event listener from the list and returns it.  It then
1181   // becomes the caller's responsibility to delete the listener. Returns
1182   // NULL if the listener is not found in the list.
1183   TestEventListener* Release(TestEventListener* listener);
1184 
1185   // Returns the standard listener responsible for the default console
1186   // output.  Can be removed from the listeners list to shut down default
1187   // console output.  Note that removing this object from the listener list
1188   // with Release transfers its ownership to the caller and makes this
1189   // function return NULL the next time.
default_result_printer()1190   TestEventListener* default_result_printer() const {
1191     return default_result_printer_;
1192   }
1193 
1194   // Returns the standard listener responsible for the default XML output
1195   // controlled by the --gtest_output=xml flag.  Can be removed from the
1196   // listeners list by users who want to shut down the default XML output
1197   // controlled by this flag and substitute it with custom one.  Note that
1198   // removing this object from the listener list with Release transfers its
1199   // ownership to the caller and makes this function return NULL the next
1200   // time.
default_xml_generator()1201   TestEventListener* default_xml_generator() const {
1202     return default_xml_generator_;
1203   }
1204 
1205  private:
1206   friend class TestSuite;
1207   friend class TestInfo;
1208   friend class internal::DefaultGlobalTestPartResultReporter;
1209   friend class internal::NoExecDeathTest;
1210   friend class internal::TestEventListenersAccessor;
1211   friend class internal::UnitTestImpl;
1212 
1213   // Returns repeater that broadcasts the TestEventListener events to all
1214   // subscribers.
1215   TestEventListener* repeater();
1216 
1217   // Sets the default_result_printer attribute to the provided listener.
1218   // The listener is also added to the listener list and previous
1219   // default_result_printer is removed from it and deleted. The listener can
1220   // also be NULL in which case it will not be added to the list. Does
1221   // nothing if the previous and the current listener objects are the same.
1222   void SetDefaultResultPrinter(TestEventListener* listener);
1223 
1224   // Sets the default_xml_generator attribute to the provided listener.  The
1225   // listener is also added to the listener list and previous
1226   // default_xml_generator is removed from it and deleted. The listener can
1227   // also be NULL in which case it will not be added to the list. Does
1228   // nothing if the previous and the current listener objects are the same.
1229   void SetDefaultXmlGenerator(TestEventListener* listener);
1230 
1231   // Controls whether events will be forwarded by the repeater to the
1232   // listeners in the list.
1233   bool EventForwardingEnabled() const;
1234   void SuppressEventForwarding();
1235 
1236   // The actual list of listeners.
1237   internal::TestEventRepeater* repeater_;
1238   // Listener responsible for the standard result output.
1239   TestEventListener* default_result_printer_;
1240   // Listener responsible for the creation of the XML output file.
1241   TestEventListener* default_xml_generator_;
1242 
1243   // We disallow copying TestEventListeners.
1244   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1245 };
1246 
1247 // A UnitTest consists of a vector of TestSuites.
1248 //
1249 // This is a singleton class.  The only instance of UnitTest is
1250 // created when UnitTest::GetInstance() is first called.  This
1251 // instance is never deleted.
1252 //
1253 // UnitTest is not copyable.
1254 //
1255 // This class is thread-safe as long as the methods are called
1256 // according to their specification.
1257 class GTEST_API_ UnitTest {
1258  public:
1259   // Gets the singleton UnitTest object.  The first time this method
1260   // is called, a UnitTest object is constructed and returned.
1261   // Consecutive calls will return the same object.
1262   static UnitTest* GetInstance();
1263 
1264   // Runs all tests in this UnitTest object and prints the result.
1265   // Returns 0 if successful, or 1 otherwise.
1266   //
1267   // This method can only be called from the main thread.
1268   //
1269   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1270   int Run() GTEST_MUST_USE_RESULT_;
1271 
1272   // Returns the working directory when the first TEST() or TEST_F()
1273   // was executed.  The UnitTest object owns the string.
1274   const char* original_working_dir() const;
1275 
1276   // Returns the TestSuite object for the test that's currently running,
1277   // or NULL if no test is running.
1278   const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
1279 
1280 // Legacy API is still available but deprecated
1281 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1282   const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
1283 #endif
1284 
1285   // Returns the TestInfo object for the test that's currently running,
1286   // or NULL if no test is running.
1287   const TestInfo* current_test_info() const
1288       GTEST_LOCK_EXCLUDED_(mutex_);
1289 
1290   // Returns the random seed used at the start of the current test run.
1291   int random_seed() const;
1292 
1293   // Returns the ParameterizedTestSuiteRegistry object used to keep track of
1294   // value-parameterized tests and instantiate and register them.
1295   //
1296   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1297   internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
1298       GTEST_LOCK_EXCLUDED_(mutex_);
1299 
1300   // Gets the number of successful test suites.
1301   int successful_test_suite_count() const;
1302 
1303   // Gets the number of failed test suites.
1304   int failed_test_suite_count() const;
1305 
1306   // Gets the number of all test suites.
1307   int total_test_suite_count() const;
1308 
1309   // Gets the number of all test suites that contain at least one test
1310   // that should run.
1311   int test_suite_to_run_count() const;
1312 
1313   //  Legacy API is deprecated but still available
1314 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1315   int successful_test_case_count() const;
1316   int failed_test_case_count() const;
1317   int total_test_case_count() const;
1318   int test_case_to_run_count() const;
1319 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1320 
1321   // Gets the number of successful tests.
1322   int successful_test_count() const;
1323 
1324   // Gets the number of skipped tests.
1325   int skipped_test_count() const;
1326 
1327   // Gets the number of failed tests.
1328   int failed_test_count() const;
1329 
1330   // Gets the number of disabled tests that will be reported in the XML report.
1331   int reportable_disabled_test_count() const;
1332 
1333   // Gets the number of disabled tests.
1334   int disabled_test_count() const;
1335 
1336   // Gets the number of tests to be printed in the XML report.
1337   int reportable_test_count() const;
1338 
1339   // Gets the number of all tests.
1340   int total_test_count() const;
1341 
1342   // Gets the number of tests that should run.
1343   int test_to_run_count() const;
1344 
1345   // Gets the time of the test program start, in ms from the start of the
1346   // UNIX epoch.
1347   TimeInMillis start_timestamp() const;
1348 
1349   // Gets the elapsed time, in milliseconds.
1350   TimeInMillis elapsed_time() const;
1351 
1352   // Returns true if and only if the unit test passed (i.e. all test suites
1353   // passed).
1354   bool Passed() const;
1355 
1356   // Returns true if and only if the unit test failed (i.e. some test suite
1357   // failed or something outside of all tests failed).
1358   bool Failed() const;
1359 
1360   // Gets the i-th test suite among all the test suites. i can range from 0 to
1361   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
1362   const TestSuite* GetTestSuite(int i) const;
1363 
1364 //  Legacy API is deprecated but still available
1365 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1366   const TestCase* GetTestCase(int i) const;
1367 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1368 
1369   // Returns the TestResult containing information on test failures and
1370   // properties logged outside of individual test suites.
1371   const TestResult& ad_hoc_test_result() const;
1372 
1373   // Returns the list of event listeners that can be used to track events
1374   // inside Google Test.
1375   TestEventListeners& listeners();
1376 
1377  private:
1378   // Registers and returns a global test environment.  When a test
1379   // program is run, all global test environments will be set-up in
1380   // the order they were registered.  After all tests in the program
1381   // have finished, all global test environments will be torn-down in
1382   // the *reverse* order they were registered.
1383   //
1384   // The UnitTest object takes ownership of the given environment.
1385   //
1386   // This method can only be called from the main thread.
1387   Environment* AddEnvironment(Environment* env);
1388 
1389   // Adds a TestPartResult to the current TestResult object.  All
1390   // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
1391   // eventually call this to report their results.  The user code
1392   // should use the assertion macros instead of calling this directly.
1393   void AddTestPartResult(TestPartResult::Type result_type,
1394                          const char* file_name,
1395                          int line_number,
1396                          const std::string& message,
1397                          const std::string& os_stack_trace)
1398       GTEST_LOCK_EXCLUDED_(mutex_);
1399 
1400   // Adds a TestProperty to the current TestResult object when invoked from
1401   // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
1402   // from SetUpTestSuite or TearDownTestSuite, or to the global property set
1403   // when invoked elsewhere.  If the result already contains a property with
1404   // the same key, the value will be updated.
1405   void RecordProperty(const std::string& key, const std::string& value);
1406 
1407   // Gets the i-th test suite among all the test suites. i can range from 0 to
1408   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
1409   TestSuite* GetMutableTestSuite(int i);
1410 
1411   // Accessors for the implementation object.
impl()1412   internal::UnitTestImpl* impl() { return impl_; }
impl()1413   const internal::UnitTestImpl* impl() const { return impl_; }
1414 
1415   // These classes and functions are friends as they need to access private
1416   // members of UnitTest.
1417   friend class ScopedTrace;
1418   friend class Test;
1419   friend class internal::AssertHelper;
1420   friend class internal::StreamingListenerTest;
1421   friend class internal::UnitTestRecordPropertyTestHelper;
1422   friend Environment* AddGlobalTestEnvironment(Environment* env);
1423   friend internal::UnitTestImpl* internal::GetUnitTestImpl();
1424   friend void internal::ReportFailureInUnknownLocation(
1425       TestPartResult::Type result_type,
1426       const std::string& message);
1427 
1428   // Creates an empty UnitTest.
1429   UnitTest();
1430 
1431   // D'tor
1432   virtual ~UnitTest();
1433 
1434   // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
1435   // Google Test trace stack.
1436   void PushGTestTrace(const internal::TraceInfo& trace)
1437       GTEST_LOCK_EXCLUDED_(mutex_);
1438 
1439   // Pops a trace from the per-thread Google Test trace stack.
1440   void PopGTestTrace()
1441       GTEST_LOCK_EXCLUDED_(mutex_);
1442 
1443   // Protects mutable state in *impl_.  This is mutable as some const
1444   // methods need to lock it too.
1445   mutable internal::Mutex mutex_;
1446 
1447   // Opaque implementation object.  This field is never changed once
1448   // the object is constructed.  We don't mark it as const here, as
1449   // doing so will cause a warning in the constructor of UnitTest.
1450   // Mutable state in *impl_ is protected by mutex_.
1451   internal::UnitTestImpl* impl_;
1452 
1453   // We disallow copying UnitTest.
1454   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
1455 };
1456 
1457 // A convenient wrapper for adding an environment for the test
1458 // program.
1459 //
1460 // You should call this before RUN_ALL_TESTS() is called, probably in
1461 // main().  If you use gtest_main, you need to call this before main()
1462 // starts for it to take effect.  For example, you can define a global
1463 // variable like this:
1464 //
1465 //   testing::Environment* const foo_env =
1466 //       testing::AddGlobalTestEnvironment(new FooEnvironment);
1467 //
1468 // However, we strongly recommend you to write your own main() and
1469 // call AddGlobalTestEnvironment() there, as relying on initialization
1470 // of global variables makes the code harder to read and may cause
1471 // problems when you register multiple environments from different
1472 // translation units and the environments have dependencies among them
1473 // (remember that the compiler doesn't guarantee the order in which
1474 // global variables from different translation units are initialized).
AddGlobalTestEnvironment(Environment * env)1475 inline Environment* AddGlobalTestEnvironment(Environment* env) {
1476   return UnitTest::GetInstance()->AddEnvironment(env);
1477 }
1478 
1479 // Initializes Google Test.  This must be called before calling
1480 // RUN_ALL_TESTS().  In particular, it parses a command line for the
1481 // flags that Google Test recognizes.  Whenever a Google Test flag is
1482 // seen, it is removed from argv, and *argc is decremented.
1483 //
1484 // No value is returned.  Instead, the Google Test flag variables are
1485 // updated.
1486 //
1487 // Calling the function for the second time has no user-visible effect.
1488 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
1489 
1490 // This overloaded version can be used in Windows programs compiled in
1491 // UNICODE mode.
1492 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
1493 
1494 // This overloaded version can be used on Arduino/embedded platforms where
1495 // there is no argc/argv.
1496 GTEST_API_ void InitGoogleTest();
1497 
1498 namespace internal {
1499 
1500 // Separate the error generating code from the code path to reduce the stack
1501 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
1502 // when calling EXPECT_* in a tight loop.
1503 template <typename T1, typename T2>
CmpHelperEQFailure(const char * lhs_expression,const char * rhs_expression,const T1 & lhs,const T2 & rhs)1504 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
1505                                    const char* rhs_expression,
1506                                    const T1& lhs, const T2& rhs) {
1507   return EqFailure(lhs_expression,
1508                    rhs_expression,
1509                    FormatForComparisonFailureMessage(lhs, rhs),
1510                    FormatForComparisonFailureMessage(rhs, lhs),
1511                    false);
1512 }
1513 
1514 // This block of code defines operator==/!=
1515 // to block lexical scope lookup.
1516 // It prevents using invalid operator==/!= defined at namespace scope.
1517 struct faketype {};
1518 inline bool operator==(faketype, faketype) { return true; }
1519 inline bool operator!=(faketype, faketype) { return false; }
1520 
1521 // The helper function for {ASSERT|EXPECT}_EQ.
1522 template <typename T1, typename T2>
CmpHelperEQ(const char * lhs_expression,const char * rhs_expression,const T1 & lhs,const T2 & rhs)1523 AssertionResult CmpHelperEQ(const char* lhs_expression,
1524                             const char* rhs_expression,
1525                             const T1& lhs,
1526                             const T2& rhs) {
1527   if (lhs == rhs) {
1528     return AssertionSuccess();
1529   }
1530 
1531   return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
1532 }
1533 
1534 // With this overloaded version, we allow anonymous enums to be used
1535 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
1536 // can be implicitly cast to BiggestInt.
1537 GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
1538                                        const char* rhs_expression,
1539                                        BiggestInt lhs,
1540                                        BiggestInt rhs);
1541 
1542 class EqHelper {
1543  public:
1544   // This templatized version is for the general case.
1545   template <
1546       typename T1, typename T2,
1547       // Disable this overload for cases where one argument is a pointer
1548       // and the other is the null pointer constant.
1549       typename std::enable_if<!std::is_integral<T1>::value ||
1550                               !std::is_pointer<T2>::value>::type* = nullptr>
Compare(const char * lhs_expression,const char * rhs_expression,const T1 & lhs,const T2 & rhs)1551   static AssertionResult Compare(const char* lhs_expression,
1552                                  const char* rhs_expression, const T1& lhs,
1553                                  const T2& rhs) {
1554     return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
1555   }
1556 
1557   // With this overloaded version, we allow anonymous enums to be used
1558   // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
1559   // enums can be implicitly cast to BiggestInt.
1560   //
1561   // Even though its body looks the same as the above version, we
1562   // cannot merge the two, as it will make anonymous enums unhappy.
Compare(const char * lhs_expression,const char * rhs_expression,BiggestInt lhs,BiggestInt rhs)1563   static AssertionResult Compare(const char* lhs_expression,
1564                                  const char* rhs_expression,
1565                                  BiggestInt lhs,
1566                                  BiggestInt rhs) {
1567     return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
1568   }
1569 
1570   template <typename T>
Compare(const char * lhs_expression,const char * rhs_expression,std::nullptr_t,T * rhs)1571   static AssertionResult Compare(
1572       const char* lhs_expression, const char* rhs_expression,
1573       // Handle cases where '0' is used as a null pointer literal.
1574       std::nullptr_t /* lhs */, T* rhs) {
1575     // We already know that 'lhs' is a null pointer.
1576     return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
1577                        rhs);
1578   }
1579 };
1580 
1581 // Separate the error generating code from the code path to reduce the stack
1582 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
1583 // when calling EXPECT_OP in a tight loop.
1584 template <typename T1, typename T2>
CmpHelperOpFailure(const char * expr1,const char * expr2,const T1 & val1,const T2 & val2,const char * op)1585 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
1586                                    const T1& val1, const T2& val2,
1587                                    const char* op) {
1588   return AssertionFailure()
1589          << "Expected: (" << expr1 << ") " << op << " (" << expr2
1590          << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
1591          << " vs " << FormatForComparisonFailureMessage(val2, val1);
1592 }
1593 
1594 // A macro for implementing the helper functions needed to implement
1595 // ASSERT_?? and EXPECT_??.  It is here just to avoid copy-and-paste
1596 // of similar code.
1597 //
1598 // For each templatized helper function, we also define an overloaded
1599 // version for BiggestInt in order to reduce code bloat and allow
1600 // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
1601 // with gcc 4.
1602 //
1603 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1604 
1605 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1606 template <typename T1, typename T2>\
1607 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1608                                    const T1& val1, const T2& val2) {\
1609   if (val1 op val2) {\
1610     return AssertionSuccess();\
1611   } else {\
1612     return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
1613   }\
1614 }\
1615 GTEST_API_ AssertionResult CmpHelper##op_name(\
1616     const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
1617 
1618 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1619 
1620 // Implements the helper function for {ASSERT|EXPECT}_NE
1621 GTEST_IMPL_CMP_HELPER_(NE, !=);
1622 // Implements the helper function for {ASSERT|EXPECT}_LE
1623 GTEST_IMPL_CMP_HELPER_(LE, <=);
1624 // Implements the helper function for {ASSERT|EXPECT}_LT
1625 GTEST_IMPL_CMP_HELPER_(LT, <);
1626 // Implements the helper function for {ASSERT|EXPECT}_GE
1627 GTEST_IMPL_CMP_HELPER_(GE, >=);
1628 // Implements the helper function for {ASSERT|EXPECT}_GT
1629 GTEST_IMPL_CMP_HELPER_(GT, >);
1630 
1631 #undef GTEST_IMPL_CMP_HELPER_
1632 
1633 // The helper function for {ASSERT|EXPECT}_STREQ.
1634 //
1635 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1636 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
1637                                           const char* s2_expression,
1638                                           const char* s1,
1639                                           const char* s2);
1640 
1641 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1642 //
1643 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1644 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
1645                                               const char* s2_expression,
1646                                               const char* s1,
1647                                               const char* s2);
1648 
1649 // The helper function for {ASSERT|EXPECT}_STRNE.
1650 //
1651 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1652 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1653                                           const char* s2_expression,
1654                                           const char* s1,
1655                                           const char* s2);
1656 
1657 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1658 //
1659 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1660 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1661                                               const char* s2_expression,
1662                                               const char* s1,
1663                                               const char* s2);
1664 
1665 
1666 // Helper function for *_STREQ on wide strings.
1667 //
1668 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1669 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
1670                                           const char* s2_expression,
1671                                           const wchar_t* s1,
1672                                           const wchar_t* s2);
1673 
1674 // Helper function for *_STRNE on wide strings.
1675 //
1676 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1677 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1678                                           const char* s2_expression,
1679                                           const wchar_t* s1,
1680                                           const wchar_t* s2);
1681 
1682 }  // namespace internal
1683 
1684 // IsSubstring() and IsNotSubstring() are intended to be used as the
1685 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
1686 // themselves.  They check whether needle is a substring of haystack
1687 // (NULL is considered a substring of itself only), and return an
1688 // appropriate error message when they fail.
1689 //
1690 // The {needle,haystack}_expr arguments are the stringified
1691 // expressions that generated the two real arguments.
1692 GTEST_API_ AssertionResult IsSubstring(
1693     const char* needle_expr, const char* haystack_expr,
1694     const char* needle, const char* haystack);
1695 GTEST_API_ AssertionResult IsSubstring(
1696     const char* needle_expr, const char* haystack_expr,
1697     const wchar_t* needle, const wchar_t* haystack);
1698 GTEST_API_ AssertionResult IsNotSubstring(
1699     const char* needle_expr, const char* haystack_expr,
1700     const char* needle, const char* haystack);
1701 GTEST_API_ AssertionResult IsNotSubstring(
1702     const char* needle_expr, const char* haystack_expr,
1703     const wchar_t* needle, const wchar_t* haystack);
1704 GTEST_API_ AssertionResult IsSubstring(
1705     const char* needle_expr, const char* haystack_expr,
1706     const ::std::string& needle, const ::std::string& haystack);
1707 GTEST_API_ AssertionResult IsNotSubstring(
1708     const char* needle_expr, const char* haystack_expr,
1709     const ::std::string& needle, const ::std::string& haystack);
1710 
1711 #if GTEST_HAS_STD_WSTRING
1712 GTEST_API_ AssertionResult IsSubstring(
1713     const char* needle_expr, const char* haystack_expr,
1714     const ::std::wstring& needle, const ::std::wstring& haystack);
1715 GTEST_API_ AssertionResult IsNotSubstring(
1716     const char* needle_expr, const char* haystack_expr,
1717     const ::std::wstring& needle, const ::std::wstring& haystack);
1718 #endif  // GTEST_HAS_STD_WSTRING
1719 
1720 namespace internal {
1721 
1722 // Helper template function for comparing floating-points.
1723 //
1724 // Template parameter:
1725 //
1726 //   RawType: the raw floating-point type (either float or double)
1727 //
1728 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1729 template <typename RawType>
CmpHelperFloatingPointEQ(const char * lhs_expression,const char * rhs_expression,RawType lhs_value,RawType rhs_value)1730 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
1731                                          const char* rhs_expression,
1732                                          RawType lhs_value,
1733                                          RawType rhs_value) {
1734   const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
1735 
1736   if (lhs.AlmostEquals(rhs)) {
1737     return AssertionSuccess();
1738   }
1739 
1740   ::std::stringstream lhs_ss;
1741   lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1742          << lhs_value;
1743 
1744   ::std::stringstream rhs_ss;
1745   rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1746          << rhs_value;
1747 
1748   return EqFailure(lhs_expression,
1749                    rhs_expression,
1750                    StringStreamToString(&lhs_ss),
1751                    StringStreamToString(&rhs_ss),
1752                    false);
1753 }
1754 
1755 // Helper function for implementing ASSERT_NEAR.
1756 //
1757 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1758 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
1759                                                 const char* expr2,
1760                                                 const char* abs_error_expr,
1761                                                 double val1,
1762                                                 double val2,
1763                                                 double abs_error);
1764 
1765 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1766 // A class that enables one to stream messages to assertion macros
1767 class GTEST_API_ AssertHelper {
1768  public:
1769   // Constructor.
1770   AssertHelper(TestPartResult::Type type,
1771                const char* file,
1772                int line,
1773                const char* message);
1774   ~AssertHelper();
1775 
1776   // Message assignment is a semantic trick to enable assertion
1777   // streaming; see the GTEST_MESSAGE_ macro below.
1778   void operator=(const Message& message) const;
1779 
1780  private:
1781   // We put our data in a struct so that the size of the AssertHelper class can
1782   // be as small as possible.  This is important because gcc is incapable of
1783   // re-using stack space even for temporary variables, so every EXPECT_EQ
1784   // reserves stack space for another AssertHelper.
1785   struct AssertHelperData {
AssertHelperDataAssertHelperData1786     AssertHelperData(TestPartResult::Type t,
1787                      const char* srcfile,
1788                      int line_num,
1789                      const char* msg)
1790         : type(t), file(srcfile), line(line_num), message(msg) { }
1791 
1792     TestPartResult::Type const type;
1793     const char* const file;
1794     int const line;
1795     std::string const message;
1796 
1797    private:
1798     GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
1799   };
1800 
1801   AssertHelperData* const data_;
1802 
1803   GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
1804 };
1805 
1806 enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
1807 
1808 GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
1809                                                             const char* fmt,
1810                                                             ...);
1811 
1812 }  // namespace internal
1813 
1814 // The pure interface class that all value-parameterized tests inherit from.
1815 // A value-parameterized class must inherit from both ::testing::Test and
1816 // ::testing::WithParamInterface. In most cases that just means inheriting
1817 // from ::testing::TestWithParam, but more complicated test hierarchies
1818 // may need to inherit from Test and WithParamInterface at different levels.
1819 //
1820 // This interface has support for accessing the test parameter value via
1821 // the GetParam() method.
1822 //
1823 // Use it with one of the parameter generator defining functions, like Range(),
1824 // Values(), ValuesIn(), Bool(), and Combine().
1825 //
1826 // class FooTest : public ::testing::TestWithParam<int> {
1827 //  protected:
1828 //   FooTest() {
1829 //     // Can use GetParam() here.
1830 //   }
1831 //   ~FooTest() override {
1832 //     // Can use GetParam() here.
1833 //   }
1834 //   void SetUp() override {
1835 //     // Can use GetParam() here.
1836 //   }
1837 //   void TearDown override {
1838 //     // Can use GetParam() here.
1839 //   }
1840 // };
1841 // TEST_P(FooTest, DoesBar) {
1842 //   // Can use GetParam() method here.
1843 //   Foo foo;
1844 //   ASSERT_TRUE(foo.DoesBar(GetParam()));
1845 // }
1846 // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
1847 
1848 template <typename T>
1849 class WithParamInterface {
1850  public:
1851   typedef T ParamType;
~WithParamInterface()1852   virtual ~WithParamInterface() {}
1853 
1854   // The current parameter value. Is also available in the test fixture's
1855   // constructor.
GetParam()1856   static const ParamType& GetParam() {
1857     GTEST_CHECK_(parameter_ != nullptr)
1858         << "GetParam() can only be called inside a value-parameterized test "
1859         << "-- did you intend to write TEST_P instead of TEST_F?";
1860     return *parameter_;
1861   }
1862 
1863  private:
1864   // Sets parameter value. The caller is responsible for making sure the value
1865   // remains alive and unchanged throughout the current test.
SetParam(const ParamType * parameter)1866   static void SetParam(const ParamType* parameter) {
1867     parameter_ = parameter;
1868   }
1869 
1870   // Static value used for accessing parameter during a test lifetime.
1871   static const ParamType* parameter_;
1872 
1873   // TestClass must be a subclass of WithParamInterface<T> and Test.
1874   template <class TestClass> friend class internal::ParameterizedTestFactory;
1875 };
1876 
1877 template <typename T>
1878 const T* WithParamInterface<T>::parameter_ = nullptr;
1879 
1880 // Most value-parameterized classes can ignore the existence of
1881 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
1882 
1883 template <typename T>
1884 class TestWithParam : public Test, public WithParamInterface<T> {
1885 };
1886 
1887 // Macros for indicating success/failure in test code.
1888 
1889 // Skips test in runtime.
1890 // Skipping test aborts current function.
1891 // Skipped tests are neither successful nor failed.
1892 #define GTEST_SKIP() GTEST_SKIP_("Skipped")
1893 
1894 // ADD_FAILURE unconditionally adds a failure to the current test.
1895 // SUCCEED generates a success - it doesn't automatically make the
1896 // current test successful, as a test is only successful when it has
1897 // no failure.
1898 //
1899 // EXPECT_* verifies that a certain condition is satisfied.  If not,
1900 // it behaves like ADD_FAILURE.  In particular:
1901 //
1902 //   EXPECT_TRUE  verifies that a Boolean condition is true.
1903 //   EXPECT_FALSE verifies that a Boolean condition is false.
1904 //
1905 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
1906 // that they will also abort the current function on failure.  People
1907 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
1908 // writing data-driven tests often find themselves using ADD_FAILURE
1909 // and EXPECT_* more.
1910 
1911 // Generates a nonfatal failure with a generic message.
1912 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
1913 
1914 // Generates a nonfatal failure at the given source file location with
1915 // a generic message.
1916 #define ADD_FAILURE_AT(file, line) \
1917   GTEST_MESSAGE_AT_(file, line, "Failed", \
1918                     ::testing::TestPartResult::kNonFatalFailure)
1919 
1920 // Generates a fatal failure with a generic message.
1921 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
1922 
1923 // Like GTEST_FAIL(), but at the given source file location.
1924 #define GTEST_FAIL_AT(file, line)         \
1925   GTEST_MESSAGE_AT_(file, line, "Failed", \
1926                     ::testing::TestPartResult::kFatalFailure)
1927 
1928 // Define this macro to 1 to omit the definition of FAIL(), which is a
1929 // generic name and clashes with some other libraries.
1930 #if !GTEST_DONT_DEFINE_FAIL
1931 # define FAIL() GTEST_FAIL()
1932 #endif
1933 
1934 // Generates a success with a generic message.
1935 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
1936 
1937 // Define this macro to 1 to omit the definition of SUCCEED(), which
1938 // is a generic name and clashes with some other libraries.
1939 #if !GTEST_DONT_DEFINE_SUCCEED
1940 # define SUCCEED() GTEST_SUCCEED()
1941 #endif
1942 
1943 // Macros for testing exceptions.
1944 //
1945 //    * {ASSERT|EXPECT}_THROW(statement, expected_exception):
1946 //         Tests that the statement throws the expected exception.
1947 //    * {ASSERT|EXPECT}_NO_THROW(statement):
1948 //         Tests that the statement doesn't throw any exception.
1949 //    * {ASSERT|EXPECT}_ANY_THROW(statement):
1950 //         Tests that the statement throws an exception.
1951 
1952 #define EXPECT_THROW(statement, expected_exception) \
1953   GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1954 #define EXPECT_NO_THROW(statement) \
1955   GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1956 #define EXPECT_ANY_THROW(statement) \
1957   GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1958 #define ASSERT_THROW(statement, expected_exception) \
1959   GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1960 #define ASSERT_NO_THROW(statement) \
1961   GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1962 #define ASSERT_ANY_THROW(statement) \
1963   GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1964 
1965 // Boolean assertions. Condition can be either a Boolean expression or an
1966 // AssertionResult. For more information on how to use AssertionResult with
1967 // these macros see comments on that class.
1968 #define EXPECT_TRUE(condition) \
1969   GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1970                       GTEST_NONFATAL_FAILURE_)
1971 #define EXPECT_FALSE(condition) \
1972   GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1973                       GTEST_NONFATAL_FAILURE_)
1974 #define ASSERT_TRUE(condition) \
1975   GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1976                       GTEST_FATAL_FAILURE_)
1977 #define ASSERT_FALSE(condition) \
1978   GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1979                       GTEST_FATAL_FAILURE_)
1980 
1981 // Macros for testing equalities and inequalities.
1982 //
1983 //    * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
1984 //    * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
1985 //    * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
1986 //    * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
1987 //    * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
1988 //    * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
1989 //
1990 // When they are not, Google Test prints both the tested expressions and
1991 // their actual values.  The values must be compatible built-in types,
1992 // or you will get a compiler error.  By "compatible" we mean that the
1993 // values can be compared by the respective operator.
1994 //
1995 // Note:
1996 //
1997 //   1. It is possible to make a user-defined type work with
1998 //   {ASSERT|EXPECT}_??(), but that requires overloading the
1999 //   comparison operators and is thus discouraged by the Google C++
2000 //   Usage Guide.  Therefore, you are advised to use the
2001 //   {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
2002 //   equal.
2003 //
2004 //   2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
2005 //   pointers (in particular, C strings).  Therefore, if you use it
2006 //   with two C strings, you are testing how their locations in memory
2007 //   are related, not how their content is related.  To compare two C
2008 //   strings by content, use {ASSERT|EXPECT}_STR*().
2009 //
2010 //   3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
2011 //   {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
2012 //   what the actual value is when it fails, and similarly for the
2013 //   other comparisons.
2014 //
2015 //   4. Do not depend on the order in which {ASSERT|EXPECT}_??()
2016 //   evaluate their arguments, which is undefined.
2017 //
2018 //   5. These macros evaluate their arguments exactly once.
2019 //
2020 // Examples:
2021 //
2022 //   EXPECT_NE(Foo(), 5);
2023 //   EXPECT_EQ(a_pointer, NULL);
2024 //   ASSERT_LT(i, array_size);
2025 //   ASSERT_GT(records.size(), 0) << "There is no record left.";
2026 
2027 #define EXPECT_EQ(val1, val2) \
2028   EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
2029 #define EXPECT_NE(val1, val2) \
2030   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
2031 #define EXPECT_LE(val1, val2) \
2032   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
2033 #define EXPECT_LT(val1, val2) \
2034   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
2035 #define EXPECT_GE(val1, val2) \
2036   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
2037 #define EXPECT_GT(val1, val2) \
2038   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
2039 
2040 #define GTEST_ASSERT_EQ(val1, val2) \
2041   ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
2042 #define GTEST_ASSERT_NE(val1, val2) \
2043   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
2044 #define GTEST_ASSERT_LE(val1, val2) \
2045   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
2046 #define GTEST_ASSERT_LT(val1, val2) \
2047   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
2048 #define GTEST_ASSERT_GE(val1, val2) \
2049   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
2050 #define GTEST_ASSERT_GT(val1, val2) \
2051   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
2052 
2053 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
2054 // ASSERT_XY(), which clashes with some users' own code.
2055 
2056 #if !GTEST_DONT_DEFINE_ASSERT_EQ
2057 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
2058 #endif
2059 
2060 #if !GTEST_DONT_DEFINE_ASSERT_NE
2061 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
2062 #endif
2063 
2064 #if !GTEST_DONT_DEFINE_ASSERT_LE
2065 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
2066 #endif
2067 
2068 #if !GTEST_DONT_DEFINE_ASSERT_LT
2069 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
2070 #endif
2071 
2072 #if !GTEST_DONT_DEFINE_ASSERT_GE
2073 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
2074 #endif
2075 
2076 #if !GTEST_DONT_DEFINE_ASSERT_GT
2077 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
2078 #endif
2079 
2080 // C-string Comparisons.  All tests treat NULL and any non-NULL string
2081 // as different.  Two NULLs are equal.
2082 //
2083 //    * {ASSERT|EXPECT}_STREQ(s1, s2):     Tests that s1 == s2
2084 //    * {ASSERT|EXPECT}_STRNE(s1, s2):     Tests that s1 != s2
2085 //    * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
2086 //    * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
2087 //
2088 // For wide or narrow string objects, you can use the
2089 // {ASSERT|EXPECT}_??() macros.
2090 //
2091 // Don't depend on the order in which the arguments are evaluated,
2092 // which is undefined.
2093 //
2094 // These macros evaluate their arguments exactly once.
2095 
2096 #define EXPECT_STREQ(s1, s2) \
2097   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2098 #define EXPECT_STRNE(s1, s2) \
2099   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2100 #define EXPECT_STRCASEEQ(s1, s2) \
2101   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
2102 #define EXPECT_STRCASENE(s1, s2)\
2103   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2104 
2105 #define ASSERT_STREQ(s1, s2) \
2106   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2107 #define ASSERT_STRNE(s1, s2) \
2108   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2109 #define ASSERT_STRCASEEQ(s1, s2) \
2110   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
2111 #define ASSERT_STRCASENE(s1, s2)\
2112   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2113 
2114 // Macros for comparing floating-point numbers.
2115 //
2116 //    * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
2117 //         Tests that two float values are almost equal.
2118 //    * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
2119 //         Tests that two double values are almost equal.
2120 //    * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
2121 //         Tests that v1 and v2 are within the given distance to each other.
2122 //
2123 // Google Test uses ULP-based comparison to automatically pick a default
2124 // error bound that is appropriate for the operands.  See the
2125 // FloatingPoint template class in gtest-internal.h if you are
2126 // interested in the implementation details.
2127 
2128 #define EXPECT_FLOAT_EQ(val1, val2)\
2129   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2130                       val1, val2)
2131 
2132 #define EXPECT_DOUBLE_EQ(val1, val2)\
2133   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2134                       val1, val2)
2135 
2136 #define ASSERT_FLOAT_EQ(val1, val2)\
2137   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2138                       val1, val2)
2139 
2140 #define ASSERT_DOUBLE_EQ(val1, val2)\
2141   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2142                       val1, val2)
2143 
2144 #define EXPECT_NEAR(val1, val2, abs_error)\
2145   EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2146                       val1, val2, abs_error)
2147 
2148 #define ASSERT_NEAR(val1, val2, abs_error)\
2149   ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2150                       val1, val2, abs_error)
2151 
2152 // These predicate format functions work on floating-point values, and
2153 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
2154 //
2155 //   EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
2156 
2157 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2158 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
2159 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
2160                                    float val1, float val2);
2161 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
2162                                     double val1, double val2);
2163 
2164 
2165 #if GTEST_OS_WINDOWS
2166 
2167 // Macros that test for HRESULT failure and success, these are only useful
2168 // on Windows, and rely on Windows SDK macros and APIs to compile.
2169 //
2170 //    * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
2171 //
2172 // When expr unexpectedly fails or succeeds, Google Test prints the
2173 // expected result and the actual result with both a human-readable
2174 // string representation of the error, if available, as well as the
2175 // hex result code.
2176 # define EXPECT_HRESULT_SUCCEEDED(expr) \
2177     EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2178 
2179 # define ASSERT_HRESULT_SUCCEEDED(expr) \
2180     ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2181 
2182 # define EXPECT_HRESULT_FAILED(expr) \
2183     EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2184 
2185 # define ASSERT_HRESULT_FAILED(expr) \
2186     ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2187 
2188 #endif  // GTEST_OS_WINDOWS
2189 
2190 // Macros that execute statement and check that it doesn't generate new fatal
2191 // failures in the current thread.
2192 //
2193 //   * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
2194 //
2195 // Examples:
2196 //
2197 //   EXPECT_NO_FATAL_FAILURE(Process());
2198 //   ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
2199 //
2200 #define ASSERT_NO_FATAL_FAILURE(statement) \
2201     GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
2202 #define EXPECT_NO_FATAL_FAILURE(statement) \
2203     GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
2204 
2205 // Causes a trace (including the given source file path and line number,
2206 // and the given message) to be included in every test failure message generated
2207 // by code in the scope of the lifetime of an instance of this class. The effect
2208 // is undone with the destruction of the instance.
2209 //
2210 // The message argument can be anything streamable to std::ostream.
2211 //
2212 // Example:
2213 //   testing::ScopedTrace trace("file.cc", 123, "message");
2214 //
2215 class GTEST_API_ ScopedTrace {
2216  public:
2217   // The c'tor pushes the given source file location and message onto
2218   // a trace stack maintained by Google Test.
2219 
2220   // Template version. Uses Message() to convert the values into strings.
2221   // Slow, but flexible.
2222   template <typename T>
ScopedTrace(const char * file,int line,const T & message)2223   ScopedTrace(const char* file, int line, const T& message) {
2224     PushTrace(file, line, (Message() << message).GetString());
2225   }
2226 
2227   // Optimize for some known types.
ScopedTrace(const char * file,int line,const char * message)2228   ScopedTrace(const char* file, int line, const char* message) {
2229     PushTrace(file, line, message ? message : "(null)");
2230   }
2231 
ScopedTrace(const char * file,int line,const std::string & message)2232   ScopedTrace(const char* file, int line, const std::string& message) {
2233     PushTrace(file, line, message);
2234   }
2235 
2236   // The d'tor pops the info pushed by the c'tor.
2237   //
2238   // Note that the d'tor is not virtual in order to be efficient.
2239   // Don't inherit from ScopedTrace!
2240   ~ScopedTrace();
2241 
2242  private:
2243   void PushTrace(const char* file, int line, std::string message);
2244 
2245   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
2246 } GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its
2247                             // c'tor and d'tor.  Therefore it doesn't
2248                             // need to be used otherwise.
2249 
2250 // Causes a trace (including the source file path, the current line
2251 // number, and the given message) to be included in every test failure
2252 // message generated by code in the current scope.  The effect is
2253 // undone when the control leaves the current scope.
2254 //
2255 // The message argument can be anything streamable to std::ostream.
2256 //
2257 // In the implementation, we include the current line number as part
2258 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
2259 // to appear in the same block - as long as they are on different
2260 // lines.
2261 //
2262 // Assuming that each thread maintains its own stack of traces.
2263 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
2264 // assertions in its own thread.
2265 #define SCOPED_TRACE(message) \
2266   ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
2267     __FILE__, __LINE__, (message))
2268 
2269 // Compile-time assertion for type equality.
2270 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
2271 // are the same type.  The value it returns is not interesting.
2272 //
2273 // Instead of making StaticAssertTypeEq a class template, we make it a
2274 // function template that invokes a helper class template.  This
2275 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
2276 // defining objects of that type.
2277 //
2278 // CAVEAT:
2279 //
2280 // When used inside a method of a class template,
2281 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
2282 // instantiated.  For example, given:
2283 //
2284 //   template <typename T> class Foo {
2285 //    public:
2286 //     void Bar() { testing::StaticAssertTypeEq<int, T>(); }
2287 //   };
2288 //
2289 // the code:
2290 //
2291 //   void Test1() { Foo<bool> foo; }
2292 //
2293 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
2294 // actually instantiated.  Instead, you need:
2295 //
2296 //   void Test2() { Foo<bool> foo; foo.Bar(); }
2297 //
2298 // to cause a compiler error.
2299 template <typename T1, typename T2>
StaticAssertTypeEq()2300 constexpr bool StaticAssertTypeEq() noexcept {
2301   static_assert(std::is_same<T1, T2>::value,
2302                 "type1 and type2 are not the same type");
2303   return true;
2304 }
2305 
2306 // Defines a test.
2307 //
2308 // The first parameter is the name of the test suite, and the second
2309 // parameter is the name of the test within the test suite.
2310 //
2311 // The convention is to end the test suite name with "Test".  For
2312 // example, a test suite for the Foo class can be named FooTest.
2313 //
2314 // Test code should appear between braces after an invocation of
2315 // this macro.  Example:
2316 //
2317 //   TEST(FooTest, InitializesCorrectly) {
2318 //     Foo foo;
2319 //     EXPECT_TRUE(foo.StatusIsOK());
2320 //   }
2321 
2322 // Note that we call GetTestTypeId() instead of GetTypeId<
2323 // ::testing::Test>() here to get the type ID of testing::Test.  This
2324 // is to work around a suspected linker bug when using Google Test as
2325 // a framework on Mac OS X.  The bug causes GetTypeId<
2326 // ::testing::Test>() to return different values depending on whether
2327 // the call is from the Google Test framework itself or from user test
2328 // code.  GetTestTypeId() is guaranteed to always return the same
2329 // value, as it always calls GetTypeId<>() from the Google Test
2330 // framework.
2331 #define GTEST_TEST(test_suite_name, test_name)             \
2332   GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
2333               ::testing::internal::GetTestTypeId())
2334 
2335 // Define this macro to 1 to omit the definition of TEST(), which
2336 // is a generic name and clashes with some other libraries.
2337 #if !GTEST_DONT_DEFINE_TEST
2338 #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
2339 #endif
2340 
2341 // Defines a test that uses a test fixture.
2342 //
2343 // The first parameter is the name of the test fixture class, which
2344 // also doubles as the test suite name.  The second parameter is the
2345 // name of the test within the test suite.
2346 //
2347 // A test fixture class must be declared earlier.  The user should put
2348 // the test code between braces after using this macro.  Example:
2349 //
2350 //   class FooTest : public testing::Test {
2351 //    protected:
2352 //     void SetUp() override { b_.AddElement(3); }
2353 //
2354 //     Foo a_;
2355 //     Foo b_;
2356 //   };
2357 //
2358 //   TEST_F(FooTest, InitializesCorrectly) {
2359 //     EXPECT_TRUE(a_.StatusIsOK());
2360 //   }
2361 //
2362 //   TEST_F(FooTest, ReturnsElementCountCorrectly) {
2363 //     EXPECT_EQ(a_.size(), 0);
2364 //     EXPECT_EQ(b_.size(), 1);
2365 //   }
2366 //
2367 // GOOGLETEST_CM0011 DO NOT DELETE
2368 #define TEST_F(test_fixture, test_name)\
2369   GTEST_TEST_(test_fixture, test_name, test_fixture, \
2370               ::testing::internal::GetTypeId<test_fixture>())
2371 
2372 // Returns a path to temporary directory.
2373 // Tries to determine an appropriate directory for the platform.
2374 GTEST_API_ std::string TempDir();
2375 
2376 #ifdef _MSC_VER
2377 #  pragma warning(pop)
2378 #endif
2379 
2380 // Dynamically registers a test with the framework.
2381 //
2382 // This is an advanced API only to be used when the `TEST` macros are
2383 // insufficient. The macros should be preferred when possible, as they avoid
2384 // most of the complexity of calling this function.
2385 //
2386 // The `factory` argument is a factory callable (move-constructible) object or
2387 // function pointer that creates a new instance of the Test object. It
2388 // handles ownership to the caller. The signature of the callable is
2389 // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
2390 // tests registered with the same `test_suite_name` must return the same
2391 // fixture type. This is checked at runtime.
2392 //
2393 // The framework will infer the fixture class from the factory and will call
2394 // the `SetUpTestSuite` and `TearDownTestSuite` for it.
2395 //
2396 // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
2397 // undefined.
2398 //
2399 // Use case example:
2400 //
2401 // class MyFixture : public ::testing::Test {
2402 //  public:
2403 //   // All of these optional, just like in regular macro usage.
2404 //   static void SetUpTestSuite() { ... }
2405 //   static void TearDownTestSuite() { ... }
2406 //   void SetUp() override { ... }
2407 //   void TearDown() override { ... }
2408 // };
2409 //
2410 // class MyTest : public MyFixture {
2411 //  public:
2412 //   explicit MyTest(int data) : data_(data) {}
2413 //   void TestBody() override { ... }
2414 //
2415 //  private:
2416 //   int data_;
2417 // };
2418 //
2419 // void RegisterMyTests(const std::vector<int>& values) {
2420 //   for (int v : values) {
2421 //     ::testing::RegisterTest(
2422 //         "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
2423 //         std::to_string(v).c_str(),
2424 //         __FILE__, __LINE__,
2425 //         // Important to use the fixture type as the return type here.
2426 //         [=]() -> MyFixture* { return new MyTest(v); });
2427 //   }
2428 // }
2429 // ...
2430 // int main(int argc, char** argv) {
2431 //   std::vector<int> values_to_test = LoadValuesFromConfig();
2432 //   RegisterMyTests(values_to_test);
2433 //   ...
2434 //   return RUN_ALL_TESTS();
2435 // }
2436 //
2437 template <int&... ExplicitParameterBarrier, typename Factory>
RegisterTest(const char * test_suite_name,const char * test_name,const char * type_param,const char * value_param,const char * file,int line,Factory factory)2438 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
2439                        const char* type_param, const char* value_param,
2440                        const char* file, int line, Factory factory) {
2441   using TestT = typename std::remove_pointer<decltype(factory())>::type;
2442 
2443   class FactoryImpl : public internal::TestFactoryBase {
2444    public:
2445     explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
2446     Test* CreateTest() override { return factory_(); }
2447 
2448    private:
2449     Factory factory_;
2450   };
2451 
2452   return internal::MakeAndRegisterTestInfo(
2453       test_suite_name, test_name, type_param, value_param,
2454       internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
2455       internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
2456       internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
2457       new FactoryImpl{std::move(factory)});
2458 }
2459 
2460 }  // namespace testing
2461 
2462 // Use this function in main() to run all tests.  It returns 0 if all
2463 // tests are successful, or 1 otherwise.
2464 //
2465 // RUN_ALL_TESTS() should be invoked after the command line has been
2466 // parsed by InitGoogleTest().
2467 //
2468 // This function was formerly a macro; thus, it is in the global
2469 // namespace and has an all-caps name.
2470 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
2471 
RUN_ALL_TESTS()2472 inline int RUN_ALL_TESTS() {
2473   return ::testing::UnitTest::GetInstance()->Run();
2474 }
2475 
2476 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
2477 
2478 #endif  // GTEST_INCLUDE_GTEST_GTEST_H_
2479