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