internal/user_intent_regression_test.go

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