package peer import ( "encoding/json" "net/http" "net/http/httptest" "testing" "time" "git.dracodev.net/Projets/clip-sync/internal/config" "git.dracodev.net/Projets/clip-sync/internal/dedup" ) func TestBroadcastSendsPayload(t *testing.T) { received := make(chan dedup.Payload, 1) // Start a fake peer server. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { t.Errorf("expected POST, got %s", r.Method) } if r.URL.Path != "/clip" { t.Errorf("expected /clip, got %s", r.URL.Path) } var p dedup.Payload if err := json.NewDecoder(r.Body).Decode(&p); err != nil { t.Errorf("decode: %v", err) } received <- p w.WriteHeader(http.StatusNoContent) })) defer ts.Close() peers := []config.PeerConfig{ {Name: "test-peer", Addr: ts.Listener.Addr().String()}, } b := NewBroadcaster(peers, "my-machine", Options{}) b.Broadcast("hello, peer!") select { case p := <-received: if p.Text != "hello, peer!" { t.Errorf("text = %q, want \"hello, peer!\"", p.Text) } if p.Origin != "my-machine" { t.Errorf("origin = %q, want \"my-machine\"", p.Origin) } if p.Ts == 0 { t.Error("timestamp should be non-zero") } case <-time.After(5 * time.Second): t.Fatal("timeout waiting for broadcast") } } func TestBroadcastEmptyPeers(t *testing.T) { // Should not panic or error with zero peers. b := NewBroadcaster(nil, "my-machine", Options{}) b.Broadcast("test") b.Broadcast("") }