From d4fa389a3f3cd252f7199bd7fd05358b1c7f6050 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Tue, 24 Sep 2024 17:23:18 +0300 Subject: [PATCH] refactor: Simplify temp file creation in tests --- github/github_test.go | 29 +++++++++++------------------ github/repos_releases_test.go | 7 +------ 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/github/github_test.go b/github/github_test.go index 8c6c38a84f..8255959882 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -15,7 +15,7 @@ import ( "net/http/httptest" "net/url" "os" - "path" + "path/filepath" "reflect" "strconv" "strings" @@ -68,29 +68,22 @@ func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown fun // openTestFile creates a new file with the given name and content for testing. // In order to ensure the exact file name, this function will create a new temp -// directory, and create the file in that directory. It is the caller's -// responsibility to remove the directory and its contents when no longer needed. -func openTestFile(name, content string) (file *os.File, dir string, err error) { - dir, err = os.MkdirTemp("", "go-github") +// directory, and create the file in that directory. The file is automatically +// cleaned up after the test. +func openTestFile(t *testing.T, name, content string) *os.File { + fname := filepath.Join(t.TempDir(), name) + err := os.WriteFile(fname, []byte(content), 0600) if err != nil { - return nil, dir, err + t.Fatal(err) } - - file, err = os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + file, err := os.Open(fname) if err != nil { - return nil, dir, err + t.Fatal(err) } - fmt.Fprint(file, content) - - // close and re-open the file to keep file.Stat() happy - file.Close() - file, err = os.Open(file.Name()) - if err != nil { - return nil, dir, err - } + t.Cleanup(func() { file.Close() }) - return file, dir, err + return file } func testMethod(t *testing.T, r *http.Request, want string) { diff --git a/github/repos_releases_test.go b/github/repos_releases_test.go index d7efd096d2..2cca2bd570 100644 --- a/github/repos_releases_test.go +++ b/github/repos_releases_test.go @@ -12,7 +12,6 @@ import ( "fmt" "io" "net/http" - "os" "strings" "testing" @@ -707,11 +706,7 @@ func TestRepositoriesService_UploadReleaseAsset(t *testing.T) { fmt.Fprintf(w, `{"id":1}`) }) - file, dir, err := openTestFile(test.fileName, "Upload me !\n") - if err != nil { - t.Fatalf("Unable to create temp file: %v", err) - } - defer os.RemoveAll(dir) + file := openTestFile(t, test.fileName, "Upload me !\n") ctx := context.Background() asset, _, err := client.Repositories.UploadReleaseAsset(ctx, "o", "r", int64(key), test.uploadOpts, file)