-
Notifications
You must be signed in to change notification settings - Fork 0
Improve JSON unmarshal error handling and add tests #21
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
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
82fc869
Fix: Improve JSON unmarshal error handling in parseInput function
moutonjeremy c02ec07
Test: Add JSON type mismatch error handling tests
moutonjeremy d48a68c
Fix: Update JSON request and response types in TestJSONTypeMismatchEr…
moutonjeremy 37e329c
Fix: Enhance JSON unmarshal error handling in parseInput function
moutonjeremy 96b1b3f
Fix: Add tests for JSON type mismatch error handling with wrapped errors
moutonjeremy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| package fiberoapi | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/gofiber/fiber/v2" | ||
| ) | ||
|
|
||
| // Test for JSON type mismatch errors | ||
| func TestJSONTypeMismatchErrors(t *testing.T) { | ||
| app := fiber.New() | ||
| oapi := New(app) | ||
|
|
||
| type CreateRequest struct { | ||
| Description string `json:"description,omitempty" validate:"omitempty,max=255"` | ||
| Ips []string `json:"ips,omitempty" validate:"dive,cidrv4|ip4_addr"` | ||
| } | ||
|
|
||
| type CreateResponse struct { | ||
| Message string `json:"message"` | ||
| } | ||
|
|
||
| Post(oapi, "/test", func(c *fiber.Ctx, input CreateRequest) (CreateResponse, TestError) { | ||
| return CreateResponse{Message: "created"}, TestError{} | ||
| }, OpenAPIOptions{ | ||
| OperationID: "create", | ||
| Summary: "Create a new entry", | ||
| }) | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| body string | ||
| expectedStatus int | ||
| errorContains string | ||
| }{ | ||
| { | ||
| name: "Valid request with string description", | ||
| body: `{"description": "A valid description"}`, | ||
| expectedStatus: 200, | ||
| }, | ||
| { | ||
| name: "Invalid request - description is a number", | ||
| body: `{"description": 0.0}`, | ||
| expectedStatus: 400, | ||
| errorContains: "invalid type for field 'description'", | ||
| }, | ||
| { | ||
| name: "Invalid request - description is an object", | ||
| body: `{"description": {"test": "test"}}`, | ||
| expectedStatus: 400, | ||
| errorContains: "invalid type for field 'description'", | ||
| }, | ||
| { | ||
| name: "Invalid request - ips contains number", | ||
| body: `{"ips": [123]}`, | ||
| expectedStatus: 400, | ||
| errorContains: "invalid type", | ||
| }, | ||
| { | ||
| name: "Valid request with empty body", | ||
| body: `{}`, | ||
| expectedStatus: 200, | ||
| }, | ||
| { | ||
| name: "Valid request with valid IPs", | ||
| body: `{"description": "Test", "ips": ["192.168.1.0/24", "10.0.0.1"]}`, | ||
| expectedStatus: 200, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| req := httptest.NewRequest("POST", "/test", 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) | ||
| } | ||
|
|
||
| body, _ := io.ReadAll(resp.Body) | ||
| bodyStr := string(body) | ||
|
|
||
| if resp.StatusCode != tt.expectedStatus { | ||
| t.Errorf("Expected status %d, got %d. Body: %s", tt.expectedStatus, resp.StatusCode, bodyStr) | ||
| } | ||
|
|
||
| if tt.errorContains != "" { | ||
| if !strings.Contains(bodyStr, tt.errorContains) { | ||
| t.Errorf("Expected error to contain '%s', got %s", tt.errorContains, bodyStr) | ||
| } | ||
| // Ensure it returns validation_error type | ||
| if !strings.Contains(bodyStr, "validation_error") { | ||
| t.Errorf("Expected validation_error type, got %s", bodyStr) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // Test with custom validation error handler | ||
| func TestJSONTypeMismatchWithCustomHandler(t *testing.T) { | ||
| app := fiber.New() | ||
|
|
||
| // Create a custom validation error handler | ||
| customHandler := func(c *fiber.Ctx, err error) error { | ||
| return c.Status(422).JSON(fiber.Map{ | ||
| "status": "error", | ||
| "message": err.Error(), | ||
| }) | ||
| } | ||
|
|
||
| oapi := New(app, Config{ | ||
| ValidationErrorHandler: customHandler, | ||
| }) | ||
|
|
||
| type TestRequest struct { | ||
| Value string `json:"value"` | ||
| } | ||
|
|
||
| type TestResponse struct { | ||
| Result string `json:"result"` | ||
| } | ||
|
|
||
| Post(oapi, "/test", func(c *fiber.Ctx, input TestRequest) (TestResponse, TestError) { | ||
| return TestResponse{Result: "OK"}, TestError{} | ||
| }, OpenAPIOptions{}) | ||
|
|
||
| // Test with wrong type | ||
| req := httptest.NewRequest("POST", "/test", strings.NewReader(`{"value": 123}`)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| resp, err := app.Test(req) | ||
| if err != nil { | ||
| t.Fatalf("Expected no error, got %v", err) | ||
| } | ||
|
|
||
| // Should use custom handler status code | ||
| if resp.StatusCode != 422 { | ||
| t.Errorf("Expected status 422, got %d", resp.StatusCode) | ||
| } | ||
|
|
||
| body, _ := io.ReadAll(resp.Body) | ||
| bodyStr := string(body) | ||
|
|
||
| // Should contain custom error format | ||
| if !strings.Contains(bodyStr, "status") || !strings.Contains(bodyStr, "error") { | ||
| t.Errorf("Expected custom error format, got %s", bodyStr) | ||
| } | ||
|
|
||
| // Should still contain the error message about invalid type | ||
| if !strings.Contains(bodyStr, "invalid type") { | ||
| t.Errorf("Expected 'invalid type' in error message, got %s", bodyStr) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.