Skip to content

Commit 3d0de6f

Browse files
authored
Use testing.Cleanup (#242)
1 parent 941986d commit 3d0de6f

File tree

1 file changed

+28
-33
lines changed

1 file changed

+28
-33
lines changed

cmd/src/main_test.go

Lines changed: 28 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,6 @@ import (
1111
)
1212

1313
func TestReadConfig(t *testing.T) {
14-
makeTempConfig := func(t *testing.T, c config) (string, func()) {
15-
data, err := json.Marshal(c)
16-
if err != nil {
17-
t.Fatal(err)
18-
}
19-
tmpDir, err := ioutil.TempDir("", "")
20-
if err != nil {
21-
t.Fatal(err)
22-
}
23-
filePath := filepath.Join(tmpDir, "config.json")
24-
err = ioutil.WriteFile(filePath, data, 0600)
25-
if err != nil {
26-
t.Fatal(err)
27-
}
28-
return filePath, func() { os.RemoveAll(tmpDir) }
29-
}
30-
3114
tests := []struct {
3215
name string
3316
fileContents *config
@@ -138,31 +121,43 @@ func TestReadConfig(t *testing.T) {
138121

139122
for _, test := range tests {
140123
t.Run(test.name, func(t *testing.T) {
141-
oldConfigPath := *configPath
142-
defer func() { *configPath = oldConfigPath }()
124+
setEnv := func(name, val string) {
125+
old := os.Getenv(name)
126+
if err := os.Setenv(name, val); err != nil {
127+
t.Fatal(err)
128+
}
129+
t.Cleanup(func() { os.Setenv(name, old) })
130+
}
131+
setEnv("SRC_ACCESS_TOKEN", test.envToken)
132+
setEnv("SRC_ENDPOINT", test.envEndpoint)
143133

144134
if test.flagEndpoint != "" {
145135
val := test.flagEndpoint
146136
endpoint = &val
147-
defer func() { endpoint = nil }()
137+
t.Cleanup(func() { endpoint = nil })
148138
}
149139

150140
if test.fileContents != nil {
151-
p, cleanup := makeTempConfig(t, *test.fileContents)
152-
defer cleanup()
153-
*configPath = p
154-
}
155-
oldToken := os.Getenv("SRC_ACCESS_TOKEN")
156-
defer func() { os.Setenv("SRC_ACCESS_TOKEN", oldToken) }()
157-
oldEndpoint := os.Getenv("SRC_ENDPOINT")
158-
defer func() { os.Setenv("SRC_ENDPOINT", oldEndpoint) }()
141+
oldConfigPath := *configPath
142+
t.Cleanup(func() { *configPath = oldConfigPath })
159143

160-
if err := os.Setenv("SRC_ACCESS_TOKEN", test.envToken); err != nil {
161-
t.Fatal(err)
162-
}
163-
if err := os.Setenv("SRC_ENDPOINT", test.envEndpoint); err != nil {
164-
t.Fatal(err)
144+
data, err := json.Marshal(*test.fileContents)
145+
if err != nil {
146+
t.Fatal(err)
147+
}
148+
tmpDir, err := ioutil.TempDir("", "")
149+
if err != nil {
150+
t.Fatal(err)
151+
}
152+
t.Cleanup(func() { os.RemoveAll(tmpDir) })
153+
filePath := filepath.Join(tmpDir, "config.json")
154+
err = ioutil.WriteFile(filePath, data, 0600)
155+
if err != nil {
156+
t.Fatal(err)
157+
}
158+
*configPath = filePath
165159
}
160+
166161
config, err := readConfig()
167162
if diff := cmp.Diff(test.want, config); diff != "" {
168163
t.Errorf("config: %v", diff)

0 commit comments

Comments
 (0)