Skip to content

Commit f29d820

Browse files
k1LoWdaveshanley
authored andcommitted
Support range definition for response codes.
ref: https://swagger.io/docs/specification/describing-responses/
1 parent b3f6e33 commit f29d820

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

responses/validate_body.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package responses
55

66
import (
7+
"fmt"
78
"net/http"
89
"strconv"
910
"strings"
@@ -47,7 +48,12 @@ func (v *responseBodyValidator) ValidateResponseBody(
4748
mediaTypeSting, _, _ := helpers.ExtractContentType(contentType)
4849

4950
// check if the response code is in the contract
50-
foundResponse := operation.Responses.FindResponseByCode(httpCode)
51+
foundResponse := operation.Responses.Codes.GetOrZero(fmt.Sprintf("%d", httpCode))
52+
if foundResponse == nil {
53+
// check range definition for response codes
54+
foundResponse = operation.Responses.Codes.GetOrZero(fmt.Sprintf("%dXX", httpCode/100))
55+
}
56+
5157
if foundResponse != nil {
5258
if foundResponse.Content != nil { // only validate if we have content types.
5359
// check content type has been defined in the contract

validator_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1170,3 +1170,46 @@ func TestNewValidator_PetStore_PetFindByStatusGet200_Valid_responseOnly(t *testi
11701170
assert.True(t, valid)
11711171
assert.Len(t, errors, 0)
11721172
}
1173+
1174+
func TestNewValidator_ValidateHttpResponse_RangeResponseCode(t *testing.T) {
1175+
1176+
spec := `openapi: 3.1.0
1177+
paths:
1178+
/burgers:
1179+
get:
1180+
responses:
1181+
'200':
1182+
description: OK
1183+
content:
1184+
application/json:
1185+
schema:
1186+
type: array
1187+
items:
1188+
type: object
1189+
properties:
1190+
name:
1191+
type: string
1192+
patties:
1193+
type: integer
1194+
vegetarian:
1195+
type: boolean
1196+
'4XX':
1197+
description: Bad request
1198+
'5XX':
1199+
description: Server error`
1200+
1201+
doc, _ := libopenapi.NewDocument([]byte(spec))
1202+
1203+
v, _ := NewValidator(doc)
1204+
1205+
request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers", nil)
1206+
request.Header.Set("Content-Type", "application/json")
1207+
response := &http.Response{
1208+
StatusCode: 400,
1209+
Header: http.Header{"Content-Type": []string{"application/json"}},
1210+
}
1211+
valid, errors := v.ValidateHttpResponse(request, response)
1212+
1213+
assert.True(t, valid)
1214+
assert.Len(t, errors, 0)
1215+
}

0 commit comments

Comments
 (0)