(t *testing.T, timeout time.Duration, ctx *testContext, httpMethod string, endpoint string, headers map[string]string, body any)
| 362 | } |
| 363 | |
| 364 | func sendHttpRequest[Res any](t *testing.T, timeout time.Duration, ctx *testContext, httpMethod string, endpoint string, headers map[string]string, body any) Res { |
| 365 | t.Helper() |
| 366 | defer func() { |
| 367 | ctx.client.expectedStatusCode = 0 |
| 368 | }() |
| 369 | b := ToJson(body) |
| 370 | if ctx.printPayload { |
| 371 | coloredPrintf("calling:\n\t%s %s\nwith:\n%s\n", httpMethod, endpoint, string(ToCleanJson(ctx.inlineJson, body))) |
| 372 | } |
| 373 | var result Res |
| 374 | err := runWithTimeout(timeout, func() (bool, errors.Error) { |
| 375 | request, err := http.NewRequest(httpMethod, endpoint, bytes.NewReader(b)) |
| 376 | if err != nil { |
| 377 | return false, errors.Convert(err) |
| 378 | } |
| 379 | request.Close = true |
| 380 | request.Header.Add("Content-Type", "application/json") |
| 381 | for header, headerVal := range headers { |
| 382 | request.Header.Add(header, headerVal) |
| 383 | } |
| 384 | response, err := http.DefaultClient.Do(request) |
| 385 | if err != nil { |
| 386 | return false, errors.Convert(err) |
| 387 | } |
| 388 | defer func() { |
| 389 | ctx.client.lastReturnedStatusCode = response.StatusCode |
| 390 | }() |
| 391 | if ctx.client.expectedStatusCode > 0 || response.StatusCode >= 300 { |
| 392 | if ctx.client.expectedStatusCode == 0 || ctx.client.expectedStatusCode != response.StatusCode { |
| 393 | if err = response.Body.Close(); err != nil { |
| 394 | return false, errors.Convert(err) |
| 395 | } |
| 396 | response.Close = true |
| 397 | return false, errors.HttpStatus(response.StatusCode).New(fmt.Sprintf("unexpected http status code calling [%s] %s: %d", httpMethod, endpoint, response.StatusCode)) |
| 398 | } |
| 399 | } |
| 400 | b, _ = io.ReadAll(response.Body) |
| 401 | if err = json.Unmarshal(b, &result); err != nil { |
| 402 | if response.StatusCode < 300 { |
| 403 | return false, errors.Convert(err) |
| 404 | } |
| 405 | // it's probably ok since the request failed anyway |
| 406 | } |
| 407 | if ctx.printPayload { |
| 408 | coloredPrintf("result: %s\n", ToCleanJson(ctx.inlineJson, b)) |
| 409 | } |
| 410 | if err = response.Body.Close(); err != nil { |
| 411 | return false, errors.Convert(err) |
| 412 | } |
| 413 | response.Close = true |
| 414 | return true, nil |
| 415 | }) |
| 416 | require.NoError(t, err) |
| 417 | return result |
| 418 | } |
| 419 | |
| 420 | func coloredPrintf(msg string, args ...any) { |
| 421 | msg = fmt.Sprintf(msg, args...) |
no test coverage detected