func()

in infra/blueprint-test/pkg/utils/asserthttp.go [136:192]


func (ah *AssertHTTP) httpResponse(t testing.TB, r *http.Request, wantCode int, want ...string) func() (bool, error) {
	t.Helper()
	logger := GetLoggerFromT()

	return func() (bool, error) {
		t.Logf("Sending HTTP Request %s %s", r.Method, r.URL.String())
		got, err := ah.httpClient.Do(r)
		if err != nil {
			return false, err
		}
		defer got.Body.Close()

		// Determine if the request is successful, and if the response indicates
		// we should attempt a retry.
		ok, retry := httpRetryCondition(got.StatusCode)
		if ok {
			logger.Logf(t, "Successful HTTP Request %s %s", r.Method, r.URL.String())
		}

		// e is the wrapped error for all expectation mismatches.
		var e error
		if got.StatusCode != wantCode {
			e = errors.Join(e, fmt.Errorf("response code: got %d, want %d", got.StatusCode, wantCode))
		}

		// No further processing required.
		if len(want) == 0 {
			return false, e
		}

		b, err := io.ReadAll(got.Body)
		if err != nil {
			return retry, errors.Join(e, err)
		}

		if len(b) == 0 {
			return retry, errors.Join(e, errors.New("empty response body"))
		}

		out := string(b)
		var bodyErr error
		for _, fragment := range want {
			if !strings.Contains(out, fragment) {
				bodyErr = errors.Join(bodyErr, fmt.Errorf("response body does not contain %q", fragment))
			}
		}

		// Only log errors and response body once.
		if bodyErr != nil {
			logger.Logf(t, "response output:")
			logger.Logf(t, strings.TrimSpace(out))
			return retry, errors.Join(e, bodyErr)
		}

		return retry, e
	}
}