-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_server_test.go
85 lines (70 loc) · 1.47 KB
/
test_server_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
package lameduck
import (
"context"
"sync"
)
// NOTE: This file contains no tests of its own.
//
// Instead, it contains the definition for type testServer - a test
// object implementing this package's Server interface.
//
type testServer struct {
logger Logger
serve *gate
shutdown *gate
close *gate
}
func newTestServer(logger Logger, serveErr, shutdownErr, closeErr error) *testServer {
serveBlocking := true
if serveErr != nil {
serveBlocking = false
}
ts := &testServer{
logger: logger,
serve: newGate(serveErr, serveBlocking),
shutdown: newGate(shutdownErr, true),
close: newGate(closeErr, false),
}
return ts
}
func (ts *testServer) Serve(ctx context.Context) error {
err := ts.serve.wait(ctx)
ts.logger.Infof("Serve returned: %v", err)
return err
}
func (ts *testServer) Shutdown(ctx context.Context) error {
ts.serve.finish()
return ts.shutdown.wait(ctx)
}
func (ts *testServer) Close() error {
ts.serve.finish()
return ts.close.wait(context.Background())
}
type gate struct {
err error
done chan struct{}
once sync.Once
}
func newGate(err error, blocking bool) *gate {
g := &gate{err: err}
if blocking {
g.done = make(chan struct{})
}
return g
}
func (g *gate) wait(ctx context.Context) error {
if g.done == nil {
return g.err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-g.done:
return g.err
}
}
func (g *gate) finish() {
if g != nil && g.done != nil {
g.once.Do(func() { close(g.done) })
}
}