-
Notifications
You must be signed in to change notification settings - Fork 50
/
testcase_httpserver_extended.go
217 lines (179 loc) · 6.53 KB
/
testcase_httpserver_extended.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
package suite
import (
"fmt"
"net/http"
"os"
"path"
"reflect"
"github.com/go-resty/resty/v2"
"github.com/justtrackio/gosoline/pkg/funk"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
)
func init() {
testCaseDefinitions["httpserverExtended"] = testCaseDefinition{
matcher: isTestCaseHttpserverExtended,
builder: buildTestCaseHttpserverExtended,
}
}
type HttpserverTestCase struct {
Method string
Url string
Headers map[string]string
// Body will be used as the request body. Supported request body data types is `string`,
// `[]byte`, `struct`, `map`, `slice` and `io.Reader`. Body value can be pointer or non-pointer.
// Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`.
//
// If you call EncodeBodyProtobuf on your body before assigning it to this field, it will instead be
// encoded using protobuf.
//
// To send the contents of a file, you can use ReadBodyFile and assign the result to this field. The
// test suite will read the file contents and send it as your request.
Body interface{}
// ExpectedStatusCode describes the status code the last response is required to have.
ExpectedStatusCode int
// ExpectedRedirectsToFollow describes the number of redirects we want to follow. It is an error if less redirects
// are performed. More redirects result in the last redirect being returned as the response instead (e.g., if it is
// to some external site or with a protocol different from HTTP(S) like intent://) and do not result in an error.
ExpectedRedirectsToFollow int
// ExpectedResult defines the *type* the final response should be parsed into. You can then access the unmarshalled
// response in response.Result().
ExpectedResult interface{}
// ExpectedErr is compared with the error returned by the HTTP request. Only the error messages have to match.
ExpectedErr error
// Assert allows you to provide an assertion function that can be passed to validate certain post conditions (like
// messages being written to the correct queues).
// It also allows to check that the response carries the correct response body, redirects to the correct
// // location, or has the correct headers set. You don't need to validate the response status here, this is already
// // performed automatically.
Assert func(response *resty.Response) error
// AssertResultFile can be used to read the expected response body from a file, which will be used to check equality
// with the actual response body. If the file name extension is .json, the equality check is done via assert.JSONEq.
AssertResultFile string
}
type ProtobufEncodable interface {
ToMessage() (proto.Message, error)
}
type encodeBodyProtobuf struct {
ProtobufEncodable
}
func EncodeBodyProtobuf(body ProtobufEncodable) any {
return encodeBodyProtobuf{
ProtobufEncodable: body,
}
}
type readBodyFile struct {
file string
}
func ReadBodyFile(bodyFile string) any {
return readBodyFile{
file: bodyFile,
}
}
func (c HttpserverTestCase) request(client *resty.Client) (*resty.Response, error) {
req := client.R()
if c.Headers != nil {
req.SetHeaders(c.Headers)
}
if c.Body != nil {
switch body := c.Body.(type) {
case encodeBodyProtobuf:
msg, err := body.ToMessage()
if err != nil {
return nil, fmt.Errorf("failed to convert body to message: %w", err)
}
bytes, err := proto.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("failed to marshal message as protobuf: %w", err)
}
req.SetBody(bytes)
case readBodyFile:
bytes, err := os.ReadFile(body.file)
if err != nil {
return nil, fmt.Errorf("can not read body from file %q: %w", body.file, err)
}
req.SetBody(bytes)
default:
req.SetBody(c.Body)
}
}
if c.ExpectedResult != nil {
req.SetResult(c.ExpectedResult)
}
return req.Execute(c.Method, c.Url)
}
func isTestCaseHttpserverExtended(method reflect.Method) bool {
if method.Func.Type().NumIn() != 1 {
return false
}
if method.Func.Type().NumOut() != 1 {
return false
}
actualType0 := method.Func.Type().Out(0)
expectedType := reflect.TypeOf((*HttpserverTestCase)(nil))
expectedSliceType := reflect.TypeOf([]*HttpserverTestCase{})
return actualType0 == expectedType || actualType0 == expectedSliceType
}
func buildTestCaseHttpserverExtended(suite TestingSuite, method reflect.Method) (testCaseRunner, error) {
return runTestCaseHttpserver(suite, func(suite TestingSuite, app *appUnderTest, client *resty.Client) {
out := method.Func.Call([]reflect.Value{reflect.ValueOf(suite)})[0].Interface()
var err error
var bytes []byte
var testCases []*HttpserverTestCase
if tc, ok := out.(*HttpserverTestCase); ok {
testCases = []*HttpserverTestCase{tc}
} else {
testCases = out.([]*HttpserverTestCase)
}
testCases = funk.Filter(testCases, func(elem *HttpserverTestCase) bool {
return elem != nil
})
responses := make([]*resty.Response, len(testCases))
remainingRedirects := 0
client.SetRedirectPolicy(
resty.RedirectPolicyFunc(func(request *http.Request, _ []*http.Request) error {
if remainingRedirects <= 0 {
return http.ErrUseLastResponse
}
remainingRedirects--
return nil
}),
)
for i, tc := range testCases {
remainingRedirects = tc.ExpectedRedirectsToFollow
responses[i], err = tc.request(client)
assert.NotNil(suite.T(), responses[i], "there should be a response returned")
if responses[i] != nil {
assert.Equal(suite.T(), tc.ExpectedStatusCode, responses[i].StatusCode(), "response status code should match")
assert.Equalf(suite.T(), 0, remainingRedirects, "expected %d redirects, but only %d redirects where performed", tc.ExpectedRedirectsToFollow, tc.ExpectedRedirectsToFollow-remainingRedirects)
}
if tc.ExpectedErr == nil {
assert.NoError(suite.T(), err)
} else {
assert.EqualError(suite.T(), err, tc.ExpectedErr.Error())
}
}
app.Stop()
app.WaitDone()
for i, tc := range testCases {
if tc.Assert != nil {
if err := tc.Assert(responses[i]); err != nil {
assert.FailNow(suite.T(), err.Error(), "there should be no error on assert")
}
}
if tc.AssertResultFile != "" {
if bytes, err = os.ReadFile(tc.AssertResultFile); err != nil {
assert.FailNow(suite.T(), err.Error(), "can not read result file %q", tc.AssertResultFile)
}
extension := path.Ext(tc.AssertResultFile)
actual := responses[i].Body()
switch extension {
case ".json":
assert.JSONEq(suite.T(), string(bytes), string(actual), "response doesn't match")
default:
assert.Equal(suite.T(), bytes, actual, "response doesn't match")
}
}
}
})
}