package services import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "testing" "time" ) func TestNewGiphyServiceAppliesDefaults(t *testing.T) { service := NewGiphyService(GiphyConfig{Enabled: true}, nil) if service.Config.MaxResults != 100 { t.Fatalf("expected default max results 100, got %d", service.Config.MaxResults) } if service.Config.Rating != "g" || service.Config.Lang != "en" { t.Fatalf("unexpected defaults: %#v", service.Config) } if service.BaseURL != defaultGiphyAPIBaseURL { t.Fatalf("expected default base url %q, got %q", defaultGiphyAPIBaseURL, service.BaseURL) } } func TestIsAllowedGiphyDownloadURL(t *testing.T) { if !isAllowedGiphyDownloadURL("https://media2.giphy.com/media/test/giphy.gif") { t.Fatal("expected media.giphy.com host to be allowed") } if isAllowedGiphyDownloadURL("https://example.com/file.gif") { t.Fatal("expected non-giphy host to be rejected") } } func TestBuildGiphyFilenameSanitizesInput(t *testing.T) { got := buildGiphyFilename("ABC123", "Funny Cat!!!", ".gif", time.Date(2026, 3, 24, 15, 32, 12, 0, time.UTC)) want := "giphy_abc123_funny-cat_20260324_153212.gif" if got != want { t.Fatalf("expected %q, got %q", want, got) } } func TestGiphySearchAggregatesDedupesAndCapsAt100(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/generate", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"candidates":[{"content":{"parts":[{"text":"{\"queries\":[\"funny cat\",\"happy cat gif\",\"cat reaction\",\"cat meme\",\"animated cat sticker\"]}"}]}}]}`)) }) mux.HandleFunc("/v1/gifs/search", func(w http.ResponseWriter, r *http.Request) { query := r.URL.Query().Get("q") limit := atoiOrZero(r.URL.Query().Get("limit")) offset := atoiOrZero(r.URL.Query().Get("offset")) data := make([]map[string]any, 0, limit) for idx := 0; idx < limit; idx++ { id := fmt.Sprintf("%s-%d", strings.ReplaceAll(query, " ", "-"), offset+idx) if idx == 0 { id = fmt.Sprintf("shared-%d", offset) } data = append(data, map[string]any{ "id": id, "title": fmt.Sprintf("%s %d", query, offset+idx), "slug": fmt.Sprintf("%s-%d", strings.ReplaceAll(query, " ", "-"), offset+idx), "rating": "g", "url": "https://giphy.com/gifs/" + id, "images": map[string]any{ "original": map[string]any{ "url": fmt.Sprintf("https://media.giphy.com/media/%s/giphy.gif", id), "width": "480", "height": "270", }, "fixed_width": map[string]any{ "url": fmt.Sprintf("https://media.giphy.com/media/%s/200w.gif", id), "width": "200", "height": "113", }, "fixed_width_still": map[string]any{ "url": fmt.Sprintf("https://media.giphy.com/media/%s/200w_s.gif", id), }, }, }) } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": data}) }) server := httptest.NewServer(mux) defer server.Close() gemini := NewGeminiService("dummy-key", "gemini-2.5-flash") gemini.Client = &http.Client{Timeout: 2 * time.Second} gemini.GenerateEndpoint = server.URL + "/generate" service := NewGiphyService(GiphyConfig{ Enabled: true, APIKey: "test-key", MaxResults: 100, BaseURL: server.URL, }, gemini) service.Client = &http.Client{Timeout: 2 * time.Second} resp, err := service.SearchImages("웃긴 고양이", 100) if err != nil { t.Fatalf("expected giphy search to succeed, got %v", err) } if len(resp.ExpandedQueries) != 5 { t.Fatalf("expected 5 expanded queries, got %#v", resp.ExpandedQueries) } if resp.Total != 100 || len(resp.Items) != 100 { t.Fatalf("expected capped 100 unique items, got total=%d len=%d", resp.Total, len(resp.Items)) } seen := map[string]bool{} for _, item := range resp.Items { if seen[item.ProviderID] { t.Fatalf("found duplicate providerId %q in aggregated results", item.ProviderID) } seen[item.ProviderID] = true } } func TestDownloadMediaHappyPath(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "image/gif") _, _ = w.Write([]byte("GIF89a")) })) defer server.Close() serverURL, err := url.Parse(server.URL) if err != nil { t.Fatalf("failed to parse server url: %v", err) } tempDir := t.TempDir() service := NewGiphyService(GiphyConfig{ Enabled: true, APIKey: "test-key", DownloadDir: tempDir, }, nil) service.Client = &http.Client{ Timeout: 2 * time.Second, Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { clone := req.Clone(req.Context()) if strings.HasSuffix(clone.URL.Host, "giphy.com") { clone.URL.Scheme = serverURL.Scheme clone.URL.Host = serverURL.Host clone.Host = serverURL.Host } return http.DefaultTransport.RoundTrip(clone) }), } resp, err := service.DownloadMedia(GiphyDownloadRequest{ ProviderID: "abc123", Title: "Funny Cat", DownloadURL: "https://media.giphy.com/media/abc123/giphy.gif", }) if err != nil { t.Fatalf("expected download to succeed, got %v", err) } if !resp.OK { t.Fatalf("expected ok response, got %#v", resp) } if filepath.Ext(resp.FileName) != ".gif" { t.Fatalf("expected gif extension, got %q", resp.FileName) } if _, err := os.Stat(resp.SavedPath); err != nil { t.Fatalf("expected saved file at %q: %v", resp.SavedPath, err) } }