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