The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

482 lines
19 KiB

2 months ago
  1. # Googletest Primer
  2. ## Introduction: Why googletest?
  3. *googletest* helps you write better C++ tests.
  4. googletest is a testing framework developed by the Testing Technology team with
  5. Google's specific requirements and constraints in mind. Whether you work on
  6. Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
  7. supports *any* kind of tests, not just unit tests.
  8. So what makes a good test, and how does googletest fit in? We believe:
  9. 1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
  10. that succeeds or fails as a result of other tests. googletest isolates the
  11. tests by running each of them on a different object. When a test fails,
  12. googletest allows you to run it in isolation for quick debugging.
  13. 2. Tests should be well *organized* and reflect the structure of the tested
  14. code. googletest groups related tests into test suites that can share data
  15. and subroutines. This common pattern is easy to recognize and makes tests
  16. easy to maintain. Such consistency is especially helpful when people switch
  17. projects and start to work on a new code base.
  18. 3. Tests should be *portable* and *reusable*. Google has a lot of code that is
  19. platform-neutral; its tests should also be platform-neutral. googletest
  20. works on different OSes, with different compilers, with or without
  21. exceptions, so googletest tests can work with a variety of configurations.
  22. 4. When tests fail, they should provide as much *information* about the problem
  23. as possible. googletest doesn't stop at the first test failure. Instead, it
  24. only stops the current test and continues with the next. You can also set up
  25. tests that report non-fatal failures after which the current test continues.
  26. Thus, you can detect and fix multiple bugs in a single run-edit-compile
  27. cycle.
  28. 5. The testing framework should liberate test writers from housekeeping chores
  29. and let them focus on the test *content*. googletest automatically keeps
  30. track of all tests defined, and doesn't require the user to enumerate them
  31. in order to run them.
  32. 6. Tests should be *fast*. With googletest, you can reuse shared resources
  33. across tests and pay for the set-up/tear-down only once, without making
  34. tests depend on each other.
  35. Since googletest is based on the popular xUnit architecture, you'll feel right
  36. at home if you've used JUnit or PyUnit before. If not, it will take you about 10
  37. minutes to learn the basics and get started. So let's go!
  38. ## Beware of the nomenclature
  39. {: .callout .note}
  40. _Note:_ There might be some confusion arising from different definitions of the
  41. terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
  42. Historically, googletest started to use the term _Test Case_ for grouping
  43. related tests, whereas current publications, including International Software
  44. Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
  45. various textbooks on software quality, use the term
  46. _[Test Suite][istqb test suite]_ for this.
  47. The related term _Test_, as it is used in googletest, corresponds to the term
  48. _[Test Case][istqb test case]_ of ISTQB and others.
  49. The term _Test_ is commonly of broad enough sense, including ISTQB's definition
  50. of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
  51. was used in Google Test is of contradictory sense and thus confusing.
  52. googletest recently started replacing the term _Test Case_ with _Test Suite_.
  53. The preferred API is *TestSuite*. The older TestCase API is being slowly
  54. deprecated and refactored away.
  55. So please be aware of the different definitions of the terms:
  56. Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
  57. :----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
  58. Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
  59. [istqb test case]: http://glossary.istqb.org/en/search/test%20case
  60. [istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
  61. ## Basic Concepts
  62. When using googletest, you start by writing *assertions*, which are statements
  63. that check whether a condition is true. An assertion's result can be *success*,
  64. *nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
  65. current function; otherwise the program continues normally.
  66. *Tests* use assertions to verify the tested code's behavior. If a test crashes
  67. or has a failed assertion, then it *fails*; otherwise it *succeeds*.
  68. A *test suite* contains one or many tests. You should group your tests into test
  69. suites that reflect the structure of the tested code. When multiple tests in a
  70. test suite need to share common objects and subroutines, you can put them into a
  71. *test fixture* class.
  72. A *test program* can contain multiple test suites.
  73. We'll now explain how to write a test program, starting at the individual
  74. assertion level and building up to tests and test suites.
  75. ## Assertions
  76. googletest assertions are macros that resemble function calls. You test a class
  77. or function by making assertions about its behavior. When an assertion fails,
  78. googletest prints the assertion's source file and line number location, along
  79. with a failure message. You may also supply a custom failure message which will
  80. be appended to googletest's message.
  81. The assertions come in pairs that test the same thing but have different effects
  82. on the current function. `ASSERT_*` versions generate fatal failures when they
  83. fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
  84. failures, which don't abort the current function. Usually `EXPECT_*` are
  85. preferred, as they allow more than one failure to be reported in a test.
  86. However, you should use `ASSERT_*` if it doesn't make sense to continue when the
  87. assertion in question fails.
  88. Since a failed `ASSERT_*` returns from the current function immediately,
  89. possibly skipping clean-up code that comes after it, it may cause a space leak.
  90. Depending on the nature of the leak, it may or may not be worth fixing - so keep
  91. this in mind if you get a heap checker error in addition to assertion errors.
  92. To provide a custom failure message, simply stream it into the macro using the
  93. `<<` operator or a sequence of such operators. See the following example, using
  94. the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to
  95. verify value equality:
  96. ```c++
  97. ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
  98. for (int i = 0; i < x.size(); ++i) {
  99. EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
  100. }
  101. ```
  102. Anything that can be streamed to an `ostream` can be streamed to an assertion
  103. macro--in particular, C strings and `string` objects. If a wide string
  104. (`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
  105. streamed to an assertion, it will be translated to UTF-8 when printed.
  106. GoogleTest provides a collection of assertions for verifying the behavior of
  107. your code in various ways. You can check Boolean conditions, compare values
  108. based on relational operators, verify string values, floating-point values, and
  109. much more. There are even assertions that enable you to verify more complex
  110. states by providing custom predicates. For the complete list of assertions
  111. provided by GoogleTest, see the [Assertions Reference](reference/assertions.md).
  112. ## Simple Tests
  113. To create a test:
  114. 1. Use the `TEST()` macro to define and name a test function. These are
  115. ordinary C++ functions that don't return a value.
  116. 2. In this function, along with any valid C++ statements you want to include,
  117. use the various googletest assertions to check values.
  118. 3. The test's result is determined by the assertions; if any assertion in the
  119. test fails (either fatally or non-fatally), or if the test crashes, the
  120. entire test fails. Otherwise, it succeeds.
  121. ```c++
  122. TEST(TestSuiteName, TestName) {
  123. ... test body ...
  124. }
  125. ```
  126. `TEST()` arguments go from general to specific. The *first* argument is the name
  127. of the test suite, and the *second* argument is the test's name within the test
  128. suite. Both names must be valid C++ identifiers, and they should not contain
  129. any underscores (`_`). A test's *full name* consists of its containing test suite and
  130. its individual name. Tests from different test suites can have the same
  131. individual name.
  132. For example, let's take a simple integer function:
  133. ```c++
  134. int Factorial(int n); // Returns the factorial of n
  135. ```
  136. A test suite for this function might look like:
  137. ```c++
  138. // Tests factorial of 0.
  139. TEST(FactorialTest, HandlesZeroInput) {
  140. EXPECT_EQ(Factorial(0), 1);
  141. }
  142. // Tests factorial of positive numbers.
  143. TEST(FactorialTest, HandlesPositiveInput) {
  144. EXPECT_EQ(Factorial(1), 1);
  145. EXPECT_EQ(Factorial(2), 2);
  146. EXPECT_EQ(Factorial(3), 6);
  147. EXPECT_EQ(Factorial(8), 40320);
  148. }
  149. ```
  150. googletest groups the test results by test suites, so logically related tests
  151. should be in the same test suite; in other words, the first argument to their
  152. `TEST()` should be the same. In the above example, we have two tests,
  153. `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
  154. suite `FactorialTest`.
  155. When naming your test suites and tests, you should follow the same convention as
  156. for
  157. [naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
  158. **Availability**: Linux, Windows, Mac.
  159. ## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}
  160. If you find yourself writing two or more tests that operate on similar data, you
  161. can use a *test fixture*. This allows you to reuse the same configuration of
  162. objects for several different tests.
  163. To create a fixture:
  164. 1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
  165. we'll want to access fixture members from sub-classes.
  166. 2. Inside the class, declare any objects you plan to use.
  167. 3. If necessary, write a default constructor or `SetUp()` function to prepare
  168. the objects for each test. A common mistake is to spell `SetUp()` as
  169. **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
  170. spelled it correctly.
  171. 4. If necessary, write a destructor or `TearDown()` function to release any
  172. resources you allocated in `SetUp()` . To learn when you should use the
  173. constructor/destructor and when you should use `SetUp()/TearDown()`, read
  174. the [FAQ](faq.md#CtorVsSetUp).
  175. 5. If needed, define subroutines for your tests to share.
  176. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
  177. access objects and subroutines in the test fixture:
  178. ```c++
  179. TEST_F(TestFixtureName, TestName) {
  180. ... test body ...
  181. }
  182. ```
  183. Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
  184. this must be the name of the test fixture class. You've probably guessed: `_F`
  185. is for fixture.
  186. Unfortunately, the C++ macro system does not allow us to create a single macro
  187. that can handle both types of tests. Using the wrong macro causes a compiler
  188. error.
  189. Also, you must first define a test fixture class before using it in a
  190. `TEST_F()`, or you'll get the compiler error "`virtual outside class
  191. declaration`".
  192. For each test defined with `TEST_F()`, googletest will create a *fresh* test
  193. fixture at runtime, immediately initialize it via `SetUp()`, run the test,
  194. clean up by calling `TearDown()`, and then delete the test fixture. Note that
  195. different tests in the same test suite have different test fixture objects, and
  196. googletest always deletes a test fixture before it creates the next one.
  197. googletest does **not** reuse the same test fixture for multiple tests. Any
  198. changes one test makes to the fixture do not affect other tests.
  199. As an example, let's write tests for a FIFO queue class named `Queue`, which has
  200. the following interface:
  201. ```c++
  202. template <typename E> // E is the element type.
  203. class Queue {
  204. public:
  205. Queue();
  206. void Enqueue(const E& element);
  207. E* Dequeue(); // Returns NULL if the queue is empty.
  208. size_t size() const;
  209. ...
  210. };
  211. ```
  212. First, define a fixture class. By convention, you should give it the name
  213. `FooTest` where `Foo` is the class being tested.
  214. ```c++
  215. class QueueTest : public ::testing::Test {
  216. protected:
  217. void SetUp() override {
  218. q1_.Enqueue(1);
  219. q2_.Enqueue(2);
  220. q2_.Enqueue(3);
  221. }
  222. // void TearDown() override {}
  223. Queue<int> q0_;
  224. Queue<int> q1_;
  225. Queue<int> q2_;
  226. };
  227. ```
  228. In this case, `TearDown()` is not needed since we don't have to clean up after
  229. each test, other than what's already done by the destructor.
  230. Now we'll write tests using `TEST_F()` and this fixture.
  231. ```c++
  232. TEST_F(QueueTest, IsEmptyInitially) {
  233. EXPECT_EQ(q0_.size(), 0);
  234. }
  235. TEST_F(QueueTest, DequeueWorks) {
  236. int* n = q0_.Dequeue();
  237. EXPECT_EQ(n, nullptr);
  238. n = q1_.Dequeue();
  239. ASSERT_NE(n, nullptr);
  240. EXPECT_EQ(*n, 1);
  241. EXPECT_EQ(q1_.size(), 0);
  242. delete n;
  243. n = q2_.Dequeue();
  244. ASSERT_NE(n, nullptr);
  245. EXPECT_EQ(*n, 2);
  246. EXPECT_EQ(q2_.size(), 1);
  247. delete n;
  248. }
  249. ```
  250. The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
  251. to use `EXPECT_*` when you want the test to continue to reveal more errors after
  252. the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
  253. make sense. For example, the second assertion in the `Dequeue` test is
  254. `ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which
  255. would lead to a segfault when `n` is `NULL`.
  256. When these tests run, the following happens:
  257. 1. googletest constructs a `QueueTest` object (let's call it `t1`).
  258. 2. `t1.SetUp()` initializes `t1`.
  259. 3. The first test (`IsEmptyInitially`) runs on `t1`.
  260. 4. `t1.TearDown()` cleans up after the test finishes.
  261. 5. `t1` is destructed.
  262. 6. The above steps are repeated on another `QueueTest` object, this time
  263. running the `DequeueWorks` test.
  264. **Availability**: Linux, Windows, Mac.
  265. ## Invoking the Tests
  266. `TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
  267. unlike with many other C++ testing frameworks, you don't have to re-list all
  268. your defined tests in order to run them.
  269. After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
  270. returns `0` if all the tests are successful, or `1` otherwise. Note that
  271. `RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
  272. different test suites, or even different source files.
  273. When invoked, the `RUN_ALL_TESTS()` macro:
  274. * Saves the state of all googletest flags.
  275. * Creates a test fixture object for the first test.
  276. * Initializes it via `SetUp()`.
  277. * Runs the test on the fixture object.
  278. * Cleans up the fixture via `TearDown()`.
  279. * Deletes the fixture.
  280. * Restores the state of all googletest flags.
  281. * Repeats the above steps for the next test, until all tests have run.
  282. If a fatal failure happens the subsequent steps will be skipped.
  283. {: .callout .important}
  284. > IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
  285. > you will get a compiler error. The rationale for this design is that the
  286. > automated testing service determines whether a test has passed based on its
  287. > exit code, not on its stdout/stderr output; thus your `main()` function must
  288. > return the value of `RUN_ALL_TESTS()`.
  289. >
  290. > Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
  291. > once conflicts with some advanced googletest features (e.g., thread-safe
  292. > [death tests](advanced.md#death-tests)) and thus is not supported.
  293. **Availability**: Linux, Windows, Mac.
  294. ## Writing the main() Function
  295. Most users should _not_ need to write their own `main` function and instead link
  296. with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
  297. point. See the end of this section for details. The remainder of this section
  298. should only apply when you need to do something custom before the tests run that
  299. cannot be expressed within the framework of fixtures and test suites.
  300. If you write your own `main` function, it should return the value of
  301. `RUN_ALL_TESTS()`.
  302. You can start from this boilerplate:
  303. ```c++
  304. #include "this/package/foo.h"
  305. #include "gtest/gtest.h"
  306. namespace my {
  307. namespace project {
  308. namespace {
  309. // The fixture for testing class Foo.
  310. class FooTest : public ::testing::Test {
  311. protected:
  312. // You can remove any or all of the following functions if their bodies would
  313. // be empty.
  314. FooTest() {
  315. // You can do set-up work for each test here.
  316. }
  317. ~FooTest() override {
  318. // You can do clean-up work that doesn't throw exceptions here.
  319. }
  320. // If the constructor and destructor are not enough for setting up
  321. // and cleaning up each test, you can define the following methods:
  322. void SetUp() override {
  323. // Code here will be called immediately after the constructor (right
  324. // before each test).
  325. }
  326. void TearDown() override {
  327. // Code here will be called immediately after each test (right
  328. // before the destructor).
  329. }
  330. // Class members declared here can be used by all tests in the test suite
  331. // for Foo.
  332. };
  333. // Tests that the Foo::Bar() method does Abc.
  334. TEST_F(FooTest, MethodBarDoesAbc) {
  335. const std::string input_filepath = "this/package/testdata/myinputfile.dat";
  336. const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
  337. Foo f;
  338. EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
  339. }
  340. // Tests that Foo does Xyz.
  341. TEST_F(FooTest, DoesXyz) {
  342. // Exercises the Xyz feature of Foo.
  343. }
  344. } // namespace
  345. } // namespace project
  346. } // namespace my
  347. int main(int argc, char **argv) {
  348. ::testing::InitGoogleTest(&argc, argv);
  349. return RUN_ALL_TESTS();
  350. }
  351. ```
  352. The `::testing::InitGoogleTest()` function parses the command line for
  353. googletest flags, and removes all recognized flags. This allows the user to
  354. control a test program's behavior via various flags, which we'll cover in
  355. the [AdvancedGuide](advanced.md). You **must** call this function before calling
  356. `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
  357. On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
  358. in programs compiled in `UNICODE` mode as well.
  359. But maybe you think that writing all those `main` functions is too much work? We
  360. agree with you completely, and that's why Google Test provides a basic
  361. implementation of main(). If it fits your needs, then just link your test with
  362. the `gtest_main` library and you are good to go.
  363. {: .callout .note}
  364. NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
  365. ## Known Limitations
  366. * Google Test is designed to be thread-safe. The implementation is thread-safe
  367. on systems where the `pthreads` library is available. It is currently
  368. _unsafe_ to use Google Test assertions from two threads concurrently on
  369. other systems (e.g. Windows). In most tests this is not an issue as usually
  370. the assertions are done in the main thread. If you want to help, you can
  371. volunteer to implement the necessary synchronization primitives in
  372. `gtest-port.h` for your platform.