Testing Setenv Restores Variables

Override environment variables inside a test with t.Setenv and rely on the automatic restore that keeps neighbouring tests isolated.

GoConfig Management

Code

gosnippet
39 lines
package main

import (
	"fmt"
	"os"
	"testing"
)

func readMode() string {
	if mode := os.Getenv("APP_MODE"); mode != "" {
		return mode
	}
	return "development"
}

func TestModeOverride(t *testing.T) {
	// t.Setenv injects the value and restores it when the test ends
	t.Setenv("APP_MODE", "production")
	if got := readMode(); got != "production" {
		t.Fatalf("readMode() = %q, want production", got)
	}

	// a second override in the same test is allowed, restore still wins
	t.Setenv("APP_MODE", "staging")
	if got := readMode(); got != "staging" {
		t.Fatalf("readMode() = %q, want staging", got)
	}
	fmt.Println("mode under test:", readMode())
}

func TestModeDefault(t *testing.T) {
	os.Unsetenv("APP_MODE")
	if got := readMode(); got != "development" {
		t.Fatalf("readMode() = %q, want development", got)
	}
}

// main stays empty: run this file with go test to execute the cases.
func main() {}

How the snippet works

Under the hood: the functions readMode, TestModeOverride, TestModeDefault and main.

Configuration comes from the environment — it reads APP_MODE, so the same code switches behavior between environments without edits.

Points of care

  • Only built-in APIs, which leaves no supply chain to vet.

Using it

The signature doing the primary work is func TestModeOverride(t *testing.T)

The demo output is labeled (mode under test:), so the printed output reads as a trace of the operations performed.

Key statements

func TestModeDefault(t *testing.T) {
os.Unsetenv("APP_MODE")
if got := readMode(); got != "development" {
t.Fatalf("readMode() = %q, want development", got)
}
}
func readMode() string {
if mode := os.Getenv("APP_MODE"); mode != "" {
return mode
}
return "development"
}
func main() {}

Interactive Tools for This Topic

FAQ

What does Testing Setenv Restores Variables print when run?
The script runs standalone; its 1 labeled outputs include `mode under test:`.