Skip to content

Commit

Permalink
Use a temp dir for cwd in tests (slsa-framework#633)
Browse files Browse the repository at this point in the history
* Use a temp dir for cwd in tests

* Reduce complexity
  • Loading branch information
ianlewis committed Jul 26, 2022
1 parent 8f8f267 commit 7f681d9
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions internal/utils/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,26 @@ func Test_VerifyAttestationPath(t *testing.T) {
}
}

func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
t.Parallel()
func tempWD() (func(), error) {
// Set up a temporary working directory for the test.
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
tempwd, err := os.MkdirTemp("", "slsa-github-generator-tests")
if err != nil {
return nil, err
}
if err := os.Chdir(tempwd); err != nil {
return nil, err
}
return func() {
os.RemoveAll(tempwd)
os.Chdir(cwd)
}, nil
}

func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
tests := []struct {
name string
path string
Expand All @@ -167,17 +184,19 @@ func Test_CreateNewFileUnderCurrentDirectory(t *testing.T) {
for _, tt := range tests {
tt := tt // Re-initializing variable so it is not changed while executing the closure below
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
cleanup, err := tempWD()
if err != nil {
t.Fatal(err)
}
defer cleanup()

if tt.existingPath {
if _, err := os.Stat(tt.path); err != nil {
if _, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}

_, err := CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY)
_, err = CreateNewFileUnderCurrentDirectory(tt.path, os.O_WRONLY)
if (err == nil && tt.expected != nil) ||
(err != nil && tt.expected == nil) {
t.Fatalf("unexpected error: %v", cmp.Diff(err, tt.expected, cmpopts.EquateErrors()))
Expand Down

0 comments on commit 7f681d9

Please sign in to comment.