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