openai_test.go 6.29 KB
Newer Older
1
2
3
4
5
6
7
8
package openai

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
9
	"strings"
10
11
12
13
14
15
16
17
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/ollama/ollama/api"
	"github.com/stretchr/testify/assert"
)

royjhan's avatar
royjhan committed
18
func TestMiddlewareRequests(t *testing.T) {
19
20
21
22
23
24
	type testCase struct {
		Name     string
		Method   string
		Path     string
		Handler  func() gin.HandlerFunc
		Setup    func(t *testing.T, req *http.Request)
royjhan's avatar
royjhan committed
25
		Expected func(t *testing.T, req *http.Request)
26
27
	}

royjhan's avatar
royjhan committed
28
	var capturedRequest *http.Request
29

royjhan's avatar
royjhan committed
30
31
32
33
34
35
36
37
	captureRequestMiddleware := func() gin.HandlerFunc {
		return func(c *gin.Context) {
			bodyBytes, _ := io.ReadAll(c.Request.Body)
			c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
			capturedRequest = c.Request
			c.Next()
		}
	}
38

royjhan's avatar
royjhan committed
39
40
41
42
43
44
	testCases := []testCase{
		{
			Name:    "chat handler",
			Method:  http.MethodPost,
			Path:    "/api/chat",
			Handler: ChatMiddleware,
45
46
47
48
49
50
51
52
53
54
55
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model:    "test-model",
					Messages: []Message{{Role: "user", Content: "Hello"}},
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
royjhan's avatar
royjhan committed
56
57
58
			Expected: func(t *testing.T, req *http.Request) {
				var chatReq api.ChatRequest
				if err := json.NewDecoder(req.Body).Decode(&chatReq); err != nil {
59
60
61
					t.Fatal(err)
				}

royjhan's avatar
royjhan committed
62
63
				if chatReq.Messages[0].Role != "user" {
					t.Fatalf("expected 'user', got %s", chatReq.Messages[0].Role)
64
65
				}

royjhan's avatar
royjhan committed
66
67
				if chatReq.Messages[0].Content != "Hello" {
					t.Fatalf("expected 'Hello', got %s", chatReq.Messages[0].Content)
68
69
70
				}
			},
		},
71
		{
royjhan's avatar
royjhan committed
72
73
74
75
			Name:    "completions handler",
			Method:  http.MethodPost,
			Path:    "/api/generate",
			Handler: CompletionsMiddleware,
76
			Setup: func(t *testing.T, req *http.Request) {
royjhan's avatar
royjhan committed
77
				temp := float32(0.8)
78
				body := CompletionRequest{
royjhan's avatar
royjhan committed
79
80
81
					Model:       "test-model",
					Prompt:      "Hello",
					Temperature: &temp,
82
83
84
85
86
87
88
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
royjhan's avatar
royjhan committed
89
90
91
			Expected: func(t *testing.T, req *http.Request) {
				var genReq api.GenerateRequest
				if err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {
92
93
94
					t.Fatal(err)
				}

royjhan's avatar
royjhan committed
95
96
				if genReq.Prompt != "Hello" {
					t.Fatalf("expected 'Hello', got %s", genReq.Prompt)
97
98
				}

royjhan's avatar
royjhan committed
99
100
				if genReq.Options["temperature"] != 1.6 {
					t.Fatalf("expected 1.6, got %f", genReq.Options["temperature"])
101
102
103
				}
			},
		},
royjhan's avatar
royjhan committed
104
	}
105

royjhan's avatar
royjhan committed
106
107
	gin.SetMode(gin.TestMode)
	router := gin.New()
108

royjhan's avatar
royjhan committed
109
110
111
	endpoint := func(c *gin.Context) {
		c.Status(http.StatusOK)
	}
112

royjhan's avatar
royjhan committed
113
114
115
116
117
118
119
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			router = gin.New()
			router.Use(captureRequestMiddleware())
			router.Use(tc.Handler())
			router.Handle(tc.Method, tc.Path, endpoint)
			req, _ := http.NewRequest(tc.Method, tc.Path, nil)
120

royjhan's avatar
royjhan committed
121
122
123
			if tc.Setup != nil {
				tc.Setup(t, req)
			}
124

royjhan's avatar
royjhan committed
125
126
			resp := httptest.NewRecorder()
			router.ServeHTTP(resp, req)
127

royjhan's avatar
royjhan committed
128
129
130
131
			tc.Expected(t, capturedRequest)
		})
	}
}
132

