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