-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
121 lines (101 loc) · 2.17 KB
/
Copy pathmain_test.go
File metadata and controls
121 lines (101 loc) · 2.17 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
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
package main
import (
"context"
"fmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/client-go/rest"
"net"
"os"
"os/signal"
ctrl "sigs.k8s.io/controller-runtime"
"sync"
"syscall"
"testing"
"time"
)
func Test_main(t *testing.T) {
t.Run("should start server", func(t *testing.T) {
// override default controller method to retrieve a kube config
oldGetConfigDelegate := ctrl.GetConfig
defer func() {
ctrl.GetConfig = oldGetConfigDelegate
}()
ctrl.GetConfig = func() (*rest.Config, error) {
return &rest.Config{}, nil
}
err := os.Setenv("API_KEY", "myApiKey")
err = os.Setenv("NAMESPACE", "ecosystem")
require.NoError(t, err)
// Create a channel to receive signals
sigChan := make(chan os.Signal, 1)
// Register SIGINT to the signal channel
signal.Notify(sigChan, syscall.SIGINT)
go func() {
assert.NotPanics(t, main)
}()
time.Sleep(100 * time.Millisecond)
// assert correct start of the server
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
assert.True(t, checkPort(8080, false))
}()
wg.Wait()
sendSignal(syscall.SIGINT)
// assert graceful shutdown
wg.Add(1)
go func() {
defer wg.Done()
assert.True(t, checkPort(8080, true))
}()
wg.Wait()
})
}
func checkPort(port int, available bool) bool {
ctxWithCancel, cancel := context.WithTimeout(context.TODO(), 3*time.Second)
defer cancel()
resultChan := make(chan bool)
go func() {
loop:
for {
select {
case <-ctxWithCancel.Done():
break loop
default:
if result := isPortAvailable(port); result == available {
resultChan <- result
}
}
}
}()
select {
case <-ctxWithCancel.Done():
return false
case <-resultChan:
return true
}
}
func isPortAvailable(port int) bool {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
// Port is not available
return false
}
defer func() {
_ = listener.Close()
}()
// Port is available
return true
}
// Function to send signal to the process
func sendSignal(sig os.Signal) {
pid := os.Getpid()
process, err := os.FindProcess(pid)
if err != nil {
// Handle error
return
}
process.Signal(sig)
}