royjhan's avatar
royjhan committed
133
134
135
136
137
138
139
140
141
142
143
144
145
func TestMiddlewareResponses(t *testing.T) {
	type testCase struct {
		Name     string
		Method   string
		Path     string
		TestPath string
		Handler  func() gin.HandlerFunc
		Endpoint func(c *gin.Context)
		Setup    func(t *testing.T, req *http.Request)
		Expected func(t *testing.T, resp *httptest.ResponseRecorder)
	}

	testCases := []testCase{
146
		{
royjhan's avatar
royjhan committed
147
			Name:     "completions handler error forwarding",
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
			Method:   http.MethodPost,
			Path:     "/api/generate",
			TestPath: "/api/generate",
			Handler:  CompletionsMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
			},
			Setup: func(t *testing.T, req *http.Request) {
				body := CompletionRequest{
					Model:  "test-model",
					Prompt: "Hello",
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusBadRequest {
					t.Fatalf("expected 400, got %d", resp.Code)
				}

				if !strings.Contains(resp.Body.String(), `"invalid request"`) {
					t.Fatalf("error was not forwarded")
				}
			},
		},
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
		{
			Name:     "list handler",
			Method:   http.MethodGet,
			Path:     "/api/tags",
			TestPath: "/api/tags",
			Handler:  ListMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusOK, api.ListResponse{
					Models: []api.ListModelResponse{
						{
							Name: "Test Model",
						},
					},
				})
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
192
193
				assert.Equal(t, http.StatusOK, resp.Code)

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
				var listResp ListCompletion
				if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
					t.Fatal(err)
				}

				if listResp.Object != "list" {
					t.Fatalf("expected list, got %s", listResp.Object)
				}

				if len(listResp.Data) != 1 {
					t.Fatalf("expected 1, got %d", len(listResp.Data))
				}

				if listResp.Data[0].Id != "Test Model" {
					t.Fatalf("expected Test Model, got %s", listResp.Data[0].Id)
				}
			},
		},
		{
			Name:     "retrieve model",
			Method:   http.MethodGet,
			Path:     "/api/show/:model",
			TestPath: "/api/show/test-model",
			Handler:  RetrieveMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusOK, api.ShowResponse{
					ModifiedAt: time.Date(2024, 6, 17, 13, 45, 0, 0, time.UTC),
				})
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
				var retrieveResp Model
				if err := json.NewDecoder(resp.Body).Decode(&retrieveResp); err != nil {
					t.Fatal(err)
				}

				if retrieveResp.Object != "model" {
					t.Fatalf("Expected object to be model, got %s", retrieveResp.Object)
				}

				if retrieveResp.Id != "test-model" {
					t.Fatalf("Expected id to be test-model, got %s", retrieveResp.Id)
				}
			},
		},
	}

	gin.SetMode(gin.TestMode)
	router := gin.New()

	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			router = gin.New()
			router.Use(tc.Handler())
			router.Handle(tc.Method, tc.Path, tc.Endpoint)
			req, _ := http.NewRequest(tc.Method, tc.TestPath, nil)

			if tc.Setup != nil {
				tc.Setup(t, req)
			}

			resp := httptest.NewRecorder()
			router.ServeHTTP(resp, req)

			tc.Expected(t, resp)
		})
	}
}