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