-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswagger_test.go
More file actions
319 lines (262 loc) · 7.8 KB
/
swagger_test.go
File metadata and controls
319 lines (262 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// SPDX-License-Identifier: EUPL-1.2
package api_test
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
api "dappco.re/go/core/api"
)
// ── Swagger endpoint ────────────────────────────────────────────────────
func TestSwaggerEndpoint_Good(t *testing.T) {
gin.SetMode(gin.TestMode)
e, err := api.New(api.WithSwagger("Test API", "A test API service", "1.0.0"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Use a real test server because gin-swagger reads RequestURI
// which is not populated by httptest.NewRecorder.
srv := httptest.NewServer(e.Handler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/swagger/doc.json")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
if len(body) == 0 {
t.Fatal("expected non-empty response body")
}
// Verify the body is valid JSON with expected fields.
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatalf("expected valid JSON, got unmarshal error: %v", err)
}
info, ok := doc["info"].(map[string]any)
if !ok {
t.Fatal("expected 'info' object in swagger doc")
}
if info["title"] != "Test API" {
t.Fatalf("expected title=%q, got %q", "Test API", info["title"])
}
if info["version"] != "1.0.0" {
t.Fatalf("expected version=%q, got %q", "1.0.0", info["version"])
}
}
func TestSwaggerDisabledByDefault_Good(t *testing.T) {
gin.SetMode(gin.TestMode)
// Without WithSwagger, GET /swagger/doc.json should return 404.
e, _ := api.New()
h := e.Handler()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404 for /swagger/doc.json without WithSwagger, got %d", w.Code)
}
}
func TestSwagger_Good_SpecNotEmpty(t *testing.T) {
gin.SetMode(gin.TestMode)
e, err := api.New(api.WithSwagger("Test API", "Test", "1.0.0"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Register a describable group so paths has more than just /health.
bridge := api.NewToolBridge("/tools")
bridge.Add(api.ToolDescriptor{
Name: "file_read",
Description: "Read a file",
Group: "files",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"path": map[string]any{"type": "string"},
},
},
}, func(c *gin.Context) {
c.JSON(http.StatusOK, api.OK("ok"))
})
e.Register(bridge)
srv := httptest.NewServer(e.Handler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/swagger/doc.json")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
paths, ok := doc["paths"].(map[string]any)
if !ok {
t.Fatal("expected 'paths' object in spec")
}
// Must have more than just /health since we registered a tool.
if len(paths) < 2 {
t.Fatalf("expected at least 2 paths (got %d): /health + tool endpoint", len(paths))
}
if _, ok := paths["/tools/file_read"]; !ok {
t.Fatal("expected /tools/file_read path in spec")
}
}
func TestSwagger_Good_WithToolBridge(t *testing.T) {
gin.SetMode(gin.TestMode)
e, err := api.New(api.WithSwagger("Tool API", "Tool test", "1.0.0"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
bridge := api.NewToolBridge("/api/tools")
bridge.Add(api.ToolDescriptor{
Name: "metrics_query",
Description: "Query metrics data",
Group: "metrics",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{"type": "string"},
},
},
}, func(c *gin.Context) {
c.JSON(http.StatusOK, api.OK("ok"))
})
e.Register(bridge)
srv := httptest.NewServer(e.Handler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/swagger/doc.json")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
paths := doc["paths"].(map[string]any)
if _, ok := paths["/api/tools/metrics_query"]; !ok {
t.Fatal("expected /api/tools/metrics_query path in spec")
}
// Verify the operation has the expected summary.
toolPath := paths["/api/tools/metrics_query"].(map[string]any)
postOp := toolPath["post"].(map[string]any)
if postOp["summary"] != "Query metrics data" {
t.Fatalf("expected summary=%q, got %v", "Query metrics data", postOp["summary"])
}
}
func TestSwagger_Good_CachesSpec(t *testing.T) {
spec := &swaggerSpecHelper{
title: "Cache Test",
desc: "Testing cache",
version: "0.1.0",
}
first := spec.ReadDoc()
second := spec.ReadDoc()
if first != second {
t.Fatal("expected ReadDoc() to return the same string on repeated calls")
}
if first == "" {
t.Fatal("expected non-empty spec from ReadDoc()")
}
}
func TestSwagger_Good_InfoFromOptions(t *testing.T) {
gin.SetMode(gin.TestMode)
e, err := api.New(api.WithSwagger("MyTitle", "MyDesc", "2.0.0"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
srv := httptest.NewServer(e.Handler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/swagger/doc.json")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := doc["info"].(map[string]any)
if info["title"] != "MyTitle" {
t.Fatalf("expected title=%q, got %v", "MyTitle", info["title"])
}
if info["description"] != "MyDesc" {
t.Fatalf("expected description=%q, got %v", "MyDesc", info["description"])
}
if info["version"] != "2.0.0" {
t.Fatalf("expected version=%q, got %v", "2.0.0", info["version"])
}
}
func TestSwagger_Good_ValidOpenAPI(t *testing.T) {
gin.SetMode(gin.TestMode)
e, err := api.New(api.WithSwagger("OpenAPI Test", "Verify version", "1.0.0"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
srv := httptest.NewServer(e.Handler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/swagger/doc.json")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if doc["openapi"] != "3.1.0" {
t.Fatalf("expected openapi=%q, got %v", "3.1.0", doc["openapi"])
}
}
// swaggerSpecHelper exercises the caching behaviour of swaggerSpec
// without depending on unexported internals. It creates a SpecBuilder
// inline and uses sync.Once the same way the real swaggerSpec does.
type swaggerSpecHelper struct {
title, desc, version string
called int
cache string
}
func (h *swaggerSpecHelper) ReadDoc() string {
if h.cache != "" {
return h.cache
}
h.called++
sb := &api.SpecBuilder{
Title: h.title,
Description: h.desc,
Version: h.version,
}
data, err := sb.Build(nil)
if err != nil {
h.cache = `{"openapi":"3.1.0","info":{"title":"error","version":"0.0.0"},"paths":{}}`
return h.cache
}
h.cache = string(data)
return h.cache
}