Skip to content

Commit 8faa07c

Browse files
authored
refactor: Simplify temp file creation in tests (#3290)
1 parent 3d410c2 commit 8faa07c

File tree

2 files changed

+13
-24
lines changed

2 files changed

+13
-24
lines changed

github/github_test.go

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"net/http/httptest"
1616
"net/url"
1717
"os"
18-
"path"
18+
"path/filepath"
1919
"reflect"
2020
"strconv"
2121
"strings"
@@ -68,29 +68,23 @@ func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown fun
6868

6969
// openTestFile creates a new file with the given name and content for testing.
7070
// In order to ensure the exact file name, this function will create a new temp
71-
// directory, and create the file in that directory. It is the caller's
72-
// responsibility to remove the directory and its contents when no longer needed.
73-
func openTestFile(name, content string) (file *os.File, dir string, err error) {
74-
dir, err = os.MkdirTemp("", "go-github")
71+
// directory, and create the file in that directory. The file is automatically
72+
// cleaned up after the test.
73+
func openTestFile(t *testing.T, name, content string) *os.File {
74+
t.Helper()
75+
fname := filepath.Join(t.TempDir(), name)
76+
err := os.WriteFile(fname, []byte(content), 0600)
7577
if err != nil {
76-
return nil, dir, err
78+
t.Fatal(err)
7779
}
78-
79-
file, err = os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
80+
file, err := os.Open(fname)
8081
if err != nil {
81-
return nil, dir, err
82+
t.Fatal(err)
8283
}
8384

84-
fmt.Fprint(file, content)
85-
86-
// close and re-open the file to keep file.Stat() happy
87-
file.Close()
88-
file, err = os.Open(file.Name())
89-
if err != nil {
90-
return nil, dir, err
91-
}
85+
t.Cleanup(func() { file.Close() })
9286

93-
return file, dir, err
87+
return file
9488
}
9589

9690
func testMethod(t *testing.T, r *http.Request, want string) {

github/repos_releases_test.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"fmt"
1313
"io"
1414
"net/http"
15-
"os"
1615
"strings"
1716
"testing"
1817

@@ -707,11 +706,7 @@ func TestRepositoriesService_UploadReleaseAsset(t *testing.T) {
707706
fmt.Fprintf(w, `{"id":1}`)
708707
})
709708

710-
file, dir, err := openTestFile(test.fileName, "Upload me !\n")
711-
if err != nil {
712-
t.Fatalf("Unable to create temp file: %v", err)
713-
}
714-
defer os.RemoveAll(dir)
709+
file := openTestFile(t, test.fileName, "Upload me !\n")
715710

716711
ctx := context.Background()
717712
asset, _, err := client.Repositories.UploadReleaseAsset(ctx, "o", "r", int64(key), test.uploadOpts, file)

0 commit comments

Comments
 (0)