1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package httpproxy
16
17 import (
18 "io/ioutil"
19 "net/http"
20 "net/http/httptest"
21 "net/url"
22 "testing"
23 "time"
24
25 "go.uber.org/zap"
26 )
27
28 func TestReadonlyHandler(t *testing.T) {
29 fixture := func(w http.ResponseWriter, req *http.Request) {
30 w.WriteHeader(http.StatusOK)
31 }
32 hdlrFunc := readonlyHandlerFunc(http.HandlerFunc(fixture))
33
34 tests := []struct {
35 method string
36 want int
37 }{
38
39 {"GET", http.StatusOK},
40
41
42 {"POST", http.StatusNotImplemented},
43 {"PUT", http.StatusNotImplemented},
44 {"PATCH", http.StatusNotImplemented},
45 {"DELETE", http.StatusNotImplemented},
46 {"FOO", http.StatusNotImplemented},
47 }
48
49 for i, tt := range tests {
50 req, _ := http.NewRequest(tt.method, "http://example.com", nil)
51 rr := httptest.NewRecorder()
52 hdlrFunc(rr, req)
53
54 if tt.want != rr.Code {
55 t.Errorf("#%d: incorrect HTTP status code: method=%s want=%d got=%d", i, tt.method, tt.want, rr.Code)
56 }
57 }
58 }
59
60 func TestConfigHandlerGET(t *testing.T) {
61 var err error
62 us := make([]*url.URL, 3)
63 us[0], err = url.Parse("http://example1.com")
64 if err != nil {
65 t.Fatal(err)
66 }
67 us[1], err = url.Parse("http://example2.com")
68 if err != nil {
69 t.Fatal(err)
70 }
71 us[2], err = url.Parse("http://example3.com")
72 if err != nil {
73 t.Fatal(err)
74 }
75
76 lg := zap.NewExample()
77 rp := reverseProxy{
78 lg: lg,
79 director: &director{
80 lg: lg,
81 ep: []*endpoint{
82 newEndpoint(lg, *us[0], 1*time.Second),
83 newEndpoint(lg, *us[1], 1*time.Second),
84 newEndpoint(lg, *us[2], 1*time.Second),
85 },
86 },
87 }
88
89 req, _ := http.NewRequest("GET", "http://example.com//v2/config/local/proxy", nil)
90 rr := httptest.NewRecorder()
91 rp.configHandler(rr, req)
92
93 wbody := "{\"endpoints\":[\"http://example1.com\",\"http://example2.com\",\"http://example3.com\"]}\n"
94
95 body, err := ioutil.ReadAll(rr.Body)
96 if err != nil {
97 t.Fatal(err)
98 }
99
100 if string(body) != wbody {
101 t.Errorf("body = %s, want %s", string(body), wbody)
102 }
103 }
104
View as plain text