internal/user_intent_regression_test.go

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