Files
supermarket/internal/web/content_test.go
T
davidandClaude Opus 5.5 5451fe6d63 Reddit: posted by hand, with the rules pasted
Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:48:54 -07:00

395 lines
18 KiB
Go

package web
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/models"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
func TestContentPages(t *testing.T) {
s, h := newTestServer(t, nil)
if err := profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets."}); err != nil {
t.Fatal(err)
}
e := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner, RSS: []string{"https://jitsi.example/feed"}}
if err := inventory.Save(s.DB, e); err != nil {
t.Fatal(err)
}
id := strconv.FormatInt(e.ID, 10)
now := time.Now()
if _, err := content.SaveItems(s.DB, []models.ContentItem{
{ID: "a", Source: models.SourceRSS, Title: "Jitsi 3 is out", Body: "Faster calls.", URL: "https://jitsi.example/3", PublishedAt: now, AppName: "Jitsi"},
{ID: "b", Source: models.SourceTwitterAccount, AuthorHandle: "jitsinews", Body: "Hello", PublishedAt: now.Add(-time.Hour), AppName: "Jitsi"},
}); err != nil {
t.Fatal(err)
}
rec := do(h, http.MethodGet, "/content", nil, nil)
if body := rec.Body.String(); rec.Code != 200 || !strings.Contains(body, "1 RSS feed") || !strings.Contains(body, ">2<") {
t.Errorf("content index: %d\n%s", rec.Code, body)
}
rec = do(h, http.MethodGet, "/content/"+id, nil, nil)
if body := rec.Body.String(); !strings.Contains(body, "Jitsi 3 is out") || !strings.Contains(body, "@jitsinews") ||
!strings.Contains(body, "not connected") {
t.Errorf("entry page:\n%s", body)
}
// Nothing selected, or no channel: an error on the page, no drafts.
rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}})
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Select at least one item") {
t.Errorf("write with nothing selected: %d", rec.Code)
}
rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}})
if !strings.Contains(rec.Body.String(), "Choose at least one channel") {
t.Errorf("write without channels:\n%s", rec.Body.String())
}
// No AI key: the provider's error is shown.
rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}, "channel": {"x"}})
if !strings.Contains(rec.Body.String(), "Anthropic API key") {
t.Errorf("write without an AI key:\n%s", rec.Body.String())
}
// Dismiss and restore.
rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"dismiss"}, "item": {"b"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("dismiss: %d", rec.Code)
}
if items, _ := content.ListItems(s.DB, "Jitsi", true, 10); len(items) != 1 || items[0].ID != "b" {
t.Errorf("dismissed: %+v", items)
}
postForm(h, "/content/"+id+"/items", url.Values{"action": {"restore"}, "item": {"b"}, "dismissed": {"1"}})
if items, _ := content.ListItems(s.DB, "Jitsi", true, 10); len(items) != 0 {
t.Errorf("still dismissed: %+v", items)
}
if rec := do(h, http.MethodGet, "/content/999", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("missing entry: %d", rec.Code)
}
}
func TestDraftsPage(t *testing.T) {
s, h := newTestServer(t, nil)
if _, err := content.CreateDrafts(s.DB, []content.Draft{
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelLinkedIn, Content: "LinkedIn text", SourceURL: "https://jitsi.example/3"},
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelX, Content: "X text", SourceURL: "https://jitsi.example/3"},
}); err != nil {
t.Fatal(err)
}
drafts, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
ids := map[string]string{}
for _, d := range drafts {
ids[d.Channel] = strconv.FormatInt(d.ID, 10)
}
if rec := do(h, http.MethodGet, "/drafts?msg=drafted", nil, nil); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/posts?msg=drafted" {
t.Errorf("old drafts page: %d %s", rec.Code, rec.Header().Get("Location"))
}
rec := do(h, http.MethodGet, "/posts", nil, nil)
body := rec.Body.String()
if rec.Code != 200 || strings.Index(body, "X text") > strings.Index(body, "LinkedIn text") ||
!strings.Contains(body, "31 / 280 including the link") || !strings.Contains(body, `data-reserve="25"`) ||
!strings.Contains(body, `class="count-badge" title="2 waiting for review">2<`) {
t.Errorf("inbox (X should come first, menu count 2):\n%s", body)
}
// Save an edit.
if rec := postForm(h, "/drafts/"+ids["x"]+"/save", url.Values{"content": {"Edited X"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
}
if d, _ := content.GetDraft(s.DB, mustID(ids["x"])); d.Content != "Edited X" {
t.Errorf("content = %q", d.Content)
}
// X isn't connected: the error is shown and the edit is still saved.
rec = postForm(h, "/drafts/"+ids["x"]+"/publish", url.Values{"content": {"Edited again"}})
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "X isn&#39;t connected") {
t.Errorf("publish without X: %d\n%s", rec.Code, rec.Body.String())
}
if d, _ := content.GetDraft(s.DB, mustID(ids["x"])); d.Content != "Edited again" || d.Status != content.StatusDraft {
t.Errorf("draft after refused publish: %+v", d)
}
// Discard.
if rec := postForm(h, "/drafts/"+ids["linkedin"]+"/discard", nil); rec.Code != http.StatusSeeOther {
t.Fatalf("discard: %d", rec.Code)
}
if rec := postForm(h, "/drafts/"+ids["linkedin"]+"/discard", nil); !strings.Contains(rec.Body.String(), "can&#39;t be changed") {
t.Errorf("discarding twice: %s", rec.Body.String())
}
if rec := postForm(h, "/drafts/999/save", url.Values{"content": {"x"}}); !strings.Contains(rec.Body.String(), "can&#39;t be changed") {
t.Errorf("unknown draft: %d %s", rec.Code, rec.Body.String())
}
}
func TestScheduleFromInbox(t *testing.T) {
s, h := newTestServer(t, nil)
if _, err := content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelX, Content: "Soon"}}); err != nil {
t.Fatal(err)
}
drafts, _ := content.ListDrafts(s.DB, 1, content.StatusDraft)
id := strconv.FormatInt(drafts[0].ID, 10)
// A past time, or none, is refused.
past := time.Now().Add(-time.Hour).Format(dateTimeLocal)
if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {past}}); !strings.Contains(rec.Body.String(), "That time has passed") {
t.Errorf("past time: %s", rec.Body.String())
}
if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {""}}); !strings.Contains(rec.Body.String(), "Choose a date") {
t.Errorf("no time: %s", rec.Body.String())
}
when := time.Now().Add(2 * time.Hour).Truncate(time.Minute)
rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"content": {"Soon, edited"}, "when": {when.Format(dateTimeLocal)}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("schedule: %d %s", rec.Code, rec.Body.String())
}
d, _ := content.GetDraft(s.DB, mustID(id))
if d.Status != content.StatusScheduled || !d.PublishAt.Equal(when) || d.Content != "Soon, edited" {
t.Errorf("scheduled draft: %+v (want %v)", d, when)
}
body := do(h, http.MethodGet, "/content/scheduled", nil, nil).Body.String()
if !strings.Contains(body, "Soon, edited") || !strings.Contains(body, when.Format("15:04")) || !strings.Contains(body, "not connected") {
t.Errorf("scheduled page:\n%s", body)
}
if !strings.Contains(do(h, http.MethodGet, "/posts", nil, nil).Body.String(), "Nothing waiting") {
t.Error("a scheduled draft is still in the Inbox")
}
// When it's due and X isn't connected, it goes back to the Inbox with
// the reason instead of being retried for ever.
s.publishDue(context.Background(), when.Add(time.Minute))
d, _ = content.GetDraft(s.DB, mustID(id))
if d.Status != content.StatusFailed || !strings.Contains(d.Error, "isn't connected") {
t.Errorf("after the scheduler: %+v", d)
}
// Unschedule from the Scheduled page.
_ = content.Schedule(s.DB, mustID(id), when)
if rec := postForm(h, "/drafts/"+id+"/unschedule", url.Values{"from": {"scheduled"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("unschedule: %d", rec.Code)
}
if d, _ := content.GetDraft(s.DB, mustID(id)); d.Status != content.StatusDraft {
t.Errorf("unscheduled: %+v", d)
}
}
func TestTaggerFromProfile(t *testing.T) {
s, _ := newTestServer(t, nil)
if s.tagger() != nil {
t.Error("no sites in the profile: no tagger")
}
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "x",
Websites: []profile.Website{{URL: "https://acme.example"}}, Products: []profile.Product{{Name: "P", URL: "https://app.acme.dev/p"}}})
tg := s.tagger()
if tg == nil || !tg.Own("https://acme.example/blog") || !tg.Own("https://app.acme.dev/") || tg.Own("https://jitsi.org") {
t.Errorf("tagger: %+v", tg)
}
}
func mustID(s string) int64 {
n, _ := strconv.ParseInt(s, 10, 64)
return n
}
func TestRedditInInbox(t *testing.T) {
s, h := newTestServer(t, nil)
if _, err := content.CreateDrafts(s.DB, []content.Draft{
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelReddit, Title: "Jitsi 3", Target: "selfhosted", Content: "I work at Acme.", SourceURL: "https://jitsi.example/3"},
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelReddit, Title: "Other", Target: "homelab", Content: "Body"},
}); err != nil {
t.Fatal(err)
}
if err := content.SaveRules(s.DB, "selfhosted", "1. Flair it.\n2. No self-promotion", time.Now()); err != nil {
t.Fatal(err)
}
body := do(h, http.MethodGet, "/posts", nil, nil).Body.String()
for _, want := range []string{"Reddit r/selfhosted", `name="title" id="title-`, `value="Jitsi 3"`, "1. Flair it.", "has a rule about this",
"r/homelab's rules · not pasted yet", `action="/reddit/rules/homelab"`, `href="https://www.reddit.com/r/homelab/about/rules"`,
"Copy title", `data-copy-suffix="
Source: https://jitsi.example/3"`} {
if !strings.Contains(body, want) {
t.Errorf("inbox lacks %q", want)
}
}
if strings.Contains(body, "Publish now") || strings.Contains(body, "Schedule</button>") {
t.Error("Reddit drafts mustn't offer Publish now")
}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
var id string
for _, d := range ds {
if d.Target == "selfhosted" {
id = strconv.FormatInt(d.ID, 10)
}
}
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {"Jitsi 3 is out"}, "content": {"Edited"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
}
if d, _ := content.GetDraft(s.DB, mustID(id)); d.Title != "Jitsi 3 is out" || d.Content != "Edited" {
t.Errorf("saved: %+v", d)
}
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "The title is empty") {
t.Errorf("empty title: %s", rec.Body.String())
}
for _, action := range []string{"publish", "schedule"} {
if rec := postForm(h, "/drafts/"+id+"/"+action, url.Values{"when": {time.Now().Add(time.Hour).Format("2006-01-02T15:04")}}); !strings.Contains(rec.Body.String(), "posted by hand") {
t.Errorf("%s a Reddit draft: %s", action, rec.Body.String())
}
}
// Pasting the rules keeps them; emptying the box forgets them.
if rec := postForm(h, "/reddit/rules/homelab", url.Values{"rules": {"No memes."}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save rules: %d %s", rec.Code, rec.Body.String())
}
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr == nil || sr.Rules != "No memes." {
t.Errorf("rules = %+v", sr)
}
postForm(h, "/reddit/rules/homelab", url.Values{"rules": {""}})
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr != nil {
t.Error("emptied rules kept")
}
// Reddit has no sign-in any more.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusNotFound {
t.Errorf("reddit start: %d", rec.Code)
}
if strings.Contains(do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String(), "network-Reddit") {
t.Error("Social accounts still has a Reddit card")
}
}
func TestWriteRedditNeedsSubreddit(t *testing.T) {
s, h := newTestServer(t, nil)
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Accounts: profile.Accounts{Subreddits: []string{"selfhosted"}}})
e := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner, Subreddits: []string{"r/jitsi", "selfhosted"}}
_ = inventory.Save(s.DB, e)
id := strconv.FormatInt(e.ID, 10)
_, _ = content.SaveItems(s.DB, []models.ContentItem{{ID: "a", Source: models.SourceRSS, Body: "x", PublishedAt: time.Now(), AppName: "Jitsi"}})
body := do(h, http.MethodGet, "/content/"+id, nil, nil).Body.String()
if !strings.Contains(body, `<option value="jitsi">`) || strings.Count(body, `<option value="selfhosted">`) != 1 {
t.Errorf("subreddit suggestions:\n%s", body)
}
_ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
rec := postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}, "channel": {"reddit"}, "subreddit": {" "}})
if !strings.Contains(rec.Body.String(), "Choose a subreddit") {
t.Errorf("write without subreddit: %s", rec.Body.String())
}
}
func TestOwnContentPage(t *testing.T) {
var site *httptest.Server
site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/sitemap.xml":
fmt.Fprintf(w, `<urlset><url><loc>%s/blog/launch</loc><lastmod>%s</lastmod></url></urlset>`, site.URL, time.Now().UTC().Format("2006-01-02"))
case "/blog/launch":
w.Write([]byte(`<title>We launched Acme Mail</title><meta name="description" content="Hosted email.">`))
default:
http.NotFound(w, r)
}
}))
defer site.Close()
s, h := newTestServer(t, nil)
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.",
Products: []profile.Product{{Name: "Acme Mail", Description: "Hosted email.", URL: "https://acme.example/mail"}},
Websites: []profile.Website{{URL: site.URL}}})
body := do(h, http.MethodGet, "/content", nil, nil).Body.String()
if !strings.Contains(body, `href="/content/own">Acme</a>`) || !strings.Contains(body, "1 product, new pages on your websites") {
t.Errorf("content index:\n%s", body)
}
body = do(h, http.MethodGet, "/content/own", nil, nil).Body.String()
for _, want := range []string{"<h1>Acme <span class=\"badge product\">", `value="product:acme-mail"`, `action="/content/own/fetch"`,
`href="/settings/profile">Edit profile`, `action="/content/own/items"`} {
if !strings.Contains(body, want) {
t.Errorf("own page lacks %q", want)
}
}
rec := postForm(h, "/content/own/fetch", nil)
if body := rec.Body.String(); !strings.Contains(body, "1 new item") || !strings.Contains(body, "We launched Acme Mail") {
t.Errorf("fetch:\n%s", body)
}
// Writing goes through the same form; without an AI key, its error shows.
rec = postForm(h, "/content/own/items", url.Values{"action": {"write"}, "item": {"product:acme-mail"}, "channel": {"linkedin"}})
if !strings.Contains(rec.Body.String(), "Anthropic API key") {
t.Errorf("write: %s", rec.Body.String())
}
}
func TestPostRedditByHand(t *testing.T) {
s, h := newTestServer(t, nil)
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
if _, err := content.CreateDrafts(s.DB, []content.Draft{
{InventoryName: "Acme", Kind: "product", Channel: content.ChannelReddit, Title: "Widget 2", Target: "selfhosted",
Content: "We made a widget.", SourceURL: "https://acme.example/widget"},
{InventoryName: "Acme", Kind: "product", Channel: content.ChannelReddit, Title: "Links", Target: "linksonly",
Content: "Body", SourceURL: "https://acme.example/w"},
}); err != nil {
t.Fatal(err)
}
ids := map[string]string{}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
for _, d := range ds {
ids[d.Target] = strconv.FormatInt(d.ID, 10)
}
if body := do(h, http.MethodGet, "/posts", nil, nil).Body.String(); !strings.Contains(body, "Open in Reddit") ||
!strings.Contains(body, "Post it yourself") || !strings.Contains(body, `action="/drafts/`+ids["selfhosted"]+`/posted"`) {
t.Error("inbox lacks the by-hand controls")
}
// Open saves the edits, then goes to Reddit's submit page, filled in and tagged.
rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/open", url.Values{"title": {"Widget 2 is out"}, "content": {"Edited."}})
loc, _ := url.Parse(rec.Header().Get("Location"))
q := loc.Query()
if rec.Code != http.StatusSeeOther || loc.Host != "old.reddit.com" || loc.Path != "/r/selfhosted/submit" ||
q.Get("title") != "Widget 2 is out" || q.Get("selftext") != "true" ||
!strings.HasPrefix(q.Get("text"), "Edited.\n\nSource: https://acme.example/widget?") || !strings.Contains(q.Get("text"), "utm_source=reddit") {
t.Errorf("open: %d %s", rec.Code, loc)
}
if d, _ := content.GetDraft(s.DB, mustID(ids["selfhosted"])); d.Title != "Widget 2 is out" || d.Content != "Edited." || d.Status != content.StatusDraft {
t.Errorf("open should save the edits and leave it a draft: %+v", d)
}
// Mark as posted: a bad link is refused, a good one recorded.
if rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/posted", url.Values{"post_url": {"not a link"}}); !strings.Contains(rec.Body.String(), "isn&#39;t a link to a post") {
t.Error("bad post link accepted")
}
post := "https://www.reddit.com/r/selfhosted/comments/abc/widget_2/"
if rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/posted", url.Values{"post_url": {post}}); rec.Code != http.StatusSeeOther {
t.Fatalf("posted: %d %s", rec.Code, rec.Body.String())
}
if d, _ := content.GetDraft(s.DB, mustID(ids["selfhosted"])); d.Status != content.StatusPublished || d.PostURL != post || d.PublishedAt.IsZero() {
t.Errorf("posted: %+v", d)
}
if !strings.Contains(do(h, http.MethodGet, "/content/published", nil, nil).Body.String(), post) {
t.Error("the post isn't listed under Published")
}
// Without a link it still counts as posted.
if rec := postForm(h, "/drafts/"+ids["linksonly"]+"/posted", nil); rec.Code != http.StatusSeeOther {
t.Errorf("posted without a link: %d", rec.Code)
}
// Without Reddit's API, the next draft for r/selfhosted is warned by
// Supermarket's own record; nothing about the whole account is claimed.
_, _ = content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Acme", Kind: "product", Channel: content.ChannelReddit,
Title: "Again", Target: "selfhosted", Content: "More."}})
body := do(h, http.MethodGet, "/posts", nil, nil).Body.String()
if !strings.Contains(body, "You posted in r/selfhosted 1 time in the past week through Supermarket") {
t.Error("no same-subreddit warning from the recorded post")
}
if strings.Contains(body, "hasn&#39;t posted before") || strings.Contains(body, "hasn't posted before") {
t.Error("recorded posts mustn't stand in for the account's history")
}
}