forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutil.go
61 lines (55 loc) · 1.32 KB
/
testutil.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
package test
import (
"context"
"fmt"
"log"
"net"
"time"
"k8s.io/client-go/tools/cache"
)
// StartInformer is a helper to start an informer, wait for its cache to sync and return a cancel func
func StartInformer(informer cache.SharedIndexInformer) context.CancelFunc {
ctx, cancel := context.WithCancel(context.Background())
go informer.Run(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) {
log.Fatal("Timed out waiting for informer cache to sync")
}
return cancel
}
// GetFreePort finds an available free port on the OS
func GetFreePort() (int, error) {
ln, err := net.Listen("tcp", "[::]:0")
if err != nil {
return 0, err
}
return ln.Addr().(*net.TCPAddr).Port, ln.Close()
}
// WaitForPortListen waits until the given address is listening on the port
func WaitForPortListen(addr string, timeout time.Duration) error {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
timer := time.NewTimer(timeout)
if timeout == 0 {
timer.Stop()
} else {
defer timer.Stop()
}
for {
select {
case <-ticker.C:
if portIsOpen(addr) {
return nil
}
case <-timer.C:
return fmt.Errorf("timeout after %s", timeout.String())
}
}
}
func portIsOpen(addr string) bool {
conn, err := net.Dial("tcp", addr)
if err != nil {
return false
}
_ = conn.Close()
return true
}