Simplify tests with T.TempDir (#929)

This commit is contained in:
Oleksandr Redko
2025-01-31 20:55:41 +02:00
committed by GitHub
parent 2a0ff5ac63
commit 7a2915a37d
8 changed files with 24 additions and 70 deletions

View File

@@ -206,6 +206,7 @@ linters:
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- unconvert # Remove unnecessary type conversions - unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters - unparam # Reports unused function parameters
- usetesting # Reports uses of functions with replacement inside the testing package
- wastedassign # wastedassign finds wasted assignment statements. - wastedassign # wastedassign finds wasted assignment statements.
- whitespace # Tool for detection of leading and trailing whitespace - whitespace # Tool for detection of leading and trailing whitespace
## you may want to enable ## you may want to enable

View File

@@ -40,12 +40,9 @@ func TestAudio(t *testing.T) {
ctx := context.Background() ctx := context.Background()
dir, cleanup := test.CreateTestDirectory(t)
defer cleanup()
for _, tc := range testcases { for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(dir, "fake.mp3") path := filepath.Join(t.TempDir(), "fake.mp3")
test.CreateTestFile(t, path) test.CreateTestFile(t, path)
req := openai.AudioRequest{ req := openai.AudioRequest{
@@ -90,12 +87,9 @@ func TestAudioWithOptionalArgs(t *testing.T) {
ctx := context.Background() ctx := context.Background()
dir, cleanup := test.CreateTestDirectory(t)
defer cleanup()
for _, tc := range testcases { for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(dir, "fake.mp3") path := filepath.Join(t.TempDir(), "fake.mp3")
test.CreateTestFile(t, path) test.CreateTestFile(t, path)
req := openai.AudioRequest{ req := openai.AudioRequest{

View File

@@ -13,9 +13,7 @@ import (
) )
func TestAudioWithFailingFormBuilder(t *testing.T) { func TestAudioWithFailingFormBuilder(t *testing.T) {
dir, cleanup := test.CreateTestDirectory(t) path := filepath.Join(t.TempDir(), "fake.mp3")
defer cleanup()
path := filepath.Join(dir, "fake.mp3")
test.CreateTestFile(t, path) test.CreateTestFile(t, path)
req := AudioRequest{ req := AudioRequest{
@@ -63,9 +61,7 @@ func TestAudioWithFailingFormBuilder(t *testing.T) {
func TestCreateFileField(t *testing.T) { func TestCreateFileField(t *testing.T) {
t.Run("createFileField failing file", func(t *testing.T) { t.Run("createFileField failing file", func(t *testing.T) {
dir, cleanup := test.CreateTestDirectory(t) path := filepath.Join(t.TempDir(), "fake.mp3")
defer cleanup()
path := filepath.Join(dir, "fake.mp3")
test.CreateTestFile(t, path) test.CreateTestFile(t, path)
req := AudioRequest{ req := AudioRequest{

View File

@@ -7,6 +7,7 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"path/filepath"
"testing" "testing"
"time" "time"
@@ -86,24 +87,17 @@ func TestImageEdit(t *testing.T) {
defer teardown() defer teardown()
server.RegisterHandler("/v1/images/edits", handleEditImageEndpoint) server.RegisterHandler("/v1/images/edits", handleEditImageEndpoint)
origin, err := os.Create("image.png") origin, err := os.Create(filepath.Join(t.TempDir(), "image.png"))
if err != nil { if err != nil {
t.Error("open origin file error") t.Fatalf("open origin file error: %v", err)
return
} }
defer origin.Close()
mask, err := os.Create("mask.png") mask, err := os.Create(filepath.Join(t.TempDir(), "mask.png"))
if err != nil { if err != nil {
t.Error("open mask file error") t.Fatalf("open mask file error: %v", err)
return
} }
defer mask.Close()
defer func() {
mask.Close()
origin.Close()
os.Remove("mask.png")
os.Remove("image.png")
}()
_, err = client.CreateEditImage(context.Background(), openai.ImageEditRequest{ _, err = client.CreateEditImage(context.Background(), openai.ImageEditRequest{
Image: origin, Image: origin,
@@ -121,16 +115,11 @@ func TestImageEditWithoutMask(t *testing.T) {
defer teardown() defer teardown()
server.RegisterHandler("/v1/images/edits", handleEditImageEndpoint) server.RegisterHandler("/v1/images/edits", handleEditImageEndpoint)
origin, err := os.Create("image.png") origin, err := os.Create(filepath.Join(t.TempDir(), "image.png"))
if err != nil { if err != nil {
t.Error("open origin file error") t.Fatalf("open origin file error: %v", err)
return
} }
defer origin.Close()
defer func() {
origin.Close()
os.Remove("image.png")
}()
_, err = client.CreateEditImage(context.Background(), openai.ImageEditRequest{ _, err = client.CreateEditImage(context.Background(), openai.ImageEditRequest{
Image: origin, Image: origin,
@@ -178,16 +167,11 @@ func TestImageVariation(t *testing.T) {
defer teardown() defer teardown()
server.RegisterHandler("/v1/images/variations", handleVariateImageEndpoint) server.RegisterHandler("/v1/images/variations", handleVariateImageEndpoint)
origin, err := os.Create("image.png") origin, err := os.Create(filepath.Join(t.TempDir(), "image.png"))
if err != nil { if err != nil {
t.Error("open origin file error") t.Fatalf("open origin file error: %v", err)
return
} }
defer origin.Close()
defer func() {
origin.Close()
os.Remove("image.png")
}()
_, err = client.CreateVariImage(context.Background(), openai.ImageVariRequest{ _, err = client.CreateVariImage(context.Background(), openai.ImageVariRequest{
Image: origin, Image: origin,

View File

@@ -1,7 +1,6 @@
package openai //nolint:testpackage // testing private field package openai //nolint:testpackage // testing private field
import ( import (
"github.com/sashabaranov/go-openai/internal/test"
"github.com/sashabaranov/go-openai/internal/test/checks" "github.com/sashabaranov/go-openai/internal/test/checks"
"bytes" "bytes"
@@ -20,15 +19,11 @@ func (*failingWriter) Write([]byte) (int, error) {
} }
func TestFormBuilderWithFailingWriter(t *testing.T) { func TestFormBuilderWithFailingWriter(t *testing.T) {
dir, cleanup := test.CreateTestDirectory(t) file, err := os.CreateTemp(t.TempDir(), "")
defer cleanup()
file, err := os.CreateTemp(dir, "")
if err != nil { if err != nil {
t.Errorf("Error creating tmp file: %v", err) t.Fatalf("Error creating tmp file: %v", err)
} }
defer file.Close() defer file.Close()
defer os.Remove(file.Name())
builder := NewFormBuilder(&failingWriter{}) builder := NewFormBuilder(&failingWriter{})
err = builder.CreateFormFile("file", file) err = builder.CreateFormFile("file", file)
@@ -36,15 +31,11 @@ func TestFormBuilderWithFailingWriter(t *testing.T) {
} }
func TestFormBuilderWithClosedFile(t *testing.T) { func TestFormBuilderWithClosedFile(t *testing.T) {
dir, cleanup := test.CreateTestDirectory(t) file, err := os.CreateTemp(t.TempDir(), "")
defer cleanup()
file, err := os.CreateTemp(dir, "")
if err != nil { if err != nil {
t.Errorf("Error creating tmp file: %v", err) t.Fatalf("Error creating tmp file: %v", err)
} }
file.Close() file.Close()
defer os.Remove(file.Name())
body := &bytes.Buffer{} body := &bytes.Buffer{}
builder := NewFormBuilder(body) builder := NewFormBuilder(body)

View File

@@ -19,16 +19,6 @@ func CreateTestFile(t *testing.T, path string) {
file.Close() file.Close()
} }
// CreateTestDirectory creates a temporary folder which will be deleted when cleanup is called.
func CreateTestDirectory(t *testing.T) (path string, cleanup func()) {
t.Helper()
path, err := os.MkdirTemp(os.TempDir(), "")
checks.NoError(t, err)
return path, func() { os.RemoveAll(path) }
}
// TokenRoundTripper is a struct that implements the RoundTripper // TokenRoundTripper is a struct that implements the RoundTripper
// interface, specifically to handle the authentication token by adding a token // interface, specifically to handle the authentication token by adding a token
// to the request header. We need this because the API requires that each // to the request header. We need this because the API requires that each

View File

@@ -31,7 +31,7 @@ func setupAzureTestServer() (client *openai.Client, server *test.ServerTest, tea
// This function approximates based on the rule of thumb stated by OpenAI: // This function approximates based on the rule of thumb stated by OpenAI:
// https://beta.openai.com/tokenizer // https://beta.openai.com/tokenizer
// //
// TODO: implement an actual tokenizer for GPT-3 and Codex (once available) // TODO: implement an actual tokenizer for GPT-3 and Codex (once available).
func numTokens(s string) int { func numTokens(s string) int {
return int(float32(len(s)) / 4) return int(float32(len(s)) / 4)
} }

View File

@@ -21,10 +21,8 @@ func TestSpeechIntegration(t *testing.T) {
defer teardown() defer teardown()
server.RegisterHandler("/v1/audio/speech", func(w http.ResponseWriter, r *http.Request) { server.RegisterHandler("/v1/audio/speech", func(w http.ResponseWriter, r *http.Request) {
dir, cleanup := test.CreateTestDirectory(t) path := filepath.Join(t.TempDir(), "fake.mp3")
path := filepath.Join(dir, "fake.mp3")
test.CreateTestFile(t, path) test.CreateTestFile(t, path)
defer cleanup()
// audio endpoints only accept POST requests // audio endpoints only accept POST requests
if r.Method != "POST" { if r.Method != "POST" {