]> git.proxmox.com Git - ceph.git/blame - ceph/src/jaegertracing/opentelemetry-cpp/third_party/googletest/googletest/docs/faq.md
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / jaegertracing / opentelemetry-cpp / third_party / googletest / googletest / docs / faq.md
CommitLineData
1e59de90
TL
1# Googletest FAQ
2
3<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
4
5<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
6
7## Why should test suite names and test names not contain underscore?
8
9Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
10[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
11to the following rationale.
12
13Underscore (`_`) is special, as C++ reserves the following to be used by the
14compiler and the standard library:
15
161. any identifier that starts with an `_` followed by an upper-case letter, and
172. any identifier that contains two consecutive underscores (i.e. `__`)
18 *anywhere* in its name.
19
20User code is *prohibited* from using such identifiers.
21
22Now let's look at what this means for `TEST` and `TEST_F`.
23
24Currently `TEST(TestSuiteName, TestName)` generates a class named
25`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`
26contains `_`?
27
281. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,
29 `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
30 invalid.
312. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get
32 `Foo__TestName_Test`, which is invalid.
333. If `TestName` starts with an `_` (say, `_Bar`), we get
34 `TestSuiteName__Bar_Test`, which is invalid.
354. If `TestName` ends with an `_` (say, `Bar_`), we get
36 `TestSuiteName_Bar__Test`, which is invalid.
37
38So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
39(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
40followed by an upper-case letter. But that's getting complicated. So for
41simplicity we just say that it cannot start with `_`.).
42
43It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
44middle. However, consider this:
45
46```c++
47TEST(Time, Flies_Like_An_Arrow) { ... }
48TEST(Time_Flies, Like_An_Arrow) { ... }
49```
50
51Now, the two `TEST`s will both generate the same class
52(`Time_Flies_Like_An_Arrow_Test`). That's not good.
53
54So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
55`TestName`. The rule is more constraining than necessary, but it's simple and
56easy to remember. It also gives googletest some wiggle room in case its
57implementation needs to change in the future.
58
59If you violate the rule, there may not be immediate consequences, but your test
60may (just may) break with a new compiler (or a new version of the compiler you
61are using) or with a new version of googletest. Therefore it's best to follow
62the rule.
63
64## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
65
66First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
67ptr)`. This is the preferred syntax in the style guide because nullptr does not
68have the type problems that NULL does. Which is why NULL does not work.
69
70Due to some peculiarity of C++, it requires some non-trivial template meta
71programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
72and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
73(otherwise we make the implementation of googletest harder to maintain and more
74error-prone than necessary).
75
76The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
77*actual* value as the second. It's reasonable that someone wants to write
78`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
79Therefore we implemented it.
80
81The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
82fails, you already know that `ptr` must be `NULL`, so it doesn't add any
83information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
84works just as well.
85
86If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
87support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
88convention on the order of the two arguments for `EXPECT_NE`. This means using
89the template meta programming tricks twice in the implementation, making it even
90harder to understand and maintain. We believe the benefit doesn't justify the
91cost.
92
93Finally, with the growth of the gMock matcher library, we are encouraging people
94to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
95significant advantage of the matcher approach is that matchers can be easily
96combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
97easily combined. Therefore we want to invest more in the matchers than in the
98`EXPECT_XX()` macros.
99
100## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
101
102For testing various implementations of the same interface, either typed tests or
103value-parameterized tests can get it done. It's really up to you the user to
104decide which is more convenient for you, depending on your particular case. Some
105rough guidelines:
106
107* Typed tests can be easier to write if instances of the different
108 implementations can be created the same way, modulo the type. For example,
109 if all these implementations have a public default constructor (such that
110 you can write `new TypeParam`), or if their factory functions have the same
111 form (e.g. `CreateInstance<TypeParam>()`).
112* Value-parameterized tests can be easier to write if you need different code
113 patterns to create different implementations' instances, e.g. `new Foo` vs
114 `new Bar(5)`. To accommodate for the differences, you can write factory
115 function wrappers and pass these function pointers to the tests as their
116 parameters.
117* When a typed test fails, the default output includes the name of the type,
118 which can help you quickly identify which implementation is wrong.
119 Value-parameterized tests only show the number of the failed iteration by
120 default. You will need to define a function that returns the iteration name
121 and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more
122 useful output.
123* When using typed tests, you need to make sure you are testing against the
124 interface type, not the concrete types (in other words, you want to make
125 sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
126 `my_concrete_impl` works). It's less likely to make mistakes in this area
127 when using value-parameterized tests.
128
129I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
130both approaches a try. Practice is a much better way to grasp the subtle
131differences between the two tools. Once you have some concrete experience, you
132can much more easily decide which one to use the next time.
133
134## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
135
136**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
137now. Please use `EqualsProto`, etc instead.
138
139`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
140are now less tolerant of invalid protocol buffer definitions. In particular, if
141you have a `foo.proto` that doesn't fully qualify the type of a protocol message
142it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
143will now get run-time errors like:
144
145```
146... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
147... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
148```
149
150If you see this, your `.proto` file is broken and needs to be fixed by making
151the types fully qualified. The new definition of `ProtocolMessageEquals` and
152`ProtocolMessageEquiv` just happen to reveal your bug.
153
154## My death test modifies some state, but the change seems lost after the death test finishes. Why?
155
156Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
157expected crash won't kill the test program (i.e. the parent process). As a
158result, any in-memory side effects they incur are observable in their respective
159sub-processes, but not in the parent process. You can think of them as running
160in a parallel universe, more or less.
161
162In particular, if you use mocking and the death test statement invokes some mock
163methods, the parent process will think the calls have never occurred. Therefore,
164you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
165macro.
166
167## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
168
169Actually, the bug is in `htonl()`.
170
171According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
172use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
173a *macro*, which breaks this usage.
174
175Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
176standard C++. That hacky implementation has some ad hoc limitations. In
177particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
178is a template that has an integral argument.
179
180The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
181template argument, and thus doesn't compile in opt mode when `a` contains a call
182to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
183the solution must work with different compilers on various platforms.
184
185`htonl()` has some other problems as described in `//util/endian/endian.h`,
186which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
187does, only without its problems. We suggest you to use `ghtonl()` instead of
188`htonl()`, both in your tests and production code.
189
190`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
191in `htons()`.
192
193Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
194file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
195single header file and will not bloat your binary.
196
197## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
198
199If your class has a static data member:
200
201```c++
202// foo.h
203class Foo {
204 ...
205 static const int kBar = 100;
206};
207```
208
209You also need to define it *outside* of the class body in `foo.cc`:
210
211```c++
212const int Foo::kBar; // No initializer here.
213```
214
215Otherwise your code is **invalid C++**, and may break in unexpected ways. In
216particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
217generate an "undefined reference" linker error. The fact that "it used to work"
218doesn't mean it's valid. It just means that you were lucky. :-)
219
220## Can I derive a test fixture from another?
221
222Yes.
223
224Each test fixture has a corresponding and same named test suite. This means only
225one test suite can use a particular fixture. Sometimes, however, multiple test
226cases may want to use the same or slightly different fixtures. For example, you
227may want to make sure that all of a GUI library's test suites don't leak
228important system resources like fonts and brushes.
229
230In googletest, you share a fixture among test suites by putting the shared logic
231in a base test fixture, then deriving from that base a separate fixture for each
232test suite that wants to use this common logic. You then use `TEST_F()` to write
233tests using each derived fixture.
234
235Typically, your code looks like this:
236
237```c++
238// Defines a base test fixture.
239class BaseTest : public ::testing::Test {
240 protected:
241 ...
242};
243
244// Derives a fixture FooTest from BaseTest.
245class FooTest : public BaseTest {
246 protected:
247 void SetUp() override {
248 BaseTest::SetUp(); // Sets up the base fixture first.
249 ... additional set-up work ...
250 }
251
252 void TearDown() override {
253 ... clean-up work for FooTest ...
254 BaseTest::TearDown(); // Remember to tear down the base fixture
255 // after cleaning up FooTest!
256 }
257
258 ... functions and variables for FooTest ...
259};
260
261// Tests that use the fixture FooTest.
262TEST_F(FooTest, Bar) { ... }
263TEST_F(FooTest, Baz) { ... }
264
265... additional fixtures derived from BaseTest ...
266```
267
268If necessary, you can continue to derive test fixtures from a derived fixture.
269googletest has no limit on how deep the hierarchy can be.
270
271For a complete example using derived test fixtures, see
272[sample5_unittest.cc](../samples/sample5_unittest.cc).
273
274## My compiler complains "void value not ignored as it ought to be." What does this mean?
275
276You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
277`ASSERT_*()` can only be used in `void` functions, due to exceptions being
278disabled by our build system. Please see more details
279[here](advanced.md#assertion-placement).
280
281## My death test hangs (or seg-faults). How do I fix it?
282
283In googletest, death tests are run in a child process and the way they work is
284delicate. To write death tests you really need to understand how they work.
285Please make sure you have read [this](advanced.md#how-it-works).
286
287In particular, death tests don't like having multiple threads in the parent
288process. So the first thing you can try is to eliminate creating threads outside
289of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
290instead of real ones in your tests.
291
292Sometimes this is impossible as some library you must use may be creating
293threads before `main()` is even reached. In this case, you can try to minimize
294the chance of conflicts by either moving as many activities as possible inside
295`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
296leaving as few things as possible in it. Also, you can try to set the death test
297style to `"threadsafe"`, which is safer but slower, and see if it helps.
298
299If you go with thread-safe death tests, remember that they rerun the test
300program from the beginning in the child process. Therefore make sure your
301program can run side-by-side with itself and is deterministic.
302
303In the end, this boils down to good concurrent programming. You have to make
304sure that there are no race conditions or deadlocks in your program. No silver
305bullet - sorry!
306
307## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
308
309The first thing to remember is that googletest does **not** reuse the same test
310fixture object across multiple tests. For each `TEST_F`, googletest will create
311a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
312call `TearDown()`, and then delete the test fixture object.
313
314When you need to write per-test set-up and tear-down logic, you have the choice
315between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
316The former is usually preferred, as it has the following benefits:
317
318* By initializing a member variable in the constructor, we have the option to
319 make it `const`, which helps prevent accidental changes to its value and
320 makes the tests more obviously correct.
321* In case we need to subclass the test fixture class, the subclass'
322 constructor is guaranteed to call the base class' constructor *first*, and
323 the subclass' destructor is guaranteed to call the base class' destructor
324 *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
325 forgetting to call the base class' `SetUp()/TearDown()` or call them at the
326 wrong time.
327
328You may still want to use `SetUp()/TearDown()` in the following cases:
329
330* C++ does not allow virtual function calls in constructors and destructors.
331 You can call a method declared as virtual, but it will not use dynamic
332 dispatch, it will use the definition from the class the constructor of which
333 is currently executing. This is because calling a virtual method before the
334 derived class constructor has a chance to run is very dangerous - the
335 virtual method might operate on uninitialized data. Therefore, if you need
336 to call a method that will be overridden in a derived class, you have to use
337 `SetUp()/TearDown()`.
338* In the body of a constructor (or destructor), it's not possible to use the
339 `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
340 test failure that should prevent the test from running, it's necessary to
341 use `abort` <!-- GOOGLETEST_CM0015 DO NOT DELETE --> and abort the whole test executable,
342 or to use `SetUp()` instead of a constructor.
343* If the tear-down operation could throw an exception, you must use
344 `TearDown()` as opposed to the destructor, as throwing in a destructor leads
345 to undefined behavior and usually will kill your program right away. Note
346 that many standard libraries (like STL) may throw when exceptions are
347 enabled in the compiler. Therefore you should prefer `TearDown()` if you
348 want to write portable tests that work with or without exceptions.
349* The googletest team is considering making the assertion macros throw on
350 platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
351 client-side), which will eliminate the need for the user to propagate
352 failures from a subroutine to its caller. Therefore, you shouldn't use
353 googletest assertions in a destructor if your code could run on such a
354 platform.
355
356## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
357
358If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
359overloaded or a template, the compiler will have trouble figuring out which
360overloaded version it should use. `ASSERT_PRED_FORMAT*` and
361`EXPECT_PRED_FORMAT*` don't have this problem.
362
363If you see this error, you might want to switch to
364`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
365message. If, however, that is not an option, you can resolve the problem by
366explicitly telling the compiler which version to pick.
367
368For example, suppose you have
369
370```c++
371bool IsPositive(int n) {
372 return n > 0;
373}
374
375bool IsPositive(double x) {
376 return x > 0;
377}
378```
379
380you will get a compiler error if you write
381
382```c++
383EXPECT_PRED1(IsPositive, 5);
384```
385
386However, this will work:
387
388```c++
389EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
390```
391
392(The stuff inside the angled brackets for the `static_cast` operator is the type
393of the function pointer for the `int`-version of `IsPositive()`.)
394
395As another example, when you have a template function
396
397```c++
398template <typename T>
399bool IsNegative(T x) {
400 return x < 0;
401}
402```
403
404you can use it in a predicate assertion like this:
405
406```c++
407ASSERT_PRED1(IsNegative<int>, -5);
408```
409
410Things are more interesting if your template has more than one parameter. The
411following won't compile:
412
413```c++
414ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
415```
416
417as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
418is one more than expected. The workaround is to wrap the predicate function in
419parentheses:
420
421```c++
422ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
423```
424
425## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
426
427Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
428instead of
429
430```c++
431 return RUN_ALL_TESTS();
432```
433
434they write
435
436```c++
437 RUN_ALL_TESTS();
438```
439
440This is **wrong and dangerous**. The testing services needs to see the return
441value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
442`main()` function ignores it, your test will be considered successful even if it
443has a googletest assertion failure. Very bad.
444
445We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
446code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
447`gcc`. If you do so, you'll get a compiler error.
448
449If you see the compiler complaining about you ignoring the return value of
450`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
451return value of `main()`.
452
453But how could we introduce a change that breaks existing tests? Well, in this
454case, the code was already broken in the first place, so we didn't break it. :-)
455
456## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
457
458Due to a peculiarity of C++, in order to support the syntax for streaming
459messages to an `ASSERT_*`, e.g.
460
461```c++
462 ASSERT_EQ(1, Foo()) << "blah blah" << foo;
463```
464
465we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
466`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
467content of your constructor/destructor to a private void member function, or
468switch to `EXPECT_*()` if that works. This
469[section](advanced.md#assertion-placement) in the user's guide explains it.
470
471## My SetUp() function is not called. Why?
472
473C++ is case-sensitive. Did you spell it as `Setup()`?
474
475Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
476wonder why it's never called.
477
478
479## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
480
481You don't have to. Instead of
482
483```c++
484class FooTest : public BaseTest {};
485
486TEST_F(FooTest, Abc) { ... }
487TEST_F(FooTest, Def) { ... }
488
489class BarTest : public BaseTest {};
490
491TEST_F(BarTest, Abc) { ... }
492TEST_F(BarTest, Def) { ... }
493```
494
495you can simply `typedef` the test fixtures:
496
497```c++
498typedef BaseTest FooTest;
499
500TEST_F(FooTest, Abc) { ... }
501TEST_F(FooTest, Def) { ... }
502
503typedef BaseTest BarTest;
504
505TEST_F(BarTest, Abc) { ... }
506TEST_F(BarTest, Def) { ... }
507```
508
509## googletest output is buried in a whole bunch of LOG messages. What do I do?
510
511The googletest output is meant to be a concise and human-friendly report. If
512your test generates textual output itself, it will mix with the googletest
513output, making it hard to read. However, there is an easy solution to this
514problem.
515
516Since `LOG` messages go to stderr, we decided to let googletest output go to
517stdout. This way, you can easily separate the two using redirection. For
518example:
519
520```shell
521$ ./my_test > gtest_output.txt
522```
523
524## Why should I prefer test fixtures over global variables?
525
526There are several good reasons:
527
5281. It's likely your test needs to change the states of its global variables.
529 This makes it difficult to keep side effects from escaping one test and
530 contaminating others, making debugging difficult. By using fixtures, each
531 test has a fresh set of variables that's different (but with the same
532 names). Thus, tests are kept independent of each other.
5332. Global variables pollute the global namespace.
5343. Test fixtures can be reused via subclassing, which cannot be done easily
535 with global variables. This is useful if many test suites have something in
536 common.
537
538## What can the statement argument in ASSERT_DEATH() be?
539
540`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used
541wherever *`statement`* is valid. So basically *`statement`* can be any C++
542statement that makes sense in the current context. In particular, it can
543reference global and/or local variables, and can be:
544
545* a simple function call (often the case),
546* a complex expression, or
547* a compound statement.
548
549Some examples are shown here:
550
551```c++
552// A death test can be a simple function call.
553TEST(MyDeathTest, FunctionCall) {
554 ASSERT_DEATH(Xyz(5), "Xyz failed");
555}
556
557// Or a complex expression that references variables and functions.
558TEST(MyDeathTest, ComplexExpression) {
559 const bool c = Condition();
560 ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
561 "(Func1|Method) failed");
562}
563
564// Death assertions can be used anywhere in a function. In
565// particular, they can be inside a loop.
566TEST(MyDeathTest, InsideLoop) {
567 // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
568 for (int i = 0; i < 5; i++) {
569 EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
570 ::testing::Message() << "where i is " << i);
571 }
572}
573
574// A death assertion can contain a compound statement.
575TEST(MyDeathTest, CompoundStatement) {
576 // Verifies that at lease one of Bar(0), Bar(1), ..., and
577 // Bar(4) dies.
578 ASSERT_DEATH({
579 for (int i = 0; i < 5; i++) {
580 Bar(i);
581 }
582 },
583 "Bar has \\d+ errors");
584}
585```
586
587gtest-death-test_test.cc contains more examples if you are interested.
588
589## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
590
591Googletest needs to be able to create objects of your test fixture class, so it
592must have a default constructor. Normally the compiler will define one for you.
593However, there are cases where you have to define your own:
594
595* If you explicitly declare a non-default constructor for class `FooTest`
596 (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
597 default constructor, even if it would be empty.
598* If `FooTest` has a const non-static data member, then you have to define the
599 default constructor *and* initialize the const member in the initializer
600 list of the constructor. (Early versions of `gcc` doesn't force you to
601 initialize the const member. It's a bug that has been fixed in `gcc 4`.)
602
603## Why does ASSERT_DEATH complain about previous threads that were already joined?
604
605With the Linux pthread library, there is no turning back once you cross the line
606from a single thread to multiple threads. The first time you create a thread, a
607manager thread is created in addition, so you get 3, not 2, threads. Later when
608the thread you create joins the main thread, the thread count decrements by 1,
609but the manager thread will never be killed, so you still have 2 threads, which
610means you cannot safely run a death test.
611
612The new NPTL thread library doesn't suffer from this problem, as it doesn't
613create a manager thread. However, if you don't control which machine your test
614runs on, you shouldn't depend on this.
615
616## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
617
618googletest does not interleave tests from different test suites. That is, it
619runs all tests in one test suite first, and then runs all tests in the next test
620suite, and so on. googletest does this because it needs to set up a test suite
621before the first test in it is run, and tear it down afterwards. Splitting up
622the test case would require multiple set-up and tear-down processes, which is
623inefficient and makes the semantics unclean.
624
625If we were to determine the order of tests based on test name instead of test
626case name, then we would have a problem with the following situation:
627
628```c++
629TEST_F(FooTest, AbcDeathTest) { ... }
630TEST_F(FooTest, Uvw) { ... }
631
632TEST_F(BarTest, DefDeathTest) { ... }
633TEST_F(BarTest, Xyz) { ... }
634```
635
636Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
637interleave tests from different test suites, we need to run all tests in the
638`FooTest` case before running any test in the `BarTest` case. This contradicts
639with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
640
641## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
642
643You don't have to, but if you like, you may split up the test suite into
644`FooTest` and `FooDeathTest`, where the names make it clear that they are
645related:
646
647```c++
648class FooTest : public ::testing::Test { ... };
649
650TEST_F(FooTest, Abc) { ... }
651TEST_F(FooTest, Def) { ... }
652
653using FooDeathTest = FooTest;
654
655TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
656TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
657```
658
659## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
660
661Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
662makes it harder to search for real problems in the parent's log. Therefore,
663googletest only prints them when the death test has failed.
664
665If you really need to see such LOG messages, a workaround is to temporarily
666break the death test (e.g. by changing the regex pattern it is expected to
667match). Admittedly, this is a hack. We'll consider a more permanent solution
668after the fork-and-exec-style death tests are implemented.
669
670## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
671
672If you use a user-defined type `FooType` in an assertion, you must make sure
673there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
674defined such that we can print a value of `FooType`.
675
676In addition, if `FooType` is declared in a name space, the `<<` operator also
677needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details.
678
679## How do I suppress the memory leak messages on Windows?
680
681Since the statically initialized googletest singleton requires allocations on
682the heap, the Visual C++ memory leak detector will report memory leaks at the
683end of the program run. The easiest way to avoid this is to use the
684`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
685statically initialized heap objects. See MSDN for more details and additional
686heap check/debug routines.
687
688## How can my code detect if it is running in a test?
689
690If you write code that sniffs whether it's running in a test and does different
691things accordingly, you are leaking test-only logic into production code and
692there is no easy way to ensure that the test-only code paths aren't run by
693mistake in production. Such cleverness also leads to
694[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
695advise against the practice, and googletest doesn't provide a way to do it.
696
697In general, the recommended way to cause the code to behave differently under
698test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
699different functionality from the test and from the production code. Since your
700production code doesn't link in the for-test logic at all (the
701[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
702that), there is no danger in accidentally running it.
703
704However, if you *really*, *really*, *really* have no choice, and if you follow
705the rule of ending your test program names with `_test`, you can use the
706*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
707whether the code is under test.
708
709## How do I temporarily disable a test?
710
711If you have a broken test that you cannot fix right away, you can add the
712DISABLED_ prefix to its name. This will exclude it from execution. This is
713better than commenting out the code or using #if 0, as disabled tests are still
714compiled (and thus won't rot).
715
716To include disabled tests in test execution, just invoke the test program with
717the --gtest_also_run_disabled_tests flag.
718
719## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
720
721Yes.
722
723The rule is **all test methods in the same test suite must use the same fixture
724class.** This means that the following is **allowed** because both tests use the
725same fixture class (`::testing::Test`).
726
727```c++
728namespace foo {
729TEST(CoolTest, DoSomething) {
730 SUCCEED();
731}
732} // namespace foo
733
734namespace bar {
735TEST(CoolTest, DoSomething) {
736 SUCCEED();
737}
738} // namespace bar
739```
740
741However, the following code is **not allowed** and will produce a runtime error
742from googletest because the test methods are using different test fixture
743classes with the same test suite name.
744
745```c++
746namespace foo {
747class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
748TEST_F(CoolTest, DoSomething) {
749 SUCCEED();
750}
751} // namespace foo
752
753namespace bar {
754class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
755TEST_F(CoolTest, DoSomething) {
756 SUCCEED();
757}
758} // namespace bar
759```