-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttp_test.go
More file actions
98 lines (94 loc) · 2.5 KB
/
http_test.go
File metadata and controls
98 lines (94 loc) · 2.5 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
93
94
95
96
97
98
package kitty
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/go-kit/kit/endpoint"
)
func TestEndpointResponseEncode(t *testing.T) {
cfg := Config{}
HTTPTransport := NewHTTPTransport(cfg)
HTTPTransport.Endpoint("GET", "/test/default", func(ctx context.Context, r interface{}) (interface{}, error) {
return "default response", nil
}).Endpoint("GET", "/test/override", func(ctx context.Context, r interface{}) (interface{}, error) {
return "override response", nil
}, Encoder(func(ctx context.Context, w http.ResponseWriter, r interface{}) error {
w.WriteHeader(501)
return nil
}))
HTTPTransport.RegisterEndpoints(func(e endpoint.Endpoint) endpoint.Endpoint {
return e
})
{
rec := httptest.NewRecorder()
HTTPTransport.ServeHTTP(rec, &http.Request{
Method: "GET",
RequestURI: "/test/default",
URL: &url.URL{
Path: "/test/default",
},
})
if rec.Code != 200 {
t.Errorf("default HTTP response status expected: %d", rec.Code)
}
body := rec.Body.String()
if strings.TrimSpace(body) != `"default response"` {
t.Errorf("different body expected: %s", body)
}
}
{
rec := httptest.NewRecorder()
HTTPTransport.ServeHTTP(rec, &http.Request{
Method: "GET",
RequestURI: "/test/override",
URL: &url.URL{
Path: "/test/override",
},
})
if rec.Code != 501 {
t.Errorf("override HTTP response status expected: %d", rec.Code)
}
body := rec.Body.String()
if body != "" {
t.Errorf("different body expected: %s", body)
}
}
}
func TestDefaultResponseEncode(t *testing.T) {
cfg := Config{
EncodeResponse: func(ctx context.Context, w http.ResponseWriter, r interface{}) error {
w.WriteHeader(501)
w.Write([]byte("response:"))
return json.NewEncoder(w).Encode(r)
},
}
HTTPTransport := NewHTTPTransport(cfg).
Endpoint("GET", "/test", func(ctx context.Context, r interface{}) (interface{}, error) {
return "default response", nil
})
err := HTTPTransport.RegisterEndpoints(func(e endpoint.Endpoint) endpoint.Endpoint {
return e
})
if err != nil {
t.Errorf("error occurred: %+v", err)
}
rec := httptest.NewRecorder()
HTTPTransport.ServeHTTP(rec, &http.Request{
Method: "GET",
RequestURI: "/test",
URL: &url.URL{
Path: "/test",
},
})
if rec.Code != 501 {
t.Errorf("default HTTP response status expected: %d", rec.Code)
}
body := rec.Body.String()
if strings.TrimSpace(body) != `response:"default response"` {
t.Errorf("different body expected: %s", body)
}
}