From 277ce40a878266af84e22c7cffabdb3c21330ea1 Mon Sep 17 00:00:00 2001 From: k1LoW Date: Sun, 21 Apr 2024 17:23:39 +0900 Subject: [PATCH] Add test for response with already closed body --- responses/validate_body_test.go | 57 ++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/responses/validate_body_test.go b/responses/validate_body_test.go index bb9c682..184f169 100644 --- a/responses/validate_body_test.go +++ b/responses/validate_body_test.go @@ -7,13 +7,15 @@ import ( "bytes" "encoding/json" "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + "github.com/pb33f/libopenapi" "github.com/pb33f/libopenapi-validator/helpers" "github.com/pb33f/libopenapi-validator/paths" "github.com/stretchr/testify/assert" - "net/http" - "net/http/httptest" - "testing" ) func TestValidateBody_MissingContentType(t *testing.T) { @@ -374,7 +376,7 @@ paths: //assert.Len(t, errors[0].SchemaValidationErrors, 2) } -func TestValidateBody_InvalidResponse(t *testing.T) { +func TestValidateBody_InvalidResponseNil(t *testing.T) { spec := `openapi: 3.1.0 paths: /burgers/createBurger: @@ -419,6 +421,53 @@ paths: assert.Len(t, errors, 1) } +func TestValidateBody_InvalidResponseAlreadyClosed(t *testing.T) { + spec := `openapi: 3.1.0 +paths: + /burgers/createBurger: + post: + responses: + '200': + content: + application/json: + schema: + type: object + properties: + name: + type: string + patties: + type: integer + vegetarian: + type: boolean` + + doc, _ := libopenapi.NewDocument([]byte(spec)) + + m, _ := doc.BuildV3Model() + v := NewResponseBodyValidator(&m.Model) + + // build a request + request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", http.NoBody) + request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) + + // invalid response + body := io.NopCloser(bytes.NewReader([]byte("hello"))) + response := &http.Response{ + Header: http.Header{}, + StatusCode: http.StatusOK, + Body: body, + } + body.Close() // close the body + response.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType) + + // validate! + valid, errors := v.ValidateResponseBody(request, response) + // doubletap to hit cache + _, _ = v.ValidateResponseBody(request, response) + + assert.False(t, valid) + assert.Len(t, errors, 1) +} + func TestValidateBody_InvalidBasicSchema_SetPath(t *testing.T) { spec := `openapi: 3.1.0 paths: