package seo import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os/exec" "path/filepath" "strings" "testing" "time" "supermarket/internal/ai" "supermarket/internal/api/gitea" "supermarket/internal/hugorepo" "supermarket/internal/hugorepo/hugotest" "supermarket/internal/profile" ) func TestClaims(t *testing.T) { text := `## Prices We compared 12 tubs in March. The cheapest is $0.61 per 20 g. After two months of use, the flavour held up. Prices change often. - In our test, mixing was easy. I think it's fine.` got := Claims(text) want := []string{"We compared 12 tubs in March.", "After two months of use, the flavour held up.", "In our test, mixing was easy."} if strings.Join(got, "|") != strings.Join(want, "|") { t.Errorf("claims: %q", got) } } type briefAI struct{ prompts []string } func (b *briefAI) Generate(_ context.Context, req ai.Request) (string, error) { b.prompts = append(b.prompts, req.Prompt) return "## Plans\n\nEvery plan has a flat price. We tested the migration from Google Workspace with 12 users.\n\n## Questions\n\nStorage isn't tested.", nil } func (b *briefAI) Research(_ context.Context, req ai.ResearchRequest) (*ai.ResearchResult, error) { b.prompts = append(b.prompts, req.Prompt) return &ai.ResearchResult{Searches: 4, Sources: []ai.Source{{URL: "https://rival.example/alt"}}, Text: `{"finding":"The page is shown for price searches, not what its title says.", "top":[{"url":"https://rival.example/alt","title":"10 alternatives","promises":"a list","lacks":"no prices","read":true}, {"url":"https://hidden.example/x","title":"X","promises":"?","lacks":"?","read":true}], "plan":{"title":"Google Workspace alternative with flat pricing","description":"Compare plans.","h1":"A Google Workspace alternative", "angle":"Real prices per user","sections":["Prices","Migration"],"questions":["How much?"], "links":[{"url":"%SITE%/pricing/","why":"prices"},{"url":"https://elsewhere.example/","why":"no"}], "ask":["Did you migrate a team yourself?","What does a plan cost?"],"needs":["a price table"]}}`}, nil } func TestBriefToPullRequest(t *testing.T) { if hugorepo.HugoVersion(context.Background()) == "" { t.Skip("no hugo") } ctx := context.Background() d := openDB(t) clone := hugotest.Site(t) var site *httptest.Server merged := false site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/sitemap.xml": fmt.Fprintf(w, `%[1]s/%[1]s/pricing/`, site.URL) case "/pricing/": fmt.Fprint(w, `Pricing · Site

Pricing

Old text.

`) case "/google-workspace-alternative/": if !merged { http.NotFound(w, r) return } fmt.Fprint(w, `Google Workspace alternative with flat pricing · Sitex`) default: http.NotFound(w, r) } })) defer site.Close() var opened []map[string]string g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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: var m map[string]string json.NewDecoder(r.Body).Decode(&m) opened = append(opened, m) json.NewEncoder(w).Encode(map[string]any{"number": len(opened), "state": "open", "html_url": "https://gitea.example/pr"}) case strings.HasPrefix(r.URL.Path, "/api/v1/repos/o/site/pulls/"): json.NewEncoder(w).Encode(map[string]any{"number": 1, "state": "closed", "merged": merged}) } })) defer g.Close() ai := &briefAI{} f := NewFetcher("test") f.Delay = 0 w := &Writer{Research: researchWithSite{ai, site.URL}, AI: ai, Profile: &profile.Profile{Name: "Site"}, Fetcher: f} b, err := w.NewBrief(ctx, d, site.URL+"/", "", "Google Workspace alternative", "", time.Now()) if err != nil { t.Fatal(err) } if b.Path != "/google-workspace-alternative/" || len(b.Plan.Links) != 1 || b.Plan.Finding == "" || b.Searches != 4 || !b.Top[0].Read || b.Top[1].Read || len(b.Answers) != 2 { t.Fatalf("brief: %+v", b) } if !strings.Contains(ai.prompts[0], site.URL+"/pricing/") { t.Error("the brief's prompt doesn't list our pages") } if _, err := w.WritePage(ctx, d, b.ID); err == nil || !strings.Contains(err.Error(), "answer the brief's questions") { t.Errorf("wrote a page without answers: %v", err) } if err := EditBrief(d, b.ID, b.Plan, []string{"Yes, 12 users from Google Workspace.", "From $5 a user."}, "/google-workspace-alternative/"); err != nil { t.Fatal(err) } b, err = w.WritePage(ctx, d, b.ID) if err != nil { t.Fatal(err) } if !strings.Contains(ai.prompts[1], "A: From $5 a user.") || len(b.Claims) != 1 || b.Status != BriefPage { t.Fatalf("page: %+v %q", b.Claims, ai.prompts[1]) } ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "Pat "} if err := ap.ApplyBrief(ctx, d, b.ID, nil); err == nil || !strings.Contains(err.Error(), "confirm or remove this claim") { t.Errorf("opened a pull request with an unconfirmed claim: %v", err) } if err := ap.ApplyBrief(ctx, d, b.ID, b.Claims); err != nil { t.Fatal(err) } b, _ = GetBrief(d, b.ID) if b.Status != BriefPR || b.File != "content/google-workspace-alternative.md" || !strings.HasPrefix(b.Note, "Checked with a build") { t.Fatalf("applied: %+v", b) } if !strings.Contains(opened[0]["body"], "We tested the migration") || !strings.Contains(opened[0]["title"], "new page /google-workspace-alternative/") { t.Errorf("pull request: %+v", opened[0]) } show := exec.Command("git", "-C", strings.TrimPrefix(clone, "file://"), "show", fmt.Sprintf("supermarket/page-%d:content/google-workspace-alternative.md", b.ID)) if out, err := show.CombinedOutput(); err != nil || !strings.Contains(string(out), `title: "Google Workspace alternative with flat pricing"`) || !strings.Contains(string(out), "## Plans") { t.Errorf("file: %s %v", out, err) } // Merged and live. merged = true if err := RefreshBriefs(ctx, d, ap.Gitea, "o/site", site.URL+"/", f, time.Now()); err != nil { t.Fatal(err) } if b, _ = GetBrief(d, b.ID); b.Status != BriefLive || b.Page != site.URL+"/google-workspace-alternative/" { t.Errorf("live: %+v", b.Status) } // A rewrite of an existing page. merged = false r, err := w.NewBrief(ctx, d, site.URL+"/", "", "", site.URL+"/pricing/", time.Now()) if err == nil { t.Errorf("a rewrite without a search or Search Console data: %+v", r) } r, err = w.NewBrief(ctx, d, site.URL+"/", "", "site pricing", site.URL+"/pricing/", time.Now()) if err != nil { t.Fatal(err) } EditBrief(d, r.ID, r.Plan, []string{"No", "$5"}, "") r, _ = w.WritePage(ctx, d, r.ID) if _, err := SaveDraft(d, r.ID, "## Plans\n\nEvery plan has a flat price."); err != nil { t.Fatal(err) } if err := ap.ApplyBrief(ctx, d, r.ID, nil); err != nil { t.Fatal(err) } r, _ = GetBrief(d, r.ID) if r.Status != BriefPR || r.File != "content/pricing.md" { t.Errorf("rewrite: %+v", r) } show = exec.Command("git", "-C", strings.TrimPrefix(clone, "file://"), "show", fmt.Sprintf("supermarket/page-%d:content/pricing.md", r.ID)) if out, _ := show.CombinedOutput(); !strings.Contains(string(out), "Every plan has a flat price.") || strings.Contains(string(out), "Our prices.") || !strings.Contains(string(out), "draft: false") { t.Errorf("rewritten file: %s", out) } } // researchWithSite puts the test site's address into the canned answer. type researchWithSite struct { *briefAI site string } func (r researchWithSite) Research(ctx context.Context, req ai.ResearchRequest) (*ai.ResearchResult, error) { res, err := r.briefAI.Research(ctx, req) if res != nil { res.Text = strings.ReplaceAll(res.Text, "%SITE%", r.site) } return res, err }