-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_handler_test.go
82 lines (70 loc) · 1.99 KB
/
log_handler_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
package middlewares
import (
"bytes"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLogFormat(t *testing.T) {
req, err := http.NewRequest("GET", "/index.html", nil)
req.Header.Set("User-Agent", "MWTests")
req.Header.Set("Referer", "testing")
if err != nil {
log.Fatal(err)
}
status := http.StatusOK
conLen := 23
var b bytes.Buffer
SetOutput(&b)
printLog(status, conLen, req)
rval := string(b.Bytes())
assert.Contains(t, rval, "GET HTTP/1.1 200 23 testing MWTests")
}
func TestShadowResponse(t *testing.T) {
rr := httptest.NewRecorder()
l := loggingHandler{rr, http.StatusOK, 0}
l.WriteHeader(http.StatusBadGateway)
sval := "this is a body"
l.Write([]byte(sval))
assert.Equal(t, http.StatusBadGateway, l.statusCode, "should be equal")
assert.Equal(t, len(sval), l.contentLen, "should be equal")
}
func TestLoggingHandler(t *testing.T) {
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("empty response")) //14 chars
})
notfoundHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
req, err := http.NewRequest("GET", "/index", nil)
if err != nil {
log.Fatal(err)
}
t.Run("200 OK Content Length", func(t *testing.T) {
var b bytes.Buffer
rr := httptest.NewRecorder()
SetOutput(&b)
handler := LoggingHandler(emptyHandler)
handler.ServeHTTP(rr, req)
rval := string(b.Bytes())
assert.Contains(t, rval, "GET HTTP/1.1 200 14")
})
t.Run("404 Not Found", func(t *testing.T) {
var b bytes.Buffer
rr := httptest.NewRecorder()
SetOutput(&b)
handler := LoggingHandler(notfoundHandler)
handler.ServeHTTP(rr, req)
rval := string(b.Bytes())
assert.Contains(t, rval, "GET HTTP/1.1 404 0")
})
}
func ExampleLoggingHandler() {
defaultHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// do something
})
http.Handle("/", LoggingHandler(defaultHandler))
http.ListenAndServe(":3000", nil)
}