client_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package client // import "miniflux.app/http/client"
  4. import (
  5. "fmt"
  6. "net/http/httptest"
  7. "os"
  8. "testing"
  9. "github.com/mccutchen/go-httpbin/v2/httpbin"
  10. )
  11. var srv *httptest.Server
  12. func TestMain(m *testing.M) {
  13. srv = httptest.NewServer(httpbin.New())
  14. exitCode := m.Run()
  15. srv.Close()
  16. os.Exit(exitCode)
  17. }
  18. func MakeClient(path string) *Client {
  19. return New(fmt.Sprintf("%s%s", srv.URL, path))
  20. }
  21. func TestClientWithDelay(t *testing.T) {
  22. clt := MakeClient("/delay/5")
  23. clt.ClientTimeout = 1
  24. _, err := clt.Get()
  25. if err == nil {
  26. t.Fatal(`The client should stops after 1 second`)
  27. }
  28. }
  29. func TestClientWithError(t *testing.T) {
  30. clt := MakeClient("/status/502")
  31. clt.ClientTimeout = 5
  32. response, err := clt.Get()
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. if response.StatusCode != 502 {
  37. t.Fatalf(`Unexpected response status code: %d`, response.StatusCode)
  38. }
  39. if !response.HasServerFailure() {
  40. t.Fatal(`A 502 error is considered as server failure`)
  41. }
  42. }
  43. func TestClientWithResponseTooLarge(t *testing.T) {
  44. clt := MakeClient("/bytes/100")
  45. clt.ClientMaxBodySize = 10
  46. _, err := clt.Get()
  47. if err == nil {
  48. t.Fatal(`The client should fails when reading a response too large`)
  49. }
  50. }
  51. func TestClientWithBasicAuth(t *testing.T) {
  52. clt := MakeClient("/basic-auth/testuser/testpassword")
  53. clt.WithCredentials("testuser", "testpassword")
  54. _, err := clt.Get()
  55. if err != nil {
  56. t.Fatalf(`The client should be authenticated successfully: %v`, err)
  57. }
  58. }