Files
mailgoserver/internal/webui/webmail_compose_contacts_test.go
T

67 lines
2.5 KiB
Go

package webui
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
// TestWebmailComposeSendAutoSavesContacts confirms a successful send auto-adds its
// To/Cc recipients to the sender's own Contacts address book (tests/todo.md's Claude
// suggestion #5), preserving a typed display name, while never adding the sender's
// own address and never overwriting a contact that already exists.
func TestWebmailComposeSendAutoSavesContacts(t *testing.T) {
app := newTestApp(t)
mux := app.Mux()
domains, _ := app.DB.ListDomains()
domainID := domains[0].ID
senderID := createTestMailboxWithPassword(t, app, "sender2@example.com", domainID, "sender-password-1!")
createTestMailboxWithPassword(t, app, "recipient2@example.com", domainID, "recipient-password-1!")
cookie := webmailLoginSession(t, app, senderID)
// A contact already on file should keep its own name, not get overwritten by
// whatever display name this send happens to use.
if _, err := app.DB.CreateContact(senderID, "existing@example.com", "Already Saved", "555-0000"); err != nil {
t.Fatal(err)
}
form := url.Values{
"to": {"Recipient Two <recipient2@example.com>"},
"cc": {"existing@example.com, sender2@example.com"},
"subject": {"Hello there"},
"body_html": {"This is the message body."},
}
req := httptest.NewRequest(http.MethodPost, MailboxPrefix+"/mail/compose", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(cookie)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusFound {
t.Fatalf("compose send: status=%d body=%s", rec.Code, rec.Body.String())
}
contacts, err := app.DB.ListContacts(senderID)
if err != nil {
t.Fatal(err)
}
byEmail := map[string]string{}
for _, c := range contacts {
byEmail[c.Email] = c.Name
}
if name, ok := byEmail["recipient2@example.com"]; !ok || name != "Recipient Two" {
t.Errorf("expected an auto-saved contact 'Recipient Two <recipient2@example.com>', got %+v", byEmail)
}
if name, ok := byEmail["existing@example.com"]; !ok || name != "Already Saved" {
t.Errorf("expected the existing contact's name left untouched, got %+v", byEmail)
}
if _, ok := byEmail["sender2@example.com"]; ok {
t.Errorf("did not expect the sender's own address auto-saved as a contact, got %+v", byEmail)
}
if len(contacts) != 2 {
t.Errorf("expected exactly 2 contacts (existing + newly auto-saved), got %d: %+v", len(contacts), contacts)
}
}