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