Test Temp Dirs With t.TempDir
Give each test its own temporary directory with t.TempDir, write fixtures there, and let the testing package remove everything on cleanup.
Code
package config
import (
"os"
"path/filepath"
"testing"
)
func writeConfig(t *testing.T, dir, body string) string {
t.Helper() // 失败时报告调用行,而不是这个辅助函数
path := filepath.Join(dir, "config.json")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
return path
}
func TestLoadConfigFromTempDir(t *testing.T) {
dir := t.TempDir() // 测试结束自动递归删除
path := writeConfig(t, dir, `{"port":8080}`)
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read config: %v", err)
}
if len(data) == 0 {
t.Fatal("config file is empty")
}
t.Run("isolated subtest", func(t *testing.T) {
sub := t.TempDir() // 子测试拿到另一个独立目录
if sub == dir {
t.Fatal("temp dirs must differ")
}
other := writeConfig(t, sub, `{"port":9090}`)
if filepath.Dir(other) != sub {
t.Fatalf("config written outside temp dir: %s", other)
}
})
}A line-by-line account
Test Temp Dirs With t.TempDir comes down to the functions writeConfig and TestLoadConfigFromTempDir.
Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Applying it
Entry signature: func TestLoadConfigFromTempDir(t *testing.T)
Import TestLoadConfigFromTempDir from the file and call it — the rest of the code is implementation detail.
Statements that matter
func writeConfig(t *testing.T, dir, body string) string {
t.Helper() // 失败时报告调用行,而不是这个辅助函数
path := filepath.Join(dir, "config.json")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
return path
}
if err != nil {
t.Fatalf("read config: %v", err)
}
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
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `os`, `path/filepath`, `testing`. The file defines `writeConfig`, `TestLoadConfigFromTempDir` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.