@@ -18,6 +18,7 @@ import (
1818
1919 "github.com/pb33f/libopenapi-validator/cache"
2020 "github.com/pb33f/libopenapi-validator/config"
21+ liberrors "github.com/pb33f/libopenapi-validator/errors"
2122 validatorhelpers "github.com/pb33f/libopenapi-validator/helpers"
2223 "github.com/pb33f/libopenapi-validator/schema_validation"
2324)
@@ -472,6 +473,52 @@ func TestValidateResponseSchema_EmptyBodySkipsValidation(t *testing.T) {
472473 assert .Empty (t , errs )
473474}
474475
476+ func TestValidateResponseSchema_UnreadableBodyReturnsStructuredError (t * testing.T ) {
477+ schema := parseSchemaFromSpec (t , `type: object` , 3.1 )
478+
479+ valid , errs := ValidateResponseSchema (& ValidateResponseSchemaInput {
480+ Request : postRequest (),
481+ Response : & http.Response {StatusCode : http .StatusOK , Body : & errorReader {}},
482+ Schema : schema ,
483+ Version : 3.1 ,
484+ })
485+
486+ assert .False (t , valid )
487+ require .Len (t , errs , 1 )
488+ assert .Equal (t , validatorhelpers .ResponseBodyValidation , errs [0 ].ValidationType )
489+ assert .Equal (t , validatorhelpers .Schema , errs [0 ].ValidationSubType )
490+ assert .Contains (t , errs [0 ].Message , "response body for '/test' cannot be read" )
491+ assert .Equal (t , "The response body cannot be decoded: some io error" , errs [0 ].Reason )
492+ assert .Equal (t , "ensure body is not empty" , errs [0 ].HowToFix )
493+ assert .Same (t , schema , errs [0 ].Context )
494+ }
495+
496+ func TestValidateResponseSchema_MalformedJSONReturnsStructuredErrorAndRestoresBody (t * testing.T ) {
497+ schema := parseSchemaFromSpec (t , `type: object` , 3.1 )
498+ const malformed = `{"name":`
499+ response := responseWithBody (malformed )
500+
501+ valid , errs := ValidateResponseSchema (& ValidateResponseSchemaInput {
502+ Request : postRequest (),
503+ Response : response ,
504+ Schema : schema ,
505+ Version : 3.1 ,
506+ })
507+
508+ assert .False (t , valid )
509+ require .Len (t , errs , 1 )
510+ assert .Equal (t , validatorhelpers .ResponseBodyValidation , errs [0 ].ValidationType )
511+ assert .Equal (t , validatorhelpers .Schema , errs [0 ].ValidationSubType )
512+ assert .Contains (t , errs [0 ].Message , "response body for '/test' failed to validate schema" )
513+ assert .Contains (t , errs [0 ].Reason , "The response body cannot be decoded: unexpected end of JSON input" )
514+ assert .Equal (t , liberrors .HowToFixInvalidSchema , errs [0 ].HowToFix )
515+ assert .Same (t , schema , errs [0 ].Context )
516+
517+ replayed , err := io .ReadAll (response .Body )
518+ require .NoError (t , err )
519+ assert .Equal (t , malformed , string (replayed ))
520+ }
521+
475522func TestValidateResponseSchema_CachedSchemaWithoutRenderedNodeFallsBackToRenderedBytes (t * testing.T ) {
476523 schema := parseSchemaFromSpec (t , `anyOf:
477524 - type: string
0 commit comments