-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse_test.go
104 lines (85 loc) · 2.42 KB
/
response_test.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
package snorlax_test
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/nickcorin/snorlax"
"github.com/stretchr/testify/suite"
)
type ResponseTestSuite struct {
suite.Suite
client snorlax.Client
server *httptest.Server
}
func EchoHandler(w http.ResponseWriter, r *http.Request) {
for headerKey, headerValues := range r.Header {
for _, headerValue := range headerValues {
w.Header().Add(headerKey, headerValue)
}
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(body)
}
func (suite *ResponseTestSuite) SetupSuite() {
suite.server = httptest.NewServer(http.HandlerFunc(EchoHandler))
suite.client = snorlax.DefaultClient.SetBaseURL(suite.server.URL)
}
func (suite *ResponseTestSuite) TearDownSuite() {
suite.server.Close()
}
func (suite *ResponseTestSuite) TestIsSuccess() {
successResponse := snorlax.Response{http.Response{
StatusCode: http.StatusOK,
}}
failedResponse := snorlax.Response{http.Response{
StatusCode: http.StatusInternalServerError,
}}
suite.Require().True(successResponse.IsSuccess())
suite.Require().False(failedResponse.IsSuccess())
}
func (suite *ResponseTestSuite) TestJSON() {
type Pokemon struct {
Name string `json:"name"`
Number int `json:"number"`
}
body := []byte(`{"name": "snorlax", "number": 143}`)
res, err := suite.client.Post(context.TODO(), "/example", nil,
bytes.NewBuffer(body))
suite.Require().NoError(err)
suite.Require().NotNil(res)
var pokemon Pokemon
err = res.JSON(&pokemon)
suite.Require().NoError(err)
suite.Require().Equal("snorlax", pokemon.Name)
suite.Require().Equal(143, pokemon.Number)
}
func (suite *ResponseTestSuite) TestRawBody() {
type Pokemon struct {
Name string `json:"name"`
Number int `json:"number"`
}
body := []byte(`{"name": "snorlax", "number": 143}`)
res, err := suite.client.Post(context.TODO(), "/example", nil,
bytes.NewBuffer(body))
suite.Require().NoError(err)
suite.Require().NotNil(res)
responseReader, err := res.RawBody()
suite.Require().NoError(err)
suite.Require().NotNil(responseReader)
responseBody, err := ioutil.ReadAll(responseReader)
suite.Require().NoError(err)
suite.Require().NotNil(responseBody)
suite.Require().EqualValues(body, responseBody)
}
func TestResponseTestSuite(t *testing.T) {
suite.Run(t, new(ResponseTestSuite))
}