package api import ( "bytes" "context" "net/http" "net/http/httptest" "testing" "github.com/go-chi/chi/v5" ) func newMeProfileRouter(h *handlers) chi.Router { r := chi.NewRouter() r.Put("/api/me/profile", h.handleUpdateMyProfile) return r } // A profile update changes only the fields it sends: an empty display name // clears it, an email is stored lowercased, and an invalid email or one // another account holds is refused with the profile unchanged. func TestUpdateProfile_ChangesOnlyTheFieldsSent(t *testing.T) { h, pool := testHandlers(t) other := seedUser(t, pool, "profother", "pw", false) if _, err := pool.Exec(context.Background(), "UPDATE users SET email = 'taken@example.com' WHERE id = $1", other.ID); err != nil { t.Fatalf("give the other account an email: %v", err) } user := seedUser(t, pool, "prof", "pw", false) str := func(s string) *string { return &s } for _, step := range []struct { body string status int wantName, wantMail *string // the stored profile after the request }{ {`{"display_name":"My Name"}`, http.StatusOK, str("My Name"), nil}, {`{"email":"User@Example.COM"}`, http.StatusOK, str("My Name"), str("user@example.com")}, {`{}`, http.StatusOK, str("My Name"), str("user@example.com")}, {`{"display_name":"Both","email":"both@example.com"}`, http.StatusOK, str("Both"), str("both@example.com")}, {`{"display_name":""}`, http.StatusOK, nil, str("both@example.com")}, {`{"email":"notanemail"}`, http.StatusBadRequest, nil, str("both@example.com")}, {`{"email":"taken@example.com"}`, http.StatusConflict, nil, str("both@example.com")}, } { req := withUser(httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(step.body))), user) rec := httptest.NewRecorder() newMeProfileRouter(h).ServeHTTP(rec, req) if rec.Code != step.status { t.Fatalf("%s: status %d, want %d; body=%s", step.body, rec.Code, step.status, rec.Body.String()) } var name, mail *string if err := pool.QueryRow(context.Background(), "SELECT display_name, email FROM users WHERE id = $1", user.ID).Scan(&name, &mail); err != nil { t.Fatalf("read profile: %v", err) } if !sameOptional(name, step.wantName) || !sameOptional(mail, step.wantMail) { t.Errorf("after %s: profile = (%q, %q), want (%q, %q)", step.body, deref(name), deref(mail), deref(step.wantName), deref(step.wantMail)) } } } // sameOptional reports whether two optional strings are both unset or equal. func sameOptional(a, b *string) bool { return (a == nil && b == nil) || (a != nil && b != nil && *a == *b) }