This repository has been archived by the owner on Mar 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
graceful_test.go
124 lines (97 loc) · 2.29 KB
/
graceful_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
114
115
116
117
118
119
120
121
122
123
124
package graceful
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"testing"
"time"
)
func TestListenAndServeTLS(t *testing.T) {
var buf bytes.Buffer
logger := log.New(&buf, "", 0)
go func() {
time.Sleep(10 * time.Millisecond)
signals <- os.Interrupt
}()
ListenAndServeTLS(&http.Server{
Addr: ":0", Handler: &testHandler{logger},
}, "testdata/server.crt", "testdata/server.key")
s := buf.String()
for _, want := range []string{
"Shutdown in testHandler",
} {
if !strings.Contains(s, want) {
t.Fatalf("log output does not include %q", want)
}
}
}
func TestLogListenAndServe(t *testing.T) {
t.Run("with logger", func(t *testing.T) {
var buf bytes.Buffer
logger := log.New(&buf, "", 0)
go func() {
time.Sleep(10 * time.Millisecond)
signals <- os.Interrupt
}()
LogListenAndServe(&http.Server{
Addr: ":0", Handler: &testHandler{logger},
}, logger)
s := buf.String()
for _, want := range []string{
"Server shutdown with timeout: 15s",
"Shutdown in testHandler",
} {
if !strings.Contains(s, want) {
t.Fatalf("log output does not include %q", want)
}
}
})
t.Run("with no logger", func(t *testing.T) {
go func() {
time.Sleep(10 * time.Millisecond)
signals <- os.Interrupt
}()
LogListenAndServe(&http.Server{
Addr: ":0", Handler: &testHandler{},
})
})
t.Run("with nil logger", func(t *testing.T) {
go func() {
time.Sleep(10 * time.Millisecond)
signals <- os.Interrupt
}()
LogListenAndServe(&http.Server{
Addr: ":0", Handler: &testHandler{},
}, nil)
})
}
func TestShutdown(t *testing.T) {
t.Run("nil-hs", func(t *testing.T) {
shutdown(nil, nil)
})
t.Run("nil-logger", func(t *testing.T) {
shutdown(&http.Server{}, nil)
})
t.Run("logger", func(t *testing.T) {
var buf bytes.Buffer
shutdown(&http.Server{}, log.New(&buf, "", 0))
want := fmt.Sprintf(ShutdownFormat+FinishedHTTP+FinishedFormat, Timeout, 15)
if got := buf.String(); got != want {
t.Fatalf("buf.String() = %q, want %q", got, want)
}
})
}
type testHandler struct {
logger *log.Logger
}
func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}
func (h *testHandler) Shutdown(ctx context.Context) error {
if h.logger != nil {
h.logger.Println("Shutdown in testHandler")
}
return nil
}