forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpLogs_test.go
110 lines (78 loc) · 2.07 KB
/
httpLogs_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
package main
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_httpLogsConfig(t *testing.T) {
app := &goBlog{
cfg: createDefaultTestConfig(t),
}
_ = app.initConfig(false)
assert.Equal(t, false, app.cfg.Server.Logging)
assert.Equal(t, "data/access.log", app.cfg.Server.LogFile)
}
func initTestHttpLogs(logFile string) (http.Handler, error) {
app := &goBlog{
cfg: &config{
Server: &configServer{
Logging: true,
LogFile: logFile,
},
},
}
err := app.initHTTPLog()
if err != nil {
return nil, err
}
return app.logMiddleware(testHttpHandler()), nil
}
func testHttpHandler() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write([]byte("Test"))
})
}
func Test_httpLogs(t *testing.T) {
// Init
logFile := filepath.Join(t.TempDir(), "access.log")
handler, err := initTestHttpLogs(logFile)
require.NoError(t, err)
// Do fake request
req := httptest.NewRequest(http.MethodGet, "/testpath", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
// Check response
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "Test")
// Check log
logBytes, err := os.ReadFile(logFile)
require.NoError(t, err)
logString := string(logBytes)
assert.Contains(t, logString, "GET /testpath")
}
func Benchmark_httpLogs(b *testing.B) {
// Init
logFile := filepath.Join(b.TempDir(), "access.log")
logHandler, err := initTestHttpLogs(logFile)
require.NoError(b, err)
noLogHandler := testHttpHandler()
// Run benchmarks
b.Run("With logging", func(b *testing.B) {
b.RunParallel(func(p *testing.PB) {
for p.Next() {
logHandler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/testpath", nil))
}
})
})
b.Run("Without logging", func(b *testing.B) {
b.RunParallel(func(p *testing.PB) {
for p.Next() {
noLogHandler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/testpath", nil))
}
})
})
}