client_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2020 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package client // import "miniflux.app/http/client"
  5. import (
  6. "os"
  7. "testing"
  8. "miniflux.app/config"
  9. )
  10. func TestClientWithDelay(t *testing.T) {
  11. clt := New("http://httpbin.org/delay/5")
  12. clt.ClientTimeout = 1
  13. _, err := clt.Get()
  14. if err == nil {
  15. t.Fatal(`The client should stops after 1 second`)
  16. }
  17. }
  18. func TestClientWithError(t *testing.T) {
  19. clt := New("http://httpbin.org/status/502")
  20. clt.ClientTimeout = 1
  21. response, err := clt.Get()
  22. if err != nil {
  23. t.Fatal(err)
  24. }
  25. if response.StatusCode != 502 {
  26. t.Fatalf(`Unexpected response status code: %d`, response.StatusCode)
  27. }
  28. if !response.HasServerFailure() {
  29. t.Fatal(`A 500 error is considered as server failure`)
  30. }
  31. }
  32. func TestClientWithResponseTooLarge(t *testing.T) {
  33. clt := New("http://httpbin.org/bytes/100")
  34. clt.ClientMaxBodySize = 10
  35. _, err := clt.Get()
  36. if err == nil {
  37. t.Fatal(`The client should fails when reading a response too large`)
  38. }
  39. }
  40. func TestClientWithBasicAuth(t *testing.T) {
  41. clt := New("http://httpbin.org/basic-auth/testuser/testpassword")
  42. clt.WithCredentials("testuser", "testpassword")
  43. _, err := clt.Get()
  44. if err != nil {
  45. t.Fatalf(`The client should be authenticated successfully: %v`, err)
  46. }
  47. }
  48. func TestClientRequestUserAgent(t *testing.T) {
  49. clt := New("http://httpbin.org")
  50. if clt.requestUserAgent != DefaultUserAgent {
  51. t.Errorf(`The client had default User-Agent %q, wanted %q`, clt.requestUserAgent, DefaultUserAgent)
  52. }
  53. userAgent := "Custom User Agent"
  54. os.Setenv("HTTP_CLIENT_USER_AGENT", userAgent)
  55. opts, err := config.NewParser().ParseEnvironmentVariables()
  56. if err != nil {
  57. t.Fatalf(`Parsing config failed: %v`, err)
  58. }
  59. clt = NewClientWithConfig("http://httpbin.org", opts)
  60. if clt.requestUserAgent != userAgent {
  61. t.Errorf(`The client had User-Agent %q, wanted %q`, clt.requestUserAgent, userAgent)
  62. }
  63. }