Skip to content

Commit 016b8cd

Browse files
k1LoWdaveshanley
authored andcommitted
Add test for invalid response body ( read error )
1 parent 285c6d3 commit 016b8cd

File tree

1 file changed

+60
-4
lines changed

1 file changed

+60
-4
lines changed

responses/validate_body_test.go

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ package responses
66
import (
77
"bytes"
88
"encoding/json"
9+
"errors"
910
"fmt"
11+
"net/http"
12+
"net/http/httptest"
13+
"testing"
14+
1015
"github.com/pb33f/libopenapi"
1116
"github.com/pb33f/libopenapi-validator/helpers"
1217
"github.com/pb33f/libopenapi-validator/paths"
1318
"github.com/stretchr/testify/assert"
14-
"net/http"
15-
"net/http/httptest"
16-
"testing"
1719
)
1820

1921
func TestValidateBody_MissingContentType(t *testing.T) {
@@ -374,7 +376,7 @@ paths:
374376
//assert.Len(t, errors[0].SchemaValidationErrors, 2)
375377
}
376378

377-
func TestValidateBody_InvalidResponse(t *testing.T) {
379+
func TestValidateBody_InvalidResponseBodyNil(t *testing.T) {
378380
spec := `openapi: 3.1.0
379381
paths:
380382
/burgers/createBurger:
@@ -419,6 +421,51 @@ paths:
419421
assert.Len(t, errors, 1)
420422
}
421423

424+
func TestValidateBody_InvalidResponseBodyError(t *testing.T) {
425+
spec := `openapi: 3.1.0
426+
paths:
427+
/burgers/createBurger:
428+
post:
429+
responses:
430+
'200':
431+
content:
432+
application/json:
433+
schema:
434+
type: object
435+
properties:
436+
name:
437+
type: string
438+
patties:
439+
type: integer
440+
vegetarian:
441+
type: boolean`
442+
443+
doc, _ := libopenapi.NewDocument([]byte(spec))
444+
445+
m, _ := doc.BuildV3Model()
446+
v := NewResponseBodyValidator(&m.Model)
447+
448+
// build a request
449+
request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", http.NoBody)
450+
request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
451+
452+
// invalid response
453+
response := &http.Response{
454+
Header: http.Header{},
455+
StatusCode: http.StatusOK,
456+
Body: &errorReader{},
457+
}
458+
response.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
459+
460+
// validate!
461+
valid, errors := v.ValidateResponseBody(request, response)
462+
// doubletap to hit cache
463+
_, _ = v.ValidateResponseBody(request, response)
464+
465+
assert.False(t, valid)
466+
assert.Len(t, errors, 1)
467+
}
468+
422469
func TestValidateBody_InvalidBasicSchema_SetPath(t *testing.T) {
423470
spec := `openapi: 3.1.0
424471
paths:
@@ -1135,3 +1182,12 @@ paths:
11351182
assert.Len(t, errors, 0)
11361183

11371184
}
1185+
1186+
type errorReader struct{}
1187+
1188+
func (er *errorReader) Read(p []byte) (n int, err error) {
1189+
return 0, errors.New("some io error")
1190+
}
1191+
func (er *errorReader) Close() error {
1192+
return nil
1193+
}

0 commit comments

Comments
 (0)