Skip to content

Commit 7201668

Browse files
committed
Add the response body validation
1 parent f11b293 commit 7201668

6 files changed

+279
-36
lines changed

analyzer.go

+43-13
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package oaichecker
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"errors"
67
"fmt"
8+
"io/ioutil"
79
"net/http"
810
"strconv"
911
"strings"
@@ -60,7 +62,7 @@ func createRouter(analyzer *analysis.Spec) *denco.Router {
6062
return r
6163
}
6264

63-
func (t *Analyzer) Analyze(req *http.Request) error {
65+
func (t *Analyzer) Analyze(req *http.Request, res *http.Response) error {
6466
if req == nil {
6567
return errors.New("no request defined")
6668
}
@@ -95,7 +97,45 @@ func (t *Analyzer) Analyze(req *http.Request) error {
9597
}
9698
}
9799

98-
return nil
100+
err := t.validateResponse(res, operation.Responses)
101+
102+
return err
103+
}
104+
105+
func (t *Analyzer) validateResponse(res *http.Response, resSpec *spec.Responses) error {
106+
for status, response := range resSpec.StatusCodeResponses {
107+
if status == res.StatusCode {
108+
109+
body, err := ioutil.ReadAll(res.Body)
110+
if err != nil {
111+
return err
112+
}
113+
114+
res.Body = ioutil.NopCloser(bytes.NewReader(body))
115+
116+
if response.ResponseProps.Schema == nil {
117+
if len(body) > 0 {
118+
return fmt.Errorf("validation failure list:\nno response body defined inside the specs but have %q", body)
119+
}
120+
return nil
121+
}
122+
123+
var input interface{}
124+
err = json.Unmarshal(body, &input)
125+
if err != nil {
126+
return fmt.Errorf("failed to parse json body: %s", err)
127+
}
128+
129+
err = validate.AgainstSchema(response.Schema, input, strfmt.Default)
130+
if err != nil {
131+
return err
132+
}
133+
134+
return nil
135+
}
136+
}
137+
138+
return fmt.Errorf("validation failure list:\nresponse status %s not defined inside the specs", res.Status)
99139
}
100140

101141
func (t *Analyzer) validateBodyParameter(req *http.Request, param *spec.Parameter) error {
@@ -110,17 +150,7 @@ func (t *Analyzer) validateBodyParameter(req *http.Request, param *spec.Paramete
110150
return err
111151
}
112152

113-
paramRef := param.ParamProps.Schema.Ref.String()
114-
115-
var schema *spec.Schema
116-
for _, def := range t.analyzer.AllDefinitions() {
117-
if paramRef == def.Ref.String() {
118-
schema = def.Schema
119-
break
120-
}
121-
}
122-
123-
err = validate.AgainstSchema(schema, input, strfmt.Default)
153+
err = validate.AgainstSchema(param.Schema, input, strfmt.Default)
124154
if err != nil {
125155
return err
126156
}

0 commit comments

Comments
 (0)