internal/user_intent_regression_test.go

412 lines · 12908 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"errors"
  7	"io"
  8	"net/http"
  9	"os"
 10	"path/filepath"
 11	"strings"
 12	"testing"
 13)
 14
 15type fakePlaybackProvider struct {
 16	name              string
 17	linksByMode       map[string][]string
 18	errByMode         map[string]error
 19	episodeListByMode map[string][]string
 20	episodeErrByMode  map[string]error
 21	modes             []string
 22	episodeModes      []string
 23}
 24
 25func (p *fakePlaybackProvider) Name() string {
 26	if p.name != "" {
 27		return p.name
 28	}
 29	return "fake"
 30}
 31
 32func (p *fakePlaybackProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
 33	return nil, nil
 34}
 35
 36func (p *fakePlaybackProvider) EpisodesList(showID, mode string) ([]string, error) {
 37	mode = normalizeTranslationType(mode)
 38	p.episodeModes = append(p.episodeModes, mode)
 39	if err := p.episodeErrByMode[mode]; err != nil {
 40		return nil, err
 41	}
 42	if episodes, ok := p.episodeListByMode[mode]; ok {
 43		return episodes, nil
 44	}
 45	return []string{"1"}, nil
 46}
 47
 48func (p *fakePlaybackProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
 49	mode := normalizeTranslationType(config.SubOrDub)
 50	p.modes = append(p.modes, mode)
 51	if err := p.errByMode[mode]; err != nil {
 52		return nil, err
 53	}
 54	return p.linksByMode[mode], nil
 55}
 56
 57func withPromptSelect(t *testing.T, fn func([]SelectionOption) (SelectionOption, error)) {
 58	t.Helper()
 59	previous := promptSelect
 60	previousOrdered := promptSelectOrdered
 61	promptSelect = fn
 62	promptSelectOrdered = fn
 63	t.Cleanup(func() {
 64		promptSelect = previous
 65		promptSelectOrdered = previousOrdered
 66	})
 67}
 68
 69func withProvider(t *testing.T, provider Provider) {
 70	t.Helper()
 71	previous := CurrentProvider
 72	CurrentProvider = provider
 73	t.Cleanup(func() {
 74		CurrentProvider = previous
 75	})
 76}
 77
 78func TestInferTotalEpisodesFromEpisodeListUsesHighestWholeEpisode(t *testing.T) {
 79	episodes := []string{"1", "12", "2", "12.5", "special", "0"}
 80
 81	if got := inferTotalEpisodesFromEpisodeList(episodes); got != 12 {
 82		t.Fatalf("expected highest whole episode 12, got %d", got)
 83	}
 84}
 85
 86func TestGetProviderTotalEpisodesUsesHighestEpisodeAcrossModes(t *testing.T) {
 87	provider := &fakePlaybackProvider{
 88		episodeListByMode: map[string][]string{
 89			"dub": {"1", "2", "12"},
 90			"sub": {"1", "99", "100", "100.5"},
 91		},
 92	}
 93	withProvider(t, provider)
 94
 95	total, err := GetProviderTotalEpisodes("one-piece-id", "dub")
 96	if err != nil {
 97		t.Fatalf("expected provider total lookup to succeed: %v", err)
 98	}
 99	if total != 100 {
100		t.Fatalf("expected highest provider episode across modes, got %d", total)
101	}
102	if got := strings.Join(provider.episodeModes, ","); got != "dub,sub" {
103		t.Fatalf("expected preferred then alternate episode lookups, got %s", got)
104	}
105}
106
107func TestGetProviderTotalEpisodesQueriesAnimepaheOnce(t *testing.T) {
108	provider := &fakePlaybackProvider{
109		name: "animepahe",
110		episodeListByMode: map[string][]string{
111			"sub": {"1", "500", "1100"},
112		},
113	}
114	withProvider(t, provider)
115
116	total, err := GetProviderTotalEpisodes("one-piece-id", "sub")
117	if err != nil {
118		t.Fatalf("expected animepahe total lookup to succeed: %v", err)
119	}
120	if total != 3 {
121		t.Fatalf("expected animepahe provider total, got %d", total)
122	}
123	if got := strings.Join(provider.episodeModes, ","); got != "sub" {
124		t.Fatalf("expected animepahe to be queried once, got %s", got)
125	}
126}
127
128func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testing.T) {
129	provider := &fakePlaybackProvider{
130		episodeErrByMode: map[string]error{
131			"sub": errors.New("no sub episodes"),
132			"dub": errors.New("no dub episodes"),
133		},
134	}
135	withProvider(t, provider)
136
137	_, err := GetProviderTotalEpisodes("show-id", "sub")
138	if err == nil {
139		t.Fatalf("expected provider total lookup to fail")
140	}
141	if !strings.Contains(err.Error(), "no sub episodes") || !strings.Contains(err.Error(), "no dub episodes") {
142		t.Fatalf("expected both lookup errors, got %v", err)
143	}
144}
145
146func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
147	withAllProvidersEnabledForTest(t)
148	previousClient := sharedHTTPClient
149	t.Cleanup(func() {
150		sharedHTTPClient = previousClient
151	})
152
153	sharedHTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
154		var payload struct {
155			Query     string            `json:"query"`
156			Variables map[string]string `json:"variables"`
157		}
158		if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
159			t.Fatalf("decode allanime episode request: %v", err)
160		}
161		if !strings.Contains(payload.Query, "query ($showId: String!)") {
162			t.Fatalf("episode list query is missing valid variable syntax: %q", payload.Query)
163		}
164		if payload.Variables["showId"] != "show-id" {
165			t.Fatalf("unexpected show id variable: %#v", payload.Variables)
166		}
167		return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
168	})}
169
170	episodes, err := func() ([]string, error) {
171		provider, err := ProviderByName("allanime")
172		if err != nil {
173			return nil, err
174		}
175		return provider.EpisodesList("show-id", "sub")
176	}()
177	if err != nil {
178		t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
179	}
180	if got := strings.Join(episodes, ","); got != "1,2,12" {
181		t.Fatalf("unexpected episodes: %s", got)
182	}
183}
184
185func captureStdout(t *testing.T, fn func()) string {
186	t.Helper()
187
188	originalStdout := os.Stdout
189	reader, writer, err := os.Pipe()
190	if err != nil {
191		t.Fatalf("create stdout pipe: %v", err)
192	}
193	os.Stdout = writer
194
195	fn()
196
197	if err := writer.Close(); err != nil {
198		t.Fatalf("close stdout writer: %v", err)
199	}
200	os.Stdout = originalStdout
201
202	var buf bytes.Buffer
203	if _, err := io.Copy(&buf, reader); err != nil {
204		t.Fatalf("read captured stdout: %v", err)
205	}
206	return buf.String()
207}
208
209func TestGetEpisodeURLForPlaybackUsesPreferredAudioOnlyWhenAvailable(t *testing.T) {
210	provider := &fakePlaybackProvider{
211		linksByMode: map[string][]string{"sub": {"sub-url"}, "dub": {"dub-url"}},
212		errByMode:   map[string]error{},
213	}
214	withProvider(t, provider)
215
216	links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
217	if err != nil {
218		t.Fatalf("expected preferred audio to succeed: %v", err)
219	}
220	if mode != "sub" || len(links) != 1 || links[0] != "sub-url" {
221		t.Fatalf("unexpected playback result: mode=%q links=%v", mode, links)
222	}
223	if got := strings.Join(provider.modes, ","); got != "sub" {
224		t.Fatalf("expected only preferred mode lookup, got %s", got)
225	}
226}
227
228func TestGetEpisodeURLForPlaybackRequiresExplicitFallbackApproval(t *testing.T) {
229	provider := &fakePlaybackProvider{
230		linksByMode: map[string][]string{"dub": {"dub-url"}},
231		errByMode:   map[string]error{"sub": errors.New("no sub streams")},
232	}
233	withProvider(t, provider)
234	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
235		if len(options) != 2 || options[0].Key != "play" {
236			t.Fatalf("unexpected fallback options: %+v", options)
237		}
238		return SelectionOption{Key: "play"}, nil
239	})
240
241	links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
242	if err != nil {
243		t.Fatalf("expected accepted fallback to succeed: %v", err)
244	}
245	if mode != "dub" || len(links) != 1 || links[0] != "dub-url" {
246		t.Fatalf("unexpected fallback result: mode=%q links=%v", mode, links)
247	}
248	if got := strings.Join(provider.modes, ","); got != "sub,dub" {
249		t.Fatalf("expected preferred then fallback lookup, got %s", got)
250	}
251}
252
253func TestGetEpisodeURLForPlaybackCancelsAudioFallback(t *testing.T) {
254	provider := &fakePlaybackProvider{
255		linksByMode: map[string][]string{"dub": {"dub-url"}},
256		errByMode:   map[string]error{"sub": errors.New("no sub streams")},
257	}
258	withProvider(t, provider)
259	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
260		return SelectionOption{Key: "cancel"}, nil
261	})
262
263	links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
264	if err == nil {
265		t.Fatalf("expected cancelled fallback to return preferred-mode error")
266	}
267	if mode != "sub" || len(links) != 0 {
268		t.Fatalf("unexpected cancelled fallback result: mode=%q links=%v", mode, links)
269	}
270}
271
272func TestShouldWriteRemoteTrackingHonorsSessionSkip(t *testing.T) {
273	config := &CurdConfig{TrackingRemote: TrackingRemoteAniList}
274	if !ShouldWriteRemoteTracking(config, &Anime{}) {
275		t.Fatalf("expected normal remote tracking to write")
276	}
277	if ShouldWriteRemoteTracking(config, &Anime{SkipRemoteSync: true}) {
278		t.Fatalf("expected session skip flag to suppress remote writes")
279	}
280	if ShouldWriteRemoteTracking(&CurdConfig{TrackingRemote: TrackingRemoteNone}, &Anime{}) {
281		t.Fatalf("expected local-only mode to suppress remote writes")
282	}
283}
284
285func TestMaybeImportAniListToMyAnimeListDismissesWithoutMarkingImported(t *testing.T) {
286	tempDir := t.TempDir()
287	configPath := filepath.Join(tempDir, "curd.conf")
288	if err := createDefaultConfig(configPath); err != nil {
289		t.Fatalf("create config: %v", err)
290	}
291
292	previousConfigPath := GlobalConfigPath
293	GlobalConfigPath = configPath
294	t.Cleanup(func() {
295		GlobalConfigPath = previousConfigPath
296	})
297
298	config := &CurdConfig{
299		StoragePath:         tempDir,
300		TrackingRemote:      TrackingRemoteMyAnimeList,
301		TrackingConfigured:  true,
302		MyAnimeListImported: false,
303	}
304	if err := os.WriteFile(filepath.Join(tempDir, "anilist_token.json"), []byte("legacy-token"), 0600); err != nil {
305		t.Fatalf("write token: %v", err)
306	}
307
308	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
309		return SelectionOption{Key: "no"}, nil
310	})
311
312	if err := maybeImportAniListToMyAnimeList(config, &User{}); err != nil {
313		t.Fatalf("maybe import: %v", err)
314	}
315	if config.MyAnimeListImported {
316		t.Fatalf("declining import must not mark import completed")
317	}
318	if !config.MyAnimeListImportDismissed {
319		t.Fatalf("declining import should mark the prompt dismissed")
320	}
321}
322
323func TestWriteTrackingBackupCreatesSnapshot(t *testing.T) {
324	config := &CurdConfig{StoragePath: t.TempDir()}
325	aniList := AnimeList{Watching: []Entry{{Media: Media{ID: 1, MalID: 11}, Status: "CURRENT"}}}
326	myAnimeList := AnimeList{Planning: []Entry{{Media: Media{ID: 2, MalID: 22}, Status: "PLANNING"}}}
327
328	backupPath, err := writeTrackingBackup(config, "test action", aniList, myAnimeList)
329	if err != nil {
330		t.Fatalf("write backup: %v", err)
331	}
332	data, err := os.ReadFile(backupPath)
333	if err != nil {
334		t.Fatalf("read backup: %v", err)
335	}
336	if !strings.Contains(string(data), `"action": "test action"`) || !strings.Contains(string(data), `"id": 1`) || !strings.Contains(string(data), `"id": 2`) {
337		t.Fatalf("backup did not contain expected snapshot data: %s", string(data))
338	}
339}
340
341func TestConfirmProviderMatchRequiresUserApproval(t *testing.T) {
342	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
343		if options[0].Key != "use" || options[1].Key != "manual" {
344			t.Fatalf("unexpected provider confirmation options: %+v", options)
345		}
346		return SelectionOption{Key: "manual"}, nil
347	})
348
349	if confirmProviderMatch(SelectionOption{Label: "Example"}, "title") {
350		t.Fatalf("manual selection should reject guessed provider match")
351	}
352}
353
354func TestSelectSequelAndUnreleasedSequelActions(t *testing.T) {
355	sequels := []SequelInfo{
356		{ID: 1, Title: AnimeTitle{Romaji: "First"}, Status: "FINISHED"},
357		{ID: 2, Title: AnimeTitle{Romaji: "Second"}, Status: "NOT_YET_RELEASED"},
358	}
359	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
360		return SelectionOption{Key: "1"}, nil
361	})
362
363	selected, ok := selectSequel(&CurdConfig{}, sequels)
364	if !ok || selected.ID != 2 {
365		t.Fatalf("expected second sequel selection, got ok=%v selected=%+v", ok, selected)
366	}
367
368	var captured []SelectionOption
369	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
370		captured = append([]SelectionOption(nil), options...)
371		return SelectionOption{Key: "skip"}, nil
372	})
373	summary := promptSequelAction(&CurdConfig{}, selected, "token")
374	if summary != "sequel skipped" {
375		t.Fatalf("expected skipped summary, got %q", summary)
376	}
377	for _, option := range captured {
378		if option.Key == "watching" {
379			t.Fatalf("not-yet-released sequel should not offer Watching action: %+v", captured)
380		}
381	}
382}
383
384func TestHandleLastEpisodeCompletionSummarizesSkippedTrackerWrites(t *testing.T) {
385	previousConfig := GetGlobalConfig()
386	config := &CurdConfig{
387		RofiSelection:     false,
388		ScoreOnCompletion: true,
389		TrackingRemote:    TrackingRemoteAniList,
390	}
391	SetGlobalConfig(config)
392	t.Cleanup(func() {
393		SetGlobalConfig(previousConfig)
394	})
395
396	output := captureStdout(t, func() {
397		HandleLastEpisodeCompletion(config, &Anime{
398			AnilistId:      1,
399			TotalEpisodes:  12,
400			SkipRemoteSync: true,
401			Ep: Episode{
402				Number: 12,
403			},
404		}, "token")
405	})
406
407	if !strings.Contains(output, "Completion summary:") ||
408		!strings.Contains(output, "tracker updates skipped") ||
409		!strings.Contains(output, "sequel check skipped") {
410		t.Fatalf("completion summary did not report skipped tracker writes: %q", output)
411	}
412}