testHTTPRequest tries the given test case, comparing the result code, content type, and result prefix.
(t *testing.T, baseURL string, tc httpTestCase, apikey string)
| 444 | // testHTTPRequest tries the given test case, comparing the result code, |
| 445 | // content type, and result prefix. |
| 446 | func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) { |
| 447 | // Since running tests in parallel, the previous 1s timeout proved to be too short. |
| 448 | // https://github.com/syncthing/syncthing/issues/9455 |
| 449 | timeout := 10 * time.Second |
| 450 | if tc.Timeout > 0 { |
| 451 | timeout = tc.Timeout |
| 452 | } |
| 453 | cli := &http.Client{ |
| 454 | Timeout: timeout, |
| 455 | } |
| 456 | |
| 457 | req, err := http.NewRequest("GET", baseURL+tc.URL, nil) |
| 458 | if err != nil { |
| 459 | t.Errorf("Unexpected error requesting %s: %v", tc.URL, err) |
| 460 | return |
| 461 | } |
| 462 | req.Header.Set("X-API-Key", apikey) |
| 463 | |
| 464 | resp, err := cli.Do(req) |
| 465 | if err != nil { |
| 466 | t.Errorf("Unexpected error requesting %s: %v", tc.URL, err) |
| 467 | return |
| 468 | } |
| 469 | defer resp.Body.Close() |
| 470 | |
| 471 | if resp.StatusCode != tc.Code { |
| 472 | t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status) |
| 473 | return |
| 474 | } |
| 475 | |
| 476 | ct := resp.Header.Get("Content-Type") |
| 477 | if !strings.HasPrefix(ct, tc.Type) { |
| 478 | t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct) |
| 479 | return |
| 480 | } |
| 481 | |
| 482 | data, err := io.ReadAll(resp.Body) |
| 483 | if err != nil { |
| 484 | t.Errorf("Unexpected error reading %s: %v", tc.URL, err) |
| 485 | return |
| 486 | } |
| 487 | |
| 488 | if !bytes.HasPrefix(data, []byte(tc.Prefix)) { |
| 489 | t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data) |
| 490 | return |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | func getSessionCookie(cookies []*http.Cookie) (*http.Cookie, bool) { |
| 495 | for _, cookie := range cookies { |
no test coverage detected