package signalbot import ( "context" "encoding/json" "errors" "io" "net/http" "reflect" "testing" ) // captureSend serves POST /v2/send, recording the decoded body, and answers // with status/body. func (f *fakeAPI) captureSend(t *testing.T, status int, body string) *map[string]any { t.Helper() got := new(map[string]any) f.mux.HandleFunc("POST /v2/send", func(w http.ResponseWriter, r *http.Request) { if ct := r.Header.Get("Content-Type"); ct != "application/json" { t.Errorf("Content-Type = %q", ct) } b, _ := io.ReadAll(r.Body) if err := json.Unmarshal(b, got); err != nil { t.Errorf("decode body %s: %v", b, err) } w.WriteHeader(status) _, _ = w.Write([]byte(body)) }) return got } func TestSendPayload(t *testing.T) { f := newFakeAPI(t) f.accounts(`[{"number":"+331","aci":"a-1"}]`) got := f.captureSend(t, 201, `{"timestamp":"1"}`) if err := mustNew(t, f.URL).Send(context.Background(), "group.QUJD", "hi"); err != nil { t.Fatalf("Send: %v", err) } want := map[string]any{ "number": "+331", "recipients": []any{"group.QUJD"}, "message": "hi", "text_mode": "normal", } if !reflect.DeepEqual(*got, want) { t.Fatalf("body = %v, want %v", *got, want) } } func TestSendUsesACIWhenNoNumber(t *testing.T) { f := newFakeAPI(t) f.accounts(`[{"number":"","aci":"a-2"}]`) got := f.captureSend(t, 201, ``) if err := mustNew(t, f.URL).Send(context.Background(), "+332", "hi"); err != nil { t.Fatalf("Send: %v", err) } if (*got)["number"] != "a-2" { t.Fatalf("number = %v, want a-2", (*got)["number"]) } } func TestSendEmptyText(t *testing.T) { f := newFakeAPI(t) f.accounts(`[{"number":"+331"}]`) f.captureSend(t, 201, ``) c := mustNew(t, f.URL) for _, text := range []string{"", " \n"} { if err := c.Send(context.Background(), "+332", text); !errors.Is(err, ErrEmptyText) { t.Errorf("Send(%q) err = %v, want ErrEmptyText", text, err) } } if n := f.hitCount("POST /v2/send"); n != 0 { t.Fatalf("send endpoint hit %d times, want 0", n) } } func TestSendUnicodeRoundTrip(t *testing.T) { f := newFakeAPI(t) f.accounts(`[{"number":"+331"}]`) got := f.captureSend(t, 201, ``) text := "Nouveauté 🎬\nligne 2" if err := mustNew(t, f.URL).Send(context.Background(), "+332", text); err != nil { t.Fatalf("Send: %v", err) } if (*got)["message"] != text { t.Fatalf("message = %q, want %q", (*got)["message"], text) } } func TestSendErrors(t *testing.T) { f := newFakeAPI(t) f.accounts(`[{"number":"+331"}]`) f.captureSend(t, 400, `{"error":"Invalid group id"}`) err := mustNew(t, f.URL).Send(context.Background(), "group.x", "hi") var apiErr *APIError if !errors.As(err, &apiErr) || apiErr.StatusCode != 400 || apiErr.Message != "Invalid group id" { t.Fatalf("err = %v, want APIError 400 Invalid group id", err) } f2 := newFakeAPI(t) f2.accounts(`[{"number":"+331"}]`) f2.captureSend(t, 429, `{"error":"rate limit","challenge_tokens":["t"]}`) err = mustNew(t, f2.URL).Send(context.Background(), "group.x", "hi") if !errors.Is(err, ErrRateLimited) { t.Fatalf("err = %v, want ErrRateLimited", err) } }