-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
101 lines (86 loc) · 2.05 KB
/
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package httpok
import (
"fmt"
"log"
"net"
"net/http"
"os"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func isPortInUse(port int) (bool, error) {
// Try to listen on the specified port
ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
// If there's an error, check if it's because the port is already in use
if opErr, ok := err.(*net.OpError); ok && opErr.Op == "listen" {
return true, nil
}
// Return the error if it's something else
return false, err
}
// If we can listen, the port is not in use, so close the listener
ln.Close()
return false, nil
}
// Helper function to get a free port
func getFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func TestGracefulServer(t *testing.T) {
// Generate a random free port
port, err := getFreePort()
if err != nil {
t.Fatalf("Failed to get free port: %v", err)
}
addr := fmt.Sprintf(":%d", port)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("Request received")
})
srv := &http.Server{
Addr: addr,
Handler: mux,
}
// Create GracefulServer with our custom server
gs := NewGracefulServer(srv)
var c chan os.Signal
go func() {
c = gs.Run()
}()
time.Sleep(1 * time.Second)
ok, err := isPortInUse(port)
if err != nil {
t.Fatalf("failed to check port in use: %v", err)
}
assert.True(t, ok)
resp, err := http.Get("http://localhost" + addr)
if err != nil {
t.Fatalf("failed to make request: %v", err)
}
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()
// Send SIGTERM down the pipe
c <- syscall.SIGTERM
time.Sleep(1 * time.Second)
resp, err = http.Get("http://localhost" + addr)
if err != nil {
assert.Error(t, err)
}
ok, err = isPortInUse(port)
if err != nil {
t.Fatalf("failed to check port in use: %v", err)
}
assert.False(t, ok)
}