-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
80 lines (59 loc) · 2.27 KB
/
main_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
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type mockRoute struct {
Path string
Callback func(http.ResponseWriter, *http.Request)
}
type mockRouter struct {
mock.Mock
Registered []mockRoute
}
type mockHTTP struct {
mock.Mock
}
func (m *mockHTTP) ListenAndServe(addr string, handler http.Handler) error {
m.Called(addr, handler)
return nil
}
func (m *mockRouter) HandleFunc(path string, handleFunc func(http.ResponseWriter, *http.Request)) *mux.Route {
m.Called(path, handleFunc)
m.Registered = append(m.Registered, mockRoute{Path: path, Callback: handleFunc})
return &mux.Route{}
}
func (m *mockRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
func TestDefaultConfigIsLoadedWhenNotSpecified(t *testing.T) {
router := &mockRouter{}
http := &mockHTTP{}
router.On("HandleFunc", "/test", mock.AnythingOfType("func(http.ResponseWriter, *http.Request)")).Return(nil)
router.On("HandleFunc", "/test/{id}", mock.AnythingOfType("func(http.ResponseWriter, *http.Request)")).Return(nil)
http.On("ListenAndServe", ":12345", router).Return(nil)
params := &FakeServerParams{Router: router, HTTP: http}
NewFakeServer(params)
assert.Equal(t, "config.yaml.dist", params.ConfigFilename)
}
func TestNewFakeServer(t *testing.T) {
router := &mockRouter{}
http := &mockHTTP{}
router.On("HandleFunc", "/test", mock.AnythingOfType("func(http.ResponseWriter, *http.Request)")).Return(nil)
router.On("HandleFunc", "/test/{id}", mock.AnythingOfType("func(http.ResponseWriter, *http.Request)")).Return(nil)
http.On("ListenAndServe", ":12345", router).Return(nil)
NewFakeServer(&FakeServerParams{Router: router, HTTP: http, ConfigFilename: "fixtures/config.yaml.dist"})
router.AssertExpectations(t)
http.AssertExpectations(t)
assert.Len(t, router.Registered, 2, "Lenght of the registerd routes is not correct")
assert.Equal(t, "/test/{id}", router.Registered[0].Path)
assert.Equal(t, "/test", router.Registered[1].Path)
w := httptest.NewRecorder()
router.Registered[0].Callback(w, nil)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
router.Registered[1].Callback(w, nil)
assert.Equal(t, "text/plain", w.Header().Get("Content-Type"))
}