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