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