-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
86 lines (72 loc) · 1.76 KB
/
main_test.go
File metadata and controls
86 lines (72 loc) · 1.76 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
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"testing"
"time"
)
func Test_run(t *testing.T) {
t.Parallel()
// creates listener on random free port
listenerForSrv := func(t *testing.T) net.Listener {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to create listener: %v", err)
}
return ln
}
t.Run("cancelling context stops the service", func(t *testing.T) {
ln := listenerForSrv(t)
defer ln.Close()
ctx, cancel := context.WithCancel(context.Background())
srvErr := make(chan error, 1)
go func() {
srvErr <- run(ctx, &srvConf{l: ln})
}()
cancel()
select {
case <-time.After(time.Second):
t.Fatal("server didn't stop within timeout")
case err := <-srvErr:
if err == nil {
t.Fatal("unexpectedly run returned nil error")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("expected %q, got %q", context.Canceled, err)
}
}
})
t.Run("http server is up", func(t *testing.T) {
ln := listenerForSrv(t)
defer ln.Close()
ctx, cancel := context.WithCancel(context.Background())
srvErr := make(chan error, 1)
go func() {
srvErr <- run(ctx, &srvConf{l: ln})
}()
c := &http.Client{Timeout: time.Second}
rsp, err := c.Get(fmt.Sprintf("http://%s", ln.Addr().String()))
if err != nil {
t.Errorf("GET request returned unexpected error: %v", err)
}
if rsp == nil {
t.Error("unexpectedly GET request returned nil response")
}
cancel()
select {
case <-time.After(time.Second):
t.Fatal("server didn't stop within timeout")
case err := <-srvErr:
if err == nil {
t.Fatal("unexpectedly run returned nil error")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("expected %q, got %q", context.Canceled, err)
}
}
})
}