package inventory import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "supermarket/internal/ai" "supermarket/internal/profile" ) type fakeAI struct { calls int prompt string reply any } func (f *fakeAI) Generate(_ context.Context, req ai.Request) (string, error) { f.calls++ f.prompt = req.Prompt raw, _ := json.Marshal(f.reply) return string(raw), nil } func rivalSite(t *testing.T) *httptest.Server { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/html") w.Write([]byte(`Rival

Rival makes hosted widgets.

X LinkedIn`)) })) t.Cleanup(srv.Close) return srv } func TestFillKeepsWhatWasTyped(t *testing.T) { srv := rivalSite(t) fake := &fakeAI{reply: map[string]any{ "name": "Rival Inc", "description": "Hosted widgets.", "talking_points": "We self-host; they don't.", "keywords": []string{"widgets"}, "hashtags": []string{"Rival"}, }} e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"} ours := &profile.Profile{Name: "Acme", Description: "Self-hosted widgets."} filled, err := Fill(context.Background(), fake, e, srv.URL, ours) if err != nil { t.Fatal(err) } if e.Name != "Rival" || e.TwitterHandle != "typed" { t.Errorf("typed values changed: %+v", e) } if e.LinkedIn != "https://www.linkedin.com/company/rival" || len(e.RSS) != 1 || e.RSS[0] != srv.URL+"/feed" || len(e.Websites) != 1 || e.Description != "Hosted widgets." || e.TalkingPoints == "" { t.Errorf("not filled: %+v", e) } want := "website, LinkedIn page, feeds, description, talking points, keywords, hashtags" if strings.Join(filled, ", ") != want { t.Errorf("filled = %q", strings.Join(filled, ", ")) } for _, s := range []string{"Relationship: competitor", "Name: Acme", "Rival makes hosted widgets."} { if !strings.Contains(fake.prompt, s) { t.Errorf("prompt lacks %q", s) } } if err := e.Normalize(); err != nil || e.Hashtags[0] != "#Rival" { t.Errorf("normalize: %v %q", err, e.Hashtags) } } func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) { srv := rivalSite(t) fake := &fakeAI{} e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t", Keywords: []string{"k"}, Hashtags: []string{"#h"}} if _, err := Fill(context.Background(), fake, e, srv.URL, nil); err != nil { t.Fatal(err) } if fake.calls != 0 { t.Errorf("model called %d times", fake.calls) } if e.TwitterHandle != "rivalhq" { t.Errorf("links not read: %+v", e) } }