package metadata import ( "context" "net/http" "net/http/httptest" "strings" "testing" ) func TestComicVineSearch(t *testing.T) { var gotPath, gotAPIKey, gotUA string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotPath = r.URL.Path gotAPIKey = r.URL.Query().Get("api_key") gotUA = r.Header.Get("User-Agent") w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{ "status_code": 1, "results": [ { "id": 796, "name": "Saga", "start_year": "2012", "description": "
A space opera.
", "publisher": {"name": "Image Comics"}, "image": {"medium_url": "https://example.test/saga.jpg", "small_url": ""} } ] }`)) })) defer srv.Close() p := NewComicVine("secret-key") p.BaseURL = srv.URL cands, err := p.Search(context.Background(), Query{Title: "Saga"}) if err != nil { t.Fatalf("Search: %v", err) } if len(cands) != 1 { t.Fatalf("got %d candidates, want 1", len(cands)) } c := cands[0] if c.Title != "Saga" { t.Errorf("Title = %q", c.Title) } if c.ExternalID != "796" { t.Errorf("ExternalID = %q", c.ExternalID) } if c.Year != 2012 { t.Errorf("Year = %d, want 2012", c.Year) } if c.Publisher != "Image Comics" { t.Errorf("Publisher = %q", c.Publisher) } if c.CoverURL != "https://example.test/saga.jpg" { t.Errorf("CoverURL = %q", c.CoverURL) } if c.Description != "A space opera." { t.Errorf("Description = %q (HTML should be stripped)", c.Description) } if gotPath != "/search/" { t.Errorf("request path = %q, want /search/", gotPath) } if gotAPIKey != "secret-key" { t.Errorf("api_key = %q, want secret-key", gotAPIKey) } if gotUA == "" { t.Error("no User-Agent sent; ComicVine rejects those") } } func TestComicVineRejectsBadAPIKey(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"status_code": 100, "error": "Invalid API Key", "results": []}`)) })) defer srv.Close() p := NewComicVine("wrong") p.BaseURL = srv.URL if _, err := p.Search(context.Background(), Query{Title: "Saga"}); err == nil { t.Fatal("expected an error for status_code 100") } else if !strings.Contains(err.Error(), "API key") { t.Errorf("error %q should mention the API key", err) } } func TestComicVineWithoutKeyDoesNothing(t *testing.T) { p := NewComicVine("") cands, err := p.Search(context.Background(), Query{Title: "Saga"}) if err != nil { t.Fatalf("Search: %v", err) } if len(cands) != 0 { t.Errorf("got %d candidates with no key, want 0", len(cands)) } } func TestStripHTML(t *testing.T) { cases := map[string]string{ "A space opera.
": "A space opera.", "plain text": "plain text", "Bold and italic.": "Bold and italic.", "": "", } for in, want := range cases { if got := stripHTML(in); got != want { t.Errorf("stripHTML(%q) = %q, want %q", in, got, want) } } }