package web import ( "context" "errors" "log/slog" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) // signupAccounts is an account service whose sign-up answers with err. type signupAccounts struct { fakeAccounts err error } func (s signupAccounts) SignUp(context.Context, string, string, string) error { return s.err } func (signupAccounts) SignupOpen() bool { return true } func signupBody(t *testing.T, err error) string { t.Helper() mux := http.NewServeMux() NewAccountPages(signupAccounts{err: err}, nil, nil, "v0", slog.New(slog.DiscardHandler)).Register(mux) form := url.Values{"email": {"a@b.c"}, "name": {"A"}, "password": {"long enough password"}} req := httptest.NewRequest(http.MethodPost, "/signup", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) return rec.Body.String() } func TestASignupThatFailsSaysSoWithAReferenceAndNoDatabaseWords(t *testing.T) { body := signupBody(t, errors.New(`duplicate key value violates unique constraint "users_email_key"`)) if strings.Contains(body, "users_email_key") || strings.Contains(body, "constraint") { t.Errorf("the database's own words reached the page: %s", body) } if !strings.Contains(body, "was not created") || !strings.Contains(body, "reference: err-") { t.Errorf("no plain failure with a reference to give an operator: %s", body) } } func TestASignupSaysWhatToDoIfTheAddressHadAnAccount(t *testing.T) { // The service answers a taken address as it does a new one, so nobody // can find out from this page who has an account; what the page can do // is say what to do in either case. body := signupBody(t, nil) if !strings.Contains(body, "already had an account") || !strings.Contains(body, `href="/login"`) || !strings.Contains(body, "reset it") { t.Errorf("the done page leaves someone who already had an account stuck: %s", body) } }