-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathput_test.go
More file actions
423 lines (386 loc) · 12.8 KB
/
put_test.go
File metadata and controls
423 lines (386 loc) · 12.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package fiberoapi
import (
"fmt"
"io"
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v2"
)
// Test structs pour PUT
type PutUserInput struct {
ID string `path:"id" validate:"required"`
Username string `json:"username" validate:"omitempty,min=3,max=20,alphanum"`
Email string `json:"email" validate:"omitempty,email"`
Age int `json:"age" validate:"omitempty,min=13,max=120"`
Bio string `json:"bio" validate:"omitempty,max=500"`
}
type PutProductInput struct {
CategoryID string `path:"categoryId" validate:"required,uuid4"`
ProductID string `path:"productId" validate:"required,uuid4"`
Name string `json:"name" validate:"omitempty,min=2,max=100"`
Description string `json:"description" validate:"omitempty,max=1000"`
Price float64 `json:"price" validate:"omitempty,min=0"`
Quantity int `json:"quantity" validate:"omitempty,min=0"`
Tags []string `json:"tags" validate:"omitempty,dive,min=1,max=20"`
}
type PutOutput struct {
ID string `json:"id"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Updated bool `json:"updated"`
}
type PutError struct {
StatusCode int `json:"statusCode"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
}
func TestPutOApi_SimplePut(t *testing.T) {
app := fiber.New()
oapi := New(app)
// Test with simple PUT (path param + JSON body)
Put(oapi, "/users/:id", func(c *fiber.Ctx, input PutUserInput) (PutOutput, PutError) {
return PutOutput{
ID: input.ID,
Message: fmt.Sprintf("User %s updated successfully", input.ID),
Data: map[string]interface{}{
"username": input.Username,
"email": input.Email,
"age": input.Age,
"bio": input.Bio,
},
Updated: true,
}, PutError{}
}, OpenAPIOptions{
OperationID: "update-user",
Summary: "Update an existing user",
Tags: []string{"users"},
})
// Test with valid data
body := `{"username":"john123","email":"john@example.com","age":25,"bio":"Updated bio"}`
req := httptest.NewRequest("PUT", "/users/user123", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
respBody, _ := io.ReadAll(resp.Body)
respStr := string(respBody)
if !strings.Contains(respStr, `"id":"user123"`) {
t.Errorf("Expected response to contain user ID, got %s", respStr)
}
if !strings.Contains(respStr, `"updated":true`) {
t.Errorf("Expected response to contain updated flag, got %s", respStr)
}
if !strings.Contains(respStr, `"username":"john123"`) {
t.Errorf("Expected response to contain username, got %s", respStr)
}
}
func TestPutOApi_MultiplePathParams(t *testing.T) {
app := fiber.New()
oapi := New(app)
// Test with PUT + multiple path parameters
Put(oapi, "/categories/:categoryId/products/:productId", func(c *fiber.Ctx, input PutProductInput) (PutOutput, PutError) {
return PutOutput{
ID: input.ProductID,
Message: fmt.Sprintf("Product %s updated in category %s", input.ProductID, input.CategoryID),
Data: map[string]interface{}{
"categoryId": input.CategoryID,
"productId": input.ProductID,
"name": input.Name,
"price": input.Price,
"quantity": input.Quantity,
"tags": input.Tags,
},
Updated: true,
}, PutError{}
}, OpenAPIOptions{
OperationID: "update-product",
Summary: "Update a product",
Tags: []string{"products"},
})
// Test with valid data
body := `{"name":"Updated Laptop","description":"Gaming laptop updated","price":1199.99,"quantity":15,"tags":["gaming","electronics","updated"]}`
req := httptest.NewRequest("PUT", "/categories/550e8400-e29b-41d4-a716-446655440000/products/550e8400-e29b-41d4-a716-446655440001", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
respBody, _ := io.ReadAll(resp.Body)
respStr := string(respBody)
if !strings.Contains(respStr, `"categoryId":"550e8400-e29b-41d4-a716-446655440000"`) {
t.Errorf("Expected response to contain category ID, got %s", respStr)
}
if !strings.Contains(respStr, `"productId":"550e8400-e29b-41d4-a716-446655440001"`) {
t.Errorf("Expected response to contain product ID, got %s", respStr)
}
if !strings.Contains(respStr, `"name":"Updated Laptop"`) {
t.Errorf("Expected response to contain updated name, got %s", respStr)
}
}
func TestPutOApi_Validation(t *testing.T) {
app := fiber.New()
oapi := New(app)
Put(oapi, "/users/:id", func(c *fiber.Ctx, input PutUserInput) (PutOutput, PutError) {
return PutOutput{
ID: input.ID,
Message: "User updated",
Updated: true,
}, PutError{}
}, OpenAPIOptions{
OperationID: "update-user-validation",
Summary: "Update user with validation",
})
tests := []struct {
name string
url string
body string
expectedStatus int
shouldPass bool
errorContains string
}{
{
name: "Valid partial update",
url: "/users/user123",
body: `{"username":"alice123","email":"alice@example.com"}`,
expectedStatus: 200,
shouldPass: true,
},
{
name: "Valid single field update",
url: "/users/user456",
body: `{"age":30}`,
expectedStatus: 200,
shouldPass: true,
},
{
name: "Valid empty body (all fields optional)",
url: "/users/user789",
body: `{}`,
expectedStatus: 200,
shouldPass: true,
},
{
name: "Username too short",
url: "/users/user123",
body: `{"username":"al"}`,
expectedStatus: 400,
shouldPass: false,
errorContains: "min",
},
{
name: "Invalid email format",
url: "/users/user123",
body: `{"email":"not-an-email"}`,
expectedStatus: 400,
shouldPass: false,
errorContains: "email",
},
{
name: "Age too young",
url: "/users/user123",
body: `{"age":10}`,
expectedStatus: 400,
shouldPass: false,
errorContains: "min",
},
{
name: "Bio too long",
url: "/users/user123",
body: fmt.Sprintf(`{"bio":"%s"}`, strings.Repeat("a", 501)),
expectedStatus: 400,
shouldPass: false,
errorContains: "max",
},
{
name: "Invalid JSON",
url: "/users/user123",
body: `{"username":"alice123","email":"alice@example.com",}`,
expectedStatus: 400,
shouldPass: false,
errorContains: "validation_error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("PUT", tt.url, strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp.StatusCode != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
if tt.shouldPass {
if !strings.Contains(bodyStr, "User updated") {
t.Errorf("Expected success message, got %s", bodyStr)
}
} else {
if !strings.Contains(bodyStr, "validation_error") {
t.Errorf("Expected validation error, got %s", bodyStr)
}
if tt.errorContains != "" && !strings.Contains(bodyStr, tt.errorContains) {
t.Errorf("Expected error to contain '%s', got %s", tt.errorContains, bodyStr)
}
}
})
}
}
func TestPutOApi_ErrorHandling(t *testing.T) {
app := fiber.New()
oapi := New(app)
// Test with custom error handling
Put(oapi, "/users/:id", func(c *fiber.Ctx, input PutUserInput) (PutOutput, PutError) {
if input.ID == "notfound" {
return PutOutput{}, PutError{
StatusCode: 404,
Message: "User not found",
Details: "The specified user does not exist",
}
}
if input.ID == "readonly" {
return PutOutput{}, PutError{
StatusCode: 403,
Message: "User is read-only",
Details: "This user cannot be modified",
}
}
if input.Username == "taken" {
return PutOutput{}, PutError{
StatusCode: 409,
Message: "Username already taken",
Details: "Please choose a different username",
}
}
return PutOutput{
ID: input.ID,
Message: "User updated successfully",
Updated: true,
}, PutError{}
}, OpenAPIOptions{
OperationID: "update-user-with-errors",
Summary: "Update user with custom error handling",
})
// Test 1: User not found
body1 := `{"username":"newname","email":"test@example.com"}`
req1 := httptest.NewRequest("PUT", "/users/notfound", strings.NewReader(body1))
req1.Header.Set("Content-Type", "application/json")
resp1, err := app.Test(req1)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp1.StatusCode != 404 {
t.Errorf("Expected status 404, got %d", resp1.StatusCode)
}
body1Resp, _ := io.ReadAll(resp1.Body)
if !strings.Contains(string(body1Resp), "User not found") {
t.Errorf("Expected not found error message, got %s", string(body1Resp))
}
// Test 2: Read-only user
body2 := `{"username":"newname","email":"test@example.com"}`
req2 := httptest.NewRequest("PUT", "/users/readonly", strings.NewReader(body2))
req2.Header.Set("Content-Type", "application/json")
resp2, err := app.Test(req2)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp2.StatusCode != 403 {
t.Errorf("Expected status 403, got %d", resp2.StatusCode)
}
body2Resp, _ := io.ReadAll(resp2.Body)
if !strings.Contains(string(body2Resp), "User is read-only") {
t.Errorf("Expected read-only error message, got %s", string(body2Resp))
}
// Test 3: Username taken
body3 := `{"username":"taken"}`
req3 := httptest.NewRequest("PUT", "/users/user123", strings.NewReader(body3))
req3.Header.Set("Content-Type", "application/json")
resp3, err := app.Test(req3)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp3.StatusCode != 409 {
t.Errorf("Expected status 409, got %d", resp3.StatusCode)
}
body3Resp, _ := io.ReadAll(resp3.Body)
if !strings.Contains(string(body3Resp), "Username already taken") {
t.Errorf("Expected username taken error message, got %s", string(body3Resp))
}
// Test 4: Success case
body4 := `{"username":"validname","email":"valid@example.com"}`
req4 := httptest.NewRequest("PUT", "/users/user123", strings.NewReader(body4))
req4.Header.Set("Content-Type", "application/json")
resp4, err := app.Test(req4)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if resp4.StatusCode != 200 {
t.Errorf("Expected status 200, got %d", resp4.StatusCode)
}
body4Resp, _ := io.ReadAll(resp4.Body)
if !strings.Contains(string(body4Resp), "User updated successfully") {
t.Errorf("Expected success message, got %s", string(body4Resp))
}
if !strings.Contains(string(body4Resp), `"updated":true`) {
t.Errorf("Expected updated flag, got %s", string(body4Resp))
}
}
func TestPutOApi_OperationStorage(t *testing.T) {
app := fiber.New()
oapi := New(app)
// Check that PUT operations are properly stored
initialCount := len(oapi.operations)
Put(oapi, "/test/:id", func(c *fiber.Ctx, input PutUserInput) (PutOutput, PutError) {
return PutOutput{Message: "test", Updated: true}, PutError{}
}, OpenAPIOptions{
OperationID: "test-put-operation",
Summary: "Test PUT operation",
Tags: []string{"test", "put"},
Description: "This is a test PUT operation",
})
// Check that an operation was added
if len(oapi.operations) != initialCount+1 {
t.Errorf("Expected %d operations, got %d", initialCount+1, len(oapi.operations))
}
// Check the operation content
lastOp := oapi.operations[len(oapi.operations)-1]
if lastOp.Method != "PUT" {
t.Errorf("Expected method PUT, got %s", lastOp.Method)
}
if lastOp.Path != "/test/:id" {
t.Errorf("Expected path /test/:id, got %s", lastOp.Path)
}
if lastOp.Options.OperationID != "test-put-operation" {
t.Errorf("Expected operationId test-put-operation, got %s", lastOp.Options.OperationID)
}
if lastOp.Options.Summary != "Test PUT operation" {
t.Errorf("Expected summary 'Test PUT operation', got %s", lastOp.Options.Summary)
}
if lastOp.Options.Description != "This is a test PUT operation" {
t.Errorf("Expected description 'This is a test PUT operation', got %s", lastOp.Options.Description)
}
// Check the tags
expectedTags := []string{"test", "put"}
for _, expectedTag := range expectedTags {
found := false
for _, tag := range lastOp.Options.Tags {
if tag == expectedTag {
found = true
break
}
}
if !found {
t.Errorf("Expected to find '%s' in tags, got %v", expectedTag, lastOp.Options.Tags)
}
}
}