forked from k8s-community/step-by-step
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_test.go
81 lines (66 loc) · 1.49 KB
/
handlers_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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Sirupsen/logrus"
"github.com/takama/router"
)
// buffer is a special variable to save log messages
var buffer bytes.Buffer
func init() {
log.Out = &buffer
log.Formatter = &logrus.JSONFormatter{}
}
// TestHandler is the simplest test: check base (/) URL
func TestHandler(t *testing.T) {
r := router.New()
r.GET("/", home)
ts := httptest.NewServer(r)
defer ts.Close()
res, err := http.Get(ts.URL + "/")
if err != nil {
t.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
expectedGreeting := "Repo: UNKNOWN, Commit: UNKNOWN, Version: UNKNOWN"
testingGreeting := strings.Trim(string(greeting), " \n")
if testingGreeting != expectedGreeting {
t.Fatalf(
"Wrong greeting '%s', expected '%s'",
testingGreeting, expectedGreeting,
)
}
}
// TestLogger checks if logger handler works correctly
func TestLogger(t *testing.T) {
r := router.New()
r.Logger = logger
ts := httptest.NewServer(r)
defer ts.Close()
_, err := http.Get(ts.URL + "/")
if err != nil {
t.Fatal(err)
}
formated := struct {
Level string `json:"level"`
Msg string `json:"msg"`
Time string `json:"time"`
}{}
err = json.NewDecoder(&buffer).Decode(&formated)
if err != nil {
t.Fatal(err)
}
msgParts := strings.Split(formated.Msg, " ")
if len(msgParts) != 3 {
t.Fatalf("Wrong message was logged: %s", formated.Msg)
}
}