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