Skip to content
quarry Artifact [c86d78a72c]
Login

Artifact [c86d78a72c]

Artifact c86d78a72c1e2447ff1be92bad214824d39abbfbd11241f2087959df869ec06d:


package mail

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// The client speaks Resend's one endpoint: bearer key, JSON body, the
// id back on success and the service's own reason on refusal.
func TestSendSpeaksResend(t *testing.T) {
	var got map[string]any
	var auth string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		auth = r.Header.Get("Authorization")
		_ = json.NewDecoder(r.Body).Decode(&got)
		if r.URL.Path != "/emails" {
			w.WriteHeader(404)
			return
		}
		if strings.Contains(got["to"].([]any)[0].(string), "refuse") {
			w.WriteHeader(422)
			w.Write([]byte(`{"name":"validation_error","message":"The from domain is not verified"}`))
			return
		}
		w.Write([]byte(`{"id":"em_123"}`))
	}))
	defer srv.Close()
	c := New("re_key", "quarry <[email protected]>").WithBase(srv.URL)
	id, err := c.Send(context.Background(), Message{To: "[email protected]", Subject: "hi", Text: "link"})
	if err != nil || id != "em_123" {
		t.Fatalf("send = %q %v", id, err)
	}
	if auth != "Bearer re_key" || got["from"] != "quarry <[email protected]>" || got["subject"] != "hi" {
		t.Errorf("request was %v with auth %q", got, auth)
	}
	_, err = c.Send(context.Background(), Message{To: "[email protected]", Subject: "hi", Text: "x"})
	if err == nil || !strings.Contains(err.Error(), "not verified") {
		t.Errorf("a refusal does not carry the service's reason: %v", err)
	}
	if _, err := c.Send(context.Background(), Message{To: "nope", Subject: "hi"}); err == nil {
		t.Errorf("a non-address was sent")
	}
	// No key: no client, and an honest error rather than a silent drop.
	var none *Resend = New("", "")
	if _, err := none.Send(context.Background(), Message{To: "[email protected]"}); err != ErrNoMail {
		t.Errorf("nil client: %v", err)
	}
}