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