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

source code of flutter_engine/third_party/googletest/googletest/include/gtest/gtest.h