-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain_test.go
More file actions
95 lines (80 loc) · 2.11 KB
/
Copy pathmain_test.go
File metadata and controls
95 lines (80 loc) · 2.11 KB
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
package main
import (
"context"
"io"
"net"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRunWithTimeoutCompletes(t *testing.T) {
assert.True(t, runWithTimeout(time.Second, func() {}))
}
func TestRunWithTimeoutTimesOut(t *testing.T) {
start := time.Now()
assert.False(t, runWithTimeout(10*time.Millisecond, func() {
time.Sleep(500 * time.Millisecond)
}))
assert.Less(t, time.Since(start), 250*time.Millisecond)
}
func TestRunWithTimeoutRecoversPanic(t *testing.T) {
assert.True(t, runWithTimeout(time.Second, func() {
panic("quota save failed")
}))
}
func TestShutdownHTTPServerClosesActiveHandlersAfterTimeout(t *testing.T) {
handlerStarted := make(chan struct{})
handlerDone := make(chan struct{})
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(handlerStarted)
<-r.Context().Done()
close(handlerDone)
}),
}
t.Cleanup(func() {
_ = server.Close()
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
serveDone := make(chan error, 1)
go func() {
serveDone <- server.Serve(listener)
}()
client := &http.Client{Timeout: time.Second}
clientDone := make(chan error, 1)
go func() {
resp, err := client.Get("http://" + listener.Addr().String())
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}
clientDone <- err
}()
select {
case <-handlerStarted:
case <-time.After(time.Second):
t.Fatal("handler did not start")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
shutdownHTTPServer(ctx, server)
select {
case <-handlerDone:
case <-time.After(250 * time.Millisecond):
t.Fatal("active handler was not force-closed after shutdown timeout")
}
select {
case err := <-serveDone:
assert.ErrorIs(t, err, http.ErrServerClosed)
case <-time.After(250 * time.Millisecond):
t.Fatal("server did not stop after forced close")
}
select {
case <-clientDone:
case <-time.After(time.Second):
t.Fatal("client request did not finish after forced close")
}
}