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() {
217 } 217 }
218 218
219 anime.Ep.Player.Speed = 1.0 219 anime.Ep.Player.Speed = 1.0
220 if userCurdConfig.DiscordPresence {
221 internal.CurdOut("Starting Discord broadcast.")
222 }
220 223
221 // Get filler list concurrently 224 // Get filler list concurrently
222 go func() { 225 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
923 923
924 if selectedAnilistAnime.Status == "COMPLETED" { 924 if selectedAnilistAnime.Status == "COMPLETED" {
925 CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?") 925 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{
927 {Key: "rewatch", Label: "Start rewatch from episode 1"}, 927 {Key: "rewatch", Label: "Start rewatch from episode 1"},
928 {Key: "continue", Label: "Continue without updating tracker"}, 928 {Key: "continue", Label: "Continue without updating tracker"},
929 {Key: "details", Label: "Open details"}, 929 {Key: "details", Label: "Open details"},
@@ -1492,7 +1492,7 @@ func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime,
1492 SelectionOption{Key: "back", Label: "Back to list"}, 1492 SelectionOption{Key: "back", Label: "Back to list"},
1493 ) 1493 )
1494 1494
1495 selected, err := DynamicSelect(options) 1495 selected, err := promptSelect(options)
1496 if err != nil { 1496 if err != nil {
1497 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err)) 1497 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1498 anime.Ep.ContinueLast = false 1498 anime.Ep.ContinueLast = false
@@ -1533,7 +1533,7 @@ func confirmProviderMatch(option SelectionOption, reason string) bool {
1533 } 1533 }
1534 1534
1535 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label)) 1535 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1536 selected, err := DynamicSelect([]SelectionOption{ 1536 selected, err := promptSelect([]SelectionOption{
1537 {Key: "use", Label: "Use this match"}, 1537 {Key: "use", Label: "Use this match"},
1538 {Key: "manual", Label: "Select manually"}, 1538 {Key: "manual", Label: "Select manually"},
1539 }) 1539 })
@@ -1756,7 +1756,7 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
1756 } 1756 }
1757 1757
1758 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.") 1758 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1759 selected, err := DynamicSelect(options) 1759 selected, err := promptSelect(options)
1760 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" { 1760 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1761 if err != nil { 1761 if err != nil {
1762 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err)) 1762 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
@@ -2081,9 +2081,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
2081 2081
2082// HandleLastEpisodeCompletion handles scoring and completion for the last episode 2082// HandleLastEpisodeCompletion handles scoring and completion for the last episode
2083func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) { 2083func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
2084 // Check if this is the last episode and scoring is enabled 2084 if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
2085 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring { 2085 return
2086 // Prompt user to score the anime 2086 }
2087
2088 summary := []string{}
2089 canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
2090
2091 if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
2087 CurdOut("You've completed this anime! Would you like to rate it?") 2092 CurdOut("You've completed this anime! Would you like to rate it?")
2088 2093
2089 scoreOptions := []SelectionOption{ 2094 scoreOptions := []SelectionOption{
@@ -2099,46 +2104,60 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT
2099 if err != nil { 2104 if err != nil {
2100 Log(fmt.Sprintf("Error rating anime: %v", err)) 2105 Log(fmt.Sprintf("Error rating anime: %v", err))
2101 CurdOut("Failed to rate anime") 2106 CurdOut("Failed to rate anime")
2107 summary = append(summary, "rating failed")
2102 } else { 2108 } else {
2103 CurdOut("Anime rated successfully!") 2109 CurdOut("Anime rated successfully!")
2110 summary = append(summary, "rating saved")
2104 } 2111 }
2112 } else {
2113 summary = append(summary, "rating skipped")
2105 } 2114 }
2106 // Back (-2) and no are treated as skip 2115 // Back (-2) and no are treated as skip
2116 } else {
2117 summary = append(summary, "rating skipped")
2107 } 2118 }
2108 2119
2109 // Update anime status to completed on AniList. 2120 if !anime.IsAiring && canWriteRemote {
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 {
2112 if anime.Rewatching { 2121 if anime.Rewatching {
2113 err := CompleteAnimeRewatch(userToken, *anime) 2122 err := CompleteAnimeRewatch(userToken, *anime)
2114 if err != nil { 2123 if err != nil {
2115 Log("Error completing anime rewatch: " + err.Error()) 2124 Log("Error completing anime rewatch: " + err.Error())
2125 summary = append(summary, "rewatch completion failed")
2126 } else {
2127 summary = append(summary, "rewatch completed")
2116 } 2128 }
2117 } else { 2129 } else {
2118 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED") 2130 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
2119 if err != nil { 2131 if err != nil {
2120 Log("Error updating anime status to completed: " + err.Error()) 2132 Log("Error updating anime status to completed: " + err.Error())
2133 summary = append(summary, "status update failed")
2134 } else {
2135 summary = append(summary, "marked completed")
2121 } 2136 }
2122 // Note: UpdateAnimeStatus already outputs a message on success
2123 } 2137 }
2138 } else if !anime.IsAiring {
2139 summary = append(summary, "tracker updates skipped")
2124 } 2140 }
2125 2141
2126 // Check for sequel after completion (only if this is the last episode) 2142 if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
2127 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes { 2143 summary = append(summary, sequelSummary)
2128 handleSequelCheck(userCurdConfig, anime, userToken) 2144 }
2145 if len(summary) > 0 {
2146 CurdOut("Completion summary: " + strings.Join(summary, "; "))
2129 } 2147 }
2130} 2148}
2131 2149
2132// handleSequelCheck checks for sequels and prompts the user accordingly 2150// 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) {
2134 if !ShouldWriteRemoteTracking(userCurdConfig, anime) { 2152 if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
2135 return 2153 return "sequel check skipped"
2136 } 2154 }
2137 2155
2138 // Recover from any panics in this function to prevent crashes 2156 // Recover from any panics in this function to prevent crashes
2139 defer func() { 2157 defer func() {
2140 if r := recover(); r != nil { 2158 if r := recover(); r != nil {
2141 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r)) 2159 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
2160 summary = "sequel check failed"
2142 } 2161 }
2143 }() 2162 }()
2144 2163
@@ -2146,24 +2165,24 @@ func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken strin
2146 sequels, err := GetAnimeSequel(anime.AnilistId, userToken) 2165 sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
2147 if err != nil { 2166 if err != nil {
2148 Log(fmt.Sprintf("Error fetching sequel information: %v", err)) 2167 Log(fmt.Sprintf("Error fetching sequel information: %v", err))
2149 return 2168 return "sequel check failed"
2150 } 2169 }
2151 2170
2152 if len(sequels) == 0 { 2171 if len(sequels) == 0 {
2153 Log("No sequel found for this anime") 2172 Log("No sequel found for this anime")
2154 return 2173 return "no sequel found"
2155 } 2174 }
2156 2175
2157 sequel := &sequels[0] 2176 sequel := &sequels[0]
2158 if len(sequels) > 1 { 2177 if len(sequels) > 1 {
2159 selectedSequel, ok := selectSequel(userCurdConfig, sequels) 2178 selectedSequel, ok := selectSequel(userCurdConfig, sequels)
2160 if !ok { 2179 if !ok {
2161 return 2180 return "sequel skipped"
2162 } 2181 }
2163 sequel = selectedSequel 2182 sequel = selectedSequel
2164 } 2183 }
2165 2184
2166 promptSequelAction(userCurdConfig, sequel, userToken) 2185 return promptSequelAction(userCurdConfig, sequel, userToken)
2167} 2186}
2168 2187
2169func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) { 2188func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
@@ -2179,7 +2198,7 @@ func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo
2179 } 2198 }
2180 options = append(options, SelectionOption{Key: "skip", Label: "Skip"}) 2199 options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
2181 2200
2182 selected, err := DynamicSelect(options) 2201 selected, err := promptSelect(options)
2183 if err != nil { 2202 if err != nil {
2184 Log(fmt.Sprintf("Error selecting sequel: %v", err)) 2203 Log(fmt.Sprintf("Error selecting sequel: %v", err))
2185 return nil, false 2204 return nil, false
@@ -2207,9 +2226,9 @@ func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
2207 return strconv.Itoa(sequel.ID) 2226 return strconv.Itoa(sequel.ID)
2208} 2227}
2209 2228
2210func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) { 2229func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
2211 if sequel == nil { 2230 if sequel == nil {
2212 return 2231 return ""
2213 } 2232 }
2214 2233
2215 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel) 2234 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
@@ -2245,10 +2264,10 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
2245 SelectionOption{Key: "skip", Label: "Skip"}, 2264 SelectionOption{Key: "skip", Label: "Skip"},
2246 ) 2265 )
2247 2266
2248 selected, err := DynamicSelect(options) 2267 selected, err := promptSelect(options)
2249 if err != nil { 2268 if err != nil {
2250 Log(fmt.Sprintf("Error in sequel action prompt: %v", err)) 2269 Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2251 return 2270 return "sequel action failed"
2252 } 2271 }
2253 2272
2254 switch selected.Key { 2273 switch selected.Key {
@@ -2256,15 +2275,19 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
2256 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil { 2275 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
2257 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err)) 2276 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2258 CurdOut("Failed to add sequel to Watching.") 2277 CurdOut("Failed to add sequel to Watching.")
2278 return "sequel add failed"
2259 } else { 2279 } else {
2260 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle)) 2280 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2281 return "sequel added to Watching"
2261 } 2282 }
2262 case "planning": 2283 case "planning":
2263 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil { 2284 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2264 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err)) 2285 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2265 CurdOut("Failed to add sequel to Plan to Watch.") 2286 CurdOut("Failed to add sequel to Plan to Watch.")
2287 return "sequel add failed"
2266 } else { 2288 } else {
2267 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle)) 2289 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2290 return "sequel added to Plan to Watch"
2268 } 2291 }
2269 case "details": 2292 case "details":
2270 url := sequel.SiteURL 2293 url := sequel.SiteURL
@@ -2275,10 +2298,13 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
2275 if err := browser.OpenURL(url); err != nil { 2298 if err := browser.OpenURL(url); err != nil {
2276 Log(fmt.Sprintf("Error opening browser: %v", err)) 2299 Log(fmt.Sprintf("Error opening browser: %v", err))
2277 CurdOut("Failed to open browser.") 2300 CurdOut("Failed to open browser.")
2301 return "sequel details failed"
2278 } 2302 }
2303 return "sequel details opened"
2279 case "skip", "-1", "-2": 2304 case "skip", "-1", "-2":
2280 Log("User skipped sequel action") 2305 Log("User skipped sequel action")
2281 } 2306 }
2307 return "sequel skipped"
2282} 2308}
2283 2309
2284// ChangeProvider allows the user to switch the anime provider 2310// 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,
60 } 60 }
61 61
62 CurdOut(audioFallbackPrompt(preferredMode, fallbackMode)) 62 CurdOut(audioFallbackPrompt(preferredMode, fallbackMode))
63 selected, selectErr := DynamicSelect([]SelectionOption{ 63 selected, selectErr := promptSelect([]SelectionOption{
64 {Key: "play", Label: "Play " + fallbackMode}, 64 {Key: "play", Label: "Play " + fallbackMode},
65 {Key: "cancel", Label: "Cancel"}, 65 {Key: "cancel", Label: "Cancel"},
66 }) 66 })
internal/provider_animepahe.go +31 −28
@@ -81,36 +81,39 @@ func (p *AnimepaheProvider) ensureBypass() error {
81 Log("Cached Animepahe session expired. Requesting new session...") 81 Log("Cached Animepahe session expired. Requesting new session...")
82 } 82 }
83 83
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
107 u, _ := url.Parse("https://animepahe.pw") 84 u, _ := url.Parse("https://animepahe.pw")
108 var httpCookies []*http.Cookie 85 var httpCookies []*http.Cookie
109 for _, cookie := range rodCookies { 86 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
110 httpCookies = append(httpCookies, &http.Cookie{ 87 if err := rod.Try(func() {
111 Name: cookie.Name, 88 l := launcher.New().Headless(true)
112 Value: cookie.Value, 89 defer l.Cleanup()
113 }) 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)
114 } 117 }
115 SetCookiesForAnimepahe(u, httpCookies) 118 SetCookiesForAnimepahe(u, httpCookies)
116 119
internal/selection_menu.go +2
@@ -624,6 +624,8 @@ func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
624 return dynamicSelectInternal(options, nil) 624 return dynamicSelectInternal(options, nil)
625} 625}
626 626
627var promptSelect = DynamicSelect
628
627func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) { 629func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
628 return dynamicSelectInternal(options, refreshConfig) 630 return dynamicSelectInternal(options, refreshConfig)
629} 631}
internal/tracking.go +6 −2
@@ -325,6 +325,10 @@ type remoteSyncPreview struct {
325} 325}
326 326
327func confirmRemoteSync(preview remoteSyncPreview) (bool, error) { 327func confirmRemoteSync(preview remoteSyncPreview) (bool, error) {
328 if os.Getenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC") == "1" {
329 return true, nil
330 }
331
328 CurdOut(fmt.Sprintf("%s: AniList %d, MyAnimeList %d.", preview.Action, preview.AniListEntries, preview.MyAnimeListEntries)) 332 CurdOut(fmt.Sprintf("%s: AniList %d, MyAnimeList %d.", preview.Action, preview.AniListEntries, preview.MyAnimeListEntries))
329 if preview.Deletes > 0 { 333 if preview.Deletes > 0 {
330 CurdOut(fmt.Sprintf("This will write %d entries and delete %d entries.", preview.Writes, preview.Deletes)) 334 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) {
335 CurdOut(fmt.Sprintf("%d entries need a MyAnimeList ID lookup.", preview.MissingMALIDs)) 339 CurdOut(fmt.Sprintf("%d entries need a MyAnimeList ID lookup.", preview.MissingMALIDs))
336 } 340 }
337 341
338 selected, err := DynamicSelect([]SelectionOption{ 342 selected, err := promptSelect([]SelectionOption{
339 {Key: "continue", Label: "Continue"}, 343 {Key: "continue", Label: "Continue"},
340 {Key: "cancel", Label: "Cancel"}, 344 {Key: "cancel", Label: "Cancel"},
341 }) 345 })
@@ -1144,7 +1148,7 @@ func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error {
1144 } 1148 }
1145 1149
1146 CurdOut("AniList tracking data was found.") 1150 CurdOut("AniList tracking data was found.")
1147 selected, err := DynamicSelect(options) 1151 selected, err := promptSelect(options)
1148 if err != nil { 1152 if err != nil {
1149 return err 1153 return err
1150 } 1154 }
internal/tracking_live_integration_test.go +29
@@ -421,12 +421,33 @@ func TestTrackerLiveRuntimeIntegration(t *testing.T) {
421 }) 421 })
422} 422}
423 423
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
424func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) { 444func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) {
425 t.Helper() 445 t.Helper()
426 446
427 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" { 447 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" {
428 t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests") 448 t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests")
429 } 449 }
450 t.Setenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC", "1")
430 451
431 configPath := os.Getenv("CURD_CONFIG_PATH") 452 configPath := os.Getenv("CURD_CONFIG_PATH")
432 if configPath == "" { 453 if configPath == "" {
@@ -443,6 +464,7 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
443 } 464 }
444 config.TrackingConfigured = true 465 config.TrackingConfigured = true
445 config.TrackingLocal = true 466 config.TrackingLocal = true
467 forceTerminalTestMode(&config)
446 468
447 previousGlobalConfig := GetGlobalConfig() 469 previousGlobalConfig := GetGlobalConfig()
448 previousGlobalUser := GetGlobalUser() 470 previousGlobalUser := GetGlobalUser()
@@ -477,6 +499,13 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
477 return &config, anilistToken, resolveLiveTestAnime(t), cleanup 499 return &config, anilistToken, resolveLiveTestAnime(t), cleanup
478} 500}
479 501
502func forceTerminalTestMode(config *CurdConfig) {
503 config.RofiSelection = false
504 config.ImagePreview = false
505 config.AlternateScreen = false
506 config.MyAnimeListImportDismissed = true
507}
508
480func resolveLiveTestAnime(t *testing.T) []liveTestAnime { 509func resolveLiveTestAnime(t *testing.T) []liveTestAnime {
481 t.Helper() 510 t.Helper()
482 511
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}