github.com/argoproj/argo-cd@v1.8.7/test/testutil.go (about)

     1  package test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"log"
     8  	"net"
     9  	"time"
    10  
    11  	"k8s.io/client-go/tools/cache"
    12  )
    13  
    14  // StartInformer is a helper to start an informer, wait for its cache to sync and return a cancel func
    15  func StartInformer(informer cache.SharedIndexInformer) context.CancelFunc {
    16  	ctx, cancel := context.WithCancel(context.Background())
    17  	go informer.Run(ctx.Done())
    18  	if !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) {
    19  		log.Fatal("Timed out waiting for informer cache to sync")
    20  	}
    21  	return cancel
    22  }
    23  
    24  // GetFreePort finds an available free port on the OS
    25  func GetFreePort() (int, error) {
    26  	ln, err := net.Listen("tcp", "[::]:0")
    27  	if err != nil {
    28  		return 0, err
    29  	}
    30  	return ln.Addr().(*net.TCPAddr).Port, ln.Close()
    31  }
    32  
    33  // WaitForPortListen waits until the given address is listening on the port
    34  func WaitForPortListen(addr string, timeout time.Duration) error {
    35  	ticker := time.NewTicker(100 * time.Millisecond)
    36  	defer ticker.Stop()
    37  	timer := time.NewTimer(timeout)
    38  	if timeout == 0 {
    39  		timer.Stop()
    40  	} else {
    41  		defer timer.Stop()
    42  	}
    43  	for {
    44  		select {
    45  		case <-ticker.C:
    46  			if portIsOpen(addr) {
    47  				return nil
    48  			}
    49  		case <-timer.C:
    50  			return fmt.Errorf("timeout after %s", timeout.String())
    51  		}
    52  	}
    53  }
    54  
    55  func portIsOpen(addr string) bool {
    56  	conn, err := net.Dial("tcp", addr)
    57  	if err != nil {
    58  		return false
    59  	}
    60  	_ = conn.Close()
    61  	return true
    62  }
    63  
    64  // Read the contents of a file and returns it as string. Panics on error.
    65  func MustLoadFileToString(path string) string {
    66  	o, err := ioutil.ReadFile(path)
    67  	if err != nil {
    68  		panic(err.Error())
    69  	}
    70  	return string(o)
    71  }