blob: 9b72b6369257ae699e9b1e7bc31b73652372a388 [file] [log] [blame]
Misha Brukmanc89aba32008-12-31 17:34:06 +00001// 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// The following platform macros are used throughout Google Test:
55// _WIN32_WCE Windows CE (set in project files)
56//
57// Note that even though _MSC_VER and _WIN32_WCE really indicate a compiler
58// and a Win32 implementation, respectively, we use them to indicate the
59// combination of compiler - Win 32 API - C library, since the code currently
60// only supports:
61// Windows proper with Visual C++ and MS C library (_MSC_VER && !_WIN32_WCE) and
62// Windows Mobile with Visual C++ and no C library (_WIN32_WCE).
63
64#include <limits>
65#include <gtest/internal/gtest-internal.h>
66#include <gtest/internal/gtest-string.h>
67#include <gtest/gtest-death-test.h>
68#include <gtest/gtest-message.h>
69#include <gtest/gtest-param-test.h>
70#include <gtest/gtest_prod.h>
71#include <gtest/gtest-test-part.h>
72#include <gtest/gtest-typed-test.h>
73
74// Depending on the platform, different string classes are available.
75// On Windows, ::std::string compiles only when exceptions are
76// enabled. On Linux, in addition to ::std::string, Google also makes
77// use of class ::string, which has the same interface as
78// ::std::string, but has a different implementation.
79//
80// The user can tell us whether ::std::string is available in his
81// environment by defining the macro GTEST_HAS_STD_STRING to either 1
82// or 0 on the compiler command line. He can also define
83// GTEST_HAS_GLOBAL_STRING to 1 to indicate that ::string is available
84// AND is a distinct type to ::std::string, or define it to 0 to
85// indicate otherwise.
86//
87// If the user's ::std::string and ::string are the same class due to
88// aliasing, he should define GTEST_HAS_STD_STRING to 1 and
89// GTEST_HAS_GLOBAL_STRING to 0.
90//
91// If the user doesn't define GTEST_HAS_STD_STRING and/or
92// GTEST_HAS_GLOBAL_STRING, they are defined heuristically.
93
94namespace testing {
95
Benjamin Kramerf2f40202010-06-02 22:01:25 +000096// Declares the flags.
97
98// This flag temporary enables the disabled tests.
99GTEST_DECLARE_bool_(also_run_disabled_tests);
100
101// This flag brings the debugger on an assertion failure.
102GTEST_DECLARE_bool_(break_on_failure);
103
104// This flag controls whether Google Test catches all test-thrown exceptions
105// and logs them as failures.
106GTEST_DECLARE_bool_(catch_exceptions);
107
108// This flag enables using colors in terminal output. Available values are
109// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
110// to let Google Test decide.
111GTEST_DECLARE_string_(color);
112
113// This flag sets up the filter to select by name using a glob pattern
114// the tests to run. If the filter is not given all tests are executed.
115GTEST_DECLARE_string_(filter);
116
117// This flag causes the Google Test to list tests. None of the tests listed
118// are actually run if the flag is provided.
119GTEST_DECLARE_bool_(list_tests);
120
121// This flag controls whether Google Test emits a detailed XML report to a file
122// in addition to its normal textual output.
123GTEST_DECLARE_string_(output);
124
125// This flags control whether Google Test prints the elapsed time for each
126// test.
127GTEST_DECLARE_bool_(print_time);
128
129// This flag sets how many times the tests are repeated. The default value
130// is 1. If the value is -1 the tests are repeating forever.
131GTEST_DECLARE_int32_(repeat);
132
133// This flag controls whether Google Test includes Google Test internal
134// stack frames in failure stack traces.
135GTEST_DECLARE_bool_(show_internal_stack_frames);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000136
137// This flag specifies the maximum number of stack frames to be
138// printed in a failure message.
139GTEST_DECLARE_int32_(stack_trace_depth);
140
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000141// When this flag is specified, a failed assertion will throw an
142// exception if exceptions are enabled, or exit the program with a
143// non-zero code otherwise.
144GTEST_DECLARE_bool_(throw_on_failure);
145
146// The upper limit for valid stack trace depths.
147const int kMaxStackTraceDepth = 100;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000148
149namespace internal {
150
151class GTestFlagSaver;
152
153// Converts a streamable value to a String. A NULL pointer is
154// converted to "(null)". When the input value is a ::string,
155// ::std::string, ::wstring, or ::std::wstring object, each NUL
156// character in it is replaced with "\\0".
157// Declared in gtest-internal.h but defined here, so that it has access
158// to the definition of the Message class, required by the ARM
159// compiler.
160template <typename T>
161String StreamableToString(const T& streamable) {
162 return (Message() << streamable).GetString();
163}
164
165} // namespace internal
166
167// A class for indicating whether an assertion was successful. When
168// the assertion wasn't successful, the AssertionResult object
169// remembers a non-empty message that described how it failed.
170//
171// This class is useful for defining predicate-format functions to be
172// used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
173//
174// The constructor of AssertionResult is private. To create an
175// instance of this class, use one of the factory functions
176// (AssertionSuccess() and AssertionFailure()).
177//
178// For example, in order to be able to write:
179//
180// // Verifies that Foo() returns an even number.
181// EXPECT_PRED_FORMAT1(IsEven, Foo());
182//
183// you just need to define:
184//
185// testing::AssertionResult IsEven(const char* expr, int n) {
186// if ((n % 2) == 0) return testing::AssertionSuccess();
187//
188// Message msg;
189// msg << "Expected: " << expr << " is even\n"
190// << " Actual: it's " << n;
191// return testing::AssertionFailure(msg);
192// }
193//
194// If Foo() returns 5, you will see the following message:
195//
196// Expected: Foo() is even
197// Actual: it's 5
198class AssertionResult {
199 public:
200 // Declares factory functions for making successful and failed
201 // assertion results as friends.
202 friend AssertionResult AssertionSuccess();
203 friend AssertionResult AssertionFailure(const Message&);
204
205 // Returns true iff the assertion succeeded.
206 operator bool() const { return failure_message_.c_str() == NULL; } // NOLINT
207
208 // Returns the assertion's failure message.
209 const char* failure_message() const { return failure_message_.c_str(); }
210
211 private:
212 // The default constructor. It is used when the assertion succeeded.
213 AssertionResult() {}
214
215 // The constructor used when the assertion failed.
216 explicit AssertionResult(const internal::String& failure_message);
217
218 // Stores the assertion's failure message.
219 internal::String failure_message_;
220};
221
222// Makes a successful assertion result.
223AssertionResult AssertionSuccess();
224
225// Makes a failed assertion result with the given failure message.
226AssertionResult AssertionFailure(const Message& msg);
227
228// The abstract class that all tests inherit from.
229//
230// In Google Test, a unit test program contains one or many TestCases, and
231// each TestCase contains one or many Tests.
232//
233// When you define a test using the TEST macro, you don't need to
234// explicitly derive from Test - the TEST macro automatically does
235// this for you.
236//
237// The only time you derive from Test is when defining a test fixture
238// to be used a TEST_F. For example:
239//
240// class FooTest : public testing::Test {
241// protected:
242// virtual void SetUp() { ... }
243// virtual void TearDown() { ... }
244// ...
245// };
246//
247// TEST_F(FooTest, Bar) { ... }
248// TEST_F(FooTest, Baz) { ... }
249//
250// Test is not copyable.
251class Test {
252 public:
253 friend class internal::TestInfoImpl;
254
255 // Defines types for pointers to functions that set up and tear down
256 // a test case.
257 typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
258 typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
259
260 // The d'tor is virtual as we intend to inherit from Test.
261 virtual ~Test();
262
263 // Sets up the stuff shared by all tests in this test case.
264 //
265 // Google Test will call Foo::SetUpTestCase() before running the first
266 // test in test case Foo. Hence a sub-class can define its own
267 // SetUpTestCase() method to shadow the one defined in the super
268 // class.
269 static void SetUpTestCase() {}
270
271 // Tears down the stuff shared by all tests in this test case.
272 //
273 // Google Test will call Foo::TearDownTestCase() after running the last
274 // test in test case Foo. Hence a sub-class can define its own
275 // TearDownTestCase() method to shadow the one defined in the super
276 // class.
277 static void TearDownTestCase() {}
278
279 // Returns true iff the current test has a fatal failure.
280 static bool HasFatalFailure();
281
282 // Logs a property for the current test. Only the last value for a given
283 // key is remembered.
284 // These are public static so they can be called from utility functions
285 // that are not members of the test fixture.
286 // The arguments are const char* instead strings, as Google Test is used
287 // on platforms where string doesn't compile.
288 //
289 // Note that a driving consideration for these RecordProperty methods
290 // was to produce xml output suited to the Greenspan charting utility,
291 // which at present will only chart values that fit in a 32-bit int. It
292 // is the user's responsibility to restrict their values to 32-bit ints
293 // if they intend them to be used with Greenspan.
294 static void RecordProperty(const char* key, const char* value);
295 static void RecordProperty(const char* key, int value);
296
297 protected:
298 // Creates a Test object.
299 Test();
300
301 // Sets up the test fixture.
302 virtual void SetUp();
303
304 // Tears down the test fixture.
305 virtual void TearDown();
306
307 private:
308 // Returns true iff the current test has the same fixture class as
309 // the first test in the current test case.
310 static bool HasSameFixtureClass();
311
312 // Runs the test after the test fixture has been set up.
313 //
314 // A sub-class must implement this to define the test logic.
315 //
316 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
317 // Instead, use the TEST or TEST_F macro.
318 virtual void TestBody() = 0;
319
320 // Sets up, executes, and tears down the test.
321 void Run();
322
323 // Uses a GTestFlagSaver to save and restore all Google Test flags.
324 const internal::GTestFlagSaver* const gtest_flag_saver_;
325
326 // Often a user mis-spells SetUp() as Setup() and spends a long time
327 // wondering why it is never called by Google Test. The declaration of
328 // the following method is solely for catching such an error at
329 // compile time:
330 //
331 // - The return type is deliberately chosen to be not void, so it
332 // will be a conflict if a user declares void Setup() in his test
333 // fixture.
334 //
335 // - This method is private, so it will be another compiler error
336 // if a user calls it from his test fixture.
337 //
338 // DO NOT OVERRIDE THIS FUNCTION.
339 //
340 // If you see an error about overriding the following function or
341 // about it being private, you have mis-spelled SetUp() as Setup().
342 struct Setup_should_be_spelled_SetUp {};
343 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
344
345 // We disallow copying Tests.
346 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
347};
348
349
350// A TestInfo object stores the following information about a test:
351//
352// Test case name
353// Test name
354// Whether the test should be run
355// A function pointer that creates the test object when invoked
356// Test result
357//
358// The constructor of TestInfo registers itself with the UnitTest
359// singleton such that the RUN_ALL_TESTS() macro knows which tests to
360// run.
361class TestInfo {
362 public:
363 // Destructs a TestInfo object. This function is not virtual, so
364 // don't inherit from TestInfo.
365 ~TestInfo();
366
367 // Returns the test case name.
368 const char* test_case_name() const;
369
370 // Returns the test name.
371 const char* name() const;
372
373 // Returns the test case comment.
374 const char* test_case_comment() const;
375
376 // Returns the test comment.
377 const char* comment() const;
378
379 // Returns true if this test should run.
380 //
381 // Google Test allows the user to filter the tests by their full names.
382 // The full name of a test Bar in test case Foo is defined as
383 // "Foo.Bar". Only the tests that match the filter will run.
384 //
385 // A filter is a colon-separated list of glob (not regex) patterns,
386 // optionally followed by a '-' and a colon-separated list of
387 // negative patterns (tests to exclude). A test is run if it
388 // matches one of the positive patterns and does not match any of
389 // the negative patterns.
390 //
391 // For example, *A*:Foo.* is a filter that matches any string that
392 // contains the character 'A' or starts with "Foo.".
393 bool should_run() const;
394
395 // Returns the result of the test.
396 const internal::TestResult* result() const;
397 private:
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000398#if GTEST_HAS_DEATH_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000399 friend class internal::DefaultDeathTestFactory;
400#endif // GTEST_HAS_DEATH_TEST
401 friend class internal::TestInfoImpl;
402 friend class internal::UnitTestImpl;
403 friend class Test;
404 friend class TestCase;
405 friend TestInfo* internal::MakeAndRegisterTestInfo(
406 const char* test_case_name, const char* name,
407 const char* test_case_comment, const char* comment,
408 internal::TypeId fixture_class_id,
409 Test::SetUpTestCaseFunc set_up_tc,
410 Test::TearDownTestCaseFunc tear_down_tc,
411 internal::TestFactoryBase* factory);
412
413 // Increments the number of death tests encountered in this test so
414 // far.
415 int increment_death_test_count();
416
417 // Accessors for the implementation object.
418 internal::TestInfoImpl* impl() { return impl_; }
419 const internal::TestInfoImpl* impl() const { return impl_; }
420
421 // Constructs a TestInfo object. The newly constructed instance assumes
422 // ownership of the factory object.
423 TestInfo(const char* test_case_name, const char* name,
424 const char* test_case_comment, const char* comment,
425 internal::TypeId fixture_class_id,
426 internal::TestFactoryBase* factory);
427
428 // An opaque implementation object.
429 internal::TestInfoImpl* impl_;
430
431 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
432};
433
434// An Environment object is capable of setting up and tearing down an
435// environment. The user should subclass this to define his own
436// environment(s).
437//
438// An Environment object does the set-up and tear-down in virtual
439// methods SetUp() and TearDown() instead of the constructor and the
440// destructor, as:
441//
442// 1. You cannot safely throw from a destructor. This is a problem
443// as in some cases Google Test is used where exceptions are enabled, and
444// we may want to implement ASSERT_* using exceptions where they are
445// available.
446// 2. You cannot use ASSERT_* directly in a constructor or
447// destructor.
448class Environment {
449 public:
450 // The d'tor is virtual as we need to subclass Environment.
451 virtual ~Environment() {}
452
453 // Override this to define how to set up the environment.
454 virtual void SetUp() {}
455
456 // Override this to define how to tear down the environment.
457 virtual void TearDown() {}
458 private:
459 // If you see an error about overriding the following function or
460 // about it being private, you have mis-spelled SetUp() as Setup().
461 struct Setup_should_be_spelled_SetUp {};
462 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
463};
464
465// A UnitTest consists of a list of TestCases.
466//
467// This is a singleton class. The only instance of UnitTest is
468// created when UnitTest::GetInstance() is first called. This
469// instance is never deleted.
470//
471// UnitTest is not copyable.
472//
473// This class is thread-safe as long as the methods are called
474// according to their specification.
475class UnitTest {
476 public:
477 // Gets the singleton UnitTest object. The first time this method
478 // is called, a UnitTest object is constructed and returned.
479 // Consecutive calls will return the same object.
480 static UnitTest* GetInstance();
481
482 // Registers and returns a global test environment. When a test
483 // program is run, all global test environments will be set-up in
484 // the order they were registered. After all tests in the program
485 // have finished, all global test environments will be torn-down in
486 // the *reverse* order they were registered.
487 //
488 // The UnitTest object takes ownership of the given environment.
489 //
490 // This method can only be called from the main thread.
491 Environment* AddEnvironment(Environment* env);
492
493 // Adds a TestPartResult to the current TestResult object. All
494 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
495 // eventually call this to report their results. The user code
496 // should use the assertion macros instead of calling this directly.
497 //
498 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
499 void AddTestPartResult(TestPartResultType result_type,
500 const char* file_name,
501 int line_number,
502 const internal::String& message,
503 const internal::String& os_stack_trace);
504
505 // Adds a TestProperty to the current TestResult object. If the result already
506 // contains a property with the same key, the value will be updated.
507 void RecordPropertyForCurrentTest(const char* key, const char* value);
508
509 // Runs all tests in this UnitTest object and prints the result.
510 // Returns 0 if successful, or 1 otherwise.
511 //
512 // This method can only be called from the main thread.
513 //
514 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
515 int Run() GTEST_MUST_USE_RESULT_;
516
517 // Returns the working directory when the first TEST() or TEST_F()
518 // was executed. The UnitTest object owns the string.
519 const char* original_working_dir() const;
520
521 // Returns the TestCase object for the test that's currently running,
522 // or NULL if no test is running.
523 const TestCase* current_test_case() const;
524
525 // Returns the TestInfo object for the test that's currently running,
526 // or NULL if no test is running.
527 const TestInfo* current_test_info() const;
528
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000529#if GTEST_HAS_PARAM_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000530 // Returns the ParameterizedTestCaseRegistry object used to keep track of
531 // value-parameterized tests and instantiate and register them.
532 internal::ParameterizedTestCaseRegistry& parameterized_test_registry();
533#endif // GTEST_HAS_PARAM_TEST
534
535 // Accessors for the implementation object.
536 internal::UnitTestImpl* impl() { return impl_; }
537 const internal::UnitTestImpl* impl() const { return impl_; }
538 private:
539 // ScopedTrace is a friend as it needs to modify the per-thread
540 // trace stack, which is a private member of UnitTest.
541 friend class internal::ScopedTrace;
542
543 // Creates an empty UnitTest.
544 UnitTest();
545
546 // D'tor
547 virtual ~UnitTest();
548
549 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
550 // Google Test trace stack.
551 void PushGTestTrace(const internal::TraceInfo& trace);
552
553 // Pops a trace from the per-thread Google Test trace stack.
554 void PopGTestTrace();
555
556 // Protects mutable state in *impl_. This is mutable as some const
557 // methods need to lock it too.
558 mutable internal::Mutex mutex_;
559
560 // Opaque implementation object. This field is never changed once
561 // the object is constructed. We don't mark it as const here, as
562 // doing so will cause a warning in the constructor of UnitTest.
563 // Mutable state in *impl_ is protected by mutex_.
564 internal::UnitTestImpl* impl_;
565
566 // We disallow copying UnitTest.
567 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
568};
569
570// A convenient wrapper for adding an environment for the test
571// program.
572//
573// You should call this before RUN_ALL_TESTS() is called, probably in
574// main(). If you use gtest_main, you need to call this before main()
575// starts for it to take effect. For example, you can define a global
576// variable like this:
577//
578// testing::Environment* const foo_env =
579// testing::AddGlobalTestEnvironment(new FooEnvironment);
580//
581// However, we strongly recommend you to write your own main() and
582// call AddGlobalTestEnvironment() there, as relying on initialization
583// of global variables makes the code harder to read and may cause
584// problems when you register multiple environments from different
585// translation units and the environments have dependencies among them
586// (remember that the compiler doesn't guarantee the order in which
587// global variables from different translation units are initialized).
588inline Environment* AddGlobalTestEnvironment(Environment* env) {
589 return UnitTest::GetInstance()->AddEnvironment(env);
590}
591
592// Initializes Google Test. This must be called before calling
593// RUN_ALL_TESTS(). In particular, it parses a command line for the
594// flags that Google Test recognizes. Whenever a Google Test flag is
595// seen, it is removed from argv, and *argc is decremented.
596//
597// No value is returned. Instead, the Google Test flag variables are
598// updated.
599//
600// Calling the function for the second time has no user-visible effect.
601void InitGoogleTest(int* argc, char** argv);
602
603// This overloaded version can be used in Windows programs compiled in
604// UNICODE mode.
605void InitGoogleTest(int* argc, wchar_t** argv);
606
607namespace internal {
608
609// These overloaded versions handle ::std::string and ::std::wstring.
610#if GTEST_HAS_STD_STRING
611inline String FormatForFailureMessage(const ::std::string& str) {
612 return (Message() << '"' << str << '"').GetString();
613}
614#endif // GTEST_HAS_STD_STRING
615
616#if GTEST_HAS_STD_WSTRING
617inline String FormatForFailureMessage(const ::std::wstring& wstr) {
618 return (Message() << "L\"" << wstr << '"').GetString();
619}
620#endif // GTEST_HAS_STD_WSTRING
621
622// These overloaded versions handle ::string and ::wstring.
623#if GTEST_HAS_GLOBAL_STRING
624inline String FormatForFailureMessage(const ::string& str) {
625 return (Message() << '"' << str << '"').GetString();
626}
627#endif // GTEST_HAS_GLOBAL_STRING
628
629#if GTEST_HAS_GLOBAL_WSTRING
630inline String FormatForFailureMessage(const ::wstring& wstr) {
631 return (Message() << "L\"" << wstr << '"').GetString();
632}
633#endif // GTEST_HAS_GLOBAL_WSTRING
634
635// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
636// operand to be used in a failure message. The type (but not value)
637// of the other operand may affect the format. This allows us to
638// print a char* as a raw pointer when it is compared against another
639// char*, and print it as a C string when it is compared against an
640// std::string object, for example.
641//
642// The default implementation ignores the type of the other operand.
643// Some specialized versions are used to handle formatting wide or
644// narrow C strings.
645//
646// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
647template <typename T1, typename T2>
648String FormatForComparisonFailureMessage(const T1& value,
649 const T2& /* other_operand */) {
650 return FormatForFailureMessage(value);
651}
652
653// The helper function for {ASSERT|EXPECT}_EQ.
654template <typename T1, typename T2>
655AssertionResult CmpHelperEQ(const char* expected_expression,
656 const char* actual_expression,
657 const T1& expected,
658 const T2& actual) {
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000659#ifdef _MSC_VER
660#pragma warning(push) // Saves the current warning state.
661#pragma warning(disable:4389) // Temporarily disables warning on
662 // signed/unsigned mismatch.
663#endif
664
Misha Brukmanc89aba32008-12-31 17:34:06 +0000665 if (expected == actual) {
666 return AssertionSuccess();
667 }
668
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000669#ifdef _MSC_VER
670#pragma warning(pop) // Restores the warning state.
671#endif
672
Misha Brukmanc89aba32008-12-31 17:34:06 +0000673 return EqFailure(expected_expression,
674 actual_expression,
675 FormatForComparisonFailureMessage(expected, actual),
676 FormatForComparisonFailureMessage(actual, expected),
677 false);
678}
679
680// With this overloaded version, we allow anonymous enums to be used
681// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
682// can be implicitly cast to BiggestInt.
683AssertionResult CmpHelperEQ(const char* expected_expression,
684 const char* actual_expression,
685 BiggestInt expected,
686 BiggestInt actual);
687
688// The helper class for {ASSERT|EXPECT}_EQ. The template argument
689// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
690// is a null pointer literal. The following default implementation is
691// for lhs_is_null_literal being false.
692template <bool lhs_is_null_literal>
693class EqHelper {
694 public:
695 // This templatized version is for the general case.
696 template <typename T1, typename T2>
697 static AssertionResult Compare(const char* expected_expression,
698 const char* actual_expression,
699 const T1& expected,
700 const T2& actual) {
701 return CmpHelperEQ(expected_expression, actual_expression, expected,
702 actual);
703 }
704
705 // With this overloaded version, we allow anonymous enums to be used
706 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
707 // enums can be implicitly cast to BiggestInt.
708 //
709 // Even though its body looks the same as the above version, we
710 // cannot merge the two, as it will make anonymous enums unhappy.
711 static AssertionResult Compare(const char* expected_expression,
712 const char* actual_expression,
713 BiggestInt expected,
714 BiggestInt actual) {
715 return CmpHelperEQ(expected_expression, actual_expression, expected,
716 actual);
717 }
718};
719
720// This specialization is used when the first argument to ASSERT_EQ()
721// is a null pointer literal.
722template <>
723class EqHelper<true> {
724 public:
725 // We define two overloaded versions of Compare(). The first
726 // version will be picked when the second argument to ASSERT_EQ() is
727 // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
728 // EXPECT_EQ(false, a_bool).
729 template <typename T1, typename T2>
730 static AssertionResult Compare(const char* expected_expression,
731 const char* actual_expression,
732 const T1& expected,
733 const T2& actual) {
734 return CmpHelperEQ(expected_expression, actual_expression, expected,
735 actual);
736 }
737
738 // This version will be picked when the second argument to
739 // ASSERT_EQ() is a pointer, e.g. ASSERT_EQ(NULL, a_pointer).
740 template <typename T1, typename T2>
741 static AssertionResult Compare(const char* expected_expression,
742 const char* actual_expression,
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000743 const T1& /* expected */,
Misha Brukmanc89aba32008-12-31 17:34:06 +0000744 T2* actual) {
745 // We already know that 'expected' is a null pointer.
746 return CmpHelperEQ(expected_expression, actual_expression,
747 static_cast<T2*>(NULL), actual);
748 }
749};
750
751// A macro for implementing the helper functions needed to implement
752// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
753// of similar code.
754//
755// For each templatized helper function, we also define an overloaded
756// version for BiggestInt in order to reduce code bloat and allow
757// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
758// with gcc 4.
759//
760// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
761#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
762template <typename T1, typename T2>\
763AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
764 const T1& val1, const T2& val2) {\
765 if (val1 op val2) {\
766 return AssertionSuccess();\
767 } else {\
768 Message msg;\
769 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
770 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
771 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
772 return AssertionFailure(msg);\
773 }\
774}\
775AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
776 BiggestInt val1, BiggestInt val2);
777
778// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
779
780// Implements the helper function for {ASSERT|EXPECT}_NE
781GTEST_IMPL_CMP_HELPER_(NE, !=)
782// Implements the helper function for {ASSERT|EXPECT}_LE
783GTEST_IMPL_CMP_HELPER_(LE, <=)
784// Implements the helper function for {ASSERT|EXPECT}_LT
785GTEST_IMPL_CMP_HELPER_(LT, < )
786// Implements the helper function for {ASSERT|EXPECT}_GE
787GTEST_IMPL_CMP_HELPER_(GE, >=)
788// Implements the helper function for {ASSERT|EXPECT}_GT
789GTEST_IMPL_CMP_HELPER_(GT, > )
790
791#undef GTEST_IMPL_CMP_HELPER_
792
793// The helper function for {ASSERT|EXPECT}_STREQ.
794//
795// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
796AssertionResult CmpHelperSTREQ(const char* expected_expression,
797 const char* actual_expression,
798 const char* expected,
799 const char* actual);
800
801// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
802//
803// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
804AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
805 const char* actual_expression,
806 const char* expected,
807 const char* actual);
808
809// The helper function for {ASSERT|EXPECT}_STRNE.
810//
811// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
812AssertionResult CmpHelperSTRNE(const char* s1_expression,
813 const char* s2_expression,
814 const char* s1,
815 const char* s2);
816
817// The helper function for {ASSERT|EXPECT}_STRCASENE.
818//
819// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
820AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
821 const char* s2_expression,
822 const char* s1,
823 const char* s2);
824
825
826// Helper function for *_STREQ on wide strings.
827//
828// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
829AssertionResult CmpHelperSTREQ(const char* expected_expression,
830 const char* actual_expression,
831 const wchar_t* expected,
832 const wchar_t* actual);
833
834// Helper function for *_STRNE on wide strings.
835//
836// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
837AssertionResult CmpHelperSTRNE(const char* s1_expression,
838 const char* s2_expression,
839 const wchar_t* s1,
840 const wchar_t* s2);
841
842} // namespace internal
843
844// IsSubstring() and IsNotSubstring() are intended to be used as the
845// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
846// themselves. They check whether needle is a substring of haystack
847// (NULL is considered a substring of itself only), and return an
848// appropriate error message when they fail.
849//
850// The {needle,haystack}_expr arguments are the stringified
851// expressions that generated the two real arguments.
852AssertionResult IsSubstring(
853 const char* needle_expr, const char* haystack_expr,
854 const char* needle, const char* haystack);
855AssertionResult IsSubstring(
856 const char* needle_expr, const char* haystack_expr,
857 const wchar_t* needle, const wchar_t* haystack);
858AssertionResult IsNotSubstring(
859 const char* needle_expr, const char* haystack_expr,
860 const char* needle, const char* haystack);
861AssertionResult IsNotSubstring(
862 const char* needle_expr, const char* haystack_expr,
863 const wchar_t* needle, const wchar_t* haystack);
864#if GTEST_HAS_STD_STRING
865AssertionResult IsSubstring(
866 const char* needle_expr, const char* haystack_expr,
867 const ::std::string& needle, const ::std::string& haystack);
868AssertionResult IsNotSubstring(
869 const char* needle_expr, const char* haystack_expr,
870 const ::std::string& needle, const ::std::string& haystack);
871#endif // GTEST_HAS_STD_STRING
872
873#if GTEST_HAS_STD_WSTRING
874AssertionResult IsSubstring(
875 const char* needle_expr, const char* haystack_expr,
876 const ::std::wstring& needle, const ::std::wstring& haystack);
877AssertionResult IsNotSubstring(
878 const char* needle_expr, const char* haystack_expr,
879 const ::std::wstring& needle, const ::std::wstring& haystack);
880#endif // GTEST_HAS_STD_WSTRING
881
882namespace internal {
883
884// Helper template function for comparing floating-points.
885//
886// Template parameter:
887//
888// RawType: the raw floating-point type (either float or double)
889//
890// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
891template <typename RawType>
892AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression,
893 const char* actual_expression,
894 RawType expected,
895 RawType actual) {
896 const FloatingPoint<RawType> lhs(expected), rhs(actual);
897
898 if (lhs.AlmostEquals(rhs)) {
899 return AssertionSuccess();
900 }
901
902 StrStream expected_ss;
903 expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
904 << expected;
905
906 StrStream actual_ss;
907 actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
908 << actual;
909
910 return EqFailure(expected_expression,
911 actual_expression,
912 StrStreamToString(&expected_ss),
913 StrStreamToString(&actual_ss),
914 false);
915}
916
917// Helper function for implementing ASSERT_NEAR.
918//
919// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
920AssertionResult DoubleNearPredFormat(const char* expr1,
921 const char* expr2,
922 const char* abs_error_expr,
923 double val1,
924 double val2,
925 double abs_error);
926
927// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
928// A class that enables one to stream messages to assertion macros
929class AssertHelper {
930 public:
931 // Constructor.
932 AssertHelper(TestPartResultType type, const char* file, int line,
933 const char* message);
934 // Message assignment is a semantic trick to enable assertion
935 // streaming; see the GTEST_MESSAGE_ macro below.
936 void operator=(const Message& message) const;
937 private:
938 TestPartResultType const type_;
939 const char* const file_;
940 int const line_;
941 String const message_;
942
943 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
944};
945
946} // namespace internal
947
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000948#if GTEST_HAS_PARAM_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000949// The abstract base class that all value-parameterized tests inherit from.
950//
951// This class adds support for accessing the test parameter value via
952// the GetParam() method.
953//
954// Use it with one of the parameter generator defining functions, like Range(),
955// Values(), ValuesIn(), Bool(), and Combine().
956//
957// class FooTest : public ::testing::TestWithParam<int> {
958// protected:
959// FooTest() {
960// // Can use GetParam() here.
961// }
962// virtual ~FooTest() {
963// // Can use GetParam() here.
964// }
965// virtual void SetUp() {
966// // Can use GetParam() here.
967// }
968// virtual void TearDown {
969// // Can use GetParam() here.
970// }
971// };
972// TEST_P(FooTest, DoesBar) {
973// // Can use GetParam() method here.
974// Foo foo;
975// ASSERT_TRUE(foo.DoesBar(GetParam()));
976// }
977// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
978
979template <typename T>
980class TestWithParam : public Test {
981 public:
982 typedef T ParamType;
983
984 // The current parameter value. Is also available in the test fixture's
985 // constructor.
986 const ParamType& GetParam() const { return *parameter_; }
987
988 private:
989 // Sets parameter value. The caller is responsible for making sure the value
990 // remains alive and unchanged throughout the current test.
991 static void SetParam(const ParamType* parameter) {
992 parameter_ = parameter;
993 }
994
995 // Static value used for accessing parameter during a test lifetime.
996 static const ParamType* parameter_;
997
998 // TestClass must be a subclass of TestWithParam<T>.
999 template <class TestClass> friend class internal::ParameterizedTestFactory;
1000};
1001
1002template <typename T>
1003const T* TestWithParam<T>::parameter_ = NULL;
1004
1005#endif // GTEST_HAS_PARAM_TEST
1006
1007// Macros for indicating success/failure in test code.
1008
1009// ADD_FAILURE unconditionally adds a failure to the current test.
1010// SUCCEED generates a success - it doesn't automatically make the
1011// current test successful, as a test is only successful when it has
1012// no failure.
1013//
1014// EXPECT_* verifies that a certain condition is satisfied. If not,
1015// it behaves like ADD_FAILURE. In particular:
1016//
1017// EXPECT_TRUE verifies that a Boolean condition is true.
1018// EXPECT_FALSE verifies that a Boolean condition is false.
1019//
1020// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
1021// that they will also abort the current function on failure. People
1022// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
1023// writing data-driven tests often find themselves using ADD_FAILURE
1024// and EXPECT_* more.
1025//
1026// Examples:
1027//
1028// EXPECT_TRUE(server.StatusIsOK());
1029// ASSERT_FALSE(server.HasPendingRequest(port))
1030// << "There are still pending requests " << "on port " << port;
1031
1032// Generates a nonfatal failure with a generic message.
1033#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
1034
1035// Generates a fatal failure with a generic message.
1036#define FAIL() GTEST_FATAL_FAILURE_("Failed")
1037
1038// Generates a success with a generic message.
1039#define SUCCEED() GTEST_SUCCESS_("Succeeded")
1040
1041// Macros for testing exceptions.
1042//
1043// * {ASSERT|EXPECT}_THROW(statement, expected_exception):
1044// Tests that the statement throws the expected exception.
1045// * {ASSERT|EXPECT}_NO_THROW(statement):
1046// Tests that the statement doesn't throw any exception.
1047// * {ASSERT|EXPECT}_ANY_THROW(statement):
1048// Tests that the statement throws an exception.
1049
1050#define EXPECT_THROW(statement, expected_exception) \
1051 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1052#define EXPECT_NO_THROW(statement) \
1053 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1054#define EXPECT_ANY_THROW(statement) \
1055 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1056#define ASSERT_THROW(statement, expected_exception) \
1057 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1058#define ASSERT_NO_THROW(statement) \
1059 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1060#define ASSERT_ANY_THROW(statement) \
1061 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1062
1063// Boolean assertions.
1064#define EXPECT_TRUE(condition) \
1065 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1066 GTEST_NONFATAL_FAILURE_)
1067#define EXPECT_FALSE(condition) \
1068 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1069 GTEST_NONFATAL_FAILURE_)
1070#define ASSERT_TRUE(condition) \
1071 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1072 GTEST_FATAL_FAILURE_)
1073#define ASSERT_FALSE(condition) \
1074 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1075 GTEST_FATAL_FAILURE_)
1076
1077// Includes the auto-generated header that implements a family of
1078// generic predicate assertion macros.
1079#include <gtest/gtest_pred_impl.h>
1080
1081// Macros for testing equalities and inequalities.
1082//
1083// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual
1084// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
1085// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
1086// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
1087// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
1088// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
1089//
1090// When they are not, Google Test prints both the tested expressions and
1091// their actual values. The values must be compatible built-in types,
1092// or you will get a compiler error. By "compatible" we mean that the
1093// values can be compared by the respective operator.
1094//
1095// Note:
1096//
1097// 1. It is possible to make a user-defined type work with
1098// {ASSERT|EXPECT}_??(), but that requires overloading the
1099// comparison operators and is thus discouraged by the Google C++
1100// Usage Guide. Therefore, you are advised to use the
1101// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
1102// equal.
1103//
1104// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
1105// pointers (in particular, C strings). Therefore, if you use it
1106// with two C strings, you are testing how their locations in memory
1107// are related, not how their content is related. To compare two C
1108// strings by content, use {ASSERT|EXPECT}_STR*().
1109//
1110// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to
1111// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you
1112// what the actual value is when it fails, and similarly for the
1113// other comparisons.
1114//
1115// 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
1116// evaluate their arguments, which is undefined.
1117//
1118// 5. These macros evaluate their arguments exactly once.
1119//
1120// Examples:
1121//
1122// EXPECT_NE(5, Foo());
1123// EXPECT_EQ(NULL, a_pointer);
1124// ASSERT_LT(i, array_size);
1125// ASSERT_GT(records.size(), 0) << "There is no record left.";
1126
1127#define EXPECT_EQ(expected, actual) \
1128 EXPECT_PRED_FORMAT2(::testing::internal:: \
1129 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1130 expected, actual)
1131#define EXPECT_NE(expected, actual) \
1132 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual)
1133#define EXPECT_LE(val1, val2) \
1134 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1135#define EXPECT_LT(val1, val2) \
1136 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1137#define EXPECT_GE(val1, val2) \
1138 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1139#define EXPECT_GT(val1, val2) \
1140 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1141
1142#define ASSERT_EQ(expected, actual) \
1143 ASSERT_PRED_FORMAT2(::testing::internal:: \
1144 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1145 expected, actual)
1146#define ASSERT_NE(val1, val2) \
1147 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1148#define ASSERT_LE(val1, val2) \
1149 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1150#define ASSERT_LT(val1, val2) \
1151 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1152#define ASSERT_GE(val1, val2) \
1153 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1154#define ASSERT_GT(val1, val2) \
1155 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1156
1157// C String Comparisons. All tests treat NULL and any non-NULL string
1158// as different. Two NULLs are equal.
1159//
1160// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
1161// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
1162// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
1163// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
1164//
1165// For wide or narrow string objects, you can use the
1166// {ASSERT|EXPECT}_??() macros.
1167//
1168// Don't depend on the order in which the arguments are evaluated,
1169// which is undefined.
1170//
1171// These macros evaluate their arguments exactly once.
1172
1173#define EXPECT_STREQ(expected, actual) \
1174 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
1175#define EXPECT_STRNE(s1, s2) \
1176 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
1177#define EXPECT_STRCASEEQ(expected, actual) \
1178 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
1179#define EXPECT_STRCASENE(s1, s2)\
1180 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
1181
1182#define ASSERT_STREQ(expected, actual) \
1183 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
1184#define ASSERT_STRNE(s1, s2) \
1185 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
1186#define ASSERT_STRCASEEQ(expected, actual) \
1187 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
1188#define ASSERT_STRCASENE(s1, s2)\
1189 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
1190
1191// Macros for comparing floating-point numbers.
1192//
1193// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual):
1194// Tests that two float values are almost equal.
1195// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual):
1196// Tests that two double values are almost equal.
1197// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
1198// Tests that v1 and v2 are within the given distance to each other.
1199//
1200// Google Test uses ULP-based comparison to automatically pick a default
1201// error bound that is appropriate for the operands. See the
1202// FloatingPoint template class in gtest-internal.h if you are
1203// interested in the implementation details.
1204
1205#define EXPECT_FLOAT_EQ(expected, actual)\
1206 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
1207 expected, actual)
1208
1209#define EXPECT_DOUBLE_EQ(expected, actual)\
1210 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
1211 expected, actual)
1212
1213#define ASSERT_FLOAT_EQ(expected, actual)\
1214 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
1215 expected, actual)
1216
1217#define ASSERT_DOUBLE_EQ(expected, actual)\
1218 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
1219 expected, actual)
1220
1221#define EXPECT_NEAR(val1, val2, abs_error)\
1222 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
1223 val1, val2, abs_error)
1224
1225#define ASSERT_NEAR(val1, val2, abs_error)\
1226 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
1227 val1, val2, abs_error)
1228
1229// These predicate format functions work on floating-point values, and
1230// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
1231//
1232// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
1233
1234// Asserts that val1 is less than, or almost equal to, val2. Fails
1235// otherwise. In particular, it fails if either val1 or val2 is NaN.
1236AssertionResult FloatLE(const char* expr1, const char* expr2,
1237 float val1, float val2);
1238AssertionResult DoubleLE(const char* expr1, const char* expr2,
1239 double val1, double val2);
1240
1241
Benjamin Kramerf2f40202010-06-02 22:01:25 +00001242#if GTEST_OS_WINDOWS
Misha Brukmanc89aba32008-12-31 17:34:06 +00001243
1244// Macros that test for HRESULT failure and success, these are only useful
1245// on Windows, and rely on Windows SDK macros and APIs to compile.
1246//
1247// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
1248//
1249// When expr unexpectedly fails or succeeds, Google Test prints the
1250// expected result and the actual result with both a human-readable
1251// string representation of the error, if available, as well as the
1252// hex result code.
1253#define EXPECT_HRESULT_SUCCEEDED(expr) \
1254 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
1255
1256#define ASSERT_HRESULT_SUCCEEDED(expr) \
1257 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
1258
1259#define EXPECT_HRESULT_FAILED(expr) \
1260 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
1261
1262#define ASSERT_HRESULT_FAILED(expr) \
1263 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
1264
1265#endif // GTEST_OS_WINDOWS
1266
1267// Macros that execute statement and check that it doesn't generate new fatal
1268// failures in the current thread.
1269//
1270// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
1271//
1272// Examples:
1273//
1274// EXPECT_NO_FATAL_FAILURE(Process());
1275// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
1276//
1277#define ASSERT_NO_FATAL_FAILURE(statement) \
1278 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
1279#define EXPECT_NO_FATAL_FAILURE(statement) \
1280 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
1281
1282// Causes a trace (including the source file path, the current line
1283// number, and the given message) to be included in every test failure
1284// message generated by code in the current scope. The effect is
1285// undone when the control leaves the current scope.
1286//
1287// The message argument can be anything streamable to std::ostream.
1288//
1289// In the implementation, we include the current line number as part
1290// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
1291// to appear in the same block - as long as they are on different
1292// lines.
1293#define SCOPED_TRACE(message) \
1294 ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
1295 __FILE__, __LINE__, ::testing::Message() << (message))
1296
Benjamin Kramerf2f40202010-06-02 22:01:25 +00001297namespace internal {
1298
1299// This template is declared, but intentionally undefined.
1300template <typename T1, typename T2>
1301struct StaticAssertTypeEqHelper;
1302
1303template <typename T>
1304struct StaticAssertTypeEqHelper<T, T> {};
1305
1306} // namespace internal
1307
1308// Compile-time assertion for type equality.
1309// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
1310// the same type. The value it returns is not interesting.
1311//
1312// Instead of making StaticAssertTypeEq a class template, we make it a
1313// function template that invokes a helper class template. This
1314// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
1315// defining objects of that type.
1316//
1317// CAVEAT:
1318//
1319// When used inside a method of a class template,
1320// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
1321// instantiated. For example, given:
1322//
1323// template <typename T> class Foo {
1324// public:
1325// void Bar() { testing::StaticAssertTypeEq<int, T>(); }
1326// };
1327//
1328// the code:
1329//
1330// void Test1() { Foo<bool> foo; }
1331//
1332// will NOT generate a compiler error, as Foo<bool>::Bar() is never
1333// actually instantiated. Instead, you need:
1334//
1335// void Test2() { Foo<bool> foo; foo.Bar(); }
1336//
1337// to cause a compiler error.
1338template <typename T1, typename T2>
1339bool StaticAssertTypeEq() {
1340 internal::StaticAssertTypeEqHelper<T1, T2>();
1341 return true;
1342}
Misha Brukmanc89aba32008-12-31 17:34:06 +00001343
1344// Defines a test.
1345//
1346// The first parameter is the name of the test case, and the second
1347// parameter is the name of the test within the test case.
1348//
1349// The convention is to end the test case name with "Test". For
1350// example, a test case for the Foo class can be named FooTest.
1351//
1352// The user should put his test code between braces after using this
1353// macro. Example:
1354//
1355// TEST(FooTest, InitializesCorrectly) {
1356// Foo foo;
1357// EXPECT_TRUE(foo.StatusIsOK());
1358// }
1359
1360// Note that we call GetTestTypeId() instead of GetTypeId<
1361// ::testing::Test>() here to get the type ID of testing::Test. This
1362// is to work around a suspected linker bug when using Google Test as
1363// a framework on Mac OS X. The bug causes GetTypeId<
1364// ::testing::Test>() to return different values depending on whether
1365// the call is from the Google Test framework itself or from user test
1366// code. GetTestTypeId() is guaranteed to always return the same
1367// value, as it always calls GetTypeId<>() from the Google Test
1368// framework.
1369#define TEST(test_case_name, test_name)\
Benjamin Kramerf2f40202010-06-02 22:01:25 +00001370 GTEST_TEST_(test_case_name, test_name, \
Misha Brukmanc89aba32008-12-31 17:34:06 +00001371 ::testing::Test, ::testing::internal::GetTestTypeId())
1372
1373
1374// Defines a test that uses a test fixture.
1375//
1376// The first parameter is the name of the test fixture class, which
1377// also doubles as the test case name. The second parameter is the
1378// name of the test within the test case.
1379//
1380// A test fixture class must be declared earlier. The user should put
1381// his test code between braces after using this macro. Example:
1382//
1383// class FooTest : public testing::Test {
1384// protected:
1385// virtual void SetUp() { b_.AddElement(3); }
1386//
1387// Foo a_;
1388// Foo b_;
1389// };
1390//
1391// TEST_F(FooTest, InitializesCorrectly) {
1392// EXPECT_TRUE(a_.StatusIsOK());
1393// }
1394//
1395// TEST_F(FooTest, ReturnsElementCountCorrectly) {
1396// EXPECT_EQ(0, a_.size());
1397// EXPECT_EQ(1, b_.size());
1398// }
1399
1400#define TEST_F(test_fixture, test_name)\
Benjamin Kramerf2f40202010-06-02 22:01:25 +00001401 GTEST_TEST_(test_fixture, test_name, test_fixture, \
Misha Brukmanc89aba32008-12-31 17:34:06 +00001402 ::testing::internal::GetTypeId<test_fixture>())
1403
1404// Use this macro in main() to run all tests. It returns 0 if all
1405// tests are successful, or 1 otherwise.
1406//
1407// RUN_ALL_TESTS() should be invoked after the command line has been
1408// parsed by InitGoogleTest().
1409
1410#define RUN_ALL_TESTS()\
1411 (::testing::UnitTest::GetInstance()->Run())
1412
1413} // namespace testing
1414
1415#endif // GTEST_INCLUDE_GTEST_GTEST_H_