2020-11-30 15:15:07 +00:00
|
|
|
package apiclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2023-06-22 13:01:34 +00:00
|
|
|
|
2023-07-28 14:35:08 +00:00
|
|
|
"github.com/crowdsecurity/go-cs-lib/version"
|
2020-11-30 15:15:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestNewRequestInvalid(t *testing.T) {
|
|
|
|
mux, urlx, teardown := setup()
|
|
|
|
defer teardown()
|
|
|
|
//missing slash in uri
|
|
|
|
apiURL, err := url.Parse(urlx)
|
|
|
|
if err != nil {
|
2022-10-13 08:42:46 +00:00
|
|
|
t.Fatalf("parsing api url: %s", apiURL)
|
2020-11-30 15:15:07 +00:00
|
|
|
}
|
|
|
|
client, err := NewClient(&Config{
|
|
|
|
MachineID: "test_login",
|
|
|
|
Password: "test_password",
|
2023-05-23 08:52:47 +00:00
|
|
|
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
|
2020-11-30 15:15:07 +00:00
|
|
|
URL: apiURL,
|
|
|
|
VersionPrefix: "v1",
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-06-22 13:53:53 +00:00
|
|
|
t.Fatalf("new api client: %s", err)
|
2020-11-30 15:15:07 +00:00
|
|
|
}
|
|
|
|
/*mock login*/
|
|
|
|
mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
w.Write([]byte(`{"code": 401, "message" : "bad login/password"}`))
|
|
|
|
})
|
|
|
|
|
|
|
|
mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
testMethod(t, r, "GET")
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
})
|
|
|
|
|
|
|
|
_, _, err = client.Alerts.List(context.Background(), AlertsListOpts{})
|
|
|
|
assert.Contains(t, err.Error(), `building request: BaseURL must have a trailing slash, but `)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestNewRequestTimeout(t *testing.T) {
|
|
|
|
mux, urlx, teardown := setup()
|
|
|
|
defer teardown()
|
|
|
|
//missing slash in uri
|
|
|
|
apiURL, err := url.Parse(urlx + "/")
|
|
|
|
if err != nil {
|
2022-10-13 08:42:46 +00:00
|
|
|
t.Fatalf("parsing api url: %s", apiURL)
|
2020-11-30 15:15:07 +00:00
|
|
|
}
|
|
|
|
client, err := NewClient(&Config{
|
|
|
|
MachineID: "test_login",
|
|
|
|
Password: "test_password",
|
2023-05-23 08:52:47 +00:00
|
|
|
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
|
2020-11-30 15:15:07 +00:00
|
|
|
URL: apiURL,
|
|
|
|
VersionPrefix: "v1",
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-06-22 13:53:53 +00:00
|
|
|
t.Fatalf("new api client: %s", err)
|
2020-11-30 15:15:07 +00:00
|
|
|
}
|
|
|
|
/*mock login*/
|
|
|
|
mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
})
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
_, _, err = client.Alerts.List(ctx, AlertsListOpts{})
|
|
|
|
assert.Contains(t, err.Error(), `performing request: context deadline exceeded`)
|
|
|
|
}
|