87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/monlet/agent/internal/scheduler"
|
|
)
|
|
|
|
func TestSendHeartbeatSuccess(t *testing.T) {
|
|
var got HeartbeatRequest
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/api/v1/heartbeat" || r.Header.Get("Authorization") != "Bearer tok" {
|
|
http.Error(w, "bad", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&got)
|
|
w.WriteHeader(http.StatusAccepted)
|
|
_, _ = io.WriteString(w, `{"accepted":true}`)
|
|
}))
|
|
defer srv.Close()
|
|
c := New(srv.URL, "tok", "a1", "v0")
|
|
err := c.SendHeartbeat(context.Background(), HeartbeatRequest{AgentID: "a1", ObservedAt: time.Now().UTC(), Hostname: "h", Version: "v0"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got.AgentID != "a1" {
|
|
t.Fatalf("got %+v", got)
|
|
}
|
|
}
|
|
|
|
func TestSendEventsBatch(t *testing.T) {
|
|
var got EventBatchRequest
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_ = json.NewDecoder(r.Body).Decode(&got)
|
|
w.WriteHeader(http.StatusAccepted)
|
|
_, _ = io.WriteString(w, `{"accepted":2,"deduplicated":0}`)
|
|
}))
|
|
defer srv.Close()
|
|
c := New(srv.URL, "tok", "a1", "v0")
|
|
resp, err := c.SendEvents(context.Background(), []scheduler.Event{{EventID: "x"}, {EventID: "y"}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if resp.Accepted != 2 || got.AgentID != "a1" || len(got.Events) != 2 {
|
|
t.Fatalf("resp=%+v got=%+v", resp, got)
|
|
}
|
|
}
|
|
|
|
func TestSendEventsTooBig(t *testing.T) {
|
|
c := New("http://x", "t", "a1", "v0")
|
|
big := make([]scheduler.Event, MaxBatchEvents+1)
|
|
_, err := c.SendEvents(context.Background(), big)
|
|
if err == nil {
|
|
t.Fatal("expected error")
|
|
}
|
|
}
|
|
|
|
func TestRetryableClassification(t *testing.T) {
|
|
if Retryable(&HTTPError{Status: 400, Body: ""}) {
|
|
t.Fatal("4xx should not retry")
|
|
}
|
|
if !Retryable(&HTTPError{Status: 503}) {
|
|
t.Fatal("5xx should retry")
|
|
}
|
|
if !Retryable(context.DeadlineExceeded) {
|
|
t.Fatal("network error should retry")
|
|
}
|
|
}
|
|
|
|
func TestBackoffBounds(t *testing.T) {
|
|
for a := 1; a <= 10; a++ {
|
|
d := Delay(a)
|
|
if d < BackoffMin*4/5 {
|
|
t.Fatalf("attempt %d: delay %s below min", a, d)
|
|
}
|
|
if d > BackoffMax*6/5 {
|
|
t.Fatalf("attempt %d: delay %s above max", a, d)
|
|
}
|
|
}
|
|
}
|