...

Source file src/github.com/redhat-developer/odo/tests/helper/helper_http.go

Documentation: github.com/redhat-developer/odo/tests/helper

     1  package helper
     2  
     3  import (
     4  	"crypto/tls"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"strings"
     9  	"time"
    10  
    11  	. "github.com/onsi/ginkgo/v2"
    12  )
    13  
    14  // HttpWaitForWithStatus periodically (every interval) calls GET to given url
    15  // ends when result response contains match string and status code, or after the maxRetry
    16  func HttpWaitForWithStatus(url string, match string, maxRetry int, interval int, expectedCode int) {
    17  	fmt.Fprintf(GinkgoWriter, "Checking %s, for %s\n", url, match)
    18  
    19  	var body []byte
    20  
    21  	for i := 0; i < maxRetry; i++ {
    22  		fmt.Fprintf(GinkgoWriter, "try %d of %d\n", i, maxRetry)
    23  
    24  		// #nosec
    25  		// gosec:G107, G402 -> This is safe since it's just used for testing.
    26  		transporter := &http.Transport{
    27  			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    28  		}
    29  		client := &http.Client{Transport: transporter}
    30  		resp, err := client.Get(url)
    31  		if err != nil {
    32  			// we log the error and sleep again because this could mean the component is not up yet
    33  			fmt.Fprintln(GinkgoWriter, "error while requesting:", err.Error())
    34  			time.Sleep(time.Duration(interval) * time.Second)
    35  			continue
    36  		}
    37  		defer func() {
    38  			if cErr := resp.Body.Close(); cErr != nil {
    39  				fmt.Fprintf(GinkgoWriter, "[warn] error closing response body: %v\n", cErr)
    40  			}
    41  		}()
    42  		if resp.StatusCode == expectedCode {
    43  			body, _ = io.ReadAll(resp.Body)
    44  			if strings.Contains(string(body), match) {
    45  				return
    46  			}
    47  
    48  		}
    49  		time.Sleep(time.Duration(interval) * time.Second)
    50  	}
    51  	fmt.Fprintf(GinkgoWriter, "Last output from %s: %s\n", url, string(body))
    52  	Fail(fmt.Sprintf("Failed after %d retries. Content in %s doesn't include '%s'.", maxRetry, url, match))
    53  }
    54  
    55  // GetCustomStartPort returns a port that can be used as starting value for custom port mapping.
    56  // Because of the way Ginkgo runs specs in parallel (by isolating them in different processes),
    57  // this function needs to be called in a Before* node or test spec.
    58  // It returns a starting value that aims at minimizing the probability of collisions.
    59  // Callers can then safely increment the returned value in their specs if needed.
    60  func GetCustomStartPort() int {
    61  	return 30000 + 100*GinkgoParallelProcess()
    62  }
    63  

View as plain text