Files
supermarket/internal/legacy/legacy_test.go
davidandClaude Opus 5.5 13bf18facc Phase 1, part 1: fetch, write and publish posts from the web app
Brings back posting, which Phase 0 removed with the terminal interface.

- Content page: per inventory entry, fetch its X account, X hashtag
  search, YouTube channel and RSS/Atom feeds (new), then select, dismiss
  or restore the fetched items, which are kept in the database.
- Writing: one AI call returns a draft per channel (X and LinkedIn),
  prompted from the company profile, the entry's relationship, talking
  points and mention policy, and each channel's rules. Fetched text is
  quoted as untrusted. An over-long X draft gets one request to shorten.
- Drafts page: edit with a live length counter that counts like X, then
  publish each draft on its own. A draft is claimed before posting so it
  can't go out twice; failures are kept on the draft for a retry; X
  tokens are refreshed and saved.
- Migration 2 adds content_items and drafts, and turns queued posts into
  drafts for the platforms they hadn't reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:24 -07:00

151 lines
4.4 KiB
Go

package legacy
import (
"os"
"path/filepath"
"testing"
"supermarket/internal/ai"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
const oldConfigYAML = `applications:
- name: "Nextcloud"
description: "Files"
twitter_handle: "Nextclouders"
youtube_channel_id: "UCx"
instagram_handle: ""
hashtags: ["#Nextcloud", "SelfHosted"]
- name: "Jitsi"
description: "Video"
twitter_handle: "jitsinews"
credentials:
twitter:
bearer_token: "bt"
client_id: "cid"
oauth2_access_token: "at"
oauth2_refresh_token: "rt"
linkedin:
access_token: ""
claude:
api_key: "sk-old"
model: "claude-sonnet-4-6"
posting:
twitter_handle: "federatedcomp"
max_length: 280
settings:
max_results: 15
`
func write(t *testing.T, dir, name, body string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
}
func TestImport(t *testing.T) {
dir := t.TempDir()
importDir := filepath.Join(dir, "import")
os.Mkdir(importDir, 0700)
write(t, importDir, "config.yaml", oldConfigYAML)
write(t, importDir, "state.json", `{"last_checked":{"Nextcloud":"2026-11-01T10:00:00Z"}}`)
write(t, importDir, "posts.json", `{"posts":[{"id":"1","app_name":"Jitsi","content":"Hi","source_url":"https://x.com/1","generated_at":"2026-11-02T10:00:00Z","posted_to":["x"]}]}`)
write(t, importDir, "dismissed.json", `{"ids":{"a":true,"b":true,"c":false}}`)
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
// A key entered in the new app must survive the import.
sec.Set(map[string]string{secrets.AnthropicAPIKey: "sk-new"})
st, err := Import(d, sec, importDir)
if err != nil || st == nil {
t.Fatalf("import: %v %v", st, err)
}
entries, _ := inventory.List(d, inventory.Partner)
if len(entries) != 2 || entries[1].Name != "Nextcloud" || entries[1].Hashtags[1] != "#SelfHosted" {
t.Errorf("inventory: %+v", entries)
}
if sec.Get(secrets.XAccessToken) != "at" || sec.Get(secrets.XRefreshToken) != "rt" || sec.Get(secrets.XBearerToken) != "bt" {
t.Error("X credentials not imported")
}
if sec.Get(secrets.AnthropicAPIKey) != "sk-new" {
t.Error("import overwrote a newer key")
}
if sec.Has(secrets.LinkedInAccessToken) {
t.Error("empty values must not be imported")
}
cfg, _ := ai.LoadConfig(d)
if cfg.Model != "claude-sonnet-4-6" {
t.Errorf("model = %q", cfg.Model)
}
p, _ := profile.Load(d)
if p.Accounts.X != "federatedcomp" {
t.Errorf("x account = %q", p.Accounts.X)
}
var cs ContentSettings
d.GetJSON(ContentSettingsKey, &cs)
if cs.MaxLength != 280 || cs.MaxResults != 15 || cs.LookbackDays != 7 {
t.Errorf("content settings = %+v", cs)
}
count := func(q string) int {
var n int
d.QueryRow(q).Scan(&n)
return n
}
// Posted to X already, so only the LinkedIn draft is left.
if count(`SELECT count(*) FROM drafts WHERE batch = '1' AND channel = 'linkedin'`) != 1 ||
count(`SELECT count(*) FROM drafts WHERE batch = '1' AND channel = 'x'`) != 0 {
t.Error("posts not imported as drafts")
}
if count(`SELECT count(*) FROM dismissed`) != 2 {
t.Error("dismissed not imported")
}
if count(`SELECT count(*) FROM fetch_state WHERE key = 'inventory:Nextcloud'`) != 1 {
t.Error("state not imported")
}
// Runs once.
if st, err := Import(d, sec, importDir); st != nil || err != nil {
t.Errorf("second import ran: %v %v", st, err)
}
}
func TestImportNothingToDo(t *testing.T) {
dir := t.TempDir()
d, _ := db.Open(filepath.Join(dir, "app.db"))
defer d.Close()
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
if st, err := Import(d, sec, filepath.Join(dir, "import")); st != nil || err != nil {
t.Errorf("got %v %v", st, err)
}
}
func TestImportBadFileIsRetried(t *testing.T) {
dir := t.TempDir()
write(t, dir, "config.yaml", oldConfigYAML)
write(t, dir, "posts.json", `{not json`)
d, _ := db.Open(filepath.Join(dir, "app.db"))
defer d.Close()
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
if _, err := Import(d, sec, dir); err == nil {
t.Fatal("expected an error for posts.json")
}
write(t, dir, "posts.json", `{"posts":[]}`)
if st, err := Import(d, sec, dir); err != nil || st == nil {
t.Fatalf("retry: %v %v", st, err)
}
entries, _ := inventory.List(d, "")
if len(entries) != 2 {
t.Errorf("retry duplicated or lost entries: %d", len(entries))
}
}