Commit e501cb3a5e

e501cb3a5ec24481c4ab0dace77a785a07bec158

parent: 4c0962cb42

Unsigned

Wraient <wraient.911@gmail.com> · 2026-05-23 00:53 UTC

Add intent regression coverage

Layout: unified · split

cmd/curd/main.go +3
@@ -217,6 +217,9 @@ func main() {
217217 }
218218
219219 anime.Ep.Player.Speed = 1.0
220 if userCurdConfig.DiscordPresence {
221 internal.CurdOut("Starting Discord broadcast.")
222 }
220223
221224 // Get filler list concurrently
222225 go func() {
internal/bench_test.go added +93
@@ -0,0 +1,93 @@
1package internal
2
3import (
4 "fmt"
5 "testing"
6 "time"
7)
8
9func benchmarkAnimeList(size int) AnimeList {
10 list := AnimeList{}
11 for i := 0; i < size; i++ {
12 entry := Entry{
13 Media: Media{
14 ID: i + 1,
15 MalID: 1000 + i,
16 Title: AnimeTitle{
17 English: fmt.Sprintf("Anime %d", i+1),
18 Romaji: fmt.Sprintf("Anime %d", i+1),
19 },
20 },
21 Status: "CURRENT",
22 Progress: i % 24,
23 Score: float64(i % 10),
24 UpdatedAt: time.Date(2026, 1, 1, 0, 0, i%60, 0, time.UTC),
25 }
26 switch i % 5 {
27 case 0:
28 list.Watching = append(list.Watching, entry)
29 case 1:
30 entry.Status = "COMPLETED"
31 list.Completed = append(list.Completed, entry)
32 case 2:
33 entry.Status = "PAUSED"
34 list.Paused = append(list.Paused, entry)
35 case 3:
36 entry.Status = "PLANNING"
37 list.Planning = append(list.Planning, entry)
38 default:
39 entry.Status = "DROPPED"
40 list.Dropped = append(list.Dropped, entry)
41 }
42 }
43 return list
44}
45
46func BenchmarkBuildDualRemoteSyncPlan(b *testing.B) {
47 aniList := benchmarkAnimeList(1000)
48 myAnimeList := benchmarkAnimeList(1000)
49 for i := range myAnimeList.Watching {
50 myAnimeList.Watching[i].Progress += 1
51 myAnimeList.Watching[i].UpdatedAt = myAnimeList.Watching[i].UpdatedAt.Add(time.Hour)
52 }
53
54 b.ReportAllocs()
55 b.ResetTimer()
56 for i := 0; i < b.N; i++ {
57 _ = buildDualRemoteSyncPlan(aniList, myAnimeList)
58 }
59}
60
61func BenchmarkMergeAnimeLists(b *testing.B) {
62 aniList := benchmarkAnimeList(1000)
63 myAnimeList := benchmarkAnimeList(1000)
64
65 b.ReportAllocs()
66 b.ResetTimer()
67 for i := 0; i < b.N; i++ {
68 _ = mergeAnimeLists(aniList, myAnimeList)
69 }
70}
71
72func BenchmarkSortAllanimeSourcesByPriority(b *testing.B) {
73 sources := make([]allanimeSource, 0, 1000)
74 for i := 0; i < 1000; i++ {
75 sources = append(sources, allanimeSource{
76 SourceUrl: fmt.Sprintf("https://example.com/%d.mp4", i),
77 SourceName: "Yt-mp4",
78 Priority: float64((i * 37) % 100),
79 })
80 }
81
82 b.ReportAllocs()
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 _ = sortAllanimeSourcesByPriority(sources)
86 }
87}
88
89func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
90 for i := 0; i < b.N; i++ {
91 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End")
92 }
93}
internal/curd.go +51 −25
@@ -923,7 +923,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
923923
924924 if selectedAnilistAnime.Status == "COMPLETED" {
925925 CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
926 selectedOption, err := DynamicSelect([]SelectionOption{
926 selectedOption, err := promptSelect([]SelectionOption{
927927 {Key: "rewatch", Label: "Start rewatch from episode 1"},
928928 {Key: "continue", Label: "Continue without updating tracker"},
929929 {Key: "details", Label: "Open details"},
@@ -1492,7 +1492,7 @@ func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime,
14921492 SelectionOption{Key: "back", Label: "Back to list"},
14931493 )
14941494
1495 selected, err := DynamicSelect(options)
1495 selected, err := promptSelect(options)
14961496 if err != nil {
14971497 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
14981498 anime.Ep.ContinueLast = false
@@ -1533,7 +1533,7 @@ func confirmProviderMatch(option SelectionOption, reason string) bool {
15331533 }
15341534
15351535 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1536 selected, err := DynamicSelect([]SelectionOption{
1536 selected, err := promptSelect([]SelectionOption{
15371537 {Key: "use", Label: "Use this match"},
15381538 {Key: "manual", Label: "Select manually"},
15391539 })
@@ -1756,7 +1756,7 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
17561756 }
17571757
17581758 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1759 selected, err := DynamicSelect(options)
1759 selected, err := promptSelect(options)
17601760 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
17611761 if err != nil {
17621762 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
@@ -2081,9 +2081,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
20812081
20822082// HandleLastEpisodeCompletion handles scoring and completion for the last episode
20832083func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
2084 // Check if this is the last episode and scoring is enabled
2085 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
2086 // Prompt user to score the anime
2084 if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
2085 return
2086 }
2087
2088 summary := []string{}
2089 canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
2090
2091 if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
20872092 CurdOut("You've completed this anime! Would you like to rate it?")
20882093
20892094 scoreOptions := []SelectionOption{
@@ -2099,46 +2104,60 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT
20992104 if err != nil {
21002105 Log(fmt.Sprintf("Error rating anime: %v", err))
21012106 CurdOut("Failed to rate anime")
2107 summary = append(summary, "rating failed")
21022108 } else {
21032109 CurdOut("Anime rated successfully!")
2110 summary = append(summary, "rating saved")
21042111 }
2112 } else {
2113 summary = append(summary, "rating skipped")
21052114 }
21062115 // Back (-2) and no are treated as skip
2116 } else {
2117 summary = append(summary, "rating skipped")
21072118 }
21082119
2109 // Update anime status to completed on AniList.
2110 // For rewatches, preserve the original completion date and only increment repeat count.
2111 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
2120 if !anime.IsAiring && canWriteRemote {
21122121 if anime.Rewatching {
21132122 err := CompleteAnimeRewatch(userToken, *anime)
21142123 if err != nil {
21152124 Log("Error completing anime rewatch: " + err.Error())
2125 summary = append(summary, "rewatch completion failed")
2126 } else {
2127 summary = append(summary, "rewatch completed")
21162128 }
21172129 } else {
21182130 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
21192131 if err != nil {
21202132 Log("Error updating anime status to completed: " + err.Error())
2133 summary = append(summary, "status update failed")
2134 } else {
2135 summary = append(summary, "marked completed")
21212136 }
2122 // Note: UpdateAnimeStatus already outputs a message on success
21232137 }
2138 } else if !anime.IsAiring {
2139 summary = append(summary, "tracker updates skipped")
21242140 }
21252141
2126 // Check for sequel after completion (only if this is the last episode)
2127 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
2128 handleSequelCheck(userCurdConfig, anime, userToken)
2142 if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
2143 summary = append(summary, sequelSummary)
2144 }
2145 if len(summary) > 0 {
2146 CurdOut("Completion summary: " + strings.Join(summary, "; "))
21292147 }
21302148}
21312149
21322150// handleSequelCheck checks for sequels and prompts the user accordingly
2133func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
2151func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
21342152 if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
2135 return
2153 return "sequel check skipped"
21362154 }
21372155
21382156 // Recover from any panics in this function to prevent crashes
21392157 defer func() {
21402158 if r := recover(); r != nil {
21412159 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
2160 summary = "sequel check failed"
21422161 }
21432162 }()
21442163
@@ -2146,24 +2165,24 @@ func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken strin
21462165 sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
21472166 if err != nil {
21482167 Log(fmt.Sprintf("Error fetching sequel information: %v", err))
2149 return
2168 return "sequel check failed"
21502169 }
21512170
21522171 if len(sequels) == 0 {
21532172 Log("No sequel found for this anime")
2154 return
2173 return "no sequel found"
21552174 }
21562175
21572176 sequel := &sequels[0]
21582177 if len(sequels) > 1 {
21592178 selectedSequel, ok := selectSequel(userCurdConfig, sequels)
21602179 if !ok {
2161 return
2180 return "sequel skipped"
21622181 }
21632182 sequel = selectedSequel
21642183 }
21652184
2166 promptSequelAction(userCurdConfig, sequel, userToken)
2185 return promptSequelAction(userCurdConfig, sequel, userToken)
21672186}
21682187
21692188func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
@@ -2179,7 +2198,7 @@ func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo
21792198 }
21802199 options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
21812200
2182 selected, err := DynamicSelect(options)
2201 selected, err := promptSelect(options)
21832202 if err != nil {
21842203 Log(fmt.Sprintf("Error selecting sequel: %v", err))
21852204 return nil, false
@@ -2207,9 +2226,9 @@ func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
22072226 return strconv.Itoa(sequel.ID)
22082227}
22092228
2210func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) {
2229func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
22112230 if sequel == nil {
2212 return
2231 return ""
22132232 }
22142233
22152234 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
@@ -2245,10 +2264,10 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
22452264 SelectionOption{Key: "skip", Label: "Skip"},
22462265 )
22472266
2248 selected, err := DynamicSelect(options)
2267 selected, err := promptSelect(options)
22492268 if err != nil {
22502269 Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2251 return
2270 return "sequel action failed"
22522271 }
22532272
22542273 switch selected.Key {
@@ -2256,15 +2275,19 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
22562275 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
22572276 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
22582277 CurdOut("Failed to add sequel to Watching.")
2278 return "sequel add failed"
22592279 } else {
22602280 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2281 return "sequel added to Watching"
22612282 }
22622283 case "planning":
22632284 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
22642285 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
22652286 CurdOut("Failed to add sequel to Plan to Watch.")
2287 return "sequel add failed"
22662288 } else {
22672289 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2290 return "sequel added to Plan to Watch"
22682291 }
22692292 case "details":
22702293 url := sequel.SiteURL
@@ -2275,10 +2298,13 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
22752298 if err := browser.OpenURL(url); err != nil {
22762299 Log(fmt.Sprintf("Error opening browser: %v", err))
22772300 CurdOut("Failed to open browser.")
2301 return "sequel details failed"
22782302 }
2303 return "sequel details opened"
22792304 case "skip", "-1", "-2":
22802305 Log("User skipped sequel action")
22812306 }
2307 return "sequel skipped"
22822308}
22832309
22842310// ChangeProvider allows the user to switch the anime provider
internal/provider.go +1 −1
@@ -60,7 +60,7 @@ func GetEpisodeURLForPlayback(config CurdConfig, id string, epNo int) ([]string,
6060 }
6161
6262 CurdOut(audioFallbackPrompt(preferredMode, fallbackMode))
63 selected, selectErr := DynamicSelect([]SelectionOption{
63 selected, selectErr := promptSelect([]SelectionOption{
6464 {Key: "play", Label: "Play " + fallbackMode},
6565 {Key: "cancel", Label: "Cancel"},
6666 })
internal/provider_animepahe.go +31 −28
@@ -81,36 +81,39 @@ func (p *AnimepaheProvider) ensureBypass() error {
8181 Log("Cached Animepahe session expired. Requesting new session...")
8282 }
8383
84 CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...")
85
86 l := launcher.New().Headless(true)
87 defer l.Cleanup()
88 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
89 defer browser.MustClose()
90
91 page := browser.MustPage("https://animepahe.pw/")
92 page.MustWaitLoad()
93
94 for i := 0; i < 30; i++ {
95 info, err := page.Info()
96 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
97 break
98 }
99 time.Sleep(500 * time.Millisecond)
100 }
101
102 rodCookies, err := page.Cookies(nil)
103 if err != nil {
104 return fmt.Errorf("failed to acquire DDoS guard cookies: %v", err)
105 }
106
10784 u, _ := url.Parse("https://animepahe.pw")
10885 var httpCookies []*http.Cookie
109 for _, cookie := range rodCookies {
110 httpCookies = append(httpCookies, &http.Cookie{
111 Name: cookie.Name,
112 Value: cookie.Value,
113 })
86 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
87 if err := rod.Try(func() {
88 l := launcher.New().Headless(true)
89 defer l.Cleanup()
90 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
91 defer browser.MustClose()
92
93 page := browser.MustPage("https://animepahe.pw/")
94 page.MustWaitLoad()
95
96 for i := 0; i < 30; i++ {
97 info, err := page.Info()
98 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
99 break
100 }
101 time.Sleep(500 * time.Millisecond)
102 }
103
104 rodCookies, err := page.Cookies(nil)
105 if err != nil {
106 panic(err)
107 }
108 for _, cookie := range rodCookies {
109 httpCookies = append(httpCookies, &http.Cookie{
110 Name: cookie.Name,
111 Value: cookie.Value,
112 })
113 }
114 }); err != nil {
115 CurdOut("Animepahe browser challenge failed. Try again later or switch provider.")
116 return fmt.Errorf("animepahe browser challenge failed: %w", err)
114117 }
115118 SetCookiesForAnimepahe(u, httpCookies)
116119
internal/selection_menu.go +2
@@ -624,6 +624,8 @@ func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
624624 return dynamicSelectInternal(options, nil)
625625}
626626
627var promptSelect = DynamicSelect
628
627629func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
628630 return dynamicSelectInternal(options, refreshConfig)
629631}
internal/tracking.go +6 −2
@@ -325,6 +325,10 @@ type remoteSyncPreview struct {
325325}
326326
327327func confirmRemoteSync(preview remoteSyncPreview) (bool, error) {
328 if os.Getenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC") == "1" {
329 return true, nil
330 }
331
328332 CurdOut(fmt.Sprintf("%s: AniList %d, MyAnimeList %d.", preview.Action, preview.AniListEntries, preview.MyAnimeListEntries))
329333 if preview.Deletes > 0 {
330334 CurdOut(fmt.Sprintf("This will write %d entries and delete %d entries.", preview.Writes, preview.Deletes))
@@ -335,7 +339,7 @@ func confirmRemoteSync(preview remoteSyncPreview) (bool, error) {
335339 CurdOut(fmt.Sprintf("%d entries need a MyAnimeList ID lookup.", preview.MissingMALIDs))
336340 }
337341
338 selected, err := DynamicSelect([]SelectionOption{
342 selected, err := promptSelect([]SelectionOption{
339343 {Key: "continue", Label: "Continue"},
340344 {Key: "cancel", Label: "Cancel"},
341345 })
@@ -1144,7 +1148,7 @@ func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error {
11441148 }
11451149
11461150 CurdOut("AniList tracking data was found.")
1147 selected, err := DynamicSelect(options)
1151 selected, err := promptSelect(options)
11481152 if err != nil {
11491153 return err
11501154 }
internal/tracking_live_integration_test.go +29
@@ -421,12 +421,33 @@ func TestTrackerLiveRuntimeIntegration(t *testing.T) {
421421 })
422422}
423423
424func TestLiveTrackerContextForcesTerminalPrompts(t *testing.T) {
425 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") == "1" {
426 t.Skip("live integration context is covered by the live suite")
427 }
428
429 config := CurdConfig{
430 RofiSelection: true,
431 ImagePreview: true,
432 AlternateScreen: true,
433 }
434 forceTerminalTestMode(&config)
435
436 if config.RofiSelection || config.ImagePreview || config.AlternateScreen {
437 t.Fatalf("expected live tests to force terminal prompt mode, got %+v", config)
438 }
439 if !config.MyAnimeListImportDismissed {
440 t.Fatalf("expected live tests to dismiss import prompt")
441 }
442}
443
424444func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) {
425445 t.Helper()
426446
427447 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" {
428448 t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests")
429449 }
450 t.Setenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC", "1")
430451
431452 configPath := os.Getenv("CURD_CONFIG_PATH")
432453 if configPath == "" {
@@ -443,6 +464,7 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
443464 }
444465 config.TrackingConfigured = true
445466 config.TrackingLocal = true
467 forceTerminalTestMode(&config)
446468
447469 previousGlobalConfig := GetGlobalConfig()
448470 previousGlobalUser := GetGlobalUser()
@@ -477,6 +499,13 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
477499 return &config, anilistToken, resolveLiveTestAnime(t), cleanup
478500}
479501
502func forceTerminalTestMode(config *CurdConfig) {
503 config.RofiSelection = false
504 config.ImagePreview = false
505 config.AlternateScreen = false
506 config.MyAnimeListImportDismissed = true
507}
508
480509func resolveLiveTestAnime(t *testing.T) []liveTestAnime {
481510 t.Helper()
482511
internal/user_intent_regression_test.go added +283
@@ -0,0 +1,283 @@
1package internal
2
3import (
4 "bytes"
5 "errors"
6 "io"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11)
12
13type fakePlaybackProvider struct {
14 linksByMode map[string][]string
15 errByMode map[string]error
16 modes []string
17}
18
19func (p *fakePlaybackProvider) Name() string { return "fake" }
20
21func (p *fakePlaybackProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
22 return nil, nil
23}
24
25func (p *fakePlaybackProvider) EpisodesList(showID, mode string) ([]string, error) {
26 return []string{"1"}, nil
27}
28
29func (p *fakePlaybackProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
30 mode := normalizeTranslationType(config.SubOrDub)
31 p.modes = append(p.modes, mode)
32 if err := p.errByMode[mode]; err != nil {
33 return nil, err
34 }
35 return p.linksByMode[mode], nil
36}
37
38func withPromptSelect(t *testing.T, fn func([]SelectionOption) (SelectionOption, error)) {
39 t.Helper()
40 previous := promptSelect
41 promptSelect = fn
42 t.Cleanup(func() {
43 promptSelect = previous
44 })
45}
46
47func withProvider(t *testing.T, provider Provider) {
48 t.Helper()
49 previous := CurrentProvider
50 CurrentProvider = provider
51 t.Cleanup(func() {
52 CurrentProvider = previous
53 })
54}
55
56func captureStdout(t *testing.T, fn func()) string {
57 t.Helper()
58
59 originalStdout := os.Stdout
60 reader, writer, err := os.Pipe()
61 if err != nil {
62 t.Fatalf("create stdout pipe: %v", err)
63 }
64 os.Stdout = writer
65
66 fn()
67
68 if err := writer.Close(); err != nil {
69 t.Fatalf("close stdout writer: %v", err)
70 }
71 os.Stdout = originalStdout
72
73 var buf bytes.Buffer
74 if _, err := io.Copy(&buf, reader); err != nil {
75 t.Fatalf("read captured stdout: %v", err)
76 }
77 return buf.String()
78}
79
80func TestGetEpisodeURLForPlaybackUsesPreferredAudioOnlyWhenAvailable(t *testing.T) {
81 provider := &fakePlaybackProvider{
82 linksByMode: map[string][]string{"sub": {"sub-url"}, "dub": {"dub-url"}},
83 errByMode: map[string]error{},
84 }
85 withProvider(t, provider)
86
87 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
88 if err != nil {
89 t.Fatalf("expected preferred audio to succeed: %v", err)
90 }
91 if mode != "sub" || len(links) != 1 || links[0] != "sub-url" {
92 t.Fatalf("unexpected playback result: mode=%q links=%v", mode, links)
93 }
94 if got := strings.Join(provider.modes, ","); got != "sub" {
95 t.Fatalf("expected only preferred mode lookup, got %s", got)
96 }
97}
98
99func TestGetEpisodeURLForPlaybackRequiresExplicitFallbackApproval(t *testing.T) {
100 provider := &fakePlaybackProvider{
101 linksByMode: map[string][]string{"dub": {"dub-url"}},
102 errByMode: map[string]error{"sub": errors.New("no sub streams")},
103 }
104 withProvider(t, provider)
105 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
106 if len(options) != 2 || options[0].Key != "play" {
107 t.Fatalf("unexpected fallback options: %+v", options)
108 }
109 return SelectionOption{Key: "play"}, nil
110 })
111
112 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
113 if err != nil {
114 t.Fatalf("expected accepted fallback to succeed: %v", err)
115 }
116 if mode != "dub" || len(links) != 1 || links[0] != "dub-url" {
117 t.Fatalf("unexpected fallback result: mode=%q links=%v", mode, links)
118 }
119 if got := strings.Join(provider.modes, ","); got != "sub,dub" {
120 t.Fatalf("expected preferred then fallback lookup, got %s", got)
121 }
122}
123
124func TestGetEpisodeURLForPlaybackCancelsAudioFallback(t *testing.T) {
125 provider := &fakePlaybackProvider{
126 linksByMode: map[string][]string{"dub": {"dub-url"}},
127 errByMode: map[string]error{"sub": errors.New("no sub streams")},
128 }
129 withProvider(t, provider)
130 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
131 return SelectionOption{Key: "cancel"}, nil
132 })
133
134 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
135 if err == nil {
136 t.Fatalf("expected cancelled fallback to return preferred-mode error")
137 }
138 if mode != "sub" || len(links) != 0 {
139 t.Fatalf("unexpected cancelled fallback result: mode=%q links=%v", mode, links)
140 }
141}
142
143func TestShouldWriteRemoteTrackingHonorsSessionSkip(t *testing.T) {
144 config := &CurdConfig{TrackingRemote: TrackingRemoteAniList}
145 if !ShouldWriteRemoteTracking(config, &Anime{}) {
146 t.Fatalf("expected normal remote tracking to write")
147 }
148 if ShouldWriteRemoteTracking(config, &Anime{SkipRemoteSync: true}) {
149 t.Fatalf("expected session skip flag to suppress remote writes")
150 }
151 if ShouldWriteRemoteTracking(&CurdConfig{TrackingRemote: TrackingRemoteNone}, &Anime{}) {
152 t.Fatalf("expected local-only mode to suppress remote writes")
153 }
154}
155
156func TestMaybeImportAniListToMyAnimeListDismissesWithoutMarkingImported(t *testing.T) {
157 tempDir := t.TempDir()
158 configPath := filepath.Join(tempDir, "curd.conf")
159 if err := createDefaultConfig(configPath); err != nil {
160 t.Fatalf("create config: %v", err)
161 }
162
163 previousConfigPath := GlobalConfigPath
164 GlobalConfigPath = configPath
165 t.Cleanup(func() {
166 GlobalConfigPath = previousConfigPath
167 })
168
169 config := &CurdConfig{
170 StoragePath: tempDir,
171 TrackingRemote: TrackingRemoteMyAnimeList,
172 TrackingConfigured: true,
173 MyAnimeListImported: false,
174 }
175 if err := os.WriteFile(filepath.Join(tempDir, "anilist_token.json"), []byte("legacy-token"), 0600); err != nil {
176 t.Fatalf("write token: %v", err)
177 }
178
179 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
180 return SelectionOption{Key: "no"}, nil
181 })
182
183 if err := maybeImportAniListToMyAnimeList(config, &User{}); err != nil {
184 t.Fatalf("maybe import: %v", err)
185 }
186 if config.MyAnimeListImported {
187 t.Fatalf("declining import must not mark import completed")
188 }
189 if !config.MyAnimeListImportDismissed {
190 t.Fatalf("declining import should mark the prompt dismissed")
191 }
192}
193
194func TestWriteTrackingBackupCreatesSnapshot(t *testing.T) {
195 config := &CurdConfig{StoragePath: t.TempDir()}
196 aniList := AnimeList{Watching: []Entry{{Media: Media{ID: 1, MalID: 11}, Status: "CURRENT"}}}
197 myAnimeList := AnimeList{Planning: []Entry{{Media: Media{ID: 2, MalID: 22}, Status: "PLANNING"}}}
198
199 backupPath, err := writeTrackingBackup(config, "test action", aniList, myAnimeList)
200 if err != nil {
201 t.Fatalf("write backup: %v", err)
202 }
203 data, err := os.ReadFile(backupPath)
204 if err != nil {
205 t.Fatalf("read backup: %v", err)
206 }
207 if !strings.Contains(string(data), `"action": "test action"`) || !strings.Contains(string(data), `"id": 1`) || !strings.Contains(string(data), `"id": 2`) {
208 t.Fatalf("backup did not contain expected snapshot data: %s", string(data))
209 }
210}
211
212func TestConfirmProviderMatchRequiresUserApproval(t *testing.T) {
213 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
214 if options[0].Key != "use" || options[1].Key != "manual" {
215 t.Fatalf("unexpected provider confirmation options: %+v", options)
216 }
217 return SelectionOption{Key: "manual"}, nil
218 })
219
220 if confirmProviderMatch(SelectionOption{Label: "Example"}, "title") {
221 t.Fatalf("manual selection should reject guessed provider match")
222 }
223}
224
225func TestSelectSequelAndUnreleasedSequelActions(t *testing.T) {
226 sequels := []SequelInfo{
227 {ID: 1, Title: AnimeTitle{Romaji: "First"}, Status: "FINISHED"},
228 {ID: 2, Title: AnimeTitle{Romaji: "Second"}, Status: "NOT_YET_RELEASED"},
229 }
230 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
231 return SelectionOption{Key: "1"}, nil
232 })
233
234 selected, ok := selectSequel(&CurdConfig{}, sequels)
235 if !ok || selected.ID != 2 {
236 t.Fatalf("expected second sequel selection, got ok=%v selected=%+v", ok, selected)
237 }
238
239 var captured []SelectionOption
240 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
241 captured = append([]SelectionOption(nil), options...)
242 return SelectionOption{Key: "skip"}, nil
243 })
244 summary := promptSequelAction(&CurdConfig{}, selected, "token")
245 if summary != "sequel skipped" {
246 t.Fatalf("expected skipped summary, got %q", summary)
247 }
248 for _, option := range captured {
249 if option.Key == "watching" {
250 t.Fatalf("not-yet-released sequel should not offer Watching action: %+v", captured)
251 }
252 }
253}
254
255func TestHandleLastEpisodeCompletionSummarizesSkippedTrackerWrites(t *testing.T) {
256 previousConfig := GetGlobalConfig()
257 config := &CurdConfig{
258 RofiSelection: false,
259 ScoreOnCompletion: true,
260 TrackingRemote: TrackingRemoteAniList,
261 }
262 SetGlobalConfig(config)
263 t.Cleanup(func() {
264 SetGlobalConfig(previousConfig)
265 })
266
267 output := captureStdout(t, func() {
268 HandleLastEpisodeCompletion(config, &Anime{
269 AnilistId: 1,
270 TotalEpisodes: 12,
271 SkipRemoteSync: true,
272 Ep: Episode{
273 Number: 12,
274 },
275 }, "token")
276 })
277
278 if !strings.Contains(output, "Completion summary:") ||
279 !strings.Contains(output, "tracker updates skipped") ||
280 !strings.Contains(output, "sequel check skipped") {
281 t.Fatalf("completion summary did not report skipped tracker writes: %q", output)
282 }
283}