source: gtest-1.7.0/include/gtest/gtest.h@ 12748

Last change on this file since 12748 was 12746, checked in by hock@…, 11 years ago

integrated the Google Testing Framework (gtest)

and wrote an Hello World test, to ensure the framework is working..

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