Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Testing

Node’s built-in runner for JavaScript/compiled TypeScript, Go testing, Rust cargo test, and optional GoogleTest for C++. Excerpts assume a test body and named application functions unless marked as complete.

Declare a test

Go

Put TestXxx functions in a file ending _test.go. Fatal stops this test goroutine; Error records a failure and continues.

Fragment

Import testing.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import "testing"

func TestDouble(t *testing.T) {
    if got := double(3); got != 6 {
        t.Fatalf("double(3) = %d; want 6", got)
    }
}

Run the suite with its native runner

Go

go test builds and runs tests. ./... includes packages below the current module directory.

Shell: go test ./...

Run a focused test

Go

-run selects matching test/subtest names. -count=1 bypasses the test result cache.

Shell: go test ./... -run TestDouble -count=1

Name related cases

Go

t.Run names a subtest. A table-driven loop gives each input an independently reported case.

Fragment

Import fmt and testing. Go 1.22+ has per-iteration loop variables when enabled by the module language version.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import (
    "fmt"
    "testing"
)

for _, n := range []int{0, 3} {
    t.Run(fmt.Sprint(n), func(t *testing.T) {
        if double(n) != 2*n { t.Fatal("wrong result") }
    })
}

Choose equality with the right semantics

Go

Use == for comparable values. Slices/maps need a suitable comparison such as slices.Equal, maps.Equal or reflect.DeepEqual; these have different contracts.

Fragment

Import slices (Go 1.21+); this example compares []int.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import "slices"

if !slices.Equal(got, []int{1, 2}) {
    t.Fatalf("got %v", got)
}

Compare floating-point values with a domain tolerance

Go

Specify tolerance rather than expecting decimal arithmetic to be exact.

Fragment

Import math.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import "math"

if math.IsNaN(got) || math.IsInf(got, 0) ||
    math.Abs(got-want) > 1e-9*math.Max(1, math.Abs(want)) {
    t.Fatalf("got %g; want %g", got, want)
}

Check expected failures

Go

Check error identity or type with errors.Is/As when the function wraps errors.

Fragment

Import errors and io/fs.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import (
    "errors"
    "io/fs"
)

_, err := readMissing()
if !errors.Is(err, fs.ErrNotExist) {
    t.Fatalf("expected missing file, got %v", err)
}

Report observed values and the case identity

Go

A useful failure says which input failed, what was observed and what was expected. Assert public behavior; avoid pinning incidental private details that are free to change.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
case: empty input
observed: one item
expected: no items

Register cleanup with ownership

Go

t.Cleanup runs when the test and its subtests complete. Cleanup functions run last-in-first-out.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
resource := openResource(t)
t.Cleanup(func() { resource.Close() })

Wait for the actual asynchronous result

Go

Use a completion channel or synchronization, then assert in the test goroutine. Do not call Fatal from an unrelated worker goroutine.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
result := make(chan string, 1)
go func() { result <- load() }()
if got := <-result; got != "ready" { t.Fatal(got) }

Bound a wait and stop owned work

Go

Use a deadline-aware operation and cleanup its context. The go test -timeout flag bounds the whole test binary separately.

Fragment

Import context and time; t.Context needs Go 1.24+ and is canceled before Cleanup functions run; load must observe ctx.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import (
    "context"
    "time"
)

ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
if err := load(ctx); err != nil { t.Fatal(err) }

Give each test its own mutable resources

Go

Use temporary directories, unique database names/keys, random free ports and explicit clocks/configuration. Restore global state in cleanup when isolation is impossible. Tests that run in parallel must not mutate the same process-wide state unsafely.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
test A → its own directory / namespace
test B → its own directory / namespace

Choose a double for a boundary

Go

A stub supplies answers, a fake implements simplified behavior and a mock verifies chosen interactions. Keep essential protocol semantics in the double; separately test the real adapter against the real dependency.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
core logic → fake clock/storage
adapter test → real clock/storage boundary

Control time without arbitrary sleeps

Go

Inject a clock/scheduler or use the runner’s documented fake-time facilities. Advance to an observable condition; sleeping a guessed duration creates slow and flaky tests. Real I/O and other threads may not use the fake clock.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
arrange a deadline
advance the controlled clock
assert the observable transition

Pick boundary and equivalence cases

Go

Cover ordinary input, empty/min/max values, malformed input, duplicates, missing values and meaningful ordering. Derive cases from the contract rather than repeating the implementation’s branches.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
empty / one / many
just below / at / just above a threshold
valid / malformed / missing

State an invariant before generating inputs

Go

Property testing checks a relationship over generated inputs and often shrinks a failure. The language’s test runner alone does not always supply a property framework. Define input constraints and preserve the failing seed/example.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
decode(encode(value)) = value
sort(sort(values)) = sort(values)
output length = input length

Use an explicit fuzzing tool

Go

Go fuzz targets add seed inputs and call Fuzz. The runner retains discovered failures for reproduction.

Fragment

Shell: go test -fuzz=FuzzRoundTrip -fuzztime=10s. Restrict/validate inputs for the codec’s contract.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import "testing"

func FuzzRoundTrip(f *testing.F) {
    f.Add("example")
    f.Fuzz(func(t *testing.T, value string) {
        if decode(encode(value)) != value { t.Fatal(value) }
    })
}

Test the real boundary with a focused integration case

Go

Start the actual dependency with a known configuration, create isolated data, exercise one external contract and tear it down. Include serialization, error mapping, timeouts and authorization where they belong to that boundary.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
unit: business rule with fake storage
integration: real driver + disposable database
end-to-end: supported user workflow

Use coverage to find unexercised paths

Go

Coverage shows what ran under a selected instrumentation model. A high percentage does not prove correct assertions, all input combinations or absence of races. Inspect missing meaningful behavior rather than forcing a target number.

Fragment

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
line / branch / function coverage
covered code can still have a wrong assertion