Skip to content

Use a temp dir for cwd in tests #633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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