-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
113 lines (89 loc) · 2.54 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(test *testing.T) {
request, err := http.NewRequest("GET", "", nil)
if err != nil {
test.Fatal(err)
}
recorder := httptest.NewRecorder()
httpHandler := http.HandlerFunc(handler)
httpHandler.ServeHTTP(recorder, request)
// Check status code
if status := recorder.Code; status != http.StatusOK {
test.Errorf("Handler return wrong status code: got %v want %v", status, http.StatusOK)
}
// Check response body
expected := "Hello World!"
actual := recorder.Body.String()
if actual != expected {
test.Errorf("Handler returned unexpected body: got %v want %v", actual, expected)
}
}
func TestRouter(test *testing.T) {
router := newRouter()
mockserver := httptest.NewServer(router)
response, err := http.Get(mockserver.URL + "/hello")
if err != nil {
test.Fatal(err)
}
if response.StatusCode != http.StatusOK {
test.Errorf("Status should be ok, got %d", response.StatusCode)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
test.Fatal(err)
}
responseString := string(body)
expected := "Hello World!"
if responseString != expected {
test.Errorf("Response should be %s, got %s", expected, responseString)
}
}
func TestRouterForNonExistentRoute(test *testing.T) {
router := newRouter()
mockserver := httptest.NewServer(router)
// Post
response, err := http.Post(mockserver.URL+"/hello", "", nil)
if err != nil {
test.Fatal(err)
}
// http code / msg
if response.StatusCode != http.StatusMethodNotAllowed {
test.Errorf("Status should be 405, got %d", response.StatusCode)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
test.Fatal(err)
}
responseString := string(body)
// expect ""
expected := ""
if responseString != expected {
test.Errorf("Response should be %s, got %s", expected, responseString)
}
}
func TestStaticFileServer(test *testing.T) {
router := newRouter()
mockserver := httptest.NewServer(router)
response, err := http.Get(mockserver.URL + "/assets/")
if err != nil {
test.Fatal(err)
}
if response.StatusCode != http.StatusOK {
test.Errorf("Status should be 200, got %d", response.StatusCode)
}
// Do not test the content of the index.html file
// Only test the content type
contenType := response.Header.Get("Content-Type")
expectedContentType := "text/html; charset=utf-8"
if expectedContentType != contenType {
test.Errorf("Wrong content type, expected %s, got %s", expectedContentType, contenType)
}
}