Skip to content

Commit 7f681d9

Browse files
author
Ian Lewis
authored
Use a temp dir for cwd in tests (#633)
* Use a temp dir for cwd in tests * Reduce complexity
1 parent 8f8f267 commit 7f681d9

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

internal/utils/path_test.go

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,26 @@ func Test_VerifyAttestationPath(t *testing.T) {
138138
}
139139
}
140140

141-
func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
142-
t.Parallel()
141+
func tempWD() (func(), error) {
142+
// Set up a temporary working directory for the test.
143+
cwd, err := os.Getwd()
144+
if err != nil {
145+
return nil, err
146+
}
147+
tempwd, err := os.MkdirTemp("", "slsa-github-generator-tests")
148+
if err != nil {
149+
return nil, err
150+
}
151+
if err := os.Chdir(tempwd); err != nil {
152+
return nil, err
153+
}
154+
return func() {
155+
os.RemoveAll(tempwd)
156+
os.Chdir(cwd)
157+
}, nil
158+
}
143159

160+
func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
144161
tests := []struct {
145162
name string
146163
path string
@@ -167,17 +184,19 @@ func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
167184
for _, tt := range tests {
168185
tt := tt // Re-initializing variable so it is not changed while executing the closure below
169186
t.Run(tt.name, func(t *testing.T) {
170-
t.Parallel()
187+
cleanup, err := tempWD()
188+
if err != nil {
189+
t.Fatal(err)
190+
}
191+
defer cleanup()
171192

172193
if tt.existingPath {
173-
if _, err := os.Stat(tt.path); err != nil {
174-
if _, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY); err != nil {
175-
t.Fatalf("unexpected error: %v", err)
176-
}
194+
if _, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY); err != nil {
195+
t.Fatalf("unexpected error: %v", err)
177196
}
178197
}
179198

180-
_, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY)
199+
_, err = CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY)
181200
if (err == nil && tt.expected != nil) ||
182201
(err != nil && tt.expected == nil) {
183202
t.Fatalf("unexpected error: %v", cmp.Diff(err, tt.expected, cmpopts.EquateErrors()))

0 commit comments

Comments
 (0)