Skip to content

Commit

Permalink
refactor: Simplify temp file creation in tests (#3290)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear authored Oct 1, 2024
1 parent 3d410c2 commit 8faa07c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 24 deletions.
30 changes: 12 additions & 18 deletions github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -68,29 +68,23 @@ 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 {
t.Helper()
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) {
Expand Down
7 changes: 1 addition & 6 deletions github/repos_releases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 8faa07c

Please sign in to comment.