Skip to content
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

feature/maybe seed rng #509

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
29 changes: 26 additions & 3 deletions engines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,50 @@ import (
"testing"

. "github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/internal/test"
"github.com/sashabaranov/go-openai/internal/test/checks"
)

// Helper function to test the ListEngines endpoint.
func RandomEngine() Engine {
return Engine{
ID: test.RandomString(),
Object: test.RandomString(),
Owner: test.RandomString(),
Ready: test.RandomBool(),
}
}

// TestGetEngine Tests the retrieve engine endpoint of the API using the mocked server.
func TestGetEngine(t *testing.T) {
client, server, teardown := setupOpenAITestServer()
defer teardown()

expectedEngine := RandomEngine() // move outside of handler per code review comment
server.RegisterHandler("/v1/engines/text-davinci-003", func(w http.ResponseWriter, r *http.Request) {
resBytes, _ := json.Marshal(Engine{})
resBytes, _ := json.Marshal(expectedEngine)
fmt.Fprintln(w, string(resBytes))
})
_, err := client.GetEngine(context.Background(), "text-davinci-003")
actualEngine, err := client.GetEngine(context.Background(), "text-davinci-003")
checks.NoError(t, err, "GetEngine error")

// Compare the two using only one field per code review comment
if actualEngine.ID != expectedEngine.ID {
t.Errorf("Engine ID mismatch: got %s, expected %s", actualEngine.ID, expectedEngine.ID)
}
}

// TestListEngines Tests the list engines endpoint of the API using the mocked server.
func TestListEngines(t *testing.T) {
test.MaybeSeedRNG() // see docstring at internal/test/random.go
client, server, teardown := setupOpenAITestServer()
defer teardown()
server.RegisterHandler("/v1/engines", func(w http.ResponseWriter, r *http.Request) {
resBytes, _ := json.Marshal(EnginesList{})
engines := make([]Engine, test.RandomInt(5))
for i := range engines {
engines[i] = RandomEngine()
}
resBytes, _ := json.Marshal(EnginesList{Engines: engines})
fmt.Fprintln(w, string(resBytes))
})
_, err := client.ListEngines(context.Background())
Expand Down
68 changes: 68 additions & 0 deletions internal/test/random.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package test

import (
"math/rand"
"os"
"strconv"
"strings"
"time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const strLen = 10

// #nosec G404
var r = rand.New(rand.NewSource(time.Now().UnixNano()))

// Seeding func.
// #nosec G404
func Seed(s int64) {
r = rand.New(rand.NewSource(s))
}

// See StackOverflow answer:
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
// RandomString generates a random string of length
// strLen.
func RandomString() string {
sb := strings.Builder{}
sb.Grow(strLen)

for i := 0; i < strLen; i++ {
randomIndex := r.Intn(len(letters))
sb.WriteByte(letters[randomIndex])
}

return sb.String()
}

// RandomInt generates a random integer between 0 (inclusive) and 'max'
// (exclusive).
func RandomInt(max int) int {
return r.Intn(max)
}

// RandomBool generates a random boolean value.
// #nosec G404
func RandomBool() bool {
n := 2 // #gomnd (golangci-lint magic number suppression)
return r.Intn(n) == 1
}

// MaybeSeedRNG optionally seeds the random number generator based on the
// TEST_RNG_SEED environment variable. If TEST_RNG_SEED is set to an integer
// value, the RNG is seeded with that value. If it's set to "random", the RNG
// is seeded using the current time. If the variable is not set or contains an
// invalid value, the RNG remains unseeded and retains its default behavior.
func MaybeSeedRNG() {
seedEnv := os.Getenv("TEST_RNG_SEED")

if seedValue, err := strconv.ParseInt(seedEnv, 10, 64); err == nil {
rand.Seed(seedValue)
return
}

if seedEnv == "random" {
rand.Seed(time.Now().UnixNano())
}
}
Loading