Testing Setenv Restores Variables
Override environment variables inside a test with t.Setenv and rely on the automatic restore that keeps neighbouring tests isolated.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Testing Setenv Restores Variables print when run?
- The script runs standalone; its 1 labeled outputs include `mode under test:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.