client_http_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package apiclient
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "testing"
  8. "time"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. func TestNewRequestInvalid(t *testing.T) {
  14. mux, urlx, teardown := setup()
  15. defer teardown()
  16. //missing slash in uri
  17. apiURL, err := url.Parse(urlx)
  18. if err != nil {
  19. log.Fatalf("parsing api url: %s", apiURL)
  20. }
  21. client, err := NewClient(&Config{
  22. MachineID: "test_login",
  23. Password: "test_password",
  24. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  25. URL: apiURL,
  26. VersionPrefix: "v1",
  27. })
  28. if err != nil {
  29. t.Fatalf("new api client: %s", err.Error())
  30. }
  31. /*mock login*/
  32. mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
  33. w.WriteHeader(http.StatusUnauthorized)
  34. w.Write([]byte(`{"code": 401, "message" : "bad login/password"}`))
  35. })
  36. mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
  37. testMethod(t, r, "GET")
  38. w.WriteHeader(http.StatusOK)
  39. })
  40. _, _, err = client.Alerts.List(context.Background(), AlertsListOpts{})
  41. assert.Contains(t, err.Error(), `building request: BaseURL must have a trailing slash, but `)
  42. }
  43. func TestNewRequestTimeout(t *testing.T) {
  44. mux, urlx, teardown := setup()
  45. defer teardown()
  46. //missing slash in uri
  47. apiURL, err := url.Parse(urlx + "/")
  48. if err != nil {
  49. log.Fatalf("parsing api url: %s", apiURL)
  50. }
  51. client, err := NewClient(&Config{
  52. MachineID: "test_login",
  53. Password: "test_password",
  54. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  55. URL: apiURL,
  56. VersionPrefix: "v1",
  57. })
  58. if err != nil {
  59. t.Fatalf("new api client: %s", err.Error())
  60. }
  61. /*mock login*/
  62. mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
  63. time.Sleep(2 * time.Second)
  64. })
  65. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  66. defer cancel()
  67. _, _, err = client.Alerts.List(ctx, AlertsListOpts{})
  68. assert.Contains(t, err.Error(), `performing request: context deadline exceeded`)
  69. }