internal/logic_regression_test.go

574 lines · 18325 bytes

  1package internal
  2
  3import (
  4	"os"
  5	"path/filepath"
  6	"testing"
  7
  8	tea "github.com/charmbracelet/bubbletea"
  9)
 10
 11func TestClearLogFileCreatesParentAndTruncates(t *testing.T) {
 12	logPath := filepath.Join(t.TempDir(), "missing", "debug.log")
 13
 14	if err := ClearLogFile(logPath); err != nil {
 15		t.Fatalf("ClearLogFile should create a missing parent directory: %v", err)
 16	}
 17
 18	if err := os.WriteFile(logPath, []byte("old log data"), 0o644); err != nil {
 19		t.Fatalf("write log fixture: %v", err)
 20	}
 21	if err := ClearLogFile(logPath); err != nil {
 22		t.Fatalf("ClearLogFile should truncate an existing log: %v", err)
 23	}
 24
 25	info, err := os.Stat(logPath)
 26	if err != nil {
 27		t.Fatalf("expected log file to exist: %v", err)
 28	}
 29	if info.Size() != 0 {
 30		t.Fatalf("expected log file to be truncated, got %d bytes", info.Size())
 31	}
 32}
 33
 34func TestParseAnimeRowHandlesLegacyRows(t *testing.T) {
 35	withName := parseAnimeRow([]string{"123", "provider-id", "4", "55", "Legacy Title"})
 36	if withName == nil {
 37		t.Fatalf("expected legacy name row to parse")
 38	}
 39	if withName.Ep.Duration != 0 || withName.Title.Romaji != "Legacy Title" {
 40		t.Fatalf("unexpected legacy name row parse: %+v", withName)
 41	}
 42
 43	withDuration := parseAnimeRow([]string{"123", "provider-id", "4", "55", "24"})
 44	if withDuration == nil {
 45		t.Fatalf("expected legacy duration row to parse")
 46	}
 47	if withDuration.Ep.Duration != 24 || withDuration.Title.Romaji != "123" {
 48		t.Fatalf("unexpected legacy duration row parse: %+v", withDuration)
 49	}
 50
 51	current := parseAnimeRow([]string{"123", "provider-id", "4", "55", "24", "animepahe", "Current Title"})
 52	if current == nil {
 53		t.Fatalf("expected current row to parse")
 54	}
 55	if current.Ep.Duration != 24 || current.ProviderName != "animepahe" || current.Title.Romaji != "Current Title" {
 56		t.Fatalf("unexpected current row parse: %+v", current)
 57	}
 58
 59	if invalid := parseAnimeRow([]string{"bad-id", "provider-id", "4", "55", "24", "allanime", "Broken Title"}); invalid != nil {
 60		t.Fatalf("expected invalid AniList ID row to be skipped, got %+v", invalid)
 61	}
 62}
 63
 64func TestLocalDeleteAnimeNormalizesAnimepaheIDs(t *testing.T) {
 65	historyPath := filepath.Join(t.TempDir(), "history.csv")
 66	if err := LocalUpdateAnime(historyPath, 123, "123:session-id", 4, 0, 24, "Current Title", "animepahe"); err != nil {
 67		t.Fatalf("write animepahe history: %v", err)
 68	}
 69
 70	LocalDeleteAnime(historyPath, 123, "123:other-session")
 71
 72	if entries := LocalGetAllAnime(historyPath); len(entries) != 0 {
 73		t.Fatalf("expected animepahe history entry to be deleted, got %#v", entries)
 74	}
 75}
 76
 77func TestGetAnimeNameWithoutGlobalConfig(t *testing.T) {
 78	previousConfig := GetGlobalConfig()
 79	SetGlobalConfig(nil)
 80	t.Cleanup(func() {
 81		SetGlobalConfig(previousConfig)
 82	})
 83
 84	name := GetAnimeName(Anime{Title: AnimeTitle{English: "English Title", Romaji: "Romaji Title"}})
 85	if name != "English Title" {
 86		t.Fatalf("expected English fallback without config, got %q", name)
 87	}
 88
 89	name = GetAnimeName(Anime{AnilistId: 42})
 90	if name != "42" {
 91		t.Fatalf("expected ID fallback for empty title, got %q", name)
 92	}
 93}
 94
 95func TestNextEpisodeFromProgress(t *testing.T) {
 96	if got := nextEpisodeFromProgress(0); got != 1 {
 97		t.Fatalf("progress 0 should start episode 1, got %d", got)
 98	}
 99	if got := nextEpisodeFromProgress(7); got != 8 {
100		t.Fatalf("progress 7 should start episode 8, got %d", got)
101	}
102	if got := nextEpisodeFromProgress(-3); got != 1 {
103		t.Fatalf("negative progress should clamp to episode 1, got %d", got)
104	}
105}
106
107func TestSelectionCtrlCSelectsQuit(t *testing.T) {
108	model := &Model{
109		filteredKeys: []SelectionOption{{Key: "anime", Label: "Some Anime"}},
110		selected:     0,
111		isHomeMenu:   false,
112	}
113
114	updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
115	finalModel, ok := updated.(*Model)
116	if !ok {
117		t.Fatalf("unexpected model type %T", updated)
118	}
119	if len(finalModel.filteredKeys) != 1 || finalModel.filteredKeys[0].Key != "-1" {
120		t.Fatalf("ctrl+c should select Quit, got %+v", finalModel.filteredKeys)
121	}
122}
123
124func TestVimKeysNormalModeNavigatesWithoutFiltering(t *testing.T) {
125	prev := GetGlobalConfig()
126	SetGlobalConfig(&CurdConfig{VimKeys: true})
127	t.Cleanup(func() { SetGlobalConfig(prev) })
128
129	model := &Model{
130		allOptions: []SelectionOption{
131			{Key: "1", Label: "Alpha"},
132			{Key: "2", Label: "Bravo"},
133			{Key: "3", Label: "Charlie"},
134		},
135		filteredKeys: []SelectionOption{
136			{Key: "1", Label: "Alpha"},
137			{Key: "2", Label: "Bravo"},
138			{Key: "3", Label: "Charlie"},
139		},
140		selected:   0,
141		isHomeMenu: false,
142	}
143
144	// j should move down, not type into filter.
145	updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}})
146	model = updated.(*Model)
147	if model.selected != 1 {
148		t.Fatalf("j should move down, selected=%d", model.selected)
149	}
150	if model.filter != "" {
151		t.Fatalf("j must not enter filter in normal mode, filter=%q", model.filter)
152	}
153
154	// k moves up.
155	updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'k'}})
156	model = updated.(*Model)
157	if model.selected != 0 {
158		t.Fatalf("k should move up, selected=%d", model.selected)
159	}
160
161	// / enters search mode; then typing filters — including hjkl as query text.
162	updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'/'}})
163	model = updated.(*Model)
164	if !model.filterActive {
165		t.Fatal("expected / to enter search mode")
166	}
167	updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}})
168	model = updated.(*Model)
169	if model.filter != "j" {
170		t.Fatalf("in search mode j should type into query, got filter=%q selected=%d", model.filter, model.selected)
171	}
172	if model.selected != 0 {
173		t.Fatalf("in search mode j must not move selection, selected=%d", model.selected)
174	}
175	updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'k'}})
176	model = updated.(*Model)
177	if model.filter != "jk" {
178		t.Fatalf("expected filter jk in search mode, got %q", model.filter)
179	}
180
181	// Arrows still navigate results while searching.
182	updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyDown})
183	model = updated.(*Model)
184	// After filtering to "jk" there may be no matches; selection stays valid either way.
185	_ = model
186}
187
188func TestFilterQuitOnlyShowsQuitNotBack(t *testing.T) {
189	model := &Model{
190		allOptions: []SelectionOption{
191			{Key: "CURRENT", Label: "Currently Watching"},
192			{Key: "ALL", Label: "Show All"},
193		},
194		isHomeMenu: false, // action-style menu that has Back
195		filter:     "quit",
196	}
197	model.filterOptions()
198	if len(model.filteredKeys) != 1 || model.filteredKeys[0].Key != "-1" {
199		t.Fatalf("filter 'quit' should only pin Quit, got %#v", model.filteredKeys)
200	}
201}
202
203func TestSelectionMeansQuitAndBack(t *testing.T) {
204	if !SelectionMeansQuit(SelectionOption{Key: "-1"}) {
205		t.Fatal("key -1 should mean quit")
206	}
207	if !SelectionMeansQuit(SelectionOption{Label: "Quit"}) {
208		t.Fatal("label Quit should mean quit")
209	}
210	if !SelectionMeansBack(SelectionOption{Key: "-2"}) {
211		t.Fatal("key -2 should mean back")
212	}
213	if !SelectionMeansBack(SelectionOption{Label: "Back to menu"}) {
214		t.Fatal("Back to menu should mean back")
215	}
216	got := NormalizeSelectionKey(SelectionOption{Label: "quit"})
217	if got.Key != "-1" {
218		t.Fatalf("NormalizeSelectionKey quit -> %#v", got)
219	}
220}
221
222func TestLegacyModeStillTypeToFilter(t *testing.T) {
223	prev := GetGlobalConfig()
224	SetGlobalConfig(&CurdConfig{VimKeys: false})
225	t.Cleanup(func() { SetGlobalConfig(prev) })
226
227	model := &Model{
228		allOptions: []SelectionOption{
229			{Key: "1", Label: "Alpha"},
230			{Key: "2", Label: "Bravo"},
231		},
232		filteredKeys: []SelectionOption{
233			{Key: "1", Label: "Alpha"},
234			{Key: "2", Label: "Bravo"},
235		},
236	}
237	updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}})
238	model = updated.(*Model)
239	if model.filter != "j" {
240		t.Fatalf("legacy mode should type-to-filter, got filter=%q", model.filter)
241	}
242}
243
244func TestSelectionEnterWithNoMatchesDoesNotPanic(t *testing.T) {
245	model := &Model{filteredKeys: nil, selected: 0}
246	updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
247	if cmd != nil {
248		t.Fatalf("expected no quit command for empty selection")
249	}
250	if _, ok := updated.(*Model); !ok {
251		t.Fatalf("unexpected model type %T", updated)
252	}
253}
254
255func TestVisibleItemsCountClampsTinyTerminals(t *testing.T) {
256	if got := (Model{terminalHeight: 0}).visibleItemsCount(); got != 1 {
257		t.Fatalf("expected at least one visible item, got %d", got)
258	}
259}
260
261func TestHasMPVReferrerArgDetectsHeaderAppendForms(t *testing.T) {
262	cases := [][]string{
263		{"--http-header-fields-append=Referer: https://example.test/"},
264		{"--http-header-fields-append", "Referer: https://example.test/"},
265		{"--mpv-http-header-fields-append=Referer: https://example.test/"},
266	}
267
268	for _, args := range cases {
269		if !hasMPVReferrerArg(args) {
270			t.Fatalf("expected referrer detection for args %#v", args)
271		}
272	}
273}
274
275func TestEpisodeAndProgressInputValidation(t *testing.T) {
276	if got, err := parsePositiveIntInput("12", "episode number"); err != nil || got != 12 {
277		t.Fatalf("expected valid episode number, got %d err %v", got, err)
278	}
279	for _, input := range []string{"", "0", "-1", "one"} {
280		if _, err := parsePositiveIntInput(input, "episode number"); err == nil {
281			t.Fatalf("expected invalid episode input %q to fail", input)
282		}
283	}
284
285	if got, err := parseNonNegativeIntInput("0", "progress"); err != nil || got != 0 {
286		t.Fatalf("expected progress 0 to be valid, got %d err %v", got, err)
287	}
288	if _, err := parseNonNegativeIntInput("-1", "progress"); err == nil {
289		t.Fatalf("expected negative progress to fail")
290	}
291}
292
293func TestAffirmativeAnswerAcceptsYesVariants(t *testing.T) {
294	for _, answer := range []string{"y", "Y", " yes "} {
295		if !isAffirmativeAnswer(answer) {
296			t.Fatalf("expected %q to be affirmative", answer)
297		}
298	}
299	if isAffirmativeAnswer("no") {
300		t.Fatalf("expected no to be negative")
301	}
302}
303
304func TestPopulateConfigFallsBackToDefaultsOnInvalidValues(t *testing.T) {
305	config := PopulateConfig(map[string]string{
306		"PercentageToMarkComplete": "not-a-number",
307		"SkipOp":                   "not-a-bool",
308		"MpvPlaybackStartTimeout":  "not-a-number",
309	})
310
311	if config.PercentageToMarkComplete != 85 {
312		t.Fatalf("expected default completion percentage, got %d", config.PercentageToMarkComplete)
313	}
314	if config.MpvPlaybackStartTimeout != DefaultMpvPlaybackStartTimeout {
315		t.Fatalf("expected default playback timeout, got %d", config.MpvPlaybackStartTimeout)
316	}
317	if !config.SkipOp {
318		t.Fatalf("expected invalid bool to fall back to default true")
319	}
320	if config.StoragePath == "" {
321		t.Fatalf("expected absent fields to be populated from defaults")
322	}
323}
324
325func TestParseStringArrayUsesJSONBeforeLegacySplit(t *testing.T) {
326	args := parseStringArray(`["--script-opts=foo=a,b","--really-quiet"]`)
327	if len(args) != 2 {
328		t.Fatalf("expected 2 args, got %#v", args)
329	}
330	if args[0] != "--script-opts=foo=a,b" || args[1] != "--really-quiet" {
331		t.Fatalf("unexpected args parse: %#v", args)
332	}
333}
334
335func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
336	previousProvider := CurrentProvider
337	previousConfig := GetGlobalConfig()
338	t.Cleanup(func() {
339		CurrentProvider = previousProvider
340		SetGlobalConfig(previousConfig)
341	})
342
343	CurrentProvider = nil
344	SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
345
346	if got := GetProvider().Name(); got != "senshi" {
347		t.Fatalf("expected senshi provider when allanime is disabled, got %q", got)
348	}
349}
350
351func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
352	previousProvider := CurrentProvider
353	previousConfig := GetGlobalConfig()
354	t.Cleanup(func() {
355		CurrentProvider = previousProvider
356		SetGlobalConfig(previousConfig)
357	})
358
359	CurrentProvider = nil
360	SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
361
362	if got := GetProvider().Name(); got != "senshi" {
363		t.Fatalf("expected senshi fallback for disabled provider, got %q", got)
364	}
365}
366
367func TestHTTPStatusErrorIncludesStatusAndBodySnippet(t *testing.T) {
368	err := httpStatusError("provider request", 503, []byte("  service unavailable  "))
369	if err == nil {
370		t.Fatalf("expected status error")
371	}
372	if got := err.Error(); got != "provider request failed with status 503: service unavailable" {
373		t.Fatalf("unexpected status error: %q", got)
374	}
375}
376
377func TestMPVResponseDataReturnsCommandErrors(t *testing.T) {
378	if _, err := mpvResponseData(map[string]interface{}{"error": "property unavailable"}); err == nil {
379		t.Fatalf("expected MPV error field to be returned")
380	}
381
382	data, err := mpvResponseData(map[string]interface{}{"error": "success", "data": float64(12)})
383	if err != nil {
384		t.Fatalf("expected success response: %v", err)
385	}
386	if data != float64(12) {
387		t.Fatalf("unexpected MPV data: %#v", data)
388	}
389}
390
391func TestParseMyAnimeListDateRejectsInvalidValues(t *testing.T) {
392	if got := parseMyAnimeListDate("2026-05-23"); got != (FuzzyDate{Year: 2026, Month: 5, Day: 23}) {
393		t.Fatalf("unexpected parsed date: %+v", got)
394	}
395	for _, input := range []string{"bad", "2026-aa-23", "2026-13-01", "2026-01-00"} {
396		if got := parseMyAnimeListDate(input); got != (FuzzyDate{}) {
397			t.Fatalf("expected invalid date %q to return zero value, got %+v", input, got)
398		}
399	}
400}
401
402func TestParseAnimeListMalformedInputReturnsEmptyList(t *testing.T) {
403	if got := ParseAnimeList(nil); len(getEntriesByCategory(got, "ALL")) != 0 {
404		t.Fatalf("expected nil input to produce empty list")
405	}
406	if got := ParseAnimeList(map[string]interface{}{"data": nil}); len(getEntriesByCategory(got, "ALL")) != 0 {
407		t.Fatalf("expected nil data input to produce empty list")
408	}
409}
410
411func TestParseAnimeListSkipsCustomListsThatReExportEntries(t *testing.T) {
412	// AniList returns the same MediaList entry under the status list and again
413	// under each custom list that includes it.
414	input := map[string]interface{}{
415		"data": map[string]interface{}{
416			"MediaListCollection": map[string]interface{}{
417				"lists": []interface{}{
418					map[string]interface{}{
419						"name":         "Watching",
420						"isCustomList": false,
421						"entries": []interface{}{
422							map[string]interface{}{
423								"id":        float64(1001),
424								"status":    "CURRENT",
425								"progress":  float64(3),
426								"repeat":    float64(0),
427								"updatedAt": float64(1_700_000_000),
428								"media": map[string]interface{}{
429									"id":       float64(42),
430									"idMal":    float64(420),
431									"episodes": float64(12),
432									"duration": float64(24),
433									"format":   "TV",
434									"title": map[string]interface{}{
435										"english": "Example Show",
436										"romaji":  "Example Show",
437										"native":  "例",
438									},
439									"status": "RELEASING",
440								},
441							},
442						},
443					},
444					map[string]interface{}{
445						"name":         "Favorites",
446						"isCustomList": true,
447						"entries": []interface{}{
448							map[string]interface{}{
449								"id":        float64(1001),
450								"status":    "CURRENT",
451								"progress":  float64(3),
452								"repeat":    float64(0),
453								"updatedAt": float64(1_700_000_000),
454								"media": map[string]interface{}{
455									"id":       float64(42),
456									"idMal":    float64(420),
457									"episodes": float64(12),
458									"duration": float64(24),
459									"format":   "TV",
460									"title": map[string]interface{}{
461										"english": "Example Show",
462										"romaji":  "Example Show",
463										"native":  "例",
464									},
465									"status": "RELEASING",
466								},
467							},
468						},
469					},
470				},
471			},
472		},
473	}
474
475	list := ParseAnimeList(input)
476	if len(list.Watching) != 1 {
477		t.Fatalf("expected custom-list re-export to be skipped, watching=%d", len(list.Watching))
478	}
479	all := getEntriesByCategory(list, "ALL")
480	if len(all) != 1 || all[0].Media.ID != 42 {
481		t.Fatalf("Show All should list media 42 once, got %#v", all)
482	}
483}
484
485func TestParseAnimeListDedupesSameMediaWithoutIsCustomListFlag(t *testing.T) {
486	// Older/cached payloads may omit isCustomList; still dedupe by media ID.
487	input := map[string]interface{}{
488		"data": map[string]interface{}{
489			"MediaListCollection": map[string]interface{}{
490				"lists": []interface{}{
491					map[string]interface{}{
492						"name": "Watching",
493						"entries": []interface{}{
494							map[string]interface{}{
495								"id":        float64(1),
496								"status":    "CURRENT",
497								"progress":  float64(1),
498								"updatedAt": float64(1_700_000_000),
499								"media": map[string]interface{}{
500									"id":    float64(7),
501									"title": map[string]interface{}{"english": "Seven", "romaji": "Seven"},
502								},
503							},
504						},
505					},
506					map[string]interface{}{
507						"name": "Seasonal",
508						"entries": []interface{}{
509							map[string]interface{}{
510								"id":        float64(1),
511								"status":    "CURRENT",
512								"progress":  float64(1),
513								"updatedAt": float64(1_700_000_000),
514								"media": map[string]interface{}{
515									"id":    float64(7),
516									"title": map[string]interface{}{"english": "Seven", "romaji": "Seven"},
517								},
518							},
519						},
520					},
521				},
522			},
523		},
524	}
525
526	list := ParseAnimeList(input)
527	if len(list.Watching) != 1 {
528		t.Fatalf("expected media-ID dedupe without isCustomList, watching=%d", len(list.Watching))
529	}
530}
531
532func TestGetEntriesByCategoryDedupesAcrossBuckets(t *testing.T) {
533	list := AnimeList{
534		Watching: []Entry{
535			{Media: Media{ID: 1, Title: AnimeTitle{English: "A"}}, Status: "CURRENT"},
536			{Media: Media{ID: 1, Title: AnimeTitle{English: "A (dup)"}}, Status: "CURRENT"},
537		},
538		Completed: []Entry{
539			{Media: Media{ID: 2, Title: AnimeTitle{English: "B"}}, Status: "COMPLETED"},
540		},
541	}
542	all := getEntriesByCategory(list, "ALL")
543	if len(all) != 2 {
544		t.Fatalf("expected 2 unique media IDs in ALL, got %d (%#v)", len(all), all)
545	}
546	current := getEntriesByCategory(list, "CURRENT")
547	if len(current) != 1 || current[0].Media.ID != 1 {
548		t.Fatalf("expected CURRENT to dedupe watching, got %#v", current)
549	}
550}
551
552func TestMediaDisplayTitleFallsBackToID(t *testing.T) {
553	title := mediaDisplayTitle(Media{ID: 42}, &CurdConfig{AnimeNameLanguage: "english"})
554	if title != "42" {
555		t.Fatalf("expected ID fallback for empty titles, got %q", title)
556	}
557}
558
559func TestMapEntriesByMediaIDSkipsZeroIDs(t *testing.T) {
560	list := AnimeList{
561		Watching: []Entry{
562			{Media: Media{ID: 0}, Progress: 1},
563			{Media: Media{ID: 10}, Progress: 2},
564		},
565	}
566
567	entries := mapEntriesByMediaID(list)
568	if len(entries) != 1 {
569		t.Fatalf("expected only valid media IDs, got %#v", entries)
570	}
571	if entries[10].Progress != 2 {
572		t.Fatalf("expected media 10 to be retained, got %#v", entries[10])
573	}
574}