-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_test.go
More file actions
92 lines (78 loc) · 2.14 KB
/
http_test.go
File metadata and controls
92 lines (78 loc) · 2.14 KB
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
package httpok
import (
"bytes"
"encoding/json"
"io"
"net/http"
"testing"
"github.com/candango/httpok/testrunner"
"github.com/stretchr/testify/assert"
)
func Wrap(next http.Handler, ww *WrappedWriter) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*ww = WrappedWriter{
ResponseWriter: w,
StatusCode: http.StatusOK,
}
next.ServeHTTP(ww, r)
})
}
type WrappedHandler struct {
http.Handler
}
func (h *WrappedHandler) GetOK(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("It's ok"))
}
func (h *WrappedHandler) GetInternalError(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("It's an internal error"))
w.WriteHeader(http.StatusInternalServerError)
}
func NewWrappedServeMux(ww *WrappedWriter) http.Handler {
handler := &WrappedHandler{}
h := http.NewServeMux()
h.HandleFunc("/ok", handler.GetOK)
h.HandleFunc("/internal_error", handler.GetInternalError)
return Wrap(h, ww)
}
func TestBodyAsString(t *testing.T) {
body := "hello world"
res := &http.Response{
Body: io.NopCloser(bytes.NewBufferString(body)),
}
result, err := BodyAsString(res)
assert.NoError(t, err)
assert.Equal(t, body, result)
}
func TestBodyAsJson(t *testing.T) {
type Data struct {
Message string `json:"message"`
}
expected := Data{Message: "hello"}
jsonBytes, _ := json.Marshal(expected)
res := &http.Response{
Body: io.NopCloser(bytes.NewBuffer(jsonBytes)),
}
var actual Data
err := BodyAsJson(res, &actual)
assert.NoError(t, err)
assert.Equal(t, expected, actual)
}
func TestWrappedWriter(t *testing.T) {
ww := &WrappedWriter{}
h := NewWrappedServeMux(ww)
runner := testrunner.NewHttpTestRunner(t).WithHandler(h)
t.Run("Wrapped runner", func(t *testing.T) {
res, err := runner.WithPath("/ok").Get()
if err != nil {
t.Error(err)
}
assert.Equal(t, http.StatusOK, ww.StatusCode)
assert.Equal(t, "It's ok", testrunner.BodyAsString(t, res))
res, err = runner.WithPath("/internal_error").Get()
if err != nil {
t.Error(err)
}
assert.Equal(t, http.StatusInternalServerError, ww.StatusCode)
assert.Equal(t, "It's an internal error", testrunner.BodyAsString(t, res))
})
}