Skip to content

Commit

Permalink
Support range definition for response codes.
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW committed Apr 16, 2024
1 parent b3f6e33 commit a80bbb4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
8 changes: 7 additions & 1 deletion responses/validate_body.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package responses

import (
"fmt"
"net/http"
"strconv"
"strings"
Expand Down Expand Up @@ -47,7 +48,12 @@ func (v *responseBodyValidator) ValidateResponseBody(
mediaTypeSting, _, _ := helpers.ExtractContentType(contentType)

// check if the response code is in the contract
foundResponse := operation.Responses.FindResponseByCode(httpCode)
foundResponse := operation.Responses.Codes.GetOrZero(fmt.Sprintf("%d", httpCode))
if foundResponse == nil {
// check range definition for response codes
foundResponse = operation.Responses.Codes.GetOrZero(fmt.Sprintf("%dXX", httpCode/100))
}

if foundResponse != nil {
if foundResponse.Content != nil { // only validate if we have content types.
// check content type has been defined in the contract
Expand Down
43 changes: 43 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1170,3 +1170,46 @@ func TestNewValidator_PetStore_PetFindByStatusGet200_Valid_responseOnly(t *testi
assert.True(t, valid)
assert.Len(t, errors, 0)
}

func TestNewValidator_ValidateHttpResponse_RangeResponseCode(t *testing.T) {

spec := `openapi: 3.1.0
paths:
/burgers:
get:
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
type: object
properties:
name:
type: string
patties:
type: integer
vegetarian:
type: boolean
'4XX':
description: Bad request
'5XX':
description: Server error`

doc, _ := libopenapi.NewDocument([]byte(spec))

v, _ := NewValidator(doc)

request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers", nil)
request.Header.Set("Content-Type", "application/json")
response := &http.Response{
StatusCode: 400,
Header: http.Header{"Content-Type": []string{"application/json"}},
}
valid, errors := v.ValidateHttpResponse(request, response)

assert.True(t, valid)
assert.Len(t, errors, 0)
}

0 comments on commit a80bbb4

Please sign in to comment.