package seo import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "path/filepath" "strings" "sync/atomic" "testing" "time" "supermarket/internal/ai" "supermarket/internal/api/gitea" "supermarket/internal/hugorepo" "supermarket/internal/hugorepo/hugotest" "supermarket/internal/profile" ) type fakeAI struct{ reqs []ai.Request } func (f *fakeAI) Generate(_ context.Context, req ai.Request) (string, error) { f.reqs = append(f.reqs, req) return `{"title":"Pricing and plans from $5 a month","description":"See every plan and what it costs per month, with nothing hidden: storage, users and support included."}`, nil } func TestTitleValue(t *testing.T) { for _, c := range []struct{ cur, fm, want, out, err string }{ {"Pricing", "Pricing", "Plans", "Plans", ""}, {"Pricing · Site", "Pricing", "Plans · Site", "Plans", ""}, {"Pricing · Site", "Pricing", "Plans", "", "must end with"}, {"Site | Pricing", "Pricing", "Site | Plans", "Plans", ""}, {"Site", "", "Plans", "", "doesn't come from"}, } { got, err := titleValue(c.cur, c.fm, c.want) if got != c.out || (c.err == "") != (err == nil) || (err != nil && !strings.Contains(err.Error(), c.err)) { t.Errorf("%+v: %q %v", c, got, err) } } } func TestChangeLifecycle(t *testing.T) { if hugorepo.HugoVersion(context.Background()) == "" { t.Skip("no hugo") } ctx := context.Background() d := openDB(t) clone := hugotest.Site(t) var live atomic.Value live.Store("Pricing · Site") var siteSrv *httptest.Server siteSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/pricing/" { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/html") fmt.Fprintf(w, `%s

Pricing

Plans from $5 a month: storage, users and support included.

`, live.Load()) })) defer siteSrv.Close() page := siteSrv.URL + "/pricing/" var merged atomic.Bool var opened map[string]string giteaSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "token tok" { w.WriteHeader(http.StatusUnauthorized) return } switch { case r.URL.Path == "/api/v1/repos/o/site": json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}}) case r.URL.Path == "/api/v1/repos/o/site/pulls" && r.Method == http.MethodPost: json.NewDecoder(r.Body).Decode(&opened) json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "html_url": "https://gitea.example/o/site/pulls/7"}) case r.URL.Path == "/api/v1/repos/o/site/pulls/7": m := merged.Load() json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": map[bool]string{true: "closed", false: "open"}[m], "merged": m, "merged_at": "2026-11-10T09:00:00Z"}) default: http.NotFound(w, r) } })) defer giteaSrv.Close() // Search Console: the page ranks on page one for a price search and // isn't clicked. site, prop := siteSrv.URL+"/", "sc-domain:site.example" for day := 1; day <= 30; day++ { date := fmt.Sprintf("2026-10-%02d", day) d.Exec(`INSERT INTO gsc_site_days VALUES (?, ?, 0, 200, 1400)`, prop, date) d.Exec(`INSERT INTO gsc_page_days VALUES (?, ?, ?, 0, 200, 1400)`, prop, date, page) d.Exec(`INSERT INTO gsc_query_days VALUES (?, ?, ?, 'site pricing per month', 0, 180, 1260)`, prop, date, page) } d.PutJSON(throughKey(prop), "2026-10-30") f := NewFetcher("test") f.Delay = 0 fake := &fakeAI{} pr := &Proposer{AI: fake, Profile: &profile.Profile{Name: "Site"}, Fetcher: f} n, err := pr.SuggestChanges(ctx, d, site, prop, time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)) if err != nil || n != 1 { t.Fatalf("suggest: %d %v", n, err) } if !strings.Contains(fake.reqs[0].Prompt, `"site pricing per month": 5,400 impressions`) || !strings.Contains(fake.reqs[0].Prompt, `ends with " · Site"`) { t.Errorf("prompt: %s", fake.reqs[0].Prompt) } cs, _ := Changes(d, site, 10) c := cs[0] if c.NewTitle != "Pricing and plans from $5 a month · Site" || c.CurTitle != "Pricing · Site" || !strings.Contains(c.Why, "Shown 6,000 times") { t.Fatalf("change: %+v", c) } // Nothing new to propose: the page has a change. if _, err := pr.SuggestChanges(ctx, d, site, prop, time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)); err == nil { t.Error("proposed again for the same page") } if r, _ := Weekly(d, prop, time.Now()); r == nil || len(r.Waiting) != 1 || !strings.Contains(r.Waiting[0].Why, "New title: “Pricing and plans") { t.Errorf("report's waiting list: %+v", r) } if err := EditChange(d, c.ID, "Pricing and plans from $5 · Site", c.NewDescription); err != nil { t.Fatal(err) } if err := Decide(d, c.ID, true, time.Now()); err != nil { t.Fatal(err) } ap := &Applier{Gitea: gitea.New(giteaSrv.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "Pat "} if err := ap.Apply(ctx, d, c.ID); err != nil { t.Fatal(err) } got, _ := GetChange(d, c.ID) if got.Status != ChangePR || got.PRNumber != 7 || got.File != "content/pricing.md" || !strings.Contains(got.Diff, `+title: "Pricing and plans from $5"`) || !strings.HasPrefix(got.Note, "Checked with a build") { t.Fatalf("applied: %+v", got) } if opened["head"] != fmt.Sprintf("supermarket/seo-%d", c.ID) || opened["base"] != "main" || !strings.Contains(opened["body"], "about") { t.Errorf("pull request: %+v", opened) } // Merged, but the live site hasn't changed yet; then it has. merged.Store(true) if err := Refresh(ctx, d, ap.Gitea, f, time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC)); err != nil { t.Fatal(err) } if got, _ := GetChange(d, c.ID); got.Status != ChangeMerged { t.Errorf("merged: %+v", got.Status) } live.Store("Pricing and plans from $5 · Site") // The description in the live page is still the old one in this fake, // so only check the title: make the change title-only. d.Exec(`UPDATE seo_changes SET new_description = '' WHERE id = ?`, c.ID) if err := Refresh(ctx, d, ap.Gitea, f, time.Date(2026, 11, 11, 10, 0, 0, 0, time.UTC)); err != nil { t.Fatal(err) } got, _ = GetChange(d, c.ID) if got.Status != ChangeLive || got.LiveAt.IsZero() { t.Fatalf("live: %+v", got) } // Before and after: 4 days of data after it went live. for day := 12; day <= 15; day++ { date := fmt.Sprintf("2026-11-%02d", day) d.Exec(`INSERT INTO gsc_page_days VALUES (?, ?, ?, 6, 200, 1200)`, prop, date, page) } d.PutJSON(throughKey(prop), "2026-11-15") im, err := ImpactOf(d, *got) if err != nil || im == nil || im.Days != 4 || im.After.Clicks != 24 || im.Before.Clicks != 0 { t.Errorf("impact: %+v %v", im, err) } // A failed apply can be tried again: a wrong repository. c2 := &Change{Site: site, Property: prop, Page: siteSrv.URL + "/nope/", NewTitle: "x · Site", CurTitle: "y · Site", CreatedAt: time.Now()} insertChange(d, c2) Decide(d, c2.ID, true, time.Now()) if err := ap.Apply(ctx, d, c2.ID); err == nil { t.Error("applied a change to a page without a content file") } if got, _ := GetChange(d, c2.ID); got.Status != ChangeFailed || got.Error == "" { t.Errorf("failed: %+v", got) } if err := Decide(d, c2.ID, true, time.Now()); err != nil { t.Errorf("retry: %v", err) } }