1f92157deSopenharmony_ci# Advanced googletest Topics 2f92157deSopenharmony_ci 3f92157deSopenharmony_ci## Introduction 4f92157deSopenharmony_ci 5f92157deSopenharmony_ciNow that you have read the [googletest Primer](primer.md) and learned how to 6f92157deSopenharmony_ciwrite tests using googletest, it's time to learn some new tricks. This document 7f92157deSopenharmony_ciwill show you more assertions as well as how to construct complex failure 8f92157deSopenharmony_cimessages, propagate fatal failures, reuse and speed up your test fixtures, and 9f92157deSopenharmony_ciuse various flags with your tests. 10f92157deSopenharmony_ci 11f92157deSopenharmony_ci## More Assertions 12f92157deSopenharmony_ci 13f92157deSopenharmony_ciThis section covers some less frequently used, but still significant, 14f92157deSopenharmony_ciassertions. 15f92157deSopenharmony_ci 16f92157deSopenharmony_ci### Explicit Success and Failure 17f92157deSopenharmony_ci 18f92157deSopenharmony_ciSee [Explicit Success and Failure](reference/assertions.md#success-failure) in 19f92157deSopenharmony_cithe Assertions Reference. 20f92157deSopenharmony_ci 21f92157deSopenharmony_ci### Exception Assertions 22f92157deSopenharmony_ci 23f92157deSopenharmony_ciSee [Exception Assertions](reference/assertions.md#exceptions) in the Assertions 24f92157deSopenharmony_ciReference. 25f92157deSopenharmony_ci 26f92157deSopenharmony_ci### Predicate Assertions for Better Error Messages 27f92157deSopenharmony_ci 28f92157deSopenharmony_ciEven though googletest has a rich set of assertions, they can never be complete, 29f92157deSopenharmony_cias it's impossible (nor a good idea) to anticipate all scenarios a user might 30f92157deSopenharmony_cirun into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a 31f92157deSopenharmony_cicomplex expression, for lack of a better macro. This has the problem of not 32f92157deSopenharmony_cishowing you the values of the parts of the expression, making it hard to 33f92157deSopenharmony_ciunderstand what went wrong. As a workaround, some users choose to construct the 34f92157deSopenharmony_cifailure message by themselves, streaming it into `EXPECT_TRUE()`. However, this 35f92157deSopenharmony_ciis awkward especially when the expression has side-effects or is expensive to 36f92157deSopenharmony_cievaluate. 37f92157deSopenharmony_ci 38f92157deSopenharmony_cigoogletest gives you three different options to solve this problem: 39f92157deSopenharmony_ci 40f92157deSopenharmony_ci#### Using an Existing Boolean Function 41f92157deSopenharmony_ci 42f92157deSopenharmony_ciIf you already have a function or functor that returns `bool` (or a type that 43f92157deSopenharmony_cican be implicitly converted to `bool`), you can use it in a *predicate 44f92157deSopenharmony_ciassertion* to get the function arguments printed for free. See 45f92157deSopenharmony_ci[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions 46f92157deSopenharmony_ciReference for details. 47f92157deSopenharmony_ci 48f92157deSopenharmony_ci#### Using a Function That Returns an AssertionResult 49f92157deSopenharmony_ci 50f92157deSopenharmony_ciWhile `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not 51f92157deSopenharmony_cisatisfactory: you have to use different macros for different arities, and it 52f92157deSopenharmony_cifeels more like Lisp than C++. The `::testing::AssertionResult` class solves 53f92157deSopenharmony_cithis problem. 54f92157deSopenharmony_ci 55f92157deSopenharmony_ciAn `AssertionResult` object represents the result of an assertion (whether it's 56f92157deSopenharmony_cia success or a failure, and an associated message). You can create an 57f92157deSopenharmony_ci`AssertionResult` using one of these factory functions: 58f92157deSopenharmony_ci 59f92157deSopenharmony_ci```c++ 60f92157deSopenharmony_cinamespace testing { 61f92157deSopenharmony_ci 62f92157deSopenharmony_ci// Returns an AssertionResult object to indicate that an assertion has 63f92157deSopenharmony_ci// succeeded. 64f92157deSopenharmony_ciAssertionResult AssertionSuccess(); 65f92157deSopenharmony_ci 66f92157deSopenharmony_ci// Returns an AssertionResult object to indicate that an assertion has 67f92157deSopenharmony_ci// failed. 68f92157deSopenharmony_ciAssertionResult AssertionFailure(); 69f92157deSopenharmony_ci 70f92157deSopenharmony_ci} 71f92157deSopenharmony_ci``` 72f92157deSopenharmony_ci 73f92157deSopenharmony_ciYou can then use the `<<` operator to stream messages to the `AssertionResult` 74f92157deSopenharmony_ciobject. 75f92157deSopenharmony_ci 76f92157deSopenharmony_ciTo provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), 77f92157deSopenharmony_ciwrite a predicate function that returns `AssertionResult` instead of `bool`. For 78f92157deSopenharmony_ciexample, if you define `IsEven()` as: 79f92157deSopenharmony_ci 80f92157deSopenharmony_ci```c++ 81f92157deSopenharmony_citesting::AssertionResult IsEven(int n) { 82f92157deSopenharmony_ci if ((n % 2) == 0) 83f92157deSopenharmony_ci return testing::AssertionSuccess(); 84f92157deSopenharmony_ci else 85f92157deSopenharmony_ci return testing::AssertionFailure() << n << " is odd"; 86f92157deSopenharmony_ci} 87f92157deSopenharmony_ci``` 88f92157deSopenharmony_ci 89f92157deSopenharmony_ciinstead of: 90f92157deSopenharmony_ci 91f92157deSopenharmony_ci```c++ 92f92157deSopenharmony_cibool IsEven(int n) { 93f92157deSopenharmony_ci return (n % 2) == 0; 94f92157deSopenharmony_ci} 95f92157deSopenharmony_ci``` 96f92157deSopenharmony_ci 97f92157deSopenharmony_cithe failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: 98f92157deSopenharmony_ci 99f92157deSopenharmony_ci```none 100f92157deSopenharmony_ciValue of: IsEven(Fib(4)) 101f92157deSopenharmony_ci Actual: false (3 is odd) 102f92157deSopenharmony_ciExpected: true 103f92157deSopenharmony_ci``` 104f92157deSopenharmony_ci 105f92157deSopenharmony_ciinstead of a more opaque 106f92157deSopenharmony_ci 107f92157deSopenharmony_ci```none 108f92157deSopenharmony_ciValue of: IsEven(Fib(4)) 109f92157deSopenharmony_ci Actual: false 110f92157deSopenharmony_ciExpected: true 111f92157deSopenharmony_ci``` 112f92157deSopenharmony_ci 113f92157deSopenharmony_ciIf you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well 114f92157deSopenharmony_ci(one third of Boolean assertions in the Google code base are negative ones), and 115f92157deSopenharmony_ciare fine with making the predicate slower in the success case, you can supply a 116f92157deSopenharmony_cisuccess message: 117f92157deSopenharmony_ci 118f92157deSopenharmony_ci```c++ 119f92157deSopenharmony_citesting::AssertionResult IsEven(int n) { 120f92157deSopenharmony_ci if ((n % 2) == 0) 121f92157deSopenharmony_ci return testing::AssertionSuccess() << n << " is even"; 122f92157deSopenharmony_ci else 123f92157deSopenharmony_ci return testing::AssertionFailure() << n << " is odd"; 124f92157deSopenharmony_ci} 125f92157deSopenharmony_ci``` 126f92157deSopenharmony_ci 127f92157deSopenharmony_ciThen the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print 128f92157deSopenharmony_ci 129f92157deSopenharmony_ci```none 130f92157deSopenharmony_ci Value of: IsEven(Fib(6)) 131f92157deSopenharmony_ci Actual: true (8 is even) 132f92157deSopenharmony_ci Expected: false 133f92157deSopenharmony_ci``` 134f92157deSopenharmony_ci 135f92157deSopenharmony_ci#### Using a Predicate-Formatter 136f92157deSopenharmony_ci 137f92157deSopenharmony_ciIf you find the default message generated by 138f92157deSopenharmony_ci[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and 139f92157deSopenharmony_ci[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some 140f92157deSopenharmony_ciarguments to your predicate do not support streaming to `ostream`, you can 141f92157deSopenharmony_ciinstead use *predicate-formatter assertions* to *fully* customize how the 142f92157deSopenharmony_cimessage is formatted. See 143f92157deSopenharmony_ci[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the 144f92157deSopenharmony_ciAssertions Reference for details. 145f92157deSopenharmony_ci 146f92157deSopenharmony_ci### Floating-Point Comparison 147f92157deSopenharmony_ci 148f92157deSopenharmony_ciSee [Floating-Point Comparison](reference/assertions.md#floating-point) in the 149f92157deSopenharmony_ciAssertions Reference. 150f92157deSopenharmony_ci 151f92157deSopenharmony_ci#### Floating-Point Predicate-Format Functions 152f92157deSopenharmony_ci 153f92157deSopenharmony_ciSome floating-point operations are useful, but not that often used. In order to 154f92157deSopenharmony_ciavoid an explosion of new macros, we provide them as predicate-format functions 155f92157deSopenharmony_cithat can be used in the predicate assertion macro 156f92157deSopenharmony_ci[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for 157f92157deSopenharmony_ciexample: 158f92157deSopenharmony_ci 159f92157deSopenharmony_ci```c++ 160f92157deSopenharmony_ciusing ::testing::FloatLE; 161f92157deSopenharmony_ciusing ::testing::DoubleLE; 162f92157deSopenharmony_ci... 163f92157deSopenharmony_ciEXPECT_PRED_FORMAT2(FloatLE, val1, val2); 164f92157deSopenharmony_ciEXPECT_PRED_FORMAT2(DoubleLE, val1, val2); 165f92157deSopenharmony_ci``` 166f92157deSopenharmony_ci 167f92157deSopenharmony_ciThe above code verifies that `val1` is less than, or approximately equal to, 168f92157deSopenharmony_ci`val2`. 169f92157deSopenharmony_ci 170f92157deSopenharmony_ci### Asserting Using gMock Matchers 171f92157deSopenharmony_ci 172f92157deSopenharmony_ciSee [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions 173f92157deSopenharmony_ciReference. 174f92157deSopenharmony_ci 175f92157deSopenharmony_ci### More String Assertions 176f92157deSopenharmony_ci 177f92157deSopenharmony_ci(Please read the [previous](#asserting-using-gmock-matchers) section first if 178f92157deSopenharmony_ciyou haven't.) 179f92157deSopenharmony_ci 180f92157deSopenharmony_ciYou can use the gMock [string matchers](reference/matchers.md#string-matchers) 181f92157deSopenharmony_ciwith [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string 182f92157deSopenharmony_cicomparison tricks (sub-string, prefix, suffix, regular expression, and etc). For 183f92157deSopenharmony_ciexample, 184f92157deSopenharmony_ci 185f92157deSopenharmony_ci```c++ 186f92157deSopenharmony_ciusing ::testing::HasSubstr; 187f92157deSopenharmony_ciusing ::testing::MatchesRegex; 188f92157deSopenharmony_ci... 189f92157deSopenharmony_ci ASSERT_THAT(foo_string, HasSubstr("needle")); 190f92157deSopenharmony_ci EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); 191f92157deSopenharmony_ci``` 192f92157deSopenharmony_ci 193f92157deSopenharmony_ci### Windows HRESULT assertions 194f92157deSopenharmony_ci 195f92157deSopenharmony_ciSee [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the 196f92157deSopenharmony_ciAssertions Reference. 197f92157deSopenharmony_ci 198f92157deSopenharmony_ci### Type Assertions 199f92157deSopenharmony_ci 200f92157deSopenharmony_ciYou can call the function 201f92157deSopenharmony_ci 202f92157deSopenharmony_ci```c++ 203f92157deSopenharmony_ci::testing::StaticAssertTypeEq<T1, T2>(); 204f92157deSopenharmony_ci``` 205f92157deSopenharmony_ci 206f92157deSopenharmony_cito assert that types `T1` and `T2` are the same. The function does nothing if 207f92157deSopenharmony_cithe assertion is satisfied. If the types are different, the function call will 208f92157deSopenharmony_cifail to compile, the compiler error message will say that `T1 and T2 are not the 209f92157deSopenharmony_cisame type` and most likely (depending on the compiler) show you the actual 210f92157deSopenharmony_civalues of `T1` and `T2`. This is mainly useful inside template code. 211f92157deSopenharmony_ci 212f92157deSopenharmony_ci**Caveat**: When used inside a member function of a class template or a function 213f92157deSopenharmony_citemplate, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is 214f92157deSopenharmony_ciinstantiated. For example, given: 215f92157deSopenharmony_ci 216f92157deSopenharmony_ci```c++ 217f92157deSopenharmony_citemplate <typename T> class Foo { 218f92157deSopenharmony_ci public: 219f92157deSopenharmony_ci void Bar() { testing::StaticAssertTypeEq<int, T>(); } 220f92157deSopenharmony_ci}; 221f92157deSopenharmony_ci``` 222f92157deSopenharmony_ci 223f92157deSopenharmony_cithe code: 224f92157deSopenharmony_ci 225f92157deSopenharmony_ci```c++ 226f92157deSopenharmony_civoid Test1() { Foo<bool> foo; } 227f92157deSopenharmony_ci``` 228f92157deSopenharmony_ci 229f92157deSopenharmony_ciwill not generate a compiler error, as `Foo<bool>::Bar()` is never actually 230f92157deSopenharmony_ciinstantiated. Instead, you need: 231f92157deSopenharmony_ci 232f92157deSopenharmony_ci```c++ 233f92157deSopenharmony_civoid Test2() { Foo<bool> foo; foo.Bar(); } 234f92157deSopenharmony_ci``` 235f92157deSopenharmony_ci 236f92157deSopenharmony_cito cause a compiler error. 237f92157deSopenharmony_ci 238f92157deSopenharmony_ci### Assertion Placement 239f92157deSopenharmony_ci 240f92157deSopenharmony_ciYou can use assertions in any C++ function. In particular, it doesn't have to be 241f92157deSopenharmony_cia method of the test fixture class. The one constraint is that assertions that 242f92157deSopenharmony_cigenerate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in 243f92157deSopenharmony_civoid-returning functions. This is a consequence of Google's not using 244f92157deSopenharmony_ciexceptions. By placing it in a non-void function you'll get a confusing compile 245f92157deSopenharmony_cierror like `"error: void value not ignored as it ought to be"` or `"cannot 246f92157deSopenharmony_ciinitialize return object of type 'bool' with an rvalue of type 'void'"` or 247f92157deSopenharmony_ci`"error: no viable conversion from 'void' to 'string'"`. 248f92157deSopenharmony_ci 249f92157deSopenharmony_ciIf you need to use fatal assertions in a function that returns non-void, one 250f92157deSopenharmony_cioption is to make the function return the value in an out parameter instead. For 251f92157deSopenharmony_ciexample, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You 252f92157deSopenharmony_cineed to make sure that `*result` contains some sensible value even when the 253f92157deSopenharmony_cifunction returns prematurely. As the function now returns `void`, you can use 254f92157deSopenharmony_ciany assertion inside of it. 255f92157deSopenharmony_ci 256f92157deSopenharmony_ciIf changing the function's type is not an option, you should just use assertions 257f92157deSopenharmony_cithat generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. 258f92157deSopenharmony_ci 259f92157deSopenharmony_ci{: .callout .note} 260f92157deSopenharmony_ciNOTE: Constructors and destructors are not considered void-returning functions, 261f92157deSopenharmony_ciaccording to the C++ language specification, and so you may not use fatal 262f92157deSopenharmony_ciassertions in them; you'll get a compilation error if you try. Instead, either 263f92157deSopenharmony_cicall `abort` and crash the entire test executable, or put the fatal assertion in 264f92157deSopenharmony_cia `SetUp`/`TearDown` function; see 265f92157deSopenharmony_ci[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) 266f92157deSopenharmony_ci 267f92157deSopenharmony_ci{: .callout .warning} 268f92157deSopenharmony_ciWARNING: A fatal assertion in a helper function (private void-returning method) 269f92157deSopenharmony_cicalled from a constructor or destructor does not terminate the current test, as 270f92157deSopenharmony_ciyour intuition might suggest: it merely returns from the constructor or 271f92157deSopenharmony_cidestructor early, possibly leaving your object in a partially-constructed or 272f92157deSopenharmony_cipartially-destructed state! You almost certainly want to `abort` or use 273f92157deSopenharmony_ci`SetUp`/`TearDown` instead. 274f92157deSopenharmony_ci 275f92157deSopenharmony_ci## Skipping test execution 276f92157deSopenharmony_ci 277f92157deSopenharmony_ciRelated to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test 278f92157deSopenharmony_ciexecution at runtime with the `GTEST_SKIP()` macro. This is useful when you need 279f92157deSopenharmony_cito check for preconditions of the system under test during runtime and skip 280f92157deSopenharmony_citests in a meaningful way. 281f92157deSopenharmony_ci 282f92157deSopenharmony_ci`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods 283f92157deSopenharmony_ciof classes derived from either `::testing::Environment` or `::testing::Test`. 284f92157deSopenharmony_ciFor example: 285f92157deSopenharmony_ci 286f92157deSopenharmony_ci```c++ 287f92157deSopenharmony_ciTEST(SkipTest, DoesSkip) { 288f92157deSopenharmony_ci GTEST_SKIP() << "Skipping single test"; 289f92157deSopenharmony_ci EXPECT_EQ(0, 1); // Won't fail; it won't be executed 290f92157deSopenharmony_ci} 291f92157deSopenharmony_ci 292f92157deSopenharmony_ciclass SkipFixture : public ::testing::Test { 293f92157deSopenharmony_ci protected: 294f92157deSopenharmony_ci void SetUp() override { 295f92157deSopenharmony_ci GTEST_SKIP() << "Skipping all tests for this fixture"; 296f92157deSopenharmony_ci } 297f92157deSopenharmony_ci}; 298f92157deSopenharmony_ci 299f92157deSopenharmony_ci// Tests for SkipFixture won't be executed. 300f92157deSopenharmony_ciTEST_F(SkipFixture, SkipsOneTest) { 301f92157deSopenharmony_ci EXPECT_EQ(5, 7); // Won't fail 302f92157deSopenharmony_ci} 303f92157deSopenharmony_ci``` 304f92157deSopenharmony_ci 305f92157deSopenharmony_ciAs with assertion macros, you can stream a custom message into `GTEST_SKIP()`. 306f92157deSopenharmony_ci 307f92157deSopenharmony_ci## Teaching googletest How to Print Your Values 308f92157deSopenharmony_ci 309f92157deSopenharmony_ciWhen a test assertion such as `EXPECT_EQ` fails, googletest prints the argument 310f92157deSopenharmony_civalues to help you debug. It does this using a user-extensible value printer. 311f92157deSopenharmony_ci 312f92157deSopenharmony_ciThis printer knows how to print built-in C++ types, native arrays, STL 313f92157deSopenharmony_cicontainers, and any type that supports the `<<` operator. For other types, it 314f92157deSopenharmony_ciprints the raw bytes in the value and hopes that you the user can figure it out. 315f92157deSopenharmony_ci 316f92157deSopenharmony_ciAs mentioned earlier, the printer is *extensible*. That means you can teach it 317f92157deSopenharmony_cito do a better job at printing your particular type than to dump the bytes. To 318f92157deSopenharmony_cido that, define `<<` for your type: 319f92157deSopenharmony_ci 320f92157deSopenharmony_ci```c++ 321f92157deSopenharmony_ci#include <ostream> 322f92157deSopenharmony_ci 323f92157deSopenharmony_cinamespace foo { 324f92157deSopenharmony_ci 325f92157deSopenharmony_ciclass Bar { // We want googletest to be able to print instances of this. 326f92157deSopenharmony_ci... 327f92157deSopenharmony_ci // Create a free inline friend function. 328f92157deSopenharmony_ci friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { 329f92157deSopenharmony_ci return os << bar.DebugString(); // whatever needed to print bar to os 330f92157deSopenharmony_ci } 331f92157deSopenharmony_ci}; 332f92157deSopenharmony_ci 333f92157deSopenharmony_ci// If you can't declare the function in the class it's important that the 334f92157deSopenharmony_ci// << operator is defined in the SAME namespace that defines Bar. C++'s look-up 335f92157deSopenharmony_ci// rules rely on that. 336f92157deSopenharmony_cistd::ostream& operator<<(std::ostream& os, const Bar& bar) { 337f92157deSopenharmony_ci return os << bar.DebugString(); // whatever needed to print bar to os 338f92157deSopenharmony_ci} 339f92157deSopenharmony_ci 340f92157deSopenharmony_ci} // namespace foo 341f92157deSopenharmony_ci``` 342f92157deSopenharmony_ci 343f92157deSopenharmony_ciSometimes, this might not be an option: your team may consider it bad style to 344f92157deSopenharmony_cihave a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that 345f92157deSopenharmony_cidoesn't do what you want (and you cannot change it). If so, you can instead 346f92157deSopenharmony_cidefine a `PrintTo()` function like this: 347f92157deSopenharmony_ci 348f92157deSopenharmony_ci```c++ 349f92157deSopenharmony_ci#include <ostream> 350f92157deSopenharmony_ci 351f92157deSopenharmony_cinamespace foo { 352f92157deSopenharmony_ci 353f92157deSopenharmony_ciclass Bar { 354f92157deSopenharmony_ci ... 355f92157deSopenharmony_ci friend void PrintTo(const Bar& bar, std::ostream* os) { 356f92157deSopenharmony_ci *os << bar.DebugString(); // whatever needed to print bar to os 357f92157deSopenharmony_ci } 358f92157deSopenharmony_ci}; 359f92157deSopenharmony_ci 360f92157deSopenharmony_ci// If you can't declare the function in the class it's important that PrintTo() 361f92157deSopenharmony_ci// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely 362f92157deSopenharmony_ci// on that. 363f92157deSopenharmony_civoid PrintTo(const Bar& bar, std::ostream* os) { 364f92157deSopenharmony_ci *os << bar.DebugString(); // whatever needed to print bar to os 365f92157deSopenharmony_ci} 366f92157deSopenharmony_ci 367f92157deSopenharmony_ci} // namespace foo 368f92157deSopenharmony_ci``` 369f92157deSopenharmony_ci 370f92157deSopenharmony_ciIf you have defined both `<<` and `PrintTo()`, the latter will be used when 371f92157deSopenharmony_cigoogletest is concerned. This allows you to customize how the value appears in 372f92157deSopenharmony_cigoogletest's output without affecting code that relies on the behavior of its 373f92157deSopenharmony_ci`<<` operator. 374f92157deSopenharmony_ci 375f92157deSopenharmony_ciIf you want to print a value `x` using googletest's value printer yourself, just 376f92157deSopenharmony_cicall `::testing::PrintToString(x)`, which returns an `std::string`: 377f92157deSopenharmony_ci 378f92157deSopenharmony_ci```c++ 379f92157deSopenharmony_civector<pair<Bar, int> > bar_ints = GetBarIntVector(); 380f92157deSopenharmony_ci 381f92157deSopenharmony_ciEXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) 382f92157deSopenharmony_ci << "bar_ints = " << testing::PrintToString(bar_ints); 383f92157deSopenharmony_ci``` 384f92157deSopenharmony_ci 385f92157deSopenharmony_ci## Death Tests 386f92157deSopenharmony_ci 387f92157deSopenharmony_ciIn many applications, there are assertions that can cause application failure if 388f92157deSopenharmony_cia condition is not met. These consistency checks, which ensure that the program 389f92157deSopenharmony_ciis in a known good state, are there to fail at the earliest possible time after 390f92157deSopenharmony_cisome program state is corrupted. If the assertion checks the wrong condition, 391f92157deSopenharmony_cithen the program may proceed in an erroneous state, which could lead to memory 392f92157deSopenharmony_cicorruption, security holes, or worse. Hence it is vitally important to test that 393f92157deSopenharmony_cisuch assertion statements work as expected. 394f92157deSopenharmony_ci 395f92157deSopenharmony_ciSince these precondition checks cause the processes to die, we call such tests 396f92157deSopenharmony_ci_death tests_. More generally, any test that checks that a program terminates 397f92157deSopenharmony_ci(except by throwing an exception) in an expected fashion is also a death test. 398f92157deSopenharmony_ci 399f92157deSopenharmony_ciNote that if a piece of code throws an exception, we don't consider it "death" 400f92157deSopenharmony_cifor the purpose of death tests, as the caller of the code could catch the 401f92157deSopenharmony_ciexception and avoid the crash. If you want to verify exceptions thrown by your 402f92157deSopenharmony_cicode, see [Exception Assertions](#ExceptionAssertions). 403f92157deSopenharmony_ci 404f92157deSopenharmony_ciIf you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see 405f92157deSopenharmony_ci["Catching" Failures](#catching-failures). 406f92157deSopenharmony_ci 407f92157deSopenharmony_ci### How to Write a Death Test 408f92157deSopenharmony_ci 409f92157deSopenharmony_ciGoogleTest provides assertion macros to support death tests. See 410f92157deSopenharmony_ci[Death Assertions](reference/assertions.md#death) in the Assertions Reference 411f92157deSopenharmony_cifor details. 412f92157deSopenharmony_ci 413f92157deSopenharmony_ciTo write a death test, simply use one of the macros inside your test function. 414f92157deSopenharmony_ciFor example, 415f92157deSopenharmony_ci 416f92157deSopenharmony_ci```c++ 417f92157deSopenharmony_ciTEST(MyDeathTest, Foo) { 418f92157deSopenharmony_ci // This death test uses a compound statement. 419f92157deSopenharmony_ci ASSERT_DEATH({ 420f92157deSopenharmony_ci int n = 5; 421f92157deSopenharmony_ci Foo(&n); 422f92157deSopenharmony_ci }, "Error on line .* of Foo()"); 423f92157deSopenharmony_ci} 424f92157deSopenharmony_ci 425f92157deSopenharmony_ciTEST(MyDeathTest, NormalExit) { 426f92157deSopenharmony_ci EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); 427f92157deSopenharmony_ci} 428f92157deSopenharmony_ci 429f92157deSopenharmony_ciTEST(MyDeathTest, KillProcess) { 430f92157deSopenharmony_ci EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), 431f92157deSopenharmony_ci "Sending myself unblockable signal"); 432f92157deSopenharmony_ci} 433f92157deSopenharmony_ci``` 434f92157deSopenharmony_ci 435f92157deSopenharmony_civerifies that: 436f92157deSopenharmony_ci 437f92157deSopenharmony_ci* calling `Foo(5)` causes the process to die with the given error message, 438f92157deSopenharmony_ci* calling `NormalExit()` causes the process to print `"Success"` to stderr and 439f92157deSopenharmony_ci exit with exit code 0, and 440f92157deSopenharmony_ci* calling `KillProcess()` kills the process with signal `SIGKILL`. 441f92157deSopenharmony_ci 442f92157deSopenharmony_ciThe test function body may contain other assertions and statements as well, if 443f92157deSopenharmony_cinecessary. 444f92157deSopenharmony_ci 445f92157deSopenharmony_ciNote that a death test only cares about three things: 446f92157deSopenharmony_ci 447f92157deSopenharmony_ci1. does `statement` abort or exit the process? 448f92157deSopenharmony_ci2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status 449f92157deSopenharmony_ci satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) 450f92157deSopenharmony_ci is the exit status non-zero? And 451f92157deSopenharmony_ci3. does the stderr output match `matcher`? 452f92157deSopenharmony_ci 453f92157deSopenharmony_ciIn particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it 454f92157deSopenharmony_ciwill **not** cause the death test to fail, as googletest assertions don't abort 455f92157deSopenharmony_cithe process. 456f92157deSopenharmony_ci 457f92157deSopenharmony_ci### Death Test Naming 458f92157deSopenharmony_ci 459f92157deSopenharmony_ci{: .callout .important} 460f92157deSopenharmony_ciIMPORTANT: We strongly recommend you to follow the convention of naming your 461f92157deSopenharmony_ci**test suite** (not test) `*DeathTest` when it contains a death test, as 462f92157deSopenharmony_cidemonstrated in the above example. The 463f92157deSopenharmony_ci[Death Tests And Threads](#death-tests-and-threads) section below explains why. 464f92157deSopenharmony_ci 465f92157deSopenharmony_ciIf a test fixture class is shared by normal tests and death tests, you can use 466f92157deSopenharmony_ci`using` or `typedef` to introduce an alias for the fixture class and avoid 467f92157deSopenharmony_ciduplicating its code: 468f92157deSopenharmony_ci 469f92157deSopenharmony_ci```c++ 470f92157deSopenharmony_ciclass FooTest : public testing::Test { ... }; 471f92157deSopenharmony_ci 472f92157deSopenharmony_ciusing FooDeathTest = FooTest; 473f92157deSopenharmony_ci 474f92157deSopenharmony_ciTEST_F(FooTest, DoesThis) { 475f92157deSopenharmony_ci // normal test 476f92157deSopenharmony_ci} 477f92157deSopenharmony_ci 478f92157deSopenharmony_ciTEST_F(FooDeathTest, DoesThat) { 479f92157deSopenharmony_ci // death test 480f92157deSopenharmony_ci} 481f92157deSopenharmony_ci``` 482f92157deSopenharmony_ci 483f92157deSopenharmony_ci### Regular Expression Syntax 484f92157deSopenharmony_ci 485f92157deSopenharmony_ciWhen built with Bazel and using Abseil, googletest uses the 486f92157deSopenharmony_ci[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX 487f92157deSopenharmony_cisystems (Linux, Cygwin, Mac), googletest uses the 488f92157deSopenharmony_ci[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) 489f92157deSopenharmony_cisyntax. To learn about POSIX syntax, you may want to read this 490f92157deSopenharmony_ci[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). 491f92157deSopenharmony_ci 492f92157deSopenharmony_ciOn Windows, googletest uses its own simple regular expression implementation. It 493f92157deSopenharmony_cilacks many features. For example, we don't support union (`"x|y"`), grouping 494f92157deSopenharmony_ci(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among 495f92157deSopenharmony_ciothers. Below is what we do support (`A` denotes a literal character, period 496f92157deSopenharmony_ci(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular 497f92157deSopenharmony_ciexpressions.): 498f92157deSopenharmony_ci 499f92157deSopenharmony_ciExpression | Meaning 500f92157deSopenharmony_ci---------- | -------------------------------------------------------------- 501f92157deSopenharmony_ci`c` | matches any literal character `c` 502f92157deSopenharmony_ci`\\d` | matches any decimal digit 503f92157deSopenharmony_ci`\\D` | matches any character that's not a decimal digit 504f92157deSopenharmony_ci`\\f` | matches `\f` 505f92157deSopenharmony_ci`\\n` | matches `\n` 506f92157deSopenharmony_ci`\\r` | matches `\r` 507f92157deSopenharmony_ci`\\s` | matches any ASCII whitespace, including `\n` 508f92157deSopenharmony_ci`\\S` | matches any character that's not a whitespace 509f92157deSopenharmony_ci`\\t` | matches `\t` 510f92157deSopenharmony_ci`\\v` | matches `\v` 511f92157deSopenharmony_ci`\\w` | matches any letter, `_`, or decimal digit 512f92157deSopenharmony_ci`\\W` | matches any character that `\\w` doesn't match 513f92157deSopenharmony_ci`\\c` | matches any literal character `c`, which must be a punctuation 514f92157deSopenharmony_ci`.` | matches any single character except `\n` 515f92157deSopenharmony_ci`A?` | matches 0 or 1 occurrences of `A` 516f92157deSopenharmony_ci`A*` | matches 0 or many occurrences of `A` 517f92157deSopenharmony_ci`A+` | matches 1 or many occurrences of `A` 518f92157deSopenharmony_ci`^` | matches the beginning of a string (not that of each line) 519f92157deSopenharmony_ci`$` | matches the end of a string (not that of each line) 520f92157deSopenharmony_ci`xy` | matches `x` followed by `y` 521f92157deSopenharmony_ci 522f92157deSopenharmony_ciTo help you determine which capability is available on your system, googletest 523f92157deSopenharmony_cidefines macros to govern which regular expression it is using. The macros are: 524f92157deSopenharmony_ci`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death 525f92157deSopenharmony_citests to work in all cases, you can either `#if` on these macros or use the more 526f92157deSopenharmony_cilimited syntax only. 527f92157deSopenharmony_ci 528f92157deSopenharmony_ci### How It Works 529f92157deSopenharmony_ci 530f92157deSopenharmony_ciSee [Death Assertions](reference/assertions.md#death) in the Assertions 531f92157deSopenharmony_ciReference. 532f92157deSopenharmony_ci 533f92157deSopenharmony_ci### Death Tests And Threads 534f92157deSopenharmony_ci 535f92157deSopenharmony_ciThe reason for the two death test styles has to do with thread safety. Due to 536f92157deSopenharmony_ciwell-known problems with forking in the presence of threads, death tests should 537f92157deSopenharmony_cibe run in a single-threaded context. Sometimes, however, it isn't feasible to 538f92157deSopenharmony_ciarrange that kind of environment. For example, statically-initialized modules 539f92157deSopenharmony_cimay start threads before main is ever reached. Once threads have been created, 540f92157deSopenharmony_ciit may be difficult or impossible to clean them up. 541f92157deSopenharmony_ci 542f92157deSopenharmony_cigoogletest has three features intended to raise awareness of threading issues. 543f92157deSopenharmony_ci 544f92157deSopenharmony_ci1. A warning is emitted if multiple threads are running when a death test is 545f92157deSopenharmony_ci encountered. 546f92157deSopenharmony_ci2. Test suites with a name ending in "DeathTest" are run before all other 547f92157deSopenharmony_ci tests. 548f92157deSopenharmony_ci3. It uses `clone()` instead of `fork()` to spawn the child process on Linux 549f92157deSopenharmony_ci (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely 550f92157deSopenharmony_ci to cause the child to hang when the parent process has multiple threads. 551f92157deSopenharmony_ci 552f92157deSopenharmony_ciIt's perfectly fine to create threads inside a death test statement; they are 553f92157deSopenharmony_ciexecuted in a separate process and cannot affect the parent. 554f92157deSopenharmony_ci 555f92157deSopenharmony_ci### Death Test Styles 556f92157deSopenharmony_ci 557f92157deSopenharmony_ciThe "threadsafe" death test style was introduced in order to help mitigate the 558f92157deSopenharmony_cirisks of testing in a possibly multithreaded environment. It trades increased 559f92157deSopenharmony_citest execution time (potentially dramatically so) for improved thread safety. 560f92157deSopenharmony_ci 561f92157deSopenharmony_ciThe automated testing framework does not set the style flag. You can choose a 562f92157deSopenharmony_ciparticular style of death tests by setting the flag programmatically: 563f92157deSopenharmony_ci 564f92157deSopenharmony_ci```c++ 565f92157deSopenharmony_ciGTEST_FLAG_SET(death_test_style, "threadsafe") 566f92157deSopenharmony_ci``` 567f92157deSopenharmony_ci 568f92157deSopenharmony_ciYou can do this in `main()` to set the style for all death tests in the binary, 569f92157deSopenharmony_cior in individual tests. Recall that flags are saved before running each test and 570f92157deSopenharmony_cirestored afterwards, so you need not do that yourself. For example: 571f92157deSopenharmony_ci 572f92157deSopenharmony_ci```c++ 573f92157deSopenharmony_ciint main(int argc, char** argv) { 574f92157deSopenharmony_ci testing::InitGoogleTest(&argc, argv); 575f92157deSopenharmony_ci GTEST_FLAG_SET(death_test_style, "fast"); 576f92157deSopenharmony_ci return RUN_ALL_TESTS(); 577f92157deSopenharmony_ci} 578f92157deSopenharmony_ci 579f92157deSopenharmony_ciTEST(MyDeathTest, TestOne) { 580f92157deSopenharmony_ci GTEST_FLAG_SET(death_test_style, "threadsafe"); 581f92157deSopenharmony_ci // This test is run in the "threadsafe" style: 582f92157deSopenharmony_ci ASSERT_DEATH(ThisShouldDie(), ""); 583f92157deSopenharmony_ci} 584f92157deSopenharmony_ci 585f92157deSopenharmony_ciTEST(MyDeathTest, TestTwo) { 586f92157deSopenharmony_ci // This test is run in the "fast" style: 587f92157deSopenharmony_ci ASSERT_DEATH(ThisShouldDie(), ""); 588f92157deSopenharmony_ci} 589f92157deSopenharmony_ci``` 590f92157deSopenharmony_ci 591f92157deSopenharmony_ci### Caveats 592f92157deSopenharmony_ci 593f92157deSopenharmony_ciThe `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If 594f92157deSopenharmony_ciit leaves the current function via a `return` statement or by throwing an 595f92157deSopenharmony_ciexception, the death test is considered to have failed. Some googletest macros 596f92157deSopenharmony_cimay return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid 597f92157deSopenharmony_cithem in `statement`. 598f92157deSopenharmony_ci 599f92157deSopenharmony_ciSince `statement` runs in the child process, any in-memory side effect (e.g. 600f92157deSopenharmony_cimodifying a variable, releasing memory, etc) it causes will *not* be observable 601f92157deSopenharmony_ciin the parent process. In particular, if you release memory in a death test, 602f92157deSopenharmony_ciyour program will fail the heap check as the parent process will never see the 603f92157deSopenharmony_cimemory reclaimed. To solve this problem, you can 604f92157deSopenharmony_ci 605f92157deSopenharmony_ci1. try not to free memory in a death test; 606f92157deSopenharmony_ci2. free the memory again in the parent process; or 607f92157deSopenharmony_ci3. do not use the heap checker in your program. 608f92157deSopenharmony_ci 609f92157deSopenharmony_ciDue to an implementation detail, you cannot place multiple death test assertions 610f92157deSopenharmony_cion the same line; otherwise, compilation will fail with an unobvious error 611f92157deSopenharmony_cimessage. 612f92157deSopenharmony_ci 613f92157deSopenharmony_ciDespite the improved thread safety afforded by the "threadsafe" style of death 614f92157deSopenharmony_citest, thread problems such as deadlock are still possible in the presence of 615f92157deSopenharmony_cihandlers registered with `pthread_atfork(3)`. 616f92157deSopenharmony_ci 617f92157deSopenharmony_ci## Using Assertions in Sub-routines 618f92157deSopenharmony_ci 619f92157deSopenharmony_ci{: .callout .note} 620f92157deSopenharmony_ciNote: If you want to put a series of test assertions in a subroutine to check 621f92157deSopenharmony_cifor a complex condition, consider using 622f92157deSopenharmony_ci[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you 623f92157deSopenharmony_ciprovide a more readable error message in case of failure and avoid all of the 624f92157deSopenharmony_ciissues described below. 625f92157deSopenharmony_ci 626f92157deSopenharmony_ci### Adding Traces to Assertions 627f92157deSopenharmony_ci 628f92157deSopenharmony_ciIf a test sub-routine is called from several places, when an assertion inside it 629f92157deSopenharmony_cifails, it can be hard to tell which invocation of the sub-routine the failure is 630f92157deSopenharmony_cifrom. You can alleviate this problem using extra logging or custom failure 631f92157deSopenharmony_cimessages, but that usually clutters up your tests. A better solution is to use 632f92157deSopenharmony_cithe `SCOPED_TRACE` macro or the `ScopedTrace` utility: 633f92157deSopenharmony_ci 634f92157deSopenharmony_ci```c++ 635f92157deSopenharmony_ciSCOPED_TRACE(message); 636f92157deSopenharmony_ci``` 637f92157deSopenharmony_ci 638f92157deSopenharmony_ci```c++ 639f92157deSopenharmony_ciScopedTrace trace("file_path", line_number, message); 640f92157deSopenharmony_ci``` 641f92157deSopenharmony_ci 642f92157deSopenharmony_ciwhere `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` 643f92157deSopenharmony_cimacro will cause the current file name, line number, and the given message to be 644f92157deSopenharmony_ciadded in every failure message. `ScopedTrace` accepts explicit file name and 645f92157deSopenharmony_ciline number in arguments, which is useful for writing test helpers. The effect 646f92157deSopenharmony_ciwill be undone when the control leaves the current lexical scope. 647f92157deSopenharmony_ci 648f92157deSopenharmony_ciFor example, 649f92157deSopenharmony_ci 650f92157deSopenharmony_ci```c++ 651f92157deSopenharmony_ci10: void Sub1(int n) { 652f92157deSopenharmony_ci11: EXPECT_EQ(Bar(n), 1); 653f92157deSopenharmony_ci12: EXPECT_EQ(Bar(n + 1), 2); 654f92157deSopenharmony_ci13: } 655f92157deSopenharmony_ci14: 656f92157deSopenharmony_ci15: TEST(FooTest, Bar) { 657f92157deSopenharmony_ci16: { 658f92157deSopenharmony_ci17: SCOPED_TRACE("A"); // This trace point will be included in 659f92157deSopenharmony_ci18: // every failure in this scope. 660f92157deSopenharmony_ci19: Sub1(1); 661f92157deSopenharmony_ci20: } 662f92157deSopenharmony_ci21: // Now it won't. 663f92157deSopenharmony_ci22: Sub1(9); 664f92157deSopenharmony_ci23: } 665f92157deSopenharmony_ci``` 666f92157deSopenharmony_ci 667f92157deSopenharmony_cicould result in messages like these: 668f92157deSopenharmony_ci 669f92157deSopenharmony_ci```none 670f92157deSopenharmony_cipath/to/foo_test.cc:11: Failure 671f92157deSopenharmony_ciValue of: Bar(n) 672f92157deSopenharmony_ciExpected: 1 673f92157deSopenharmony_ci Actual: 2 674f92157deSopenharmony_ciGoogle Test trace: 675f92157deSopenharmony_cipath/to/foo_test.cc:17: A 676f92157deSopenharmony_ci 677f92157deSopenharmony_cipath/to/foo_test.cc:12: Failure 678f92157deSopenharmony_ciValue of: Bar(n + 1) 679f92157deSopenharmony_ciExpected: 2 680f92157deSopenharmony_ci Actual: 3 681f92157deSopenharmony_ci``` 682f92157deSopenharmony_ci 683f92157deSopenharmony_ciWithout the trace, it would've been difficult to know which invocation of 684f92157deSopenharmony_ci`Sub1()` the two failures come from respectively. (You could add an extra 685f92157deSopenharmony_cimessage to each assertion in `Sub1()` to indicate the value of `n`, but that's 686f92157deSopenharmony_citedious.) 687f92157deSopenharmony_ci 688f92157deSopenharmony_ciSome tips on using `SCOPED_TRACE`: 689f92157deSopenharmony_ci 690f92157deSopenharmony_ci1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the 691f92157deSopenharmony_ci beginning of a sub-routine, instead of at each call site. 692f92157deSopenharmony_ci2. When calling sub-routines inside a loop, make the loop iterator part of the 693f92157deSopenharmony_ci message in `SCOPED_TRACE` such that you can know which iteration the failure 694f92157deSopenharmony_ci is from. 695f92157deSopenharmony_ci3. Sometimes the line number of the trace point is enough for identifying the 696f92157deSopenharmony_ci particular invocation of a sub-routine. In this case, you don't have to 697f92157deSopenharmony_ci choose a unique message for `SCOPED_TRACE`. You can simply use `""`. 698f92157deSopenharmony_ci4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer 699f92157deSopenharmony_ci scope. In this case, all active trace points will be included in the failure 700f92157deSopenharmony_ci messages, in reverse order they are encountered. 701f92157deSopenharmony_ci5. The trace dump is clickable in Emacs - hit `return` on a line number and 702f92157deSopenharmony_ci you'll be taken to that line in the source file! 703f92157deSopenharmony_ci 704f92157deSopenharmony_ci### Propagating Fatal Failures 705f92157deSopenharmony_ci 706f92157deSopenharmony_ciA common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that 707f92157deSopenharmony_ciwhen they fail they only abort the _current function_, not the entire test. For 708f92157deSopenharmony_ciexample, the following test will segfault: 709f92157deSopenharmony_ci 710f92157deSopenharmony_ci```c++ 711f92157deSopenharmony_civoid Subroutine() { 712f92157deSopenharmony_ci // Generates a fatal failure and aborts the current function. 713f92157deSopenharmony_ci ASSERT_EQ(1, 2); 714f92157deSopenharmony_ci 715f92157deSopenharmony_ci // The following won't be executed. 716f92157deSopenharmony_ci ... 717f92157deSopenharmony_ci} 718f92157deSopenharmony_ci 719f92157deSopenharmony_ciTEST(FooTest, Bar) { 720f92157deSopenharmony_ci Subroutine(); // The intended behavior is for the fatal failure 721f92157deSopenharmony_ci // in Subroutine() to abort the entire test. 722f92157deSopenharmony_ci 723f92157deSopenharmony_ci // The actual behavior: the function goes on after Subroutine() returns. 724f92157deSopenharmony_ci int* p = nullptr; 725f92157deSopenharmony_ci *p = 3; // Segfault! 726f92157deSopenharmony_ci} 727f92157deSopenharmony_ci``` 728f92157deSopenharmony_ci 729f92157deSopenharmony_ciTo alleviate this, googletest provides three different solutions. You could use 730f92157deSopenharmony_cieither exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the 731f92157deSopenharmony_ci`HasFatalFailure()` function. They are described in the following two 732f92157deSopenharmony_cisubsections. 733f92157deSopenharmony_ci 734f92157deSopenharmony_ci#### Asserting on Subroutines with an exception 735f92157deSopenharmony_ci 736f92157deSopenharmony_ciThe following code can turn ASSERT-failure into an exception: 737f92157deSopenharmony_ci 738f92157deSopenharmony_ci```c++ 739f92157deSopenharmony_ciclass ThrowListener : public testing::EmptyTestEventListener { 740f92157deSopenharmony_ci void OnTestPartResult(const testing::TestPartResult& result) override { 741f92157deSopenharmony_ci if (result.type() == testing::TestPartResult::kFatalFailure) { 742f92157deSopenharmony_ci throw testing::AssertionException(result); 743f92157deSopenharmony_ci } 744f92157deSopenharmony_ci } 745f92157deSopenharmony_ci}; 746f92157deSopenharmony_ciint main(int argc, char** argv) { 747f92157deSopenharmony_ci ... 748f92157deSopenharmony_ci testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); 749f92157deSopenharmony_ci return RUN_ALL_TESTS(); 750f92157deSopenharmony_ci} 751f92157deSopenharmony_ci``` 752f92157deSopenharmony_ci 753f92157deSopenharmony_ciThis listener should be added after other listeners if you have any, otherwise 754f92157deSopenharmony_cithey won't see failed `OnTestPartResult`. 755f92157deSopenharmony_ci 756f92157deSopenharmony_ci#### Asserting on Subroutines 757f92157deSopenharmony_ci 758f92157deSopenharmony_ciAs shown above, if your test calls a subroutine that has an `ASSERT_*` failure 759f92157deSopenharmony_ciin it, the test will continue after the subroutine returns. This may not be what 760f92157deSopenharmony_ciyou want. 761f92157deSopenharmony_ci 762f92157deSopenharmony_ciOften people want fatal failures to propagate like exceptions. For that 763f92157deSopenharmony_cigoogletest offers the following macros: 764f92157deSopenharmony_ci 765f92157deSopenharmony_ciFatal assertion | Nonfatal assertion | Verifies 766f92157deSopenharmony_ci------------------------------------- | ------------------------------------- | -------- 767f92157deSopenharmony_ci`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. 768f92157deSopenharmony_ci 769f92157deSopenharmony_ciOnly failures in the thread that executes the assertion are checked to determine 770f92157deSopenharmony_cithe result of this type of assertions. If `statement` creates new threads, 771f92157deSopenharmony_cifailures in these threads are ignored. 772f92157deSopenharmony_ci 773f92157deSopenharmony_ciExamples: 774f92157deSopenharmony_ci 775f92157deSopenharmony_ci```c++ 776f92157deSopenharmony_ciASSERT_NO_FATAL_FAILURE(Foo()); 777f92157deSopenharmony_ci 778f92157deSopenharmony_ciint i; 779f92157deSopenharmony_ciEXPECT_NO_FATAL_FAILURE({ 780f92157deSopenharmony_ci i = Bar(); 781f92157deSopenharmony_ci}); 782f92157deSopenharmony_ci``` 783f92157deSopenharmony_ci 784f92157deSopenharmony_ciAssertions from multiple threads are currently not supported on Windows. 785f92157deSopenharmony_ci 786f92157deSopenharmony_ci#### Checking for Failures in the Current Test 787f92157deSopenharmony_ci 788f92157deSopenharmony_ci`HasFatalFailure()` in the `::testing::Test` class returns `true` if an 789f92157deSopenharmony_ciassertion in the current test has suffered a fatal failure. This allows 790f92157deSopenharmony_cifunctions to catch fatal failures in a sub-routine and return early. 791f92157deSopenharmony_ci 792f92157deSopenharmony_ci```c++ 793f92157deSopenharmony_ciclass Test { 794f92157deSopenharmony_ci public: 795f92157deSopenharmony_ci ... 796f92157deSopenharmony_ci static bool HasFatalFailure(); 797f92157deSopenharmony_ci}; 798f92157deSopenharmony_ci``` 799f92157deSopenharmony_ci 800f92157deSopenharmony_ciThe typical usage, which basically simulates the behavior of a thrown exception, 801f92157deSopenharmony_ciis: 802f92157deSopenharmony_ci 803f92157deSopenharmony_ci```c++ 804f92157deSopenharmony_ciTEST(FooTest, Bar) { 805f92157deSopenharmony_ci Subroutine(); 806f92157deSopenharmony_ci // Aborts if Subroutine() had a fatal failure. 807f92157deSopenharmony_ci if (HasFatalFailure()) return; 808f92157deSopenharmony_ci 809f92157deSopenharmony_ci // The following won't be executed. 810f92157deSopenharmony_ci ... 811f92157deSopenharmony_ci} 812f92157deSopenharmony_ci``` 813f92157deSopenharmony_ci 814f92157deSopenharmony_ciIf `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test 815f92157deSopenharmony_cifixture, you must add the `::testing::Test::` prefix, as in: 816f92157deSopenharmony_ci 817f92157deSopenharmony_ci```c++ 818f92157deSopenharmony_ciif (testing::Test::HasFatalFailure()) return; 819f92157deSopenharmony_ci``` 820f92157deSopenharmony_ci 821f92157deSopenharmony_ciSimilarly, `HasNonfatalFailure()` returns `true` if the current test has at 822f92157deSopenharmony_cileast one non-fatal failure, and `HasFailure()` returns `true` if the current 823f92157deSopenharmony_citest has at least one failure of either kind. 824f92157deSopenharmony_ci 825f92157deSopenharmony_ci## Logging Additional Information 826f92157deSopenharmony_ci 827f92157deSopenharmony_ciIn your test code, you can call `RecordProperty("key", value)` to log additional 828f92157deSopenharmony_ciinformation, where `value` can be either a string or an `int`. The *last* value 829f92157deSopenharmony_cirecorded for a key will be emitted to the 830f92157deSopenharmony_ci[XML output](#generating-an-xml-report) if you specify one. For example, the 831f92157deSopenharmony_citest 832f92157deSopenharmony_ci 833f92157deSopenharmony_ci```c++ 834f92157deSopenharmony_ciTEST_F(WidgetUsageTest, MinAndMaxWidgets) { 835f92157deSopenharmony_ci RecordProperty("MaximumWidgets", ComputeMaxUsage()); 836f92157deSopenharmony_ci RecordProperty("MinimumWidgets", ComputeMinUsage()); 837f92157deSopenharmony_ci} 838f92157deSopenharmony_ci``` 839f92157deSopenharmony_ci 840f92157deSopenharmony_ciwill output XML like this: 841f92157deSopenharmony_ci 842f92157deSopenharmony_ci```xml 843f92157deSopenharmony_ci ... 844f92157deSopenharmony_ci <testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> 845f92157deSopenharmony_ci ... 846f92157deSopenharmony_ci``` 847f92157deSopenharmony_ci 848f92157deSopenharmony_ci{: .callout .note} 849f92157deSopenharmony_ci> NOTE: 850f92157deSopenharmony_ci> 851f92157deSopenharmony_ci> * `RecordProperty()` is a static member of the `Test` class. Therefore it 852f92157deSopenharmony_ci> needs to be prefixed with `::testing::Test::` if used outside of the 853f92157deSopenharmony_ci> `TEST` body and the test fixture class. 854f92157deSopenharmony_ci> * *`key`* must be a valid XML attribute name, and cannot conflict with the 855f92157deSopenharmony_ci> ones already used by googletest (`name`, `status`, `time`, `classname`, 856f92157deSopenharmony_ci> `type_param`, and `value_param`). 857f92157deSopenharmony_ci> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. 858f92157deSopenharmony_ci> If it's called outside of a test but between a test suite's 859f92157deSopenharmony_ci> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be 860f92157deSopenharmony_ci> attributed to the XML element for the test suite. If it's called outside 861f92157deSopenharmony_ci> of all test suites (e.g. in a test environment), it will be attributed to 862f92157deSopenharmony_ci> the top-level XML element. 863f92157deSopenharmony_ci 864f92157deSopenharmony_ci## Sharing Resources Between Tests in the Same Test Suite 865f92157deSopenharmony_ci 866f92157deSopenharmony_cigoogletest creates a new test fixture object for each test in order to make 867f92157deSopenharmony_citests independent and easier to debug. However, sometimes tests use resources 868f92157deSopenharmony_cithat are expensive to set up, making the one-copy-per-test model prohibitively 869f92157deSopenharmony_ciexpensive. 870f92157deSopenharmony_ci 871f92157deSopenharmony_ciIf the tests don't change the resource, there's no harm in their sharing a 872f92157deSopenharmony_cisingle resource copy. So, in addition to per-test set-up/tear-down, googletest 873f92157deSopenharmony_cialso supports per-test-suite set-up/tear-down. To use it: 874f92157deSopenharmony_ci 875f92157deSopenharmony_ci1. In your test fixture class (say `FooTest` ), declare as `static` some member 876f92157deSopenharmony_ci variables to hold the shared resources. 877f92157deSopenharmony_ci2. Outside your test fixture class (typically just below it), define those 878f92157deSopenharmony_ci member variables, optionally giving them initial values. 879f92157deSopenharmony_ci3. In the same test fixture class, define a `static void SetUpTestSuite()` 880f92157deSopenharmony_ci function (remember not to spell it as **`SetupTestSuite`** with a small 881f92157deSopenharmony_ci `u`!) to set up the shared resources and a `static void TearDownTestSuite()` 882f92157deSopenharmony_ci function to tear them down. 883f92157deSopenharmony_ci 884f92157deSopenharmony_ciThat's it! googletest automatically calls `SetUpTestSuite()` before running the 885f92157deSopenharmony_ci*first test* in the `FooTest` test suite (i.e. before creating the first 886f92157deSopenharmony_ci`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* 887f92157deSopenharmony_ciin it (i.e. after deleting the last `FooTest` object). In between, the tests can 888f92157deSopenharmony_ciuse the shared resources. 889f92157deSopenharmony_ci 890f92157deSopenharmony_ciRemember that the test order is undefined, so your code can't depend on a test 891f92157deSopenharmony_cipreceding or following another. Also, the tests must either not modify the state 892f92157deSopenharmony_ciof any shared resource, or, if they do modify the state, they must restore the 893f92157deSopenharmony_cistate to its original value before passing control to the next test. 894f92157deSopenharmony_ci 895f92157deSopenharmony_ciNote that `SetUpTestSuite()` may be called multiple times for a test fixture 896f92157deSopenharmony_ciclass that has derived classes, so you should not expect code in the function 897f92157deSopenharmony_cibody to be run only once. Also, derived classes still have access to shared 898f92157deSopenharmony_ciresources defined as static members, so careful consideration is needed when 899f92157deSopenharmony_cimanaging shared resources to avoid memory leaks. 900f92157deSopenharmony_ci 901f92157deSopenharmony_ciHere's an example of per-test-suite set-up and tear-down: 902f92157deSopenharmony_ci 903f92157deSopenharmony_ci```c++ 904f92157deSopenharmony_ciclass FooTest : public testing::Test { 905f92157deSopenharmony_ci protected: 906f92157deSopenharmony_ci // Per-test-suite set-up. 907f92157deSopenharmony_ci // Called before the first test in this test suite. 908f92157deSopenharmony_ci // Can be omitted if not needed. 909f92157deSopenharmony_ci static void SetUpTestSuite() { 910f92157deSopenharmony_ci // Avoid reallocating static objects if called in subclasses of FooTest. 911f92157deSopenharmony_ci if (shared_resource_ == nullptr) { 912f92157deSopenharmony_ci shared_resource_ = new ...; 913f92157deSopenharmony_ci } 914f92157deSopenharmony_ci } 915f92157deSopenharmony_ci 916f92157deSopenharmony_ci // Per-test-suite tear-down. 917f92157deSopenharmony_ci // Called after the last test in this test suite. 918f92157deSopenharmony_ci // Can be omitted if not needed. 919f92157deSopenharmony_ci static void TearDownTestSuite() { 920f92157deSopenharmony_ci delete shared_resource_; 921f92157deSopenharmony_ci shared_resource_ = nullptr; 922f92157deSopenharmony_ci } 923f92157deSopenharmony_ci 924f92157deSopenharmony_ci // You can define per-test set-up logic as usual. 925f92157deSopenharmony_ci void SetUp() override { ... } 926f92157deSopenharmony_ci 927f92157deSopenharmony_ci // You can define per-test tear-down logic as usual. 928f92157deSopenharmony_ci void TearDown() override { ... } 929f92157deSopenharmony_ci 930f92157deSopenharmony_ci // Some expensive resource shared by all tests. 931f92157deSopenharmony_ci static T* shared_resource_; 932f92157deSopenharmony_ci}; 933f92157deSopenharmony_ci 934f92157deSopenharmony_ciT* FooTest::shared_resource_ = nullptr; 935f92157deSopenharmony_ci 936f92157deSopenharmony_ciTEST_F(FooTest, Test1) { 937f92157deSopenharmony_ci ... you can refer to shared_resource_ here ... 938f92157deSopenharmony_ci} 939f92157deSopenharmony_ci 940f92157deSopenharmony_ciTEST_F(FooTest, Test2) { 941f92157deSopenharmony_ci ... you can refer to shared_resource_ here ... 942f92157deSopenharmony_ci} 943f92157deSopenharmony_ci``` 944f92157deSopenharmony_ci 945f92157deSopenharmony_ci{: .callout .note} 946f92157deSopenharmony_ciNOTE: Though the above code declares `SetUpTestSuite()` protected, it may 947f92157deSopenharmony_cisometimes be necessary to declare it public, such as when using it with 948f92157deSopenharmony_ci`TEST_P`. 949f92157deSopenharmony_ci 950f92157deSopenharmony_ci## Global Set-Up and Tear-Down 951f92157deSopenharmony_ci 952f92157deSopenharmony_ciJust as you can do set-up and tear-down at the test level and the test suite 953f92157deSopenharmony_cilevel, you can also do it at the test program level. Here's how. 954f92157deSopenharmony_ci 955f92157deSopenharmony_ciFirst, you subclass the `::testing::Environment` class to define a test 956f92157deSopenharmony_cienvironment, which knows how to set-up and tear-down: 957f92157deSopenharmony_ci 958f92157deSopenharmony_ci```c++ 959f92157deSopenharmony_ciclass Environment : public ::testing::Environment { 960f92157deSopenharmony_ci public: 961f92157deSopenharmony_ci ~Environment() override {} 962f92157deSopenharmony_ci 963f92157deSopenharmony_ci // Override this to define how to set up the environment. 964f92157deSopenharmony_ci void SetUp() override {} 965f92157deSopenharmony_ci 966f92157deSopenharmony_ci // Override this to define how to tear down the environment. 967f92157deSopenharmony_ci void TearDown() override {} 968f92157deSopenharmony_ci}; 969f92157deSopenharmony_ci``` 970f92157deSopenharmony_ci 971f92157deSopenharmony_ciThen, you register an instance of your environment class with googletest by 972f92157deSopenharmony_cicalling the `::testing::AddGlobalTestEnvironment()` function: 973f92157deSopenharmony_ci 974f92157deSopenharmony_ci```c++ 975f92157deSopenharmony_ciEnvironment* AddGlobalTestEnvironment(Environment* env); 976f92157deSopenharmony_ci``` 977f92157deSopenharmony_ci 978f92157deSopenharmony_ciNow, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of 979f92157deSopenharmony_cieach environment object, then runs the tests if none of the environments 980f92157deSopenharmony_cireported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()` 981f92157deSopenharmony_cialways calls `TearDown()` with each environment object, regardless of whether or 982f92157deSopenharmony_cinot the tests were run. 983f92157deSopenharmony_ci 984f92157deSopenharmony_ciIt's OK to register multiple environment objects. In this suite, their `SetUp()` 985f92157deSopenharmony_ciwill be called in the order they are registered, and their `TearDown()` will be 986f92157deSopenharmony_cicalled in the reverse order. 987f92157deSopenharmony_ci 988f92157deSopenharmony_ciNote that googletest takes ownership of the registered environment objects. 989f92157deSopenharmony_ciTherefore **do not delete them** by yourself. 990f92157deSopenharmony_ci 991f92157deSopenharmony_ciYou should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, 992f92157deSopenharmony_ciprobably in `main()`. If you use `gtest_main`, you need to call this before 993f92157deSopenharmony_ci`main()` starts for it to take effect. One way to do this is to define a global 994f92157deSopenharmony_civariable like this: 995f92157deSopenharmony_ci 996f92157deSopenharmony_ci```c++ 997f92157deSopenharmony_citesting::Environment* const foo_env = 998f92157deSopenharmony_ci testing::AddGlobalTestEnvironment(new FooEnvironment); 999f92157deSopenharmony_ci``` 1000f92157deSopenharmony_ci 1001f92157deSopenharmony_ciHowever, we strongly recommend you to write your own `main()` and call 1002f92157deSopenharmony_ci`AddGlobalTestEnvironment()` there, as relying on initialization of global 1003f92157deSopenharmony_civariables makes the code harder to read and may cause problems when you register 1004f92157deSopenharmony_cimultiple environments from different translation units and the environments have 1005f92157deSopenharmony_cidependencies among them (remember that the compiler doesn't guarantee the order 1006f92157deSopenharmony_ciin which global variables from different translation units are initialized). 1007f92157deSopenharmony_ci 1008f92157deSopenharmony_ci## Value-Parameterized Tests 1009f92157deSopenharmony_ci 1010f92157deSopenharmony_ci*Value-parameterized tests* allow you to test your code with different 1011f92157deSopenharmony_ciparameters without writing multiple copies of the same test. This is useful in a 1012f92157deSopenharmony_cinumber of situations, for example: 1013f92157deSopenharmony_ci 1014f92157deSopenharmony_ci* You have a piece of code whose behavior is affected by one or more 1015f92157deSopenharmony_ci command-line flags. You want to make sure your code performs correctly for 1016f92157deSopenharmony_ci various values of those flags. 1017f92157deSopenharmony_ci* You want to test different implementations of an OO interface. 1018f92157deSopenharmony_ci* You want to test your code over various inputs (a.k.a. data-driven testing). 1019f92157deSopenharmony_ci This feature is easy to abuse, so please exercise your good sense when doing 1020f92157deSopenharmony_ci it! 1021f92157deSopenharmony_ci 1022f92157deSopenharmony_ci### How to Write Value-Parameterized Tests 1023f92157deSopenharmony_ci 1024f92157deSopenharmony_ciTo write value-parameterized tests, first you should define a fixture class. It 1025f92157deSopenharmony_cimust be derived from both `testing::Test` and `testing::WithParamInterface<T>` 1026f92157deSopenharmony_ci(the latter is a pure interface), where `T` is the type of your parameter 1027f92157deSopenharmony_civalues. For convenience, you can just derive the fixture class from 1028f92157deSopenharmony_ci`testing::TestWithParam<T>`, which itself is derived from both `testing::Test` 1029f92157deSopenharmony_ciand `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a 1030f92157deSopenharmony_ciraw pointer, you are responsible for managing the lifespan of the pointed 1031f92157deSopenharmony_civalues. 1032f92157deSopenharmony_ci 1033f92157deSopenharmony_ci{: .callout .note} 1034f92157deSopenharmony_ciNOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` 1035f92157deSopenharmony_cithey must be declared **public** rather than **protected** in order to use 1036f92157deSopenharmony_ci`TEST_P`. 1037f92157deSopenharmony_ci 1038f92157deSopenharmony_ci```c++ 1039f92157deSopenharmony_ciclass FooTest : 1040f92157deSopenharmony_ci public testing::TestWithParam<const char*> { 1041f92157deSopenharmony_ci // You can implement all the usual fixture class members here. 1042f92157deSopenharmony_ci // To access the test parameter, call GetParam() from class 1043f92157deSopenharmony_ci // TestWithParam<T>. 1044f92157deSopenharmony_ci}; 1045f92157deSopenharmony_ci 1046f92157deSopenharmony_ci// Or, when you want to add parameters to a pre-existing fixture class: 1047f92157deSopenharmony_ciclass BaseTest : public testing::Test { 1048f92157deSopenharmony_ci ... 1049f92157deSopenharmony_ci}; 1050f92157deSopenharmony_ciclass BarTest : public BaseTest, 1051f92157deSopenharmony_ci public testing::WithParamInterface<const char*> { 1052f92157deSopenharmony_ci ... 1053f92157deSopenharmony_ci}; 1054f92157deSopenharmony_ci``` 1055f92157deSopenharmony_ci 1056f92157deSopenharmony_ciThen, use the `TEST_P` macro to define as many test patterns using this fixture 1057f92157deSopenharmony_cias you want. The `_P` suffix is for "parameterized" or "pattern", whichever you 1058f92157deSopenharmony_ciprefer to think. 1059f92157deSopenharmony_ci 1060f92157deSopenharmony_ci```c++ 1061f92157deSopenharmony_ciTEST_P(FooTest, DoesBlah) { 1062f92157deSopenharmony_ci // Inside a test, access the test parameter with the GetParam() method 1063f92157deSopenharmony_ci // of the TestWithParam<T> class: 1064f92157deSopenharmony_ci EXPECT_TRUE(foo.Blah(GetParam())); 1065f92157deSopenharmony_ci ... 1066f92157deSopenharmony_ci} 1067f92157deSopenharmony_ci 1068f92157deSopenharmony_ciTEST_P(FooTest, HasBlahBlah) { 1069f92157deSopenharmony_ci ... 1070f92157deSopenharmony_ci} 1071f92157deSopenharmony_ci``` 1072f92157deSopenharmony_ci 1073f92157deSopenharmony_ciFinally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the 1074f92157deSopenharmony_citest suite with any set of parameters you want. GoogleTest defines a number of 1075f92157deSopenharmony_cifunctions for generating test parameters—see details at 1076f92157deSopenharmony_ci[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in 1077f92157deSopenharmony_cithe Testing Reference. 1078f92157deSopenharmony_ci 1079f92157deSopenharmony_ciFor example, the following statement will instantiate tests from the `FooTest` 1080f92157deSopenharmony_citest suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the 1081f92157deSopenharmony_ci[`Values`](reference/testing.md#param-generators) parameter generator: 1082f92157deSopenharmony_ci 1083f92157deSopenharmony_ci```c++ 1084f92157deSopenharmony_ciINSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, 1085f92157deSopenharmony_ci FooTest, 1086f92157deSopenharmony_ci testing::Values("meeny", "miny", "moe")); 1087f92157deSopenharmony_ci``` 1088f92157deSopenharmony_ci 1089f92157deSopenharmony_ci{: .callout .note} 1090f92157deSopenharmony_ciNOTE: The code above must be placed at global or namespace scope, not at 1091f92157deSopenharmony_cifunction scope. 1092f92157deSopenharmony_ci 1093f92157deSopenharmony_ciThe first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the 1094f92157deSopenharmony_ciinstantiation of the test suite. The next argument is the name of the test 1095f92157deSopenharmony_cipattern, and the last is the 1096f92157deSopenharmony_ci[parameter generator](reference/testing.md#param-generators). 1097f92157deSopenharmony_ci 1098f92157deSopenharmony_ciThe parameter generator expression is not evaluated until GoogleTest is 1099f92157deSopenharmony_ciinitialized (via `InitGoogleTest()`). Any prior initialization done in the 1100f92157deSopenharmony_ci`main` function will be accessible from the parameter generator, for example, 1101f92157deSopenharmony_cithe results of flag parsing. 1102f92157deSopenharmony_ci 1103f92157deSopenharmony_ciYou can instantiate a test pattern more than once, so to distinguish different 1104f92157deSopenharmony_ciinstances of the pattern, the instantiation name is added as a prefix to the 1105f92157deSopenharmony_ciactual test suite name. Remember to pick unique prefixes for different 1106f92157deSopenharmony_ciinstantiations. The tests from the instantiation above will have these names: 1107f92157deSopenharmony_ci 1108f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` 1109f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` 1110f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` 1111f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` 1112f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` 1113f92157deSopenharmony_ci* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` 1114f92157deSopenharmony_ci 1115f92157deSopenharmony_ciYou can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). 1116f92157deSopenharmony_ci 1117f92157deSopenharmony_ciThe following statement will instantiate all tests from `FooTest` again, each 1118f92157deSopenharmony_ciwith parameter values `"cat"` and `"dog"` using the 1119f92157deSopenharmony_ci[`ValuesIn`](reference/testing.md#param-generators) parameter generator: 1120f92157deSopenharmony_ci 1121f92157deSopenharmony_ci```c++ 1122f92157deSopenharmony_ciconst char* pets[] = {"cat", "dog"}; 1123f92157deSopenharmony_ciINSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets)); 1124f92157deSopenharmony_ci``` 1125f92157deSopenharmony_ci 1126f92157deSopenharmony_ciThe tests from the instantiation above will have these names: 1127f92157deSopenharmony_ci 1128f92157deSopenharmony_ci* `Pets/FooTest.DoesBlah/0` for `"cat"` 1129f92157deSopenharmony_ci* `Pets/FooTest.DoesBlah/1` for `"dog"` 1130f92157deSopenharmony_ci* `Pets/FooTest.HasBlahBlah/0` for `"cat"` 1131f92157deSopenharmony_ci* `Pets/FooTest.HasBlahBlah/1` for `"dog"` 1132f92157deSopenharmony_ci 1133f92157deSopenharmony_ciPlease note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the 1134f92157deSopenharmony_cigiven test suite, whether their definitions come before or *after* the 1135f92157deSopenharmony_ci`INSTANTIATE_TEST_SUITE_P` statement. 1136f92157deSopenharmony_ci 1137f92157deSopenharmony_ciAdditionally, by default, every `TEST_P` without a corresponding 1138f92157deSopenharmony_ci`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite 1139f92157deSopenharmony_ci`GoogleTestVerification`. If you have a test suite where that omission is not an 1140f92157deSopenharmony_cierror, for example it is in a library that may be linked in for other reasons or 1141f92157deSopenharmony_ciwhere the list of test cases is dynamic and may be empty, then this check can be 1142f92157deSopenharmony_cisuppressed by tagging the test suite: 1143f92157deSopenharmony_ci 1144f92157deSopenharmony_ci```c++ 1145f92157deSopenharmony_ciGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); 1146f92157deSopenharmony_ci``` 1147f92157deSopenharmony_ci 1148f92157deSopenharmony_ciYou can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. 1149f92157deSopenharmony_ci 1150f92157deSopenharmony_ci[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" 1151f92157deSopenharmony_ci[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" 1152f92157deSopenharmony_ci 1153f92157deSopenharmony_ci### Creating Value-Parameterized Abstract Tests 1154f92157deSopenharmony_ci 1155f92157deSopenharmony_ciIn the above, we define and instantiate `FooTest` in the *same* source file. 1156f92157deSopenharmony_ciSometimes you may want to define value-parameterized tests in a library and let 1157f92157deSopenharmony_ciother people instantiate them later. This pattern is known as *abstract tests*. 1158f92157deSopenharmony_ciAs an example of its application, when you are designing an interface you can 1159f92157deSopenharmony_ciwrite a standard suite of abstract tests (perhaps using a factory function as 1160f92157deSopenharmony_cithe test parameter) that all implementations of the interface are expected to 1161f92157deSopenharmony_cipass. When someone implements the interface, they can instantiate your suite to 1162f92157deSopenharmony_ciget all the interface-conformance tests for free. 1163f92157deSopenharmony_ci 1164f92157deSopenharmony_ciTo define abstract tests, you should organize your code like this: 1165f92157deSopenharmony_ci 1166f92157deSopenharmony_ci1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) 1167f92157deSopenharmony_ci in a header file, say `foo_param_test.h`. Think of this as *declaring* your 1168f92157deSopenharmony_ci abstract tests. 1169f92157deSopenharmony_ci2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes 1170f92157deSopenharmony_ci `foo_param_test.h`. Think of this as *implementing* your abstract tests. 1171f92157deSopenharmony_ci 1172f92157deSopenharmony_ciOnce they are defined, you can instantiate them by including `foo_param_test.h`, 1173f92157deSopenharmony_ciinvoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that 1174f92157deSopenharmony_cicontains `foo_param_test.cc`. You can instantiate the same abstract test suite 1175f92157deSopenharmony_cimultiple times, possibly in different source files. 1176f92157deSopenharmony_ci 1177f92157deSopenharmony_ci### Specifying Names for Value-Parameterized Test Parameters 1178f92157deSopenharmony_ci 1179f92157deSopenharmony_ciThe optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to 1180f92157deSopenharmony_cispecify a function or functor that generates custom test name suffixes based on 1181f92157deSopenharmony_cithe test parameters. The function should accept one argument of type 1182f92157deSopenharmony_ci`testing::TestParamInfo<class ParamType>`, and return `std::string`. 1183f92157deSopenharmony_ci 1184f92157deSopenharmony_ci`testing::PrintToStringParamName` is a builtin test suffix generator that 1185f92157deSopenharmony_cireturns the value of `testing::PrintToString(GetParam())`. It does not work for 1186f92157deSopenharmony_ci`std::string` or C strings. 1187f92157deSopenharmony_ci 1188f92157deSopenharmony_ci{: .callout .note} 1189f92157deSopenharmony_ciNOTE: test names must be non-empty, unique, and may only contain ASCII 1190f92157deSopenharmony_cialphanumeric characters. In particular, they 1191f92157deSopenharmony_ci[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) 1192f92157deSopenharmony_ci 1193f92157deSopenharmony_ci```c++ 1194f92157deSopenharmony_ciclass MyTestSuite : public testing::TestWithParam<int> {}; 1195f92157deSopenharmony_ci 1196f92157deSopenharmony_ciTEST_P(MyTestSuite, MyTest) 1197f92157deSopenharmony_ci{ 1198f92157deSopenharmony_ci std::cout << "Example Test Param: " << GetParam() << std::endl; 1199f92157deSopenharmony_ci} 1200f92157deSopenharmony_ci 1201f92157deSopenharmony_ciINSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), 1202f92157deSopenharmony_ci testing::PrintToStringParamName()); 1203f92157deSopenharmony_ci``` 1204f92157deSopenharmony_ci 1205f92157deSopenharmony_ciProviding a custom functor allows for more control over test parameter name 1206f92157deSopenharmony_cigeneration, especially for types where the automatic conversion does not 1207f92157deSopenharmony_cigenerate helpful parameter names (e.g. strings as demonstrated above). The 1208f92157deSopenharmony_cifollowing example illustrates this for multiple parameters, an enumeration type 1209f92157deSopenharmony_ciand a string, and also demonstrates how to combine generators. It uses a lambda 1210f92157deSopenharmony_cifor conciseness: 1211f92157deSopenharmony_ci 1212f92157deSopenharmony_ci```c++ 1213f92157deSopenharmony_cienum class MyType { MY_FOO = 0, MY_BAR = 1 }; 1214f92157deSopenharmony_ci 1215f92157deSopenharmony_ciclass MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> { 1216f92157deSopenharmony_ci}; 1217f92157deSopenharmony_ci 1218f92157deSopenharmony_ciINSTANTIATE_TEST_SUITE_P( 1219f92157deSopenharmony_ci MyGroup, MyTestSuite, 1220f92157deSopenharmony_ci testing::Combine( 1221f92157deSopenharmony_ci testing::Values(MyType::MY_FOO, MyType::MY_BAR), 1222f92157deSopenharmony_ci testing::Values("A", "B")), 1223f92157deSopenharmony_ci [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) { 1224f92157deSopenharmony_ci std::string name = absl::StrCat( 1225f92157deSopenharmony_ci std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", 1226f92157deSopenharmony_ci std::get<1>(info.param)); 1227f92157deSopenharmony_ci absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); 1228f92157deSopenharmony_ci return name; 1229f92157deSopenharmony_ci }); 1230f92157deSopenharmony_ci``` 1231f92157deSopenharmony_ci 1232f92157deSopenharmony_ci## Typed Tests 1233f92157deSopenharmony_ci 1234f92157deSopenharmony_ciSuppose you have multiple implementations of the same interface and want to make 1235f92157deSopenharmony_cisure that all of them satisfy some common requirements. Or, you may have defined 1236f92157deSopenharmony_ciseveral types that are supposed to conform to the same "concept" and you want to 1237f92157deSopenharmony_civerify it. In both cases, you want the same test logic repeated for different 1238f92157deSopenharmony_citypes. 1239f92157deSopenharmony_ci 1240f92157deSopenharmony_ciWhile you can write one `TEST` or `TEST_F` for each type you want to test (and 1241f92157deSopenharmony_ciyou may even factor the test logic into a function template that you invoke from 1242f92157deSopenharmony_cithe `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` 1243f92157deSopenharmony_citypes, you'll end up writing `m*n` `TEST`s. 1244f92157deSopenharmony_ci 1245f92157deSopenharmony_ci*Typed tests* allow you to repeat the same test logic over a list of types. You 1246f92157deSopenharmony_cionly need to write the test logic once, although you must know the type list 1247f92157deSopenharmony_ciwhen writing typed tests. Here's how you do it: 1248f92157deSopenharmony_ci 1249f92157deSopenharmony_ciFirst, define a fixture class template. It should be parameterized by a type. 1250f92157deSopenharmony_ciRemember to derive it from `::testing::Test`: 1251f92157deSopenharmony_ci 1252f92157deSopenharmony_ci```c++ 1253f92157deSopenharmony_citemplate <typename T> 1254f92157deSopenharmony_ciclass FooTest : public testing::Test { 1255f92157deSopenharmony_ci public: 1256f92157deSopenharmony_ci ... 1257f92157deSopenharmony_ci using List = std::list<T>; 1258f92157deSopenharmony_ci static T shared_; 1259f92157deSopenharmony_ci T value_; 1260f92157deSopenharmony_ci}; 1261f92157deSopenharmony_ci``` 1262f92157deSopenharmony_ci 1263f92157deSopenharmony_ciNext, associate a list of types with the test suite, which will be repeated for 1264f92157deSopenharmony_cieach type in the list: 1265f92157deSopenharmony_ci 1266f92157deSopenharmony_ci```c++ 1267f92157deSopenharmony_ciusing MyTypes = ::testing::Types<char, int, unsigned int>; 1268f92157deSopenharmony_ciTYPED_TEST_SUITE(FooTest, MyTypes); 1269f92157deSopenharmony_ci``` 1270f92157deSopenharmony_ci 1271f92157deSopenharmony_ciThe type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` 1272f92157deSopenharmony_cimacro to parse correctly. Otherwise the compiler will think that each comma in 1273f92157deSopenharmony_cithe type list introduces a new macro argument. 1274f92157deSopenharmony_ci 1275f92157deSopenharmony_ciThen, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this 1276f92157deSopenharmony_citest suite. You can repeat this as many times as you want: 1277f92157deSopenharmony_ci 1278f92157deSopenharmony_ci```c++ 1279f92157deSopenharmony_ciTYPED_TEST(FooTest, DoesBlah) { 1280f92157deSopenharmony_ci // Inside a test, refer to the special name TypeParam to get the type 1281f92157deSopenharmony_ci // parameter. Since we are inside a derived class template, C++ requires 1282f92157deSopenharmony_ci // us to visit the members of FooTest via 'this'. 1283f92157deSopenharmony_ci TypeParam n = this->value_; 1284f92157deSopenharmony_ci 1285f92157deSopenharmony_ci // To visit static members of the fixture, add the 'TestFixture::' 1286f92157deSopenharmony_ci // prefix. 1287f92157deSopenharmony_ci n += TestFixture::shared_; 1288f92157deSopenharmony_ci 1289f92157deSopenharmony_ci // To refer to typedefs in the fixture, add the 'typename TestFixture::' 1290f92157deSopenharmony_ci // prefix. The 'typename' is required to satisfy the compiler. 1291f92157deSopenharmony_ci typename TestFixture::List values; 1292f92157deSopenharmony_ci 1293f92157deSopenharmony_ci values.push_back(n); 1294f92157deSopenharmony_ci ... 1295f92157deSopenharmony_ci} 1296f92157deSopenharmony_ci 1297f92157deSopenharmony_ciTYPED_TEST(FooTest, HasPropertyA) { ... } 1298f92157deSopenharmony_ci``` 1299f92157deSopenharmony_ci 1300f92157deSopenharmony_ciYou can see [sample6_unittest.cc] for a complete example. 1301f92157deSopenharmony_ci 1302f92157deSopenharmony_ci[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" 1303f92157deSopenharmony_ci 1304f92157deSopenharmony_ci## Type-Parameterized Tests 1305f92157deSopenharmony_ci 1306f92157deSopenharmony_ci*Type-parameterized tests* are like typed tests, except that they don't require 1307f92157deSopenharmony_ciyou to know the list of types ahead of time. Instead, you can define the test 1308f92157deSopenharmony_cilogic first and instantiate it with different type lists later. You can even 1309f92157deSopenharmony_ciinstantiate it more than once in the same program. 1310f92157deSopenharmony_ci 1311f92157deSopenharmony_ciIf you are designing an interface or concept, you can define a suite of 1312f92157deSopenharmony_citype-parameterized tests to verify properties that any valid implementation of 1313f92157deSopenharmony_cithe interface/concept should have. Then, the author of each implementation can 1314f92157deSopenharmony_cijust instantiate the test suite with their type to verify that it conforms to 1315f92157deSopenharmony_cithe requirements, without having to write similar tests repeatedly. Here's an 1316f92157deSopenharmony_ciexample: 1317f92157deSopenharmony_ci 1318f92157deSopenharmony_ciFirst, define a fixture class template, as we did with typed tests: 1319f92157deSopenharmony_ci 1320f92157deSopenharmony_ci```c++ 1321f92157deSopenharmony_citemplate <typename T> 1322f92157deSopenharmony_ciclass FooTest : public testing::Test { 1323f92157deSopenharmony_ci void DoSomethingInteresting(); 1324f92157deSopenharmony_ci ... 1325f92157deSopenharmony_ci}; 1326f92157deSopenharmony_ci``` 1327f92157deSopenharmony_ci 1328f92157deSopenharmony_ciNext, declare that you will define a type-parameterized test suite: 1329f92157deSopenharmony_ci 1330f92157deSopenharmony_ci```c++ 1331f92157deSopenharmony_ciTYPED_TEST_SUITE_P(FooTest); 1332f92157deSopenharmony_ci``` 1333f92157deSopenharmony_ci 1334f92157deSopenharmony_ciThen, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat 1335f92157deSopenharmony_cithis as many times as you want: 1336f92157deSopenharmony_ci 1337f92157deSopenharmony_ci```c++ 1338f92157deSopenharmony_ciTYPED_TEST_P(FooTest, DoesBlah) { 1339f92157deSopenharmony_ci // Inside a test, refer to TypeParam to get the type parameter. 1340f92157deSopenharmony_ci TypeParam n = 0; 1341f92157deSopenharmony_ci 1342f92157deSopenharmony_ci // You will need to use `this` explicitly to refer to fixture members. 1343f92157deSopenharmony_ci this->DoSomethingInteresting() 1344f92157deSopenharmony_ci ... 1345f92157deSopenharmony_ci} 1346f92157deSopenharmony_ci 1347f92157deSopenharmony_ciTYPED_TEST_P(FooTest, HasPropertyA) { ... } 1348f92157deSopenharmony_ci``` 1349f92157deSopenharmony_ci 1350f92157deSopenharmony_ciNow the tricky part: you need to register all test patterns using the 1351f92157deSopenharmony_ci`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first 1352f92157deSopenharmony_ciargument of the macro is the test suite name; the rest are the names of the 1353f92157deSopenharmony_citests in this test suite: 1354f92157deSopenharmony_ci 1355f92157deSopenharmony_ci```c++ 1356f92157deSopenharmony_ciREGISTER_TYPED_TEST_SUITE_P(FooTest, 1357f92157deSopenharmony_ci DoesBlah, HasPropertyA); 1358f92157deSopenharmony_ci``` 1359f92157deSopenharmony_ci 1360f92157deSopenharmony_ciFinally, you are free to instantiate the pattern with the types you want. If you 1361f92157deSopenharmony_ciput the above code in a header file, you can `#include` it in multiple C++ 1362f92157deSopenharmony_cisource files and instantiate it multiple times. 1363f92157deSopenharmony_ci 1364f92157deSopenharmony_ci```c++ 1365f92157deSopenharmony_ciusing MyTypes = ::testing::Types<char, int, unsigned int>; 1366f92157deSopenharmony_ciINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); 1367f92157deSopenharmony_ci``` 1368f92157deSopenharmony_ci 1369f92157deSopenharmony_ciTo distinguish different instances of the pattern, the first argument to the 1370f92157deSopenharmony_ci`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the 1371f92157deSopenharmony_ciactual test suite name. Remember to pick unique prefixes for different 1372f92157deSopenharmony_ciinstances. 1373f92157deSopenharmony_ci 1374f92157deSopenharmony_ciIn the special case where the type list contains only one type, you can write 1375f92157deSopenharmony_cithat type directly without `::testing::Types<...>`, like this: 1376f92157deSopenharmony_ci 1377f92157deSopenharmony_ci```c++ 1378f92157deSopenharmony_ciINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); 1379f92157deSopenharmony_ci``` 1380f92157deSopenharmony_ci 1381f92157deSopenharmony_ciYou can see [sample6_unittest.cc] for a complete example. 1382f92157deSopenharmony_ci 1383f92157deSopenharmony_ci## Testing Private Code 1384f92157deSopenharmony_ci 1385f92157deSopenharmony_ciIf you change your software's internal implementation, your tests should not 1386f92157deSopenharmony_cibreak as long as the change is not observable by users. Therefore, **per the 1387f92157deSopenharmony_ciblack-box testing principle, most of the time you should test your code through 1388f92157deSopenharmony_ciits public interfaces.** 1389f92157deSopenharmony_ci 1390f92157deSopenharmony_ci**If you still find yourself needing to test internal implementation code, 1391f92157deSopenharmony_ciconsider if there's a better design.** The desire to test internal 1392f92157deSopenharmony_ciimplementation is often a sign that the class is doing too much. Consider 1393f92157deSopenharmony_ciextracting an implementation class, and testing it. Then use that implementation 1394f92157deSopenharmony_ciclass in the original class. 1395f92157deSopenharmony_ci 1396f92157deSopenharmony_ciIf you absolutely have to test non-public interface code though, you can. There 1397f92157deSopenharmony_ciare two cases to consider: 1398f92157deSopenharmony_ci 1399f92157deSopenharmony_ci* Static functions ( *not* the same as static member functions!) or unnamed 1400f92157deSopenharmony_ci namespaces, and 1401f92157deSopenharmony_ci* Private or protected class members 1402f92157deSopenharmony_ci 1403f92157deSopenharmony_ciTo test them, we use the following special techniques: 1404f92157deSopenharmony_ci 1405f92157deSopenharmony_ci* Both static functions and definitions/declarations in an unnamed namespace 1406f92157deSopenharmony_ci are only visible within the same translation unit. To test them, you can 1407f92157deSopenharmony_ci `#include` the entire `.cc` file being tested in your `*_test.cc` file. 1408f92157deSopenharmony_ci (#including `.cc` files is not a good way to reuse code - you should not do 1409f92157deSopenharmony_ci this in production code!) 1410f92157deSopenharmony_ci 1411f92157deSopenharmony_ci However, a better approach is to move the private code into the 1412f92157deSopenharmony_ci `foo::internal` namespace, where `foo` is the namespace your project 1413f92157deSopenharmony_ci normally uses, and put the private declarations in a `*-internal.h` file. 1414f92157deSopenharmony_ci Your production `.cc` files and your tests are allowed to include this 1415f92157deSopenharmony_ci internal header, but your clients are not. This way, you can fully test your 1416f92157deSopenharmony_ci internal implementation without leaking it to your clients. 1417f92157deSopenharmony_ci 1418f92157deSopenharmony_ci* Private class members are only accessible from within the class or by 1419f92157deSopenharmony_ci friends. To access a class' private members, you can declare your test 1420f92157deSopenharmony_ci fixture as a friend to the class and define accessors in your fixture. Tests 1421f92157deSopenharmony_ci using the fixture can then access the private members of your production 1422f92157deSopenharmony_ci class via the accessors in the fixture. Note that even though your fixture 1423f92157deSopenharmony_ci is a friend to your production class, your tests are not automatically 1424f92157deSopenharmony_ci friends to it, as they are technically defined in sub-classes of the 1425f92157deSopenharmony_ci fixture. 1426f92157deSopenharmony_ci 1427f92157deSopenharmony_ci Another way to test private members is to refactor them into an 1428f92157deSopenharmony_ci implementation class, which is then declared in a `*-internal.h` file. Your 1429f92157deSopenharmony_ci clients aren't allowed to include this header but your tests can. Such is 1430f92157deSopenharmony_ci called the 1431f92157deSopenharmony_ci [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) 1432f92157deSopenharmony_ci (Private Implementation) idiom. 1433f92157deSopenharmony_ci 1434f92157deSopenharmony_ci Or, you can declare an individual test as a friend of your class by adding 1435f92157deSopenharmony_ci this line in the class body: 1436f92157deSopenharmony_ci 1437f92157deSopenharmony_ci ```c++ 1438f92157deSopenharmony_ci FRIEND_TEST(TestSuiteName, TestName); 1439f92157deSopenharmony_ci ``` 1440f92157deSopenharmony_ci 1441f92157deSopenharmony_ci For example, 1442f92157deSopenharmony_ci 1443f92157deSopenharmony_ci ```c++ 1444f92157deSopenharmony_ci // foo.h 1445f92157deSopenharmony_ci class Foo { 1446f92157deSopenharmony_ci ... 1447f92157deSopenharmony_ci private: 1448f92157deSopenharmony_ci FRIEND_TEST(FooTest, BarReturnsZeroOnNull); 1449f92157deSopenharmony_ci 1450f92157deSopenharmony_ci int Bar(void* x); 1451f92157deSopenharmony_ci }; 1452f92157deSopenharmony_ci 1453f92157deSopenharmony_ci // foo_test.cc 1454f92157deSopenharmony_ci ... 1455f92157deSopenharmony_ci TEST(FooTest, BarReturnsZeroOnNull) { 1456f92157deSopenharmony_ci Foo foo; 1457f92157deSopenharmony_ci EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). 1458f92157deSopenharmony_ci } 1459f92157deSopenharmony_ci ``` 1460f92157deSopenharmony_ci 1461f92157deSopenharmony_ci Pay special attention when your class is defined in a namespace. If you want 1462f92157deSopenharmony_ci your test fixtures and tests to be friends of your class, then they must be 1463f92157deSopenharmony_ci defined in the exact same namespace (no anonymous or inline namespaces). 1464f92157deSopenharmony_ci 1465f92157deSopenharmony_ci For example, if the code to be tested looks like: 1466f92157deSopenharmony_ci 1467f92157deSopenharmony_ci ```c++ 1468f92157deSopenharmony_ci namespace my_namespace { 1469f92157deSopenharmony_ci 1470f92157deSopenharmony_ci class Foo { 1471f92157deSopenharmony_ci friend class FooTest; 1472f92157deSopenharmony_ci FRIEND_TEST(FooTest, Bar); 1473f92157deSopenharmony_ci FRIEND_TEST(FooTest, Baz); 1474f92157deSopenharmony_ci ... definition of the class Foo ... 1475f92157deSopenharmony_ci }; 1476f92157deSopenharmony_ci 1477f92157deSopenharmony_ci } // namespace my_namespace 1478f92157deSopenharmony_ci ``` 1479f92157deSopenharmony_ci 1480f92157deSopenharmony_ci Your test code should be something like: 1481f92157deSopenharmony_ci 1482f92157deSopenharmony_ci ```c++ 1483f92157deSopenharmony_ci namespace my_namespace { 1484f92157deSopenharmony_ci 1485f92157deSopenharmony_ci class FooTest : public testing::Test { 1486f92157deSopenharmony_ci protected: 1487f92157deSopenharmony_ci ... 1488f92157deSopenharmony_ci }; 1489f92157deSopenharmony_ci 1490f92157deSopenharmony_ci TEST_F(FooTest, Bar) { ... } 1491f92157deSopenharmony_ci TEST_F(FooTest, Baz) { ... } 1492f92157deSopenharmony_ci 1493f92157deSopenharmony_ci } // namespace my_namespace 1494f92157deSopenharmony_ci ``` 1495f92157deSopenharmony_ci 1496f92157deSopenharmony_ci## "Catching" Failures 1497f92157deSopenharmony_ci 1498f92157deSopenharmony_ciIf you are building a testing utility on top of googletest, you'll want to test 1499f92157deSopenharmony_ciyour utility. What framework would you use to test it? googletest, of course. 1500f92157deSopenharmony_ci 1501f92157deSopenharmony_ciThe challenge is to verify that your testing utility reports failures correctly. 1502f92157deSopenharmony_ciIn frameworks that report a failure by throwing an exception, you could catch 1503f92157deSopenharmony_cithe exception and assert on it. But googletest doesn't use exceptions, so how do 1504f92157deSopenharmony_ciwe test that a piece of code generates an expected failure? 1505f92157deSopenharmony_ci 1506f92157deSopenharmony_ci`"gtest/gtest-spi.h"` contains some constructs to do this. 1507f92157deSopenharmony_ciAfter #including this header, you can use 1508f92157deSopenharmony_ci 1509f92157deSopenharmony_ci```c++ 1510f92157deSopenharmony_ci EXPECT_FATAL_FAILURE(statement, substring); 1511f92157deSopenharmony_ci``` 1512f92157deSopenharmony_ci 1513f92157deSopenharmony_cito assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the 1514f92157deSopenharmony_cicurrent thread whose message contains the given `substring`, or use 1515f92157deSopenharmony_ci 1516f92157deSopenharmony_ci```c++ 1517f92157deSopenharmony_ci EXPECT_NONFATAL_FAILURE(statement, substring); 1518f92157deSopenharmony_ci``` 1519f92157deSopenharmony_ci 1520f92157deSopenharmony_ciif you are expecting a non-fatal (e.g. `EXPECT_*`) failure. 1521f92157deSopenharmony_ci 1522f92157deSopenharmony_ciOnly failures in the current thread are checked to determine the result of this 1523f92157deSopenharmony_citype of expectations. If `statement` creates new threads, failures in these 1524f92157deSopenharmony_cithreads are also ignored. If you want to catch failures in other threads as 1525f92157deSopenharmony_ciwell, use one of the following macros instead: 1526f92157deSopenharmony_ci 1527f92157deSopenharmony_ci```c++ 1528f92157deSopenharmony_ci EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); 1529f92157deSopenharmony_ci EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); 1530f92157deSopenharmony_ci``` 1531f92157deSopenharmony_ci 1532f92157deSopenharmony_ci{: .callout .note} 1533f92157deSopenharmony_ciNOTE: Assertions from multiple threads are currently not supported on Windows. 1534f92157deSopenharmony_ci 1535f92157deSopenharmony_ciFor technical reasons, there are some caveats: 1536f92157deSopenharmony_ci 1537f92157deSopenharmony_ci1. You cannot stream a failure message to either macro. 1538f92157deSopenharmony_ci 1539f92157deSopenharmony_ci2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference 1540f92157deSopenharmony_ci local non-static variables or non-static members of `this` object. 1541f92157deSopenharmony_ci 1542f92157deSopenharmony_ci3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a 1543f92157deSopenharmony_ci value. 1544f92157deSopenharmony_ci 1545f92157deSopenharmony_ci## Registering tests programmatically 1546f92157deSopenharmony_ci 1547f92157deSopenharmony_ciThe `TEST` macros handle the vast majority of all use cases, but there are few 1548f92157deSopenharmony_ciwhere runtime registration logic is required. For those cases, the framework 1549f92157deSopenharmony_ciprovides the `::testing::RegisterTest` that allows callers to register arbitrary 1550f92157deSopenharmony_citests dynamically. 1551f92157deSopenharmony_ci 1552f92157deSopenharmony_ciThis is an advanced API only to be used when the `TEST` macros are insufficient. 1553f92157deSopenharmony_ciThe macros should be preferred when possible, as they avoid most of the 1554f92157deSopenharmony_cicomplexity of calling this function. 1555f92157deSopenharmony_ci 1556f92157deSopenharmony_ciIt provides the following signature: 1557f92157deSopenharmony_ci 1558f92157deSopenharmony_ci```c++ 1559f92157deSopenharmony_citemplate <typename Factory> 1560f92157deSopenharmony_ciTestInfo* RegisterTest(const char* test_suite_name, const char* test_name, 1561f92157deSopenharmony_ci const char* type_param, const char* value_param, 1562f92157deSopenharmony_ci const char* file, int line, Factory factory); 1563f92157deSopenharmony_ci``` 1564f92157deSopenharmony_ci 1565f92157deSopenharmony_ciThe `factory` argument is a factory callable (move-constructible) object or 1566f92157deSopenharmony_cifunction pointer that creates a new instance of the Test object. It handles 1567f92157deSopenharmony_ciownership to the caller. The signature of the callable is `Fixture*()`, where 1568f92157deSopenharmony_ci`Fixture` is the test fixture class for the test. All tests registered with the 1569f92157deSopenharmony_cisame `test_suite_name` must return the same fixture type. This is checked at 1570f92157deSopenharmony_ciruntime. 1571f92157deSopenharmony_ci 1572f92157deSopenharmony_ciThe framework will infer the fixture class from the factory and will call the 1573f92157deSopenharmony_ci`SetUpTestSuite` and `TearDownTestSuite` for it. 1574f92157deSopenharmony_ci 1575f92157deSopenharmony_ciMust be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is 1576f92157deSopenharmony_ciundefined. 1577f92157deSopenharmony_ci 1578f92157deSopenharmony_ciUse case example: 1579f92157deSopenharmony_ci 1580f92157deSopenharmony_ci```c++ 1581f92157deSopenharmony_ciclass MyFixture : public testing::Test { 1582f92157deSopenharmony_ci public: 1583f92157deSopenharmony_ci // All of these optional, just like in regular macro usage. 1584f92157deSopenharmony_ci static void SetUpTestSuite() { ... } 1585f92157deSopenharmony_ci static void TearDownTestSuite() { ... } 1586f92157deSopenharmony_ci void SetUp() override { ... } 1587f92157deSopenharmony_ci void TearDown() override { ... } 1588f92157deSopenharmony_ci}; 1589f92157deSopenharmony_ci 1590f92157deSopenharmony_ciclass MyTest : public MyFixture { 1591f92157deSopenharmony_ci public: 1592f92157deSopenharmony_ci explicit MyTest(int data) : data_(data) {} 1593f92157deSopenharmony_ci void TestBody() override { ... } 1594f92157deSopenharmony_ci 1595f92157deSopenharmony_ci private: 1596f92157deSopenharmony_ci int data_; 1597f92157deSopenharmony_ci}; 1598f92157deSopenharmony_ci 1599f92157deSopenharmony_civoid RegisterMyTests(const std::vector<int>& values) { 1600f92157deSopenharmony_ci for (int v : values) { 1601f92157deSopenharmony_ci testing::RegisterTest( 1602f92157deSopenharmony_ci "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, 1603f92157deSopenharmony_ci std::to_string(v).c_str(), 1604f92157deSopenharmony_ci __FILE__, __LINE__, 1605f92157deSopenharmony_ci // Important to use the fixture type as the return type here. 1606f92157deSopenharmony_ci [=]() -> MyFixture* { return new MyTest(v); }); 1607f92157deSopenharmony_ci } 1608f92157deSopenharmony_ci} 1609f92157deSopenharmony_ci... 1610f92157deSopenharmony_ciint main(int argc, char** argv) { 1611f92157deSopenharmony_ci testing::InitGoogleTest(&argc, argv); 1612f92157deSopenharmony_ci std::vector<int> values_to_test = LoadValuesFromConfig(); 1613f92157deSopenharmony_ci RegisterMyTests(values_to_test); 1614f92157deSopenharmony_ci ... 1615f92157deSopenharmony_ci return RUN_ALL_TESTS(); 1616f92157deSopenharmony_ci} 1617f92157deSopenharmony_ci``` 1618f92157deSopenharmony_ci 1619f92157deSopenharmony_ci## Getting the Current Test's Name 1620f92157deSopenharmony_ci 1621f92157deSopenharmony_ciSometimes a function may need to know the name of the currently running test. 1622f92157deSopenharmony_ciFor example, you may be using the `SetUp()` method of your test fixture to set 1623f92157deSopenharmony_cithe golden file name based on which test is running. The 1624f92157deSopenharmony_ci[`TestInfo`](reference/testing.md#TestInfo) class has this information. 1625f92157deSopenharmony_ci 1626f92157deSopenharmony_ciTo obtain a `TestInfo` object for the currently running test, call 1627f92157deSopenharmony_ci`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) 1628f92157deSopenharmony_cisingleton object: 1629f92157deSopenharmony_ci 1630f92157deSopenharmony_ci```c++ 1631f92157deSopenharmony_ci // Gets information about the currently running test. 1632f92157deSopenharmony_ci // Do NOT delete the returned object - it's managed by the UnitTest class. 1633f92157deSopenharmony_ci const testing::TestInfo* const test_info = 1634f92157deSopenharmony_ci testing::UnitTest::GetInstance()->current_test_info(); 1635f92157deSopenharmony_ci 1636f92157deSopenharmony_ci printf("We are in test %s of test suite %s.\n", 1637f92157deSopenharmony_ci test_info->name(), 1638f92157deSopenharmony_ci test_info->test_suite_name()); 1639f92157deSopenharmony_ci``` 1640f92157deSopenharmony_ci 1641f92157deSopenharmony_ci`current_test_info()` returns a null pointer if no test is running. In 1642f92157deSopenharmony_ciparticular, you cannot find the test suite name in `SetUpTestSuite()`, 1643f92157deSopenharmony_ci`TearDownTestSuite()` (where you know the test suite name implicitly), or 1644f92157deSopenharmony_cifunctions called from them. 1645f92157deSopenharmony_ci 1646f92157deSopenharmony_ci## Extending googletest by Handling Test Events 1647f92157deSopenharmony_ci 1648f92157deSopenharmony_cigoogletest provides an **event listener API** to let you receive notifications 1649f92157deSopenharmony_ciabout the progress of a test program and test failures. The events you can 1650f92157deSopenharmony_cilisten to include the start and end of the test program, a test suite, or a test 1651f92157deSopenharmony_cimethod, among others. You may use this API to augment or replace the standard 1652f92157deSopenharmony_ciconsole output, replace the XML output, or provide a completely different form 1653f92157deSopenharmony_ciof output, such as a GUI or a database. You can also use test events as 1654f92157deSopenharmony_cicheckpoints to implement a resource leak checker, for example. 1655f92157deSopenharmony_ci 1656f92157deSopenharmony_ci### Defining Event Listeners 1657f92157deSopenharmony_ci 1658f92157deSopenharmony_ciTo define a event listener, you subclass either 1659f92157deSopenharmony_ci[`testing::TestEventListener`](reference/testing.md#TestEventListener) or 1660f92157deSopenharmony_ci[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) 1661f92157deSopenharmony_ciThe former is an (abstract) interface, where *each pure virtual method can be 1662f92157deSopenharmony_cioverridden to handle a test event* (For example, when a test starts, the 1663f92157deSopenharmony_ci`OnTestStart()` method will be called.). The latter provides an empty 1664f92157deSopenharmony_ciimplementation of all methods in the interface, such that a subclass only needs 1665f92157deSopenharmony_cito override the methods it cares about. 1666f92157deSopenharmony_ci 1667f92157deSopenharmony_ciWhen an event is fired, its context is passed to the handler function as an 1668f92157deSopenharmony_ciargument. The following argument types are used: 1669f92157deSopenharmony_ci 1670f92157deSopenharmony_ci* UnitTest reflects the state of the entire test program, 1671f92157deSopenharmony_ci* TestSuite has information about a test suite, which can contain one or more 1672f92157deSopenharmony_ci tests, 1673f92157deSopenharmony_ci* TestInfo contains the state of a test, and 1674f92157deSopenharmony_ci* TestPartResult represents the result of a test assertion. 1675f92157deSopenharmony_ci 1676f92157deSopenharmony_ciAn event handler function can examine the argument it receives to find out 1677f92157deSopenharmony_ciinteresting information about the event and the test program's state. 1678f92157deSopenharmony_ci 1679f92157deSopenharmony_ciHere's an example: 1680f92157deSopenharmony_ci 1681f92157deSopenharmony_ci```c++ 1682f92157deSopenharmony_ci class MinimalistPrinter : public testing::EmptyTestEventListener { 1683f92157deSopenharmony_ci // Called before a test starts. 1684f92157deSopenharmony_ci void OnTestStart(const testing::TestInfo& test_info) override { 1685f92157deSopenharmony_ci printf("*** Test %s.%s starting.\n", 1686f92157deSopenharmony_ci test_info.test_suite_name(), test_info.name()); 1687f92157deSopenharmony_ci } 1688f92157deSopenharmony_ci 1689f92157deSopenharmony_ci // Called after a failed assertion or a SUCCESS(). 1690f92157deSopenharmony_ci void OnTestPartResult(const testing::TestPartResult& test_part_result) override { 1691f92157deSopenharmony_ci printf("%s in %s:%d\n%s\n", 1692f92157deSopenharmony_ci test_part_result.failed() ? "*** Failure" : "Success", 1693f92157deSopenharmony_ci test_part_result.file_name(), 1694f92157deSopenharmony_ci test_part_result.line_number(), 1695f92157deSopenharmony_ci test_part_result.summary()); 1696f92157deSopenharmony_ci } 1697f92157deSopenharmony_ci 1698f92157deSopenharmony_ci // Called after a test ends. 1699f92157deSopenharmony_ci void OnTestEnd(const testing::TestInfo& test_info) override { 1700f92157deSopenharmony_ci printf("*** Test %s.%s ending.\n", 1701f92157deSopenharmony_ci test_info.test_suite_name(), test_info.name()); 1702f92157deSopenharmony_ci } 1703f92157deSopenharmony_ci }; 1704f92157deSopenharmony_ci``` 1705f92157deSopenharmony_ci 1706f92157deSopenharmony_ci### Using Event Listeners 1707f92157deSopenharmony_ci 1708f92157deSopenharmony_ciTo use the event listener you have defined, add an instance of it to the 1709f92157deSopenharmony_cigoogletest event listener list (represented by class 1710f92157deSopenharmony_ci[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" 1711f92157deSopenharmony_ciat the end of the name) in your `main()` function, before calling 1712f92157deSopenharmony_ci`RUN_ALL_TESTS()`: 1713f92157deSopenharmony_ci 1714f92157deSopenharmony_ci```c++ 1715f92157deSopenharmony_ciint main(int argc, char** argv) { 1716f92157deSopenharmony_ci testing::InitGoogleTest(&argc, argv); 1717f92157deSopenharmony_ci // Gets hold of the event listener list. 1718f92157deSopenharmony_ci testing::TestEventListeners& listeners = 1719f92157deSopenharmony_ci testing::UnitTest::GetInstance()->listeners(); 1720f92157deSopenharmony_ci // Adds a listener to the end. googletest takes the ownership. 1721f92157deSopenharmony_ci listeners.Append(new MinimalistPrinter); 1722f92157deSopenharmony_ci return RUN_ALL_TESTS(); 1723f92157deSopenharmony_ci} 1724f92157deSopenharmony_ci``` 1725f92157deSopenharmony_ci 1726f92157deSopenharmony_ciThere's only one problem: the default test result printer is still in effect, so 1727f92157deSopenharmony_ciits output will mingle with the output from your minimalist printer. To suppress 1728f92157deSopenharmony_cithe default printer, just release it from the event listener list and delete it. 1729f92157deSopenharmony_ciYou can do so by adding one line: 1730f92157deSopenharmony_ci 1731f92157deSopenharmony_ci```c++ 1732f92157deSopenharmony_ci ... 1733f92157deSopenharmony_ci delete listeners.Release(listeners.default_result_printer()); 1734f92157deSopenharmony_ci listeners.Append(new MinimalistPrinter); 1735f92157deSopenharmony_ci return RUN_ALL_TESTS(); 1736f92157deSopenharmony_ci``` 1737f92157deSopenharmony_ci 1738f92157deSopenharmony_ciNow, sit back and enjoy a completely different output from your tests. For more 1739f92157deSopenharmony_cidetails, see [sample9_unittest.cc]. 1740f92157deSopenharmony_ci 1741f92157deSopenharmony_ci[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" 1742f92157deSopenharmony_ci 1743f92157deSopenharmony_ciYou may append more than one listener to the list. When an `On*Start()` or 1744f92157deSopenharmony_ci`OnTestPartResult()` event is fired, the listeners will receive it in the order 1745f92157deSopenharmony_cithey appear in the list (since new listeners are added to the end of the list, 1746f92157deSopenharmony_cithe default text printer and the default XML generator will receive the event 1747f92157deSopenharmony_cifirst). An `On*End()` event will be received by the listeners in the *reverse* 1748f92157deSopenharmony_ciorder. This allows output by listeners added later to be framed by output from 1749f92157deSopenharmony_cilisteners added earlier. 1750f92157deSopenharmony_ci 1751f92157deSopenharmony_ci### Generating Failures in Listeners 1752f92157deSopenharmony_ci 1753f92157deSopenharmony_ciYou may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) 1754f92157deSopenharmony_ciwhen processing an event. There are some restrictions: 1755f92157deSopenharmony_ci 1756f92157deSopenharmony_ci1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will 1757f92157deSopenharmony_ci cause `OnTestPartResult()` to be called recursively). 1758f92157deSopenharmony_ci2. A listener that handles `OnTestPartResult()` is not allowed to generate any 1759f92157deSopenharmony_ci failure. 1760f92157deSopenharmony_ci 1761f92157deSopenharmony_ciWhen you add listeners to the listener list, you should put listeners that 1762f92157deSopenharmony_cihandle `OnTestPartResult()` *before* listeners that can generate failures. This 1763f92157deSopenharmony_ciensures that failures generated by the latter are attributed to the right test 1764f92157deSopenharmony_ciby the former. 1765f92157deSopenharmony_ci 1766f92157deSopenharmony_ciSee [sample10_unittest.cc] for an example of a failure-raising listener. 1767f92157deSopenharmony_ci 1768f92157deSopenharmony_ci[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" 1769f92157deSopenharmony_ci 1770f92157deSopenharmony_ci## Running Test Programs: Advanced Options 1771f92157deSopenharmony_ci 1772f92157deSopenharmony_cigoogletest test programs are ordinary executables. Once built, you can run them 1773f92157deSopenharmony_cidirectly and affect their behavior via the following environment variables 1774f92157deSopenharmony_ciand/or command line flags. For the flags to work, your programs must call 1775f92157deSopenharmony_ci`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. 1776f92157deSopenharmony_ci 1777f92157deSopenharmony_ciTo see a list of supported flags and their usage, please run your test program 1778f92157deSopenharmony_ciwith the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. 1779f92157deSopenharmony_ci 1780f92157deSopenharmony_ciIf an option is specified both by an environment variable and by a flag, the 1781f92157deSopenharmony_cilatter takes precedence. 1782f92157deSopenharmony_ci 1783f92157deSopenharmony_ci### Selecting Tests 1784f92157deSopenharmony_ci 1785f92157deSopenharmony_ci#### Listing Test Names 1786f92157deSopenharmony_ci 1787f92157deSopenharmony_ciSometimes it is necessary to list the available tests in a program before 1788f92157deSopenharmony_cirunning them so that a filter may be applied if needed. Including the flag 1789f92157deSopenharmony_ci`--gtest_list_tests` overrides all other flags and lists tests in the following 1790f92157deSopenharmony_ciformat: 1791f92157deSopenharmony_ci 1792f92157deSopenharmony_ci```none 1793f92157deSopenharmony_ciTestSuite1. 1794f92157deSopenharmony_ci TestName1 1795f92157deSopenharmony_ci TestName2 1796f92157deSopenharmony_ciTestSuite2. 1797f92157deSopenharmony_ci TestName 1798f92157deSopenharmony_ci``` 1799f92157deSopenharmony_ci 1800f92157deSopenharmony_ciNone of the tests listed are actually run if the flag is provided. There is no 1801f92157deSopenharmony_cicorresponding environment variable for this flag. 1802f92157deSopenharmony_ci 1803f92157deSopenharmony_ci#### Running a Subset of the Tests 1804f92157deSopenharmony_ci 1805f92157deSopenharmony_ciBy default, a googletest program runs all tests the user has defined. Sometimes, 1806f92157deSopenharmony_ciyou want to run only a subset of the tests (e.g. for debugging or quickly 1807f92157deSopenharmony_civerifying a change). If you set the `GTEST_FILTER` environment variable or the 1808f92157deSopenharmony_ci`--gtest_filter` flag to a filter string, googletest will only run the tests 1809f92157deSopenharmony_ciwhose full names (in the form of `TestSuiteName.TestName`) match the filter. 1810f92157deSopenharmony_ci 1811f92157deSopenharmony_ciThe format of a filter is a '`:`'-separated list of wildcard patterns (called 1812f92157deSopenharmony_cithe *positive patterns*) optionally followed by a '`-`' and another 1813f92157deSopenharmony_ci'`:`'-separated pattern list (called the *negative patterns*). A test matches 1814f92157deSopenharmony_cithe filter if and only if it matches any of the positive patterns but does not 1815f92157deSopenharmony_cimatch any of the negative patterns. 1816f92157deSopenharmony_ci 1817f92157deSopenharmony_ciA pattern may contain `'*'` (matches any string) or `'?'` (matches any single 1818f92157deSopenharmony_cicharacter). For convenience, the filter `'*-NegativePatterns'` can be also 1819f92157deSopenharmony_ciwritten as `'-NegativePatterns'`. 1820f92157deSopenharmony_ci 1821f92157deSopenharmony_ciFor example: 1822f92157deSopenharmony_ci 1823f92157deSopenharmony_ci* `./foo_test` Has no flag, and thus runs all its tests. 1824f92157deSopenharmony_ci* `./foo_test --gtest_filter=*` Also runs everything, due to the single 1825f92157deSopenharmony_ci match-everything `*` value. 1826f92157deSopenharmony_ci* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite 1827f92157deSopenharmony_ci `FooTest` . 1828f92157deSopenharmony_ci* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full 1829f92157deSopenharmony_ci name contains either `"Null"` or `"Constructor"` . 1830f92157deSopenharmony_ci* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. 1831f92157deSopenharmony_ci* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test 1832f92157deSopenharmony_ci suite `FooTest` except `FooTest.Bar`. 1833f92157deSopenharmony_ci* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs 1834f92157deSopenharmony_ci everything in test suite `FooTest` except `FooTest.Bar` and everything in 1835f92157deSopenharmony_ci test suite `BarTest` except `BarTest.Foo`. 1836f92157deSopenharmony_ci 1837f92157deSopenharmony_ci#### Stop test execution upon first failure 1838f92157deSopenharmony_ci 1839f92157deSopenharmony_ciBy default, a googletest program runs all tests the user has defined. In some 1840f92157deSopenharmony_cicases (e.g. iterative test development & execution) it may be desirable stop 1841f92157deSopenharmony_citest execution upon first failure (trading improved latency for completeness). 1842f92157deSopenharmony_ciIf `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, 1843f92157deSopenharmony_cithe test runner will stop execution as soon as the first test failure is found. 1844f92157deSopenharmony_ci 1845f92157deSopenharmony_ci#### Temporarily Disabling Tests 1846f92157deSopenharmony_ci 1847f92157deSopenharmony_ciIf you have a broken test that you cannot fix right away, you can add the 1848f92157deSopenharmony_ci`DISABLED_` prefix to its name. This will exclude it from execution. This is 1849f92157deSopenharmony_cibetter than commenting out the code or using `#if 0`, as disabled tests are 1850f92157deSopenharmony_cistill compiled (and thus won't rot). 1851f92157deSopenharmony_ci 1852f92157deSopenharmony_ciIf you need to disable all tests in a test suite, you can either add `DISABLED_` 1853f92157deSopenharmony_cito the front of the name of each test, or alternatively add it to the front of 1854f92157deSopenharmony_cithe test suite name. 1855f92157deSopenharmony_ci 1856f92157deSopenharmony_ciFor example, the following tests won't be run by googletest, even though they 1857f92157deSopenharmony_ciwill still be compiled: 1858f92157deSopenharmony_ci 1859f92157deSopenharmony_ci```c++ 1860f92157deSopenharmony_ci// Tests that Foo does Abc. 1861f92157deSopenharmony_ciTEST(FooTest, DISABLED_DoesAbc) { ... } 1862f92157deSopenharmony_ci 1863f92157deSopenharmony_ciclass DISABLED_BarTest : public testing::Test { ... }; 1864f92157deSopenharmony_ci 1865f92157deSopenharmony_ci// Tests that Bar does Xyz. 1866f92157deSopenharmony_ciTEST_F(DISABLED_BarTest, DoesXyz) { ... } 1867f92157deSopenharmony_ci``` 1868f92157deSopenharmony_ci 1869f92157deSopenharmony_ci{: .callout .note} 1870f92157deSopenharmony_ciNOTE: This feature should only be used for temporary pain-relief. You still have 1871f92157deSopenharmony_cito fix the disabled tests at a later date. As a reminder, googletest will print 1872f92157deSopenharmony_cia banner warning you if a test program contains any disabled tests. 1873f92157deSopenharmony_ci 1874f92157deSopenharmony_ci{: .callout .tip} 1875f92157deSopenharmony_ciTIP: You can easily count the number of disabled tests you have using 1876f92157deSopenharmony_ci`grep`. This number can be used as a metric for 1877f92157deSopenharmony_ciimproving your test quality. 1878f92157deSopenharmony_ci 1879f92157deSopenharmony_ci#### Temporarily Enabling Disabled Tests 1880f92157deSopenharmony_ci 1881f92157deSopenharmony_ciTo include disabled tests in test execution, just invoke the test program with 1882f92157deSopenharmony_cithe `--gtest_also_run_disabled_tests` flag or set the 1883f92157deSopenharmony_ci`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. 1884f92157deSopenharmony_ciYou can combine this with the `--gtest_filter` flag to further select which 1885f92157deSopenharmony_cidisabled tests to run. 1886f92157deSopenharmony_ci 1887f92157deSopenharmony_ci### Repeating the Tests 1888f92157deSopenharmony_ci 1889f92157deSopenharmony_ciOnce in a while you'll run into a test whose result is hit-or-miss. Perhaps it 1890f92157deSopenharmony_ciwill fail only 1% of the time, making it rather hard to reproduce the bug under 1891f92157deSopenharmony_cia debugger. This can be a major source of frustration. 1892f92157deSopenharmony_ci 1893f92157deSopenharmony_ciThe `--gtest_repeat` flag allows you to repeat all (or selected) test methods in 1894f92157deSopenharmony_cia program many times. Hopefully, a flaky test will eventually fail and give you 1895f92157deSopenharmony_cia chance to debug. Here's how to use it: 1896f92157deSopenharmony_ci 1897f92157deSopenharmony_ci```none 1898f92157deSopenharmony_ci$ foo_test --gtest_repeat=1000 1899f92157deSopenharmony_ciRepeat foo_test 1000 times and don't stop at failures. 1900f92157deSopenharmony_ci 1901f92157deSopenharmony_ci$ foo_test --gtest_repeat=-1 1902f92157deSopenharmony_ciA negative count means repeating forever. 1903f92157deSopenharmony_ci 1904f92157deSopenharmony_ci$ foo_test --gtest_repeat=1000 --gtest_break_on_failure 1905f92157deSopenharmony_ciRepeat foo_test 1000 times, stopping at the first failure. This 1906f92157deSopenharmony_ciis especially useful when running under a debugger: when the test 1907f92157deSopenharmony_cifails, it will drop into the debugger and you can then inspect 1908f92157deSopenharmony_civariables and stacks. 1909f92157deSopenharmony_ci 1910f92157deSopenharmony_ci$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* 1911f92157deSopenharmony_ciRepeat the tests whose name matches the filter 1000 times. 1912f92157deSopenharmony_ci``` 1913f92157deSopenharmony_ci 1914f92157deSopenharmony_ciIf your test program contains 1915f92157deSopenharmony_ci[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be 1916f92157deSopenharmony_cirepeated in each iteration as well, as the flakiness may be in it. To avoid 1917f92157deSopenharmony_cirepeating global set-up/tear-down, specify 1918f92157deSopenharmony_ci`--gtest_recreate_environments_when_repeating=false`{.nowrap}. 1919f92157deSopenharmony_ci 1920f92157deSopenharmony_ciYou can also specify the repeat count by setting the `GTEST_REPEAT` environment 1921f92157deSopenharmony_civariable. 1922f92157deSopenharmony_ci 1923f92157deSopenharmony_ci### Shuffling the Tests 1924f92157deSopenharmony_ci 1925f92157deSopenharmony_ciYou can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` 1926f92157deSopenharmony_cienvironment variable to `1`) to run the tests in a program in a random order. 1927f92157deSopenharmony_ciThis helps to reveal bad dependencies between tests. 1928f92157deSopenharmony_ci 1929f92157deSopenharmony_ciBy default, googletest uses a random seed calculated from the current time. 1930f92157deSopenharmony_ciTherefore you'll get a different order every time. The console output includes 1931f92157deSopenharmony_cithe random seed value, such that you can reproduce an order-related test failure 1932f92157deSopenharmony_cilater. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` 1933f92157deSopenharmony_ciflag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an 1934f92157deSopenharmony_ciinteger in the range [0, 99999]. The seed value 0 is special: it tells 1935f92157deSopenharmony_cigoogletest to do the default behavior of calculating the seed from the current 1936f92157deSopenharmony_citime. 1937f92157deSopenharmony_ci 1938f92157deSopenharmony_ciIf you combine this with `--gtest_repeat=N`, googletest will pick a different 1939f92157deSopenharmony_cirandom seed and re-shuffle the tests in each iteration. 1940f92157deSopenharmony_ci 1941f92157deSopenharmony_ci### Distributing Test Functions to Multiple Machines 1942f92157deSopenharmony_ci 1943f92157deSopenharmony_ciIf you have more than one machine you can use to run a test program, you might 1944f92157deSopenharmony_ciwant to run the test functions in parallel and get the result faster. We call 1945f92157deSopenharmony_cithis technique *sharding*, where each machine is called a *shard*. 1946f92157deSopenharmony_ci 1947f92157deSopenharmony_ciGoogleTest is compatible with test sharding. To take advantage of this feature, 1948f92157deSopenharmony_ciyour test runner (not part of GoogleTest) needs to do the following: 1949f92157deSopenharmony_ci 1950f92157deSopenharmony_ci1. Allocate a number of machines (shards) to run the tests. 1951f92157deSopenharmony_ci1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total 1952f92157deSopenharmony_ci number of shards. It must be the same for all shards. 1953f92157deSopenharmony_ci1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index 1954f92157deSopenharmony_ci of the shard. Different shards must be assigned different indices, which 1955f92157deSopenharmony_ci must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. 1956f92157deSopenharmony_ci1. Run the same test program on all shards. When GoogleTest sees the above two 1957f92157deSopenharmony_ci environment variables, it will select a subset of the test functions to run. 1958f92157deSopenharmony_ci Across all shards, each test function in the program will be run exactly 1959f92157deSopenharmony_ci once. 1960f92157deSopenharmony_ci1. Wait for all shards to finish, then collect and report the results. 1961f92157deSopenharmony_ci 1962f92157deSopenharmony_ciYour project may have tests that were written without GoogleTest and thus don't 1963f92157deSopenharmony_ciunderstand this protocol. In order for your test runner to figure out which test 1964f92157deSopenharmony_cisupports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` 1965f92157deSopenharmony_cito a non-existent file path. If a test program supports sharding, it will create 1966f92157deSopenharmony_cithis file to acknowledge that fact; otherwise it will not create it. The actual 1967f92157deSopenharmony_cicontents of the file are not important at this time, although we may put some 1968f92157deSopenharmony_ciuseful information in it in the future. 1969f92157deSopenharmony_ci 1970f92157deSopenharmony_ciHere's an example to make it clear. Suppose you have a test program `foo_test` 1971f92157deSopenharmony_cithat contains the following 5 test functions: 1972f92157deSopenharmony_ci 1973f92157deSopenharmony_ci``` 1974f92157deSopenharmony_ciTEST(A, V) 1975f92157deSopenharmony_ciTEST(A, W) 1976f92157deSopenharmony_ciTEST(B, X) 1977f92157deSopenharmony_ciTEST(B, Y) 1978f92157deSopenharmony_ciTEST(B, Z) 1979f92157deSopenharmony_ci``` 1980f92157deSopenharmony_ci 1981f92157deSopenharmony_ciSuppose you have 3 machines at your disposal. To run the test functions in 1982f92157deSopenharmony_ciparallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set 1983f92157deSopenharmony_ci`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would 1984f92157deSopenharmony_cirun the same `foo_test` on each machine. 1985f92157deSopenharmony_ci 1986f92157deSopenharmony_ciGoogleTest reserves the right to change how the work is distributed across the 1987f92157deSopenharmony_cishards, but here's one possible scenario: 1988f92157deSopenharmony_ci 1989f92157deSopenharmony_ci* Machine #0 runs `A.V` and `B.X`. 1990f92157deSopenharmony_ci* Machine #1 runs `A.W` and `B.Y`. 1991f92157deSopenharmony_ci* Machine #2 runs `B.Z`. 1992f92157deSopenharmony_ci 1993f92157deSopenharmony_ci### Controlling Test Output 1994f92157deSopenharmony_ci 1995f92157deSopenharmony_ci#### Colored Terminal Output 1996f92157deSopenharmony_ci 1997f92157deSopenharmony_cigoogletest can use colors in its terminal output to make it easier to spot the 1998f92157deSopenharmony_ciimportant information: 1999f92157deSopenharmony_ci 2000f92157deSopenharmony_ci<pre>... 2001f92157deSopenharmony_ci<font color="green">[----------]</font> 1 test from FooTest 2002f92157deSopenharmony_ci<font color="green">[ RUN ]</font> FooTest.DoesAbc 2003f92157deSopenharmony_ci<font color="green">[ OK ]</font> FooTest.DoesAbc 2004f92157deSopenharmony_ci<font color="green">[----------]</font> 2 tests from BarTest 2005f92157deSopenharmony_ci<font color="green">[ RUN ]</font> BarTest.HasXyzProperty 2006f92157deSopenharmony_ci<font color="green">[ OK ]</font> BarTest.HasXyzProperty 2007f92157deSopenharmony_ci<font color="green">[ RUN ]</font> BarTest.ReturnsTrueOnSuccess 2008f92157deSopenharmony_ci... some error messages ... 2009f92157deSopenharmony_ci<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess 2010f92157deSopenharmony_ci... 2011f92157deSopenharmony_ci<font color="green">[==========]</font> 30 tests from 14 test suites ran. 2012f92157deSopenharmony_ci<font color="green">[ PASSED ]</font> 28 tests. 2013f92157deSopenharmony_ci<font color="red">[ FAILED ]</font> 2 tests, listed below: 2014f92157deSopenharmony_ci<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess 2015f92157deSopenharmony_ci<font color="red">[ FAILED ]</font> AnotherTest.DoesXyz 2016f92157deSopenharmony_ci 2017f92157deSopenharmony_ci 2 FAILED TESTS 2018f92157deSopenharmony_ci</pre> 2019f92157deSopenharmony_ci 2020f92157deSopenharmony_ciYou can set the `GTEST_COLOR` environment variable or the `--gtest_color` 2021f92157deSopenharmony_cicommand line flag to `yes`, `no`, or `auto` (the default) to enable colors, 2022f92157deSopenharmony_cidisable colors, or let googletest decide. When the value is `auto`, googletest 2023f92157deSopenharmony_ciwill use colors if and only if the output goes to a terminal and (on non-Windows 2024f92157deSopenharmony_ciplatforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. 2025f92157deSopenharmony_ci 2026f92157deSopenharmony_ci#### Suppressing test passes 2027f92157deSopenharmony_ci 2028f92157deSopenharmony_ciBy default, googletest prints 1 line of output for each test, indicating if it 2029f92157deSopenharmony_cipassed or failed. To show only test failures, run the test program with 2030f92157deSopenharmony_ci`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. 2031f92157deSopenharmony_ci 2032f92157deSopenharmony_ci#### Suppressing the Elapsed Time 2033f92157deSopenharmony_ci 2034f92157deSopenharmony_ciBy default, googletest prints the time it takes to run each test. To disable 2035f92157deSopenharmony_cithat, run the test program with the `--gtest_print_time=0` command line flag, or 2036f92157deSopenharmony_ciset the GTEST_PRINT_TIME environment variable to `0`. 2037f92157deSopenharmony_ci 2038f92157deSopenharmony_ci#### Suppressing UTF-8 Text Output 2039f92157deSopenharmony_ci 2040f92157deSopenharmony_ciIn case of assertion failures, googletest prints expected and actual values of 2041f92157deSopenharmony_citype `string` both as hex-encoded strings as well as in readable UTF-8 text if 2042f92157deSopenharmony_cithey contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 2043f92157deSopenharmony_citext because, for example, you don't have an UTF-8 compatible output medium, run 2044f92157deSopenharmony_cithe test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` 2045f92157deSopenharmony_cienvironment variable to `0`. 2046f92157deSopenharmony_ci 2047f92157deSopenharmony_ci#### Generating an XML Report 2048f92157deSopenharmony_ci 2049f92157deSopenharmony_cigoogletest can emit a detailed XML report to a file in addition to its normal 2050f92157deSopenharmony_citextual output. The report contains the duration of each test, and thus can help 2051f92157deSopenharmony_ciyou identify slow tests. 2052f92157deSopenharmony_ci 2053f92157deSopenharmony_ciTo generate the XML report, set the `GTEST_OUTPUT` environment variable or the 2054f92157deSopenharmony_ci`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will 2055f92157deSopenharmony_cicreate the file at the given location. You can also just use the string `"xml"`, 2056f92157deSopenharmony_ciin which case the output can be found in the `test_detail.xml` file in the 2057f92157deSopenharmony_cicurrent directory. 2058f92157deSopenharmony_ci 2059f92157deSopenharmony_ciIf you specify a directory (for example, `"xml:output/directory/"` on Linux or 2060f92157deSopenharmony_ci`"xml:output\directory\"` on Windows), googletest will create the XML file in 2061f92157deSopenharmony_cithat directory, named after the test executable (e.g. `foo_test.xml` for test 2062f92157deSopenharmony_ciprogram `foo_test` or `foo_test.exe`). If the file already exists (perhaps left 2063f92157deSopenharmony_ciover from a previous run), googletest will pick a different name (e.g. 2064f92157deSopenharmony_ci`foo_test_1.xml`) to avoid overwriting it. 2065f92157deSopenharmony_ci 2066f92157deSopenharmony_ciThe report is based on the `junitreport` Ant task. Since that format was 2067f92157deSopenharmony_cioriginally intended for Java, a little interpretation is required to make it 2068f92157deSopenharmony_ciapply to googletest tests, as shown here: 2069f92157deSopenharmony_ci 2070f92157deSopenharmony_ci```xml 2071f92157deSopenharmony_ci<testsuites name="AllTests" ...> 2072f92157deSopenharmony_ci <testsuite name="test_case_name" ...> 2073f92157deSopenharmony_ci <testcase name="test_name" ...> 2074f92157deSopenharmony_ci <failure message="..."/> 2075f92157deSopenharmony_ci <failure message="..."/> 2076f92157deSopenharmony_ci <failure message="..."/> 2077f92157deSopenharmony_ci </testcase> 2078f92157deSopenharmony_ci </testsuite> 2079f92157deSopenharmony_ci</testsuites> 2080f92157deSopenharmony_ci``` 2081f92157deSopenharmony_ci 2082f92157deSopenharmony_ci* The root `<testsuites>` element corresponds to the entire test program. 2083f92157deSopenharmony_ci* `<testsuite>` elements correspond to googletest test suites. 2084f92157deSopenharmony_ci* `<testcase>` elements correspond to googletest test functions. 2085f92157deSopenharmony_ci 2086f92157deSopenharmony_ciFor instance, the following program 2087f92157deSopenharmony_ci 2088f92157deSopenharmony_ci```c++ 2089f92157deSopenharmony_ciTEST(MathTest, Addition) { ... } 2090f92157deSopenharmony_ciTEST(MathTest, Subtraction) { ... } 2091f92157deSopenharmony_ciTEST(LogicTest, NonContradiction) { ... } 2092f92157deSopenharmony_ci``` 2093f92157deSopenharmony_ci 2094f92157deSopenharmony_cicould generate this report: 2095f92157deSopenharmony_ci 2096f92157deSopenharmony_ci```xml 2097f92157deSopenharmony_ci<?xml version="1.0" encoding="UTF-8"?> 2098f92157deSopenharmony_ci<testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests"> 2099f92157deSopenharmony_ci <testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015"> 2100f92157deSopenharmony_ci <testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname=""> 2101f92157deSopenharmony_ci <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type="">...</failure> 2102f92157deSopenharmony_ci <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type="">...</failure> 2103f92157deSopenharmony_ci </testcase> 2104f92157deSopenharmony_ci <testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname=""> 2105f92157deSopenharmony_ci </testcase> 2106f92157deSopenharmony_ci </testsuite> 2107f92157deSopenharmony_ci <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005"> 2108f92157deSopenharmony_ci <testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname=""> 2109f92157deSopenharmony_ci </testcase> 2110f92157deSopenharmony_ci </testsuite> 2111f92157deSopenharmony_ci</testsuites> 2112f92157deSopenharmony_ci``` 2113f92157deSopenharmony_ci 2114f92157deSopenharmony_ciThings to note: 2115f92157deSopenharmony_ci 2116f92157deSopenharmony_ci* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how 2117f92157deSopenharmony_ci many test functions the googletest program or test suite contains, while the 2118f92157deSopenharmony_ci `failures` attribute tells how many of them failed. 2119f92157deSopenharmony_ci 2120f92157deSopenharmony_ci* The `time` attribute expresses the duration of the test, test suite, or 2121f92157deSopenharmony_ci entire test program in seconds. 2122f92157deSopenharmony_ci 2123f92157deSopenharmony_ci* The `timestamp` attribute records the local date and time of the test 2124f92157deSopenharmony_ci execution. 2125f92157deSopenharmony_ci 2126f92157deSopenharmony_ci* The `file` and `line` attributes record the source file location, where the 2127f92157deSopenharmony_ci test was defined. 2128f92157deSopenharmony_ci 2129f92157deSopenharmony_ci* Each `<failure>` element corresponds to a single failed googletest 2130f92157deSopenharmony_ci assertion. 2131f92157deSopenharmony_ci 2132f92157deSopenharmony_ci#### Generating a JSON Report 2133f92157deSopenharmony_ci 2134f92157deSopenharmony_cigoogletest can also emit a JSON report as an alternative format to XML. To 2135f92157deSopenharmony_cigenerate the JSON report, set the `GTEST_OUTPUT` environment variable or the 2136f92157deSopenharmony_ci`--gtest_output` flag to the string `"json:path_to_output_file"`, which will 2137f92157deSopenharmony_cicreate the file at the given location. You can also just use the string 2138f92157deSopenharmony_ci`"json"`, in which case the output can be found in the `test_detail.json` file 2139f92157deSopenharmony_ciin the current directory. 2140f92157deSopenharmony_ci 2141f92157deSopenharmony_ciThe report format conforms to the following JSON Schema: 2142f92157deSopenharmony_ci 2143f92157deSopenharmony_ci```json 2144f92157deSopenharmony_ci{ 2145f92157deSopenharmony_ci "$schema": "http://json-schema.org/schema#", 2146f92157deSopenharmony_ci "type": "object", 2147f92157deSopenharmony_ci "definitions": { 2148f92157deSopenharmony_ci "TestCase": { 2149f92157deSopenharmony_ci "type": "object", 2150f92157deSopenharmony_ci "properties": { 2151f92157deSopenharmony_ci "name": { "type": "string" }, 2152f92157deSopenharmony_ci "tests": { "type": "integer" }, 2153f92157deSopenharmony_ci "failures": { "type": "integer" }, 2154f92157deSopenharmony_ci "disabled": { "type": "integer" }, 2155f92157deSopenharmony_ci "time": { "type": "string" }, 2156f92157deSopenharmony_ci "testsuite": { 2157f92157deSopenharmony_ci "type": "array", 2158f92157deSopenharmony_ci "items": { 2159f92157deSopenharmony_ci "$ref": "#/definitions/TestInfo" 2160f92157deSopenharmony_ci } 2161f92157deSopenharmony_ci } 2162f92157deSopenharmony_ci } 2163f92157deSopenharmony_ci }, 2164f92157deSopenharmony_ci "TestInfo": { 2165f92157deSopenharmony_ci "type": "object", 2166f92157deSopenharmony_ci "properties": { 2167f92157deSopenharmony_ci "name": { "type": "string" }, 2168f92157deSopenharmony_ci "file": { "type": "string" }, 2169f92157deSopenharmony_ci "line": { "type": "integer" }, 2170f92157deSopenharmony_ci "status": { 2171f92157deSopenharmony_ci "type": "string", 2172f92157deSopenharmony_ci "enum": ["RUN", "NOTRUN"] 2173f92157deSopenharmony_ci }, 2174f92157deSopenharmony_ci "time": { "type": "string" }, 2175f92157deSopenharmony_ci "classname": { "type": "string" }, 2176f92157deSopenharmony_ci "failures": { 2177f92157deSopenharmony_ci "type": "array", 2178f92157deSopenharmony_ci "items": { 2179f92157deSopenharmony_ci "$ref": "#/definitions/Failure" 2180f92157deSopenharmony_ci } 2181f92157deSopenharmony_ci } 2182f92157deSopenharmony_ci } 2183f92157deSopenharmony_ci }, 2184f92157deSopenharmony_ci "Failure": { 2185f92157deSopenharmony_ci "type": "object", 2186f92157deSopenharmony_ci "properties": { 2187f92157deSopenharmony_ci "failures": { "type": "string" }, 2188f92157deSopenharmony_ci "type": { "type": "string" } 2189f92157deSopenharmony_ci } 2190f92157deSopenharmony_ci } 2191f92157deSopenharmony_ci }, 2192f92157deSopenharmony_ci "properties": { 2193f92157deSopenharmony_ci "tests": { "type": "integer" }, 2194f92157deSopenharmony_ci "failures": { "type": "integer" }, 2195f92157deSopenharmony_ci "disabled": { "type": "integer" }, 2196f92157deSopenharmony_ci "errors": { "type": "integer" }, 2197f92157deSopenharmony_ci "timestamp": { 2198f92157deSopenharmony_ci "type": "string", 2199f92157deSopenharmony_ci "format": "date-time" 2200f92157deSopenharmony_ci }, 2201f92157deSopenharmony_ci "time": { "type": "string" }, 2202f92157deSopenharmony_ci "name": { "type": "string" }, 2203f92157deSopenharmony_ci "testsuites": { 2204f92157deSopenharmony_ci "type": "array", 2205f92157deSopenharmony_ci "items": { 2206f92157deSopenharmony_ci "$ref": "#/definitions/TestCase" 2207f92157deSopenharmony_ci } 2208f92157deSopenharmony_ci } 2209f92157deSopenharmony_ci } 2210f92157deSopenharmony_ci} 2211f92157deSopenharmony_ci``` 2212f92157deSopenharmony_ci 2213f92157deSopenharmony_ciThe report uses the format that conforms to the following Proto3 using the 2214f92157deSopenharmony_ci[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): 2215f92157deSopenharmony_ci 2216f92157deSopenharmony_ci```proto 2217f92157deSopenharmony_cisyntax = "proto3"; 2218f92157deSopenharmony_ci 2219f92157deSopenharmony_cipackage googletest; 2220f92157deSopenharmony_ci 2221f92157deSopenharmony_ciimport "google/protobuf/timestamp.proto"; 2222f92157deSopenharmony_ciimport "google/protobuf/duration.proto"; 2223f92157deSopenharmony_ci 2224f92157deSopenharmony_cimessage UnitTest { 2225f92157deSopenharmony_ci int32 tests = 1; 2226f92157deSopenharmony_ci int32 failures = 2; 2227f92157deSopenharmony_ci int32 disabled = 3; 2228f92157deSopenharmony_ci int32 errors = 4; 2229f92157deSopenharmony_ci google.protobuf.Timestamp timestamp = 5; 2230f92157deSopenharmony_ci google.protobuf.Duration time = 6; 2231f92157deSopenharmony_ci string name = 7; 2232f92157deSopenharmony_ci repeated TestCase testsuites = 8; 2233f92157deSopenharmony_ci} 2234f92157deSopenharmony_ci 2235f92157deSopenharmony_cimessage TestCase { 2236f92157deSopenharmony_ci string name = 1; 2237f92157deSopenharmony_ci int32 tests = 2; 2238f92157deSopenharmony_ci int32 failures = 3; 2239f92157deSopenharmony_ci int32 disabled = 4; 2240f92157deSopenharmony_ci int32 errors = 5; 2241f92157deSopenharmony_ci google.protobuf.Duration time = 6; 2242f92157deSopenharmony_ci repeated TestInfo testsuite = 7; 2243f92157deSopenharmony_ci} 2244f92157deSopenharmony_ci 2245f92157deSopenharmony_cimessage TestInfo { 2246f92157deSopenharmony_ci string name = 1; 2247f92157deSopenharmony_ci string file = 6; 2248f92157deSopenharmony_ci int32 line = 7; 2249f92157deSopenharmony_ci enum Status { 2250f92157deSopenharmony_ci RUN = 0; 2251f92157deSopenharmony_ci NOTRUN = 1; 2252f92157deSopenharmony_ci } 2253f92157deSopenharmony_ci Status status = 2; 2254f92157deSopenharmony_ci google.protobuf.Duration time = 3; 2255f92157deSopenharmony_ci string classname = 4; 2256f92157deSopenharmony_ci message Failure { 2257f92157deSopenharmony_ci string failures = 1; 2258f92157deSopenharmony_ci string type = 2; 2259f92157deSopenharmony_ci } 2260f92157deSopenharmony_ci repeated Failure failures = 5; 2261f92157deSopenharmony_ci} 2262f92157deSopenharmony_ci``` 2263f92157deSopenharmony_ci 2264f92157deSopenharmony_ciFor instance, the following program 2265f92157deSopenharmony_ci 2266f92157deSopenharmony_ci```c++ 2267f92157deSopenharmony_ciTEST(MathTest, Addition) { ... } 2268f92157deSopenharmony_ciTEST(MathTest, Subtraction) { ... } 2269f92157deSopenharmony_ciTEST(LogicTest, NonContradiction) { ... } 2270f92157deSopenharmony_ci``` 2271f92157deSopenharmony_ci 2272f92157deSopenharmony_cicould generate this report: 2273f92157deSopenharmony_ci 2274f92157deSopenharmony_ci```json 2275f92157deSopenharmony_ci{ 2276f92157deSopenharmony_ci "tests": 3, 2277f92157deSopenharmony_ci "failures": 1, 2278f92157deSopenharmony_ci "errors": 0, 2279f92157deSopenharmony_ci "time": "0.035s", 2280f92157deSopenharmony_ci "timestamp": "2011-10-31T18:52:42Z", 2281f92157deSopenharmony_ci "name": "AllTests", 2282f92157deSopenharmony_ci "testsuites": [ 2283f92157deSopenharmony_ci { 2284f92157deSopenharmony_ci "name": "MathTest", 2285f92157deSopenharmony_ci "tests": 2, 2286f92157deSopenharmony_ci "failures": 1, 2287f92157deSopenharmony_ci "errors": 0, 2288f92157deSopenharmony_ci "time": "0.015s", 2289f92157deSopenharmony_ci "testsuite": [ 2290f92157deSopenharmony_ci { 2291f92157deSopenharmony_ci "name": "Addition", 2292f92157deSopenharmony_ci "file": "test.cpp", 2293f92157deSopenharmony_ci "line": 1, 2294f92157deSopenharmony_ci "status": "RUN", 2295f92157deSopenharmony_ci "time": "0.007s", 2296f92157deSopenharmony_ci "classname": "", 2297f92157deSopenharmony_ci "failures": [ 2298f92157deSopenharmony_ci { 2299f92157deSopenharmony_ci "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", 2300f92157deSopenharmony_ci "type": "" 2301f92157deSopenharmony_ci }, 2302f92157deSopenharmony_ci { 2303f92157deSopenharmony_ci "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", 2304f92157deSopenharmony_ci "type": "" 2305f92157deSopenharmony_ci } 2306f92157deSopenharmony_ci ] 2307f92157deSopenharmony_ci }, 2308f92157deSopenharmony_ci { 2309f92157deSopenharmony_ci "name": "Subtraction", 2310f92157deSopenharmony_ci "file": "test.cpp", 2311f92157deSopenharmony_ci "line": 2, 2312f92157deSopenharmony_ci "status": "RUN", 2313f92157deSopenharmony_ci "time": "0.005s", 2314f92157deSopenharmony_ci "classname": "" 2315f92157deSopenharmony_ci } 2316f92157deSopenharmony_ci ] 2317f92157deSopenharmony_ci }, 2318f92157deSopenharmony_ci { 2319f92157deSopenharmony_ci "name": "LogicTest", 2320f92157deSopenharmony_ci "tests": 1, 2321f92157deSopenharmony_ci "failures": 0, 2322f92157deSopenharmony_ci "errors": 0, 2323f92157deSopenharmony_ci "time": "0.005s", 2324f92157deSopenharmony_ci "testsuite": [ 2325f92157deSopenharmony_ci { 2326f92157deSopenharmony_ci "name": "NonContradiction", 2327f92157deSopenharmony_ci "file": "test.cpp", 2328f92157deSopenharmony_ci "line": 3, 2329f92157deSopenharmony_ci "status": "RUN", 2330f92157deSopenharmony_ci "time": "0.005s", 2331f92157deSopenharmony_ci "classname": "" 2332f92157deSopenharmony_ci } 2333f92157deSopenharmony_ci ] 2334f92157deSopenharmony_ci } 2335f92157deSopenharmony_ci ] 2336f92157deSopenharmony_ci} 2337f92157deSopenharmony_ci``` 2338f92157deSopenharmony_ci 2339f92157deSopenharmony_ci{: .callout .important} 2340f92157deSopenharmony_ciIMPORTANT: The exact format of the JSON document is subject to change. 2341f92157deSopenharmony_ci 2342f92157deSopenharmony_ci### Controlling How Failures Are Reported 2343f92157deSopenharmony_ci 2344f92157deSopenharmony_ci#### Detecting Test Premature Exit 2345f92157deSopenharmony_ci 2346f92157deSopenharmony_ciGoogle Test implements the _premature-exit-file_ protocol for test runners to 2347f92157deSopenharmony_cicatch any kind of unexpected exits of test programs. Upon start, Google Test 2348f92157deSopenharmony_cicreates the file which will be automatically deleted after all work has been 2349f92157deSopenharmony_cifinished. Then, the test runner can check if this file exists. In case the file 2350f92157deSopenharmony_ciremains undeleted, the inspected test has exited prematurely. 2351f92157deSopenharmony_ci 2352f92157deSopenharmony_ciThis feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment 2353f92157deSopenharmony_civariable has been set. 2354f92157deSopenharmony_ci 2355f92157deSopenharmony_ci#### Turning Assertion Failures into Break-Points 2356f92157deSopenharmony_ci 2357f92157deSopenharmony_ciWhen running test programs under a debugger, it's very convenient if the 2358f92157deSopenharmony_cidebugger can catch an assertion failure and automatically drop into interactive 2359f92157deSopenharmony_cimode. googletest's *break-on-failure* mode supports this behavior. 2360f92157deSopenharmony_ci 2361f92157deSopenharmony_ciTo enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value 2362f92157deSopenharmony_ciother than `0`. Alternatively, you can use the `--gtest_break_on_failure` 2363f92157deSopenharmony_cicommand line flag. 2364f92157deSopenharmony_ci 2365f92157deSopenharmony_ci#### Disabling Catching Test-Thrown Exceptions 2366f92157deSopenharmony_ci 2367f92157deSopenharmony_cigoogletest can be used either with or without exceptions enabled. If a test 2368f92157deSopenharmony_cithrows a C++ exception or (on Windows) a structured exception (SEH), by default 2369f92157deSopenharmony_cigoogletest catches it, reports it as a test failure, and continues with the next 2370f92157deSopenharmony_citest method. This maximizes the coverage of a test run. Also, on Windows an 2371f92157deSopenharmony_ciuncaught exception will cause a pop-up window, so catching the exceptions allows 2372f92157deSopenharmony_ciyou to run the tests automatically. 2373f92157deSopenharmony_ci 2374f92157deSopenharmony_ciWhen debugging the test failures, however, you may instead want the exceptions 2375f92157deSopenharmony_cito be handled by the debugger, such that you can examine the call stack when an 2376f92157deSopenharmony_ciexception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` 2377f92157deSopenharmony_cienvironment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when 2378f92157deSopenharmony_cirunning the tests. 2379f92157deSopenharmony_ci 2380f92157deSopenharmony_ci### Sanitizer Integration 2381f92157deSopenharmony_ci 2382f92157deSopenharmony_ciThe 2383f92157deSopenharmony_ci[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), 2384f92157deSopenharmony_ci[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), 2385f92157deSopenharmony_ciand 2386f92157deSopenharmony_ci[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) 2387f92157deSopenharmony_ciall provide weak functions that you can override to trigger explicit failures 2388f92157deSopenharmony_ciwhen they detect sanitizer errors, such as creating a reference from `nullptr`. 2389f92157deSopenharmony_ciTo override these functions, place definitions for them in a source file that 2390f92157deSopenharmony_ciyou compile as part of your main binary: 2391f92157deSopenharmony_ci 2392f92157deSopenharmony_ci``` 2393f92157deSopenharmony_ciextern "C" { 2394f92157deSopenharmony_civoid __ubsan_on_report() { 2395f92157deSopenharmony_ci FAIL() << "Encountered an undefined behavior sanitizer error"; 2396f92157deSopenharmony_ci} 2397f92157deSopenharmony_civoid __asan_on_error() { 2398f92157deSopenharmony_ci FAIL() << "Encountered an address sanitizer error"; 2399f92157deSopenharmony_ci} 2400f92157deSopenharmony_civoid __tsan_on_report() { 2401f92157deSopenharmony_ci FAIL() << "Encountered a thread sanitizer error"; 2402f92157deSopenharmony_ci} 2403f92157deSopenharmony_ci} // extern "C" 2404f92157deSopenharmony_ci``` 2405f92157deSopenharmony_ci 2406f92157deSopenharmony_ciAfter compiling your project with one of the sanitizers enabled, if a particular 2407f92157deSopenharmony_citest triggers a sanitizer error, googletest will report that it failed. 2408