/
http.go
137 lines (120 loc) · 4.07 KB
/
http.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
/*******************************************************************************
*
* Copyright 2017-2018 SAP SE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You should have received a copy of the License along with this
* program. If not, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package assert
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
)
// HTTPRequestBody is the type of field HTTPRequest.RequestBody.
// It is implemented by StringData and JSONObject.
type HTTPRequestBody interface {
GetRequestBody() (io.Reader, error)
}
// HTTPResponseBody is the type of field HTTPRequest.ExpectBody.
// It is implemented by StringData and JSONObject.
type HTTPResponseBody interface {
// Checks that the given actual response body is equal to this expected value.
// `request` contains a user-readable representation of the original request,
// for use in error messages.
//
// Returns whether the assertion was successful.
AssertResponseBody(t *testing.T, requestInfo string, responseBody []byte) bool
}
// HTTPRequest is a HTTP request that gets executed by a unit test.
type HTTPRequest struct {
// request properties
Method string
Path string
Header map[string]string
Body HTTPRequestBody
// response properties
ExpectStatus int
ExpectBody HTTPResponseBody
ExpectHeader map[string]string
}
// Check performs the HTTP request described by this HTTPRequest against the
// given http.Handler and compares the response with the expectations in the
// HTTPRequest.
//
// The HTTP response is returned, along with the response body. (resp.Body is
// already exhausted when the function returns.) This is useful for tests that
// want to do further checks on `resp` or want to use data from the response.
func (r HTTPRequest) Check(t *testing.T, handler http.Handler) (resp *http.Response, responseBody []byte) {
t.Helper()
var requestBody io.Reader
if r.Body != nil {
var err error
requestBody, err = r.Body.GetRequestBody()
if err != nil {
t.Fatal(err)
}
}
request := httptest.NewRequest(r.Method, r.Path, requestBody)
if r.Header != nil {
for key, value := range r.Header {
request.Header.Set(key, value)
}
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
hadErrors := false
bodyShown := false
response := recorder.Result()
defer response.Body.Close()
responseBytes, err := io.ReadAll(response.Body)
if err != nil {
hadErrors = true
t.Errorf("Reading response body failed: %s", err.Error())
}
if response.StatusCode != r.ExpectStatus {
hadErrors = true
t.Errorf("%s %s: expected status code %d, got %d",
r.Method, r.Path, r.ExpectStatus, response.StatusCode,
)
}
for key, value := range r.ExpectHeader {
actual := response.Header.Get(key)
if actual != value {
t.Errorf("%s %s: expected %s: %q, got %s: %q",
r.Method, r.Path, key, value, key, actual,
)
}
}
if r.ExpectBody != nil {
// json.Encoder.Encode() adds a stupid extra newline that we want to ignore
if response.Header.Get("Content-Type") == "application/json" {
responseBytes = bytes.TrimSuffix(responseBytes, []byte("\n"))
}
requestInfo := fmt.Sprintf("%s %s", r.Method, r.Path)
if !r.ExpectBody.AssertResponseBody(t, requestInfo, responseBytes) {
hadErrors = true
bodyShown = true
}
}
// in case of errors, it's usually very helpful to see the response body
// (particularly for 4xx and 5xx responses), so make sure that it gets shown)
if hadErrors && !bodyShown {
t.Logf("%s %s: response body was %q", r.Method, r.Path, string(responseBytes))
}
return response, responseBytes
}