Skip to content

Commit 8127072

Browse files
authored
fix test server setup: (#549)
* fix test server setup: - go map access is not deterministic - this can lead to a route: /foo/bar/1 matching /foo/bar before matching /foo/bar/1 if the map iteration go through /foo/bar first since the regex match wasn't bound to start and end anchors - registering handlers now converts * in routes to .* for proper regex matching - test server route handling now tries to fully match the handler route * add missing /v1 prefix to fine-tuning job cancel test server handler
1 parent e3e065d commit 8127072

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

fine_tuning_job_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func TestFineTuningJob(t *testing.T) {
4242
)
4343

4444
server.RegisterHandler(
45-
"/fine_tuning/jobs/"+testFineTuninigJobID+"/cancel",
45+
"/v1/fine_tuning/jobs/"+testFineTuninigJobID+"/cancel",
4646
func(w http.ResponseWriter, _ *http.Request) {
4747
resBytes, _ := json.Marshal(openai.FineTuningJob{})
4848
fmt.Fprintln(w, string(resBytes))

internal/test/server.go

+8-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"net/http"
66
"net/http/httptest"
77
"regexp"
8+
"strings"
89
)
910

1011
const testAPI = "this-is-my-secure-token-do-not-steal!!"
@@ -23,13 +24,16 @@ func NewTestServer() *ServerTest {
2324
}
2425

2526
func (ts *ServerTest) RegisterHandler(path string, handler handler) {
27+
// to make the registered paths friendlier to a regex match in the route handler
28+
// in OpenAITestServer
29+
path = strings.ReplaceAll(path, "*", ".*")
2630
ts.handlers[path] = handler
2731
}
2832

2933
// OpenAITestServer Creates a mocked OpenAI server which can pretend to handle requests during testing.
3034
func (ts *ServerTest) OpenAITestServer() *httptest.Server {
3135
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
32-
log.Printf("received request at path %q\n", r.URL.Path)
36+
log.Printf("received a %s request at path %q\n", r.Method, r.URL.Path)
3337

3438
// check auth
3539
if r.Header.Get("Authorization") != "Bearer "+GetTestToken() && r.Header.Get("api-key") != GetTestToken() {
@@ -38,8 +42,10 @@ func (ts *ServerTest) OpenAITestServer() *httptest.Server {
3842
}
3943

4044
// Handle /path/* routes.
45+
// Note: the * is converted to a .* in register handler for proper regex handling
4146
for route, handler := range ts.handlers {
42-
pattern, _ := regexp.Compile(route)
47+
// Adding ^ and $ to make path matching deterministic since go map iteration isn't ordered
48+
pattern, _ := regexp.Compile("^" + route + "$")
4349
if pattern.MatchString(r.URL.Path) {
4450
handler(w, r)
4551
return

0 commit comments

Comments
 (0)