Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Unit Testing Practical guidelines for C++ unit testing with open-source [GoogleTest (`google/googletest`)](https://github.com/google/googletest) and **Abseil (`abseil-cpp`)**, covering test file namespace layout, how `TEST` and `TEST_F` expand under the hood, `Test Fixture` lifecycles, and choosing between `CHECK`, `ASSERT_*`, and `EXPECT_*`. --- ## 1. Namespace Structure in Test Files ### 1. Idiomatic Layout: `namespace { namespace { ... } }` When `greeter.h` and `greeter.cc` declare symbols inside `namespace greeter`, the corresponding `greeter_test.cc` should open the **same outer `namespace greeter`** and wrap the test definitions inside an inner **[anonymous namespace]({{< relref "/programming/cpp/primer/namespaces.md" >}}) (`namespace { ... }`)**. ```cpp // greeter_test.cc #include "greeter/greeter.h" #include #include #include "absl/strings/str_cat.h" namespace greeter { namespace { TEST(GreeterTest, FormatsGreetingWithUserName) { Greeter greeter; // Accessible directly without greeter:: qualification std::string name = "Alice"; EXPECT_EQ(greeter.SayHello(name), absl::StrCat("Hello, ", name)); } } // namespace } // namespace greeter ``` - **Outer `namespace greeter` (Unqualified SUT Access):** Allows tests to reference classes, functions, and constants in the package under test directly without repeating `greeter::` prefixes or `using` declarations (analogous to declaring `package greeter` at the top of `greeter_test.go` in Go). - **Inner `namespace { ... }` (Per-File Internal Linkage):** Gives helper functions, fake implementations, and the C++ classes generated by `TEST` macros **Internal Linkage** within the current translation unit (`.cc`), preventing One Definition Rule (ODR) violations and linker symbol collisions across multiple `*_test.cc` files linked into the same test binary. ### 2. Pitfall: Never Name a Nested Namespace `testing` (Name Hiding) - GoogleTest itself lives in the top-level `::testing` namespace (eg. `::testing::Test`, `::testing::ElementsAre`). - Defining `namespace greeter::testing` causes C++ unqualified name lookup to stop at the inner `greeter::testing` scope rather than reaching `::testing` (Name Hiding), breaking references such as `testing::Test` with compiler errors. --- ## 2. How the `TEST` Macro Expands & Naming Rules ### 1. What `TEST(TestSuiteName, TestName)` Actually Generates Although `TEST(QuizScorerTest, ScoresValidSubmission)` looks like a function definition, the preprocessor actually **defines a unique C++ subclass of `::testing::Test` on the spot and registers it automatically during static initialization** (`gtest/internal/gtest-internal.h`). ```cpp // What you write TEST(QuizScorerTest, ScoresValidSubmission) { QuizScorer scorer; EXPECT_EQ(scorer.Score("A"), 100); } // Simplified C++ code generated by the preprocessor class QuizScorerTest_ScoresValidSubmission_Test : public ::testing::Test { private: void TestBody() override; static ::testing::TestInfo* const test_info_; // Auto-registers before main() }; void QuizScorerTest_ScoresValidSubmission_Test::TestBody() { QuizScorer scorer; EXPECT_EQ(scorer.Score("A"), 100); } ``` ### 2. How `TestSuiteName` and `TestName` Are Used & Naming Rules In a standalone `TEST(...)`, neither `QuizScorerTest` nor `ScoresValidSubmission` is a pre-existing type or variable; **both identifiers are coined right at the macro invocation** (by convention, `TestSuiteName` appends `Test` to the class or module under test, such as `QuizScorerTest`). GoogleTest uses these two names in three places: 1. **Synthesizing the C++ Class Name:** Concatenates the two arguments with an underscore (`_`) to form `__Test`. 2. **Grouping Test Reports:** Formats console output and XML test results as `QuizScorerTest.ScoresValidSubmission`. 3. **CLI Test Filtering:** Matches patterns passed to `--gtest_filter` when running a subset of tests. ```bash $ ./quiz_scorer_test --gtest_filter="QuizScorerTest.*" ``` - **Avoid Underscores (`_`) in Both Names:** Because the macro joins the two tokens with `_`, putting underscores inside either name can cause two distinct tests (eg. `TEST(Foo_Bar, Baz)` and `TEST(Foo, Bar_Baz)`) to generate the exact same `class Foo_Bar_Baz_Test` and collide at compile or link time ([GoogleTest FAQ](https://google.github.io/googletest/faq.html#why-should-test-suite-names-and-test-names-not-contain-underscore)). Use `PascalCase` without underscores for both arguments. - **Use Descriptive `TestName` Identifiers:** Replace vague names like `Basic` or `Works` with behavior-describing names (eg. `ScoresValidSubmission`, `RejectsEmptyAnswer`) so failure logs immediately communicate what broke. --- ## 3. Test Fixtures (`TEST_F`) & Lifecycle ### 1. `TEST` vs. `TEST_F` Side-by-Side A **Test Fixture** is a reusable base class that bundles shared objects (eg. fake databases, temporary directories) and common setup/cleanup logic across multiple test cases. - **`TEST(SuiteName, TestName)`:** Requires no prior class definition; the generated test class inherits directly from `::testing::Test`. - **`TEST_F(FixtureClassName, TestName)` (`F` = Fixture):** Requires **`class FixtureClassName : public ::testing::Test` to be defined beforehand**. Because the generated test class inherits from `FixtureClassName`, `protected:` data members and helper methods on the fixture are directly accessible inside `TestBody()`. ```cpp // 1. No shared setup needed: use plain TEST (no fixture class required) TEST(GreeterTest, ReturnsFormattedHello) { Greeter greeter; EXPECT_EQ(greeter.SayHello("Bob"), "Hello, Bob"); } // 2. Multiple tests share nontrivial setup: define a fixture class and use TEST_F class UserStoreTest : public ::testing::Test { protected: void SetUp() override { ASSERT_TRUE(db_.ConnectInMemory()); store_ = std::make_unique(&db_); } FakeDatabase db_; std::unique_ptr store_; }; // Expands to -> class UserStoreTest_InsertsNewUser_Test : public UserStoreTest TEST_F(UserStoreTest, InsertsNewUser) { EXPECT_TRUE(store_->Insert("alice")); EXPECT_EQ(store_->Count(), 1); } // Expands to -> class UserStoreTest_ReturnsFalseOnDuplicate_Test : public UserStoreTest TEST_F(UserStoreTest, ReturnsFalseOnDuplicate) { ASSERT_TRUE(store_->Insert("alice")); EXPECT_FALSE(store_->Insert("alice")); } ``` ### 2. Instance Isolation & `SetUp()` / `TearDown()` Lifecycle - **Fresh Fixture Instance per Test Case (No Shared State):** GoogleTest **does not reuse** the same `UserStoreTest` object across `TEST_F` cases. To guarantee hermetic isolation so mutations in one test never pollute another, GoogleTest constructs and destroys a brand-new fixture instance for every single `TEST_F`: 1. Construct a fresh `UserStoreTest` instance (constructor runs) 2. Call `SetUp()` 3. Run the `TEST_F` body (`"alice"` inserted in `InsertsNewUser` does not carry over to the next test) 4. Call `TearDown()` (guaranteed to run even if the test body aborted early via `ASSERT_*`) 5. Destroy the `UserStoreTest` instance (destructor runs) - **Constructor/Destructor vs. `SetUp()` / `TearDown()`:** - Prefer **constructors and destructors** by default so members can be initialized in initializer lists, marked `const`, and managed cleanly via [RAII]({{< relref "/programming/cpp/raii.md" >}}). - Override `void SetUp()` when setup requires **`ASSERT_*` macros**: `ASSERT_*` expands to a `return;` statement on failure, which is legal inside `void SetUp()` but fails to compile inside a C++ constructor (and similarly when virtual dispatch is needed during setup). - **Avoid Unnecessary Fixtures:** Introducing a `TEST_F` fixture just to hold a couple of local variables forces readers to jump back and forth between the fixture class at the top of the file and the test body below. Reach for `TEST_F` only when multiple tests genuinely share setup state; otherwise, prefer plain `TEST` cases with explicit local variables or helper functions. ### 3. Comparison with Go `testing` Lifecycle (`t.Cleanup` & `t.Context`) Whereas C++ GoogleTest automates setup and teardown implicitly through **inheritance (`Fixture` class) and object lifetime ([RAII]({{< relref "/programming/cpp/raii.md" >}}))**, [Go `testing`]({{< relref "/programming/go/std/testing.md" >}}) has no fixture inheritance or `SetUp()` / `TearDown()` hooks—instead achieving the exact same per-test isolation via **explicit setup helpers and a LIFO [`t.Cleanup()`]({{< relref "/programming/go/std/testing.md#cleanup-tcleanup" >}}) callback stack**. ```text [C++ GoogleTest (TEST_F)] Constructor (members in order) ──▶ SetUp() ──▶ TestBody() ──▶ TearDown() ──▶ Destructor (members in reverse order) [Go testing (t.Run)] Init t.Context() ──▶ setupHelper(t) + register t.Cleanup() ──▶ Test body ──▶ Cancel t.Context() ──▶ Run t.Cleanup() (LIFO) ``` | Dimension | C++ GoogleTest (`TEST_F`) | Go Standard `testing` (`*testing.T`) | | :--- | :--- | :--- | | **Shared Setup** | Implicit `Fixture` constructor + `void SetUp() override` | Explicit helper call inside test body (`db := setupDB(ctx, t)`) | | **Fatal Setup Failure** | Cannot use `ASSERT_*` in constructor -> use `ASSERT_*` (`return;`) inside `SetUp()` | Call `t.Fatalf(...)` (`runtime.Goexit()`) directly inside the setup helper | | **Teardown Mechanism** | `TearDown()` followed by **automatic member destructors in reverse declaration order (RAII)** | Automatic `t.Context()` cancellation followed by **`t.Cleanup()` callbacks in LIFO order** | | **Early-Abort Safety** | `TearDown()` and destructors still run after early `return;` from `ASSERT_*` | Registered `t.Cleanup()` callbacks still run after `t.Fatalf` (`Goexit`) | | **Context State in Teardown** | Member objects remain intact until destruction | **`t.Context()` is already canceled** before `t.Cleanup()` runs; DB/RPC teardown needs `context.WithoutCancel(t.Context())` | | **Once-per-Suite Setup** | `static void SetUpTestSuite()` / `TearDownTestSuite()` | `func TestMain(m *testing.M)` (wrapping `m.Run()`) | - **Why Both Tear Down in Reverse (LIFO) Order:** In C++ `UserStoreTest`, declaring `db_` before `store_` (which holds `&db_`) constructs `db_` -> `store_` and destroys them in reverse order (`~store_()` -> `~db_()`), preventing dangling references during teardown. Because Go has no destructors, registering `t.Cleanup` callbacks as each resource is created and running them **LIFO** reproduces the exact same dependency-safe reverse destruction order as C++ RAII. --- ## 4. Verification Macros: `CHECK` vs. `ASSERT_*` vs. `EXPECT_*` ### 1. Header Ownership & Failure Behavior Although all three are C preprocessor `#define` macros invoked without a `testing::` namespace prefix, **they belong to completely different libraries and behave very differently on failure** (mirroring `panic` vs. `t.Fatalf` vs. `t.Errorf` in [Go `testing`]({{< relref "/programming/go/std/testing.md" >}})). | Macro Family | Defining Header | Allowed Scope | Behavior on Failure | Primary Purpose | | :--- | :--- | :--- | :--- | :--- | | **`CHECK*`** (`CHECK`, `CHECK_EQ`, `CHECK_OK`) | `"absl/log/check.h"` | Production & all code | Logs a stack trace and **aborts the entire process immediately** | Enforcing invariants in production code where continuing is unsafe | | **`ASSERT_*`** (`ASSERT_EQ`, `ASSERT_NE`, `ASSERT_THAT`) | `` / `` | **Test code only** | Records a test failure and **executes `return;` from the current function** (subsequent `TEST` cases still run) | Checking preconditions required for the rest of the test body to run safely (analogous to Go `t.Fatalf`) | | **`EXPECT_*`** (`EXPECT_EQ`, `EXPECT_TRUE`, `EXPECT_THAT`) | `` / `` | **Test code only** | Records a test failure and **continues executing the rest of the current test** | Standard verification of behavior under test (**default choice**, analogous to Go `t.Errorf`) | - **Why `CHECK` Should Not Verify Test Outcomes:** Using `CHECK_OK(scorer.Score(...))` or `CHECK_EQ(...)` to assert behavior under test crashes the entire test binary when a check fails, **preventing every remaining `TEST` case in the binary from running**. Reserve `CHECK` in test files strictly for internal invariants of test helper utilities themselves. - **When to Use `ASSERT_*` (and Its `void` Constraint):** Default to `EXPECT_*` so a single run surfaces all failures in a test. Upgrade to `ASSERT_*` only when continuing the current function would crash or be nonsensical—for example, `ASSERT_NE(user_ptr, nullptr);` before `user_ptr->name()`, or `ASSERT_EQ(items.size(), 1);` before `items[0]`. Because `ASSERT_*` expands to `return;`, it can only be used inside functions returning `void`. ### 2. Common Matchers & Deterministic Testing Tips 1. **String Comparisons (`EXPECT_EQ` vs. `EXPECT_STREQ`):** - Whenever at least one side is `std::string` or `absl::string_view`, overloaded `operator==` compares string contents properly—**use `EXPECT_EQ(actual_str, "Hello")`**. - Reserve `EXPECT_STREQ(a, b)` strictly for comparing two raw C string pointers (`const char*`), where `EXPECT_EQ` would compare pointer addresses instead of character contents. 2. **Verifying [`absl::Status` and `absl::StatusOr`]({{< relref "/programming/cpp/advanced/error-handling.md" >}}):** - Instead of `CHECK_OK`, use the gMock status matchers (`IsOk()`, `IsOkAndHolds()`, `StatusIs()`) from `"absl/status/status_matchers.h"`. ```cpp #include #include #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" namespace auth { namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::HasSubstr; TEST(TokenValidatorTest, ValidatesFormatAndExtractsUserId) { TokenValidator validator; // 1. Verify an OK absl::Status EXPECT_THAT(validator.Ping(), IsOk()); // 2. Verify an OK absl::StatusOr and its inner value in one assertion absl::StatusOr user_id = validator.ParseUserId("uid:42"); EXPECT_THAT(user_id, IsOkAndHolds(42)); // 3. Verify a specific error code and message substring EXPECT_THAT(validator.ParseUserId(""), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty"))); } } // namespace } // namespace auth ``` 3. **Never Sleep for Fixed Durations in Tests:** - Waiting with `absl::SleepFor(absl::Seconds(2))` or fixed wall-clock timeouts makes tests slow and causes **flaky failures** under heavy CI load. - Inject a fake clock interface when testing time-dependent logic so tests can advance time instantaneously, and use concurrency primitives like `absl::Notification` or explicit completion callbacks to synchronize asynchronous work deterministically.