This repository has been archived by the owner on Mar 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathresponse.go
226 lines (203 loc) · 5.81 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package hrp
import (
"bytes"
builtinJSON "encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"testing"
"github.com/jmespath/go-jmespath"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/hrp/internal/builtin"
"github.com/httprunner/hrp/internal/json"
)
func newResponseObject(t *testing.T, parser *parser, resp *http.Response) (*responseObject, error) {
// prepare response headers
headers := make(map[string]string)
for k, v := range resp.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
// prepare response cookies
cookies := make(map[string]string)
for _, cookie := range resp.Cookies() {
cookies[cookie.Name] = cookie.Value
}
// read response body
respBodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// parse response body
var body interface{}
if err := json.Unmarshal(respBodyBytes, &body); err != nil {
// response body is not json, use raw body
body = string(respBodyBytes)
}
respObjMeta := respObjMeta{
StatusCode: resp.StatusCode,
Headers: headers,
Cookies: cookies,
Body: body,
}
// convert respObjMeta to interface{}
respObjMetaBytes, _ := json.Marshal(respObjMeta)
var data interface{}
decoder := json.NewDecoder(bytes.NewReader(respObjMetaBytes))
decoder.UseNumber()
if err := decoder.Decode(&data); err != nil {
log.Error().
Str("respObjMeta", string(respObjMetaBytes)).
Err(err).
Msg("[NewResponseObject] convert respObjMeta to interface{} failed")
return nil, err
}
return &responseObject{
t: t,
parser: parser,
respObjMeta: data,
}, nil
}
type respObjMeta struct {
StatusCode int `json:"status_code"`
Headers map[string]string `json:"headers"`
Cookies map[string]string `json:"cookies"`
Body interface{} `json:"body"`
}
type responseObject struct {
t *testing.T
parser *parser
respObjMeta interface{}
validationResults []*validationResult
}
const textExtractorSubRegexp string = `(.*)`
func (v *responseObject) extractField(value string) interface{} {
var result interface{}
if strings.Contains(value, textExtractorSubRegexp) {
result = v.searchRegexp(value)
} else {
result = v.searchJmespath(value)
}
return result
}
func (v *responseObject) Extract(extractors map[string]string) map[string]interface{} {
if extractors == nil {
return nil
}
extractMapping := make(map[string]interface{})
for key, value := range extractors {
extractedValue := v.extractField(value)
log.Info().Str("from", value).Interface("value", extractedValue).Msg("extract value")
log.Info().Str("variable", key).Interface("value", extractedValue).Msg("set variable")
extractMapping[key] = extractedValue
}
return extractMapping
}
func (v *responseObject) Validate(iValidators []interface{}, variablesMapping map[string]interface{}) (err error) {
for _, iValidator := range iValidators {
validator, ok := iValidator.(Validator)
if !ok {
return errors.New("validator type error")
}
// parse check value
checkItem := validator.Check
var checkValue interface{}
if strings.Contains(checkItem, "$") {
// reference variable
checkValue, err = v.parser.parseData(checkItem, variablesMapping)
if err != nil {
return err
}
} else {
// regExp or jmesPath
checkValue = v.extractField(checkItem)
}
// get assert method
assertMethod := validator.Assert
assertFunc, ok := builtin.Assertions[assertMethod]
if !ok {
return errors.New(fmt.Sprintf("unexpected assertMethod: %v", assertMethod))
}
// parse expected value
expectValue, err := v.parser.parseData(validator.Expect, variablesMapping)
if err != nil {
return err
}
validResult := &validationResult{
Validator: Validator{
Check: validator.Check,
Expect: expectValue,
Assert: assertMethod,
Message: validator.Message,
},
CheckValue: checkValue,
CheckResult: "fail",
}
// do assertion
result := assertFunc(v.t, checkValue, expectValue)
if result {
validResult.CheckResult = "pass"
}
v.validationResults = append(v.validationResults, validResult)
log.Info().
Str("checkExpr", validator.Check).
Str("assertMethod", assertMethod).
Interface("expectValue", expectValue).
Interface("checkValue", checkValue).
Bool("result", result).
Msgf("validate %s", checkItem)
if !result {
v.t.Fail()
return errors.New(fmt.Sprintf(
"do assertion failed, checkExpr: %v, assertMethod: %v, checkValue: %v, expectValue: %v",
validator.Check,
assertMethod,
checkValue,
expectValue,
))
}
}
return nil
}
func (v *responseObject) searchJmespath(expr string) interface{} {
checkValue, err := jmespath.Search(expr, v.respObjMeta)
if err != nil {
log.Error().Str("expr", expr).Err(err).Msg("search jmespath failed")
return expr // jmespath not found, return the expression
}
if number, ok := checkValue.(builtinJSON.Number); ok {
checkNumber, err := parseJSONNumber(number)
if err != nil {
log.Error().Interface("json number", number).Err(err).Msg("convert json number failed")
}
return checkNumber
}
return checkValue
}
func (v *responseObject) searchRegexp(expr string) interface{} {
respMap, ok := v.respObjMeta.(map[string]interface{})
if !ok {
log.Error().Interface("resp", v.respObjMeta).Msg("convert respObjMeta to map failed")
return expr
}
bodyStr, ok := respMap["body"].(string)
if !ok {
log.Error().Interface("resp", respMap).Msg("convert body to string failed")
return expr
}
regexpCompile, err := regexp.Compile(expr)
if err != nil {
log.Error().Str("expr", expr).Err(err).Msg("compile expr failed")
return expr
}
match := regexpCompile.FindStringSubmatch(bodyStr)
if match != nil || len(match) > 1 {
return match[1] //return first matched result in parentheses
}
log.Error().Str("expr", expr).Msg("search regexp failed")
return expr
}