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/ # testing The `testing` package provides support for automated testing of Go packages. It is intended to be used in concert with the `go test` command. ## Test Functions ```go func TestXxx(t *testing.T) ``` - Test functions must start with `Test` followed by a capitalized identifier - Must accept a single parameter of type `*testing.T` ### Key Methods - `t.Fail()`: Marks the test as failed, but continues execution - `t.FailNow()`: Marks the test as failed and stops execution of the current goroutine immediately via `runtime.Goexit()` - `t.Errorf(format string, args ...any)`: Equivalent to `t.Logf` + `t.Fail()`. Logs an error and marks the test as failed, but continues execution - `t.Fatalf(format string, args ...any)`: Equivalent to `t.Errorf` + `t.FailNow()` (`t.Logf` + `t.FailNow()`). Logs an error and stops execution of the current test goroutine immediately - `t.Skip(args ...any)`: Marks the test as skipped and stops execution immediately - `t.Helper()`: Marks the calling function as a test helper. When printing file and line information in test failures, the line inside the helper function is skipped, reporting the caller's line instead - `t.Cleanup(f func())`: Registers a teardown function (eg. closing DB connections, releasing RPC clients) that executes in LIFO order **after** `t.Context()` is canceled. See [Cleanup](#cleanup-tcleanup) - `t.Context() context.Context`: Returns a context that is automatically canceled as soon as the test body finishes (**before** `t.Cleanup` callbacks run). See [Test Contexts](#test-contexts-tcontext) ### Failure Handling in Goroutines `t.Fatalf` and `t.FailNow` call `runtime.Goexit()`, which only terminates the calling goroutine. Never call `t.Fatalf` or `t.FailNow` inside a background goroutine (`go func()`); doing so leaves the main test goroutine running or hanging and violates `go vet`. Always use `t.Errorf` followed by `return` inside worker goroutines. ```go // Correct: Record failure with t.Errorf and return from worker goroutine go func() { if err := doAsyncWork(); err != nil { t.Errorf("doAsyncWork() failed: %v", err) return } }() // Prohibited: t.Fatalf in a child goroutine does not stop the main test goroutine go func() { if err := doAsyncWork(); err != nil { t.Fatalf("doAsyncWork() failed: %v", err) // Violates go vet } }() ``` ## Test Contexts (`t.Context()`) Starting in Go 1.24, `*testing.T` provides `t.Context()`, returning a `context.Context` that is automatically canceled when the test or subtest finishes. Internally, `t.Context()` is created via `context.WithCancel`, but the `cancel` function is exclusively owned by the `go test` framework and automatically invoked when the test body finishes. Returning only `context.Context` (without `CancelFunc`) prevents test helpers or sub-functions from prematurely canceling the entire test's root context. To test early cancellation, derive a child context via `ctx, cancel := context.WithCancel(t.Context())`. ### Lifecycle & Cancellation Order Understanding when `t.Context()` is canceled relative to `t.Cleanup` is critical for avoiding teardown errors: 1. `t.Run` starts and initializes `t.Context()` 2. Test function body executes 3. Test function body returns normally or exits early via `t.Fatalf` / `t.FailNow` 4. `t.Context()` is automatically canceled (`<-ctx.Done()` closes) 5. Registered `t.Cleanup` callbacks execute in LIFO order 6. Test completes and final status is reported ### Subtest Scope (Innermost Context) Always use the innermost `t.Context()` inside subtests (`t.Run`) rather than sharing a parent test context. ```go // Correct: Subtest-scoped context func TestService(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got, err := service.Fetch(t.Context(), tc.id) ... }) } } // Prohibited: Shared parent context leaks lifecycle across subtests func TestService(t *testing.T) { ctx := t.Context() // Outer scope for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got, err := service.Fetch(ctx, tc.id) }) } } ``` ### Context Derivation & Single Source of Truth When a test modifies the context (e.g., adding timeouts or metadata) or passes the context to multiple functions, capture `ctx := t.Context()` at the beginning of the test as the single source of truth. ```go // Correct: Single source of truth preserved t.Run(tc.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() db := setupDB(ctx, t) got, err := service.Process(ctx, tc.input) }) // Antipattern: Calling t.Context() repeatedly bypasses derived timeouts t.Run(tc.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() db := setupDB(t.Context(), t) // Timeout bypassed got, err := service.Process(t.Context(), tc.input) // Timeout bypassed }) ``` ### Helper Function Signatures Test helpers, fixtures, and test doubles must accept `ctx context.Context` as an explicit first parameter rather than calling `t.Context()` internally. This allows callers to pass customized contexts (e.g. earlier deadlines or cancelable contexts). ```go // Correct: Explicit context parameter func setupDatabase(ctx context.Context, t *testing.T) *Database { t.Helper() return newTestDatabase(ctx, t) } // Prohibited: Internal context extraction func setupDatabase(t *testing.T) *Database { t.Helper() return newTestDatabase(t.Context(), t) } ``` ## Table-Driven Tests Table-driven tests organize test cases in a slice of anonymous structs, enabling clean test additions and parameterized runs. ```go func TestCalculate(t *testing.T) { tests := []struct { name string input int want int wantErr bool }{ { name: "positive number", input: 5, want: 10, }, { name: "negative number returns error", input: -1, wantErr: true, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got, err := Calculate(tc.input) if (err != nil) != tc.wantErr { t.Fatalf("Calculate(%d) error = %v, wantErr %v", tc.input, err, tc.wantErr) } if got != tc.want { t.Errorf("Calculate(%d) = %d, want %d", tc.input, got, tc.want) } }) } } ``` ### Parallel Subtests Use `t.Parallel()` inside `t.Run` to run subtests concurrently. ```go for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() got := LongRunningTask(t.Context(), tc.input) ... }) } ``` ## Cleanup (`t.Cleanup`) `t.Cleanup` registers functions to be called when the test (or subtest) completes. Cleanup functions run in LIFO (last-in, first-out) order. ```go func TestResource(t *testing.T) { f := createTempFile(t) t.Cleanup(func() { os.Remove(f.Name()) }) } ``` {{% hint warning %}} **Context in Cleanup:** `t.Context()` is canceled **before** `t.Cleanup` callbacks run. For cleanup operations requiring active network or database calls, use `context.Background()` or `context.WithoutCancel(t.Context())`. {{% /hint %}} ### Creating Contexts in Cleanup Because `t.Context()` is already canceled when `t.Cleanup` executes, any teardown call (eg. closing an RPC client or dropping test database tables) that accepts a context requires a new active context: - `context.Background()`: Creates a completely new, empty root context - `context.WithoutCancel(t.Context())`: Creates a new derived context that ignores parent cancellation while preserving context values (eg. trace IDs, auth metadata, logger fields) attached to `t.Context()` - Wrap the cleanup context with `context.WithTimeout` to prevent teardown operations from hanging indefinitely ```go func TestDatabaseTeardown(t *testing.T) { db := setupDatabase(t.Context(), t) t.Cleanup(func() { // Derive a non-canceled context preserving values, bounded by a timeout cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 5*time.Second) defer cancel() if err := db.Close(cleanupCtx); err != nil { t.Errorf("db.Close() failed during cleanup: %v", err) } }) } ```