Skip to content

Commit

Permalink
Add test for response with already closed body
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW committed Apr 21, 2024
1 parent 56f6c60 commit 277ce40
Showing 1 changed file with 53 additions and 4 deletions.
57 changes: 53 additions & 4 deletions responses/validate_body_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 277ce40

Please sign in to comment.