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