Skip to content

Commit

Permalink
Make sure to handle error returned by ReadCloser.Close in 'defer' sta…
Browse files Browse the repository at this point in the history
…tements in 'helper_http.go'

This is considered unsafe by gosec otherwise. See [1].

This also makes sure to fix the warning with calling defer in a loop.

[1] securego/gosec#512
  • Loading branch information
rm3l committed Mar 27, 2023
1 parent deebf3d commit a1be6d6
Showing 1 changed file with 30 additions and 15 deletions.
45 changes: 30 additions & 15 deletions tests/helper/helper_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,49 @@ import (
func HttpWaitForWithStatus(url string, match string, maxRetry int, interval int, expectedCode int) {
fmt.Fprintf(GinkgoWriter, "Checking %s, for %s\n", url, match)

var body []byte
// #nosec
// gosec:G107, G402 -> This is safe since it's just used for testing.
transporter := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
httpClient := &http.Client{Transport: transporter}

getFromUrl := func() (statusCode int, responseBody []byte, err error) {
resp, err := httpClient.Get(url)
if err != nil {
return 0, nil, err
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
fmt.Fprintf(GinkgoWriter, "[warning] error closing response body for %q: %v\n", url, err)
}
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, body, nil
}

var body string
for i := 0; i < maxRetry; i++ {
fmt.Fprintf(GinkgoWriter, "try %d of %d\n", i, maxRetry)

// #nosec
// gosec:G107, G402 -> This is safe since it's just used for testing.
transporter := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: transporter}
resp, err := client.Get(url)
statusCode, responseBody, err := getFromUrl()
if err != nil {
// we log the error and sleep again because this could mean the component is not up yet
fmt.Fprintln(GinkgoWriter, "error while requesting:", err.Error())
fmt.Fprintf(GinkgoWriter, "error while requesting: %v\n", err)
time.Sleep(time.Duration(interval) * time.Second)
continue
}
defer resp.Body.Close()
if resp.StatusCode == expectedCode {
body, _ = io.ReadAll(resp.Body)
if strings.Contains(string(body), match) {
if statusCode == expectedCode {
body = string(responseBody)
if strings.Contains(body, match) {
return
}

}
time.Sleep(time.Duration(interval) * time.Second)
}
fmt.Fprintf(GinkgoWriter, "Last output from %s: %s\n", url, string(body))
fmt.Fprintf(GinkgoWriter, "Last output from %s: %s\n", url, body)
Fail(fmt.Sprintf("Failed after %d retries. Content in %s doesn't include '%s'.", maxRetry, url, match))
}

0 comments on commit a1be6d6

Please sign in to comment.