package web import ( "net/http" "net/url" "strings" "testing" "supermarket/internal/secrets" "supermarket/internal/users" ) func TestConnectionsPage(t *testing.T) { s, h := newServerEdition(t) addUser(t, s, "owner@example.com", users.Owner, nil) admin := addUser(t, s, "ada@example.com", users.Admin, nil) admin.Name = "Ada" users.SaveProfile(s.DB, admin) ac := sessionFor(t, s, admin) member := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit}) if rec := as(h, sessionFor(t, s, member), http.MethodGet, "/settings/connections", nil); rec.Code != http.StatusForbidden { t.Errorf("member: %d", rec.Code) } rec := as(h, ac, http.MethodGet, "/settings/connections", nil) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Hunter.io") || !strings.Contains(rec.Body.String(), "Not set up") { t.Fatalf("page: %d", rec.Code) } // Ada saves the Hunter.io key: she's recorded as having connected it. if rec := as(h, ac, http.MethodPost, "/settings/sources", url.Values{secrets.HunterAPIKey: {"hk"}}); rec.Code != http.StatusSeeOther { t.Fatalf("save: %d", rec.Code) } if s.Secrets.Get(secrets.HunterAPIKey) != "hk" { t.Fatal("not saved") } body := as(h, ac, http.MethodGet, "/settings/connections", nil).Body.String() row := body[strings.Index(body, "Hunter.io"):] row = row[:strings.Index(row, "")] if !strings.Contains(row, "Connected") || !strings.Contains(row, "Ada, just now") { t.Errorf("row: %s", row) } // A failed test shows it failing. s.noteCheckErr("hunter", "401 Unauthorized") body = as(h, ac, http.MethodGet, "/settings/connections", nil).Body.String() row = body[strings.Index(body, "Hunter.io"):] row = row[:strings.Index(row, "")] if !strings.Contains(row, "Failing") || !strings.Contains(row, "401 Unauthorized") { t.Errorf("failing row: %s", row) } // Removing it is recorded too. as(h, ac, http.MethodPost, "/settings/sources", url.Values{"remove:" + secrets.HunterAPIKey: {"on"}}) body = as(h, ac, http.MethodGet, "/settings/connections", nil).Body.String() if !strings.Contains(body, "Removed by Ada") { t.Error("removal not recorded") } } func TestServiceOf(t *testing.T) { for name, want := range map[string]string{ secrets.AnthropicAPIKey: "ai", secrets.XRefreshToken: "x", secrets.LinkedInPageAccessToken: "linkedin_page", secrets.MailPassword: "mail", secrets.GoogleClientID: "google", "totp:3": "", } { if got := serviceOf(name); got != want { t.Errorf("serviceOf(%s) = %q, want %q", name, got, want) } } }