-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
74 lines (58 loc) · 1.6 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
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(t *testing.T) {
router := newRouter()
mockServer := httptest.NewServer(router)
res, err := http.Get(mockServer.URL + "/welcome")
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("status code should be 200, got %d", res.StatusCode)
}
checkReponseBody(res, t, "Welcome to Birdpedia!")
}
func TestRouterForNonExistingRoute(t *testing.T) {
router := newRouter()
mockServer := httptest.NewServer(router)
res, err := http.Post(mockServer.URL+"/welcome", "", nil)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("status code should be 405, got %d", res.StatusCode)
}
checkReponseBody(res, t, "")
}
func TestStaticFileServer(t *testing.T) {
router := newRouter()
mockServer := httptest.NewServer(router)
res, err := http.Get(mockServer.URL + "/assets/")
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("status code should be 200, got %d", res.StatusCode)
}
contentType := res.Header.Get("Content-Type")
expectedContentType := "text/html; charset=utf-8"
if expectedContentType != contentType {
t.Errorf("Wrong content type, expected %s, got %s", expectedContentType, contentType)
}
}
func checkReponseBody(res *http.Response, t *testing.T, expected string) {
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
actual := string(body)
if actual != expected {
t.Errorf("handler returned unexpected body: got '%v' want '%v'", expected, actual)
}
}