-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduler_test.go
More file actions
818 lines (692 loc) · 21.4 KB
/
Copy pathscheduler_test.go
File metadata and controls
818 lines (692 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
package main
import (
"context"
"fmt"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"ytdm/storage"
)
func TestNormalizeChannelVideoURL(t *testing.T) {
t.Run("raw id gets watch URL", func(t *testing.T) {
got := normalizeChannelVideoURL("-0hOASBTWB4")
want := "https://www.youtube.com/watch?v=-0hOASBTWB4"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
})
t.Run("existing URL is preserved", func(t *testing.T) {
input := "https://www.youtube.com/watch?v=-0hOASBTWB4"
got := normalizeChannelVideoURL(input)
if got != input {
t.Fatalf("expected %q, got %q", input, got)
}
})
}
func TestExtractYouTubeVideoID(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{name: "raw id", input: "-0hOASBTWB4", want: "-0hOASBTWB4"},
{name: "watch url", input: "https://www.youtube.com/watch?v=-0hOASBTWB4", want: "-0hOASBTWB4"},
{name: "short url", input: "https://youtu.be/-0hOASBTWB4", want: "-0hOASBTWB4"},
{name: "shorts url", input: "https://www.youtube.com/shorts/-0hOASBTWB4", want: "-0hOASBTWB4"},
{name: "unknown url", input: "https://example.com/watch?v=abc", want: ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := extractYouTubeVideoID(tc.input)
if got != tc.want {
t.Fatalf("expected %q, got %q", tc.want, got)
}
})
}
}
// --- Download worker tests ---
func newTestConfig(t *testing.T) *Config {
t.Helper()
cfg := DefaultConfig()
cfg.DownloadDir = t.TempDir()
return cfg
}
func newTestStorage(t *testing.T) *storage.Storage {
t.Helper()
s, err := storage.NewStorage(filepath.Join(t.TempDir(), "data.db"))
if err != nil {
t.Fatalf("NewStorage: %v", err)
}
return s
}
// TestDownloadWorkerDeduplication verifies that a VideoID already in-flight is not
// re-queued if the same request arrives while the first download is still running.
func TestDownloadWorkerDeduplication(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var callCount int32
hold := make(chan struct{})
execFn := func(_ context.Context, _ DownloadRequest) {
atomic.AddInt32(&callCount, 1)
<-hold
}
cfg := newTestConfig(t)
cfg.MaxConcurrent = 3
queue := make(chan DownloadRequest, 10)
workerDone := make(chan struct{})
go func() {
runDownloadWorker(ctx, cfg, nil, nil, queue, execFn)
close(workerDone)
}()
req := DownloadRequest{VideoID: "vid1", Kind: downloadKindChannel}
// Send the first request and wait for the worker to start the download.
queue <- req
time.Sleep(50 * time.Millisecond)
// Send the same video ID again while the first is still in-flight.
queue <- req
time.Sleep(50 * time.Millisecond)
// Unblock downloads and shut down.
close(hold)
cancel()
<-workerDone
if got := atomic.LoadInt32(&callCount); got != 1 {
t.Errorf("expected 1 download call (dedup), got %d", got)
}
}
// TestDownloadWorkerMaxConcurrent verifies that the worker never exceeds
// config.MaxConcurrent parallel downloads.
func TestDownloadWorkerMaxConcurrent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const maxConcurrent = 2
cfg := newTestConfig(t)
cfg.MaxConcurrent = maxConcurrent
var activeCount int32
var peakCount int32
started := make(chan struct{}, 10)
hold := make(chan struct{})
execFn := func(_ context.Context, _ DownloadRequest) {
n := atomic.AddInt32(&activeCount, 1)
for {
peak := atomic.LoadInt32(&peakCount)
if n <= peak || atomic.CompareAndSwapInt32(&peakCount, peak, n) {
break
}
}
started <- struct{}{}
<-hold
atomic.AddInt32(&activeCount, -1)
}
queue := make(chan DownloadRequest, 10)
workerDone := make(chan struct{})
go func() {
runDownloadWorker(ctx, cfg, nil, nil, queue, execFn)
close(workerDone)
}()
const numVideos = 5
for i := 0; i < numVideos; i++ {
queue <- DownloadRequest{VideoID: fmt.Sprintf("vid%d", i)}
}
// Wait for exactly maxConcurrent downloads to start.
for i := 0; i < maxConcurrent; i++ {
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for downloads to start")
}
}
// A third download must NOT have started yet (they're all blocked on hold).
select {
case <-started:
t.Errorf("more than %d downloads started simultaneously", maxConcurrent)
case <-time.After(50 * time.Millisecond):
}
// Release downloads so the worker can finish.
close(hold)
cancel()
<-workerDone
if peak := atomic.LoadInt32(&peakCount); int(peak) > maxConcurrent {
t.Errorf("peak concurrent downloads %d exceeded MaxConcurrent %d", peak, maxConcurrent)
}
}
// TestDownloadWorkerDynamicMaxConcurrent verifies that a mid-run change to
// MaxConcurrent is respected for subsequently dispatched requests.
func TestDownloadWorkerDynamicMaxConcurrent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := newTestConfig(t)
cfg.MaxConcurrent = 1 // start at 1
var activeCount int32
var peakCount int32
hold := make(chan struct{})
started := make(chan struct{}, 10)
execFn := func(_ context.Context, _ DownloadRequest) {
n := atomic.AddInt32(&activeCount, 1)
for {
peak := atomic.LoadInt32(&peakCount)
if n <= peak || atomic.CompareAndSwapInt32(&peakCount, peak, n) {
break
}
}
started <- struct{}{}
<-hold
atomic.AddInt32(&activeCount, -1)
}
queue := make(chan DownloadRequest, 10)
workerDone := make(chan struct{})
go func() {
runDownloadWorker(ctx, cfg, nil, nil, queue, execFn)
close(workerDone)
}()
// Queue two downloads and confirm only one starts with MaxConcurrent=1.
queue <- DownloadRequest{VideoID: "vidA"}
queue <- DownloadRequest{VideoID: "vidB"}
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("first download never started")
}
select {
case <-started:
t.Error("second download started before MaxConcurrent was raised")
case <-time.After(50 * time.Millisecond):
}
// Raise MaxConcurrent to 2 and unblock the first download so the second can start.
cfg.Lock()
cfg.MaxConcurrent = 2
cfg.Unlock()
// A completion event triggers tryFlush; release one slot.
close(hold)
select {
case <-started:
// second download finally started
case <-time.After(2 * time.Second):
t.Error("second download never started after MaxConcurrent was raised")
}
cancel()
<-workerDone
}
// TestDownloadWorkerContextCancellation verifies the worker drains in-flight
// downloads and exits cleanly when the context is cancelled.
func TestDownloadWorkerContextCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var finished int32
execFn := func(ctx context.Context, _ DownloadRequest) {
// Simulate a download that respects context cancellation.
select {
case <-time.After(200 * time.Millisecond):
case <-ctx.Done():
}
atomic.AddInt32(&finished, 1)
}
cfg := newTestConfig(t)
cfg.MaxConcurrent = 3
queue := make(chan DownloadRequest, 10)
workerDone := make(chan struct{})
go func() {
runDownloadWorker(ctx, cfg, nil, nil, queue, execFn)
close(workerDone)
}()
queue <- DownloadRequest{VideoID: "v1"}
queue <- DownloadRequest{VideoID: "v2"}
time.Sleep(30 * time.Millisecond) // let both start
cancel()
select {
case <-workerDone:
case <-time.After(3 * time.Second):
t.Fatal("download worker did not stop after context cancellation")
}
}
// TestDownloadWorkerPendingDrainedAfterInFlight verifies that requests added to
// the pending queue (beyond MaxConcurrent) are eventually dispatched once a
// running download completes.
func TestDownloadWorkerPendingDrainedAfterInFlight(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := newTestConfig(t)
cfg.MaxConcurrent = 1
var completed int32
var mu sync.Mutex
completedIDs := map[string]bool{}
hold := make(chan struct{})
first := make(chan struct{}, 1)
execFn := func(_ context.Context, req DownloadRequest) {
select {
case first <- struct{}{}:
<-hold // block first download
default:
}
mu.Lock()
completedIDs[req.VideoID] = true
mu.Unlock()
atomic.AddInt32(&completed, 1)
}
queue := make(chan DownloadRequest, 10)
workerDone := make(chan struct{})
go func() {
runDownloadWorker(ctx, cfg, nil, nil, queue, execFn)
close(workerDone)
}()
queue <- DownloadRequest{VideoID: "a"}
queue <- DownloadRequest{VideoID: "b"}
queue <- DownloadRequest{VideoID: "c"}
// Wait for the first to start, then unblock it.
<-first
close(hold)
// Wait for all three to complete.
deadline := time.After(3 * time.Second)
for {
if atomic.LoadInt32(&completed) == 3 {
break
}
select {
case <-deadline:
t.Fatalf("only %d of 3 downloads completed", atomic.LoadInt32(&completed))
case <-time.After(10 * time.Millisecond):
}
}
cancel()
<-workerDone
}
// --- Monitor lifecycle tests ---
// TestRunChannelMonitorExitsWhenChannelMissing verifies the goroutine exits
// immediately when the channel ID is not present in storage.
func TestRunChannelMonitorExitsWhenChannelMissing(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
done := make(chan struct{})
go func() {
runChannelMonitor(context.Background(), "nonexistent-channel", cfg, s, downloader, queue)
close(done)
}()
select {
case <-done:
case <-time.After(500 * time.Millisecond):
t.Error("channel monitor did not exit for a missing channel")
}
}
// TestRunVideoMonitorChecksAllVideos verifies that the single video monitor goroutine
// enqueues download requests for all pending standalone videos on startup.
func TestRunVideoMonitorChecksAllVideos(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
videos := []storage.Video{
{ID: "v1", URL: "https://www.youtube.com/watch?v=v1", Title: "Video 1"},
{ID: "v2", URL: "https://www.youtube.com/watch?v=v2", Title: "Video 2"},
{ID: "v3", URL: "https://www.youtube.com/watch?v=v3", Title: "Video 3"},
}
for _, v := range videos {
if err := s.AddVideo(v); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wakeup := make(chan struct{}, 1)
done := make(chan struct{})
go func() {
runVideoMonitor(ctx, cfg, s, downloader, queue, wakeup)
close(done)
}()
// Collect queued requests (initial check runs immediately).
queued := map[string]bool{}
deadline := time.After(2 * time.Second)
for len(queued) < len(videos) {
select {
case req := <-queue:
queued[req.VideoID] = true
case <-deadline:
t.Fatalf("timed out; only queued %d of %d videos: %v", len(queued), len(videos), queued)
}
}
for _, v := range videos {
if !queued[v.ID] {
t.Errorf("video %s was not queued", v.ID)
}
}
cancel()
<-done
}
// TestRunVideoMonitorQueuesOnWakeup verifies that a video added after the monitor's
// initial check is queued when the wakeup channel is signalled — the same signal
// the manager sends when storage.AddVideo fires storage.NotifyCh().
func TestRunVideoMonitorQueuesOnWakeup(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
wakeup := make(chan struct{}, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{})
go func() {
runVideoMonitor(ctx, cfg, s, downloader, queue, wakeup)
close(done)
}()
// Let the initial check (no videos yet) complete.
time.Sleep(50 * time.Millisecond)
// Add a video after the monitor has already run its initial check.
vid := storage.Video{ID: "lateVid", URL: "https://www.youtube.com/watch?v=lateVid", Title: "Late Video"}
if err := s.AddVideo(vid); err != nil {
t.Fatal(err)
}
// Simulate what the manager does when it receives storage.NotifyCh().
select {
case wakeup <- struct{}{}:
default:
}
// The monitor should wake up and queue the newly-added video.
select {
case req := <-queue:
if req.VideoID != "lateVid" {
t.Errorf("expected lateVid, got %s", req.VideoID)
}
case <-time.After(2 * time.Second):
t.Error("video added after initial check was not queued on wakeup")
}
cancel()
<-done
}
// TestRunChannelMonitorExitsOnContextCancel verifies the goroutine stops when
// its context is cancelled (no network calls are made because the channel
// doesn't exist).
func TestRunChannelMonitorExitsOnContextCancel(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
runChannelMonitor(ctx, "nonexistent", cfg, s, downloader, queue)
close(done)
}()
cancel()
select {
case <-done:
case <-time.After(500 * time.Millisecond):
t.Error("channel monitor did not exit after context cancellation")
}
}
// TestRunVideoMonitorExitsOnContextCancel verifies the goroutine stops when
// its context is cancelled.
func TestRunVideoMonitorExitsOnContextCancel(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
wakeup := make(chan struct{}, 1)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
runVideoMonitor(ctx, cfg, s, downloader, queue, wakeup)
close(done)
}()
cancel()
select {
case <-done:
case <-time.After(500 * time.Millisecond):
t.Error("video monitor did not exit after context cancellation")
}
}
// --- checkAndQueueChannel / checkAndQueueVideo unit tests ---
func TestCheckAndQueueChannelReturnsFalseWhenMissing(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
if checkAndQueueChannel(context.Background(), "nope", s, downloader, queue) {
t.Error("expected false for missing channel")
}
}
// TestChannelNeedsInitialBacklogScan guards against two regressions:
// 1. A channel that has already completed a scan could look "new" again after its
// DownloadedVideos and PrunedVideos both empty out (e.g. via retention trimming),
// causing the wide cutoff-based backlog window to re-open and rediscover videos
// whose pruned/dismissed record was just trimmed away.
// 2. A channel whose very first scan attempt failed (transient RSS/yt-dlp error) must
// not be treated as already-scanned just because LastChecked got stamped — that
// would burn the one-time wide-window opportunity before it ever succeeded.
func TestChannelNeedsInitialBacklogScan(t *testing.T) {
tests := []struct {
name string
ch storage.Channel
want bool
}{
{
name: "never scanned",
ch: storage.Channel{},
want: true,
},
{
name: "backlog scan succeeded, still has tracked history",
ch: storage.Channel{BacklogScanComplete: true, DownloadedVideos: []storage.DownloadedVideo{{ID: "a"}}},
want: false,
},
{
name: "backlog scan succeeded, but downloaded/pruned lists have since emptied out",
ch: storage.Channel{BacklogScanComplete: true, DownloadedVideos: nil, PrunedVideos: nil},
want: false,
},
{
name: "first scan attempt failed: LastChecked stamped but backlog scan never succeeded",
ch: storage.Channel{LastChecked: time.Now(), BacklogScanComplete: false},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := channelNeedsInitialBacklogScan(tt.ch); got != tt.want {
t.Errorf("channelNeedsInitialBacklogScan() = %v, want %v", got, tt.want)
}
})
}
}
func TestCheckAndQueueVideoReturnsFalseWhenMissing(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
if checkAndQueueVideo(context.Background(), "nope", s, downloader, queue) {
t.Error("expected false for missing video")
}
}
// TestCheckAndQueueVideoAlreadyDownloaded verifies that a video with an
// existing DownloadedVideo entry is not re-queued.
func TestCheckAndQueueVideoAlreadyDownloaded(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
cfg.RetentionDays = 0 // disable pruning so cleanup is a no-op
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
vid := storage.Video{
ID: "vidAlready",
URL: "https://www.youtube.com/watch?v=vidAlready",
Title: "Already Downloaded",
DownloadedVideos: []storage.DownloadedVideo{
{ID: "vidAlready", Title: "Already Downloaded", DownloadDate: time.Now()},
},
}
if err := s.AddVideo(vid); err != nil {
t.Fatal(err)
}
ok := checkAndQueueVideo(context.Background(), "vidAlready", s, downloader, queue)
if !ok {
t.Error("expected true (video still exists)")
}
select {
case req := <-queue:
t.Errorf("unexpected download request for already-downloaded video: %+v", req)
default:
}
}
// TestCheckAndQueueVideoQueuesWhenNotDownloaded verifies that a video without any
// DownloadedVideo entries is enqueued exactly once.
func TestCheckAndQueueVideoQueuesWhenNotDownloaded(t *testing.T) {
s := newTestStorage(t)
cfg := newTestConfig(t)
downloader := NewDownloader(cfg)
queue := make(chan DownloadRequest, 10)
vid := storage.Video{
ID: "vidNew",
URL: "https://www.youtube.com/watch?v=vidNew",
Title: "New Video",
}
if err := s.AddVideo(vid); err != nil {
t.Fatal(err)
}
// Drain the notify signal from AddVideo.
select {
case <-s.NotifyCh():
default:
}
ok := checkAndQueueVideo(context.Background(), "vidNew", s, downloader, queue)
if !ok {
t.Error("expected true (video still exists)")
}
select {
case req := <-queue:
if req.VideoID != "vidNew" {
t.Errorf("queued wrong video ID: got %q", req.VideoID)
}
if req.Kind != downloadKindVideo {
t.Errorf("expected downloadKindVideo, got %v", req.Kind)
}
case <-time.After(200 * time.Millisecond):
t.Error("expected a download request but got none")
}
}
// --- Storage notify tests ---
func TestStorageGetChannel(t *testing.T) {
s := newTestStorage(t)
ch := storage.Channel{ID: "UCtest", URL: "https://yt.com/@test", Name: "Test Channel"}
if err := s.AddChannel(ch); err != nil {
t.Fatal(err)
}
got, ok := s.GetChannel("UCtest")
if !ok {
t.Fatal("GetChannel returned false for existing channel")
}
if got.ID != "UCtest" || got.Name != "Test Channel" {
t.Errorf("GetChannel returned unexpected channel: %+v", got)
}
_, ok = s.GetChannel("nonexistent")
if ok {
t.Error("GetChannel returned true for nonexistent channel")
}
}
func TestMarkChannelBacklogScanComplete(t *testing.T) {
s := newTestStorage(t)
ch := storage.Channel{ID: "UCtest", URL: "https://yt.com/@test", Name: "Test Channel"}
if err := s.AddChannel(ch); err != nil {
t.Fatal(err)
}
got, _ := s.GetChannel("UCtest")
if got.BacklogScanComplete {
t.Fatal("expected BacklogScanComplete to start false")
}
if err := s.MarkChannelBacklogScanComplete("UCtest"); err != nil {
t.Fatalf("MarkChannelBacklogScanComplete() error = %v", err)
}
got, _ = s.GetChannel("UCtest")
if !got.BacklogScanComplete {
t.Error("expected BacklogScanComplete = true after marking")
}
// Calling it again should be a harmless no-op.
if err := s.MarkChannelBacklogScanComplete("UCtest"); err != nil {
t.Fatalf("MarkChannelBacklogScanComplete() second call error = %v", err)
}
if err := s.MarkChannelBacklogScanComplete("nonexistent"); err != nil {
t.Errorf("MarkChannelBacklogScanComplete() on missing channel should not error, got %v", err)
}
}
func TestStorageGetVideo(t *testing.T) {
s := newTestStorage(t)
vid := storage.Video{ID: "vidTest", URL: "https://yt.com/watch?v=vidTest", Title: "Test Video"}
if err := s.AddVideo(vid); err != nil {
t.Fatal(err)
}
got, ok := s.GetVideo("vidTest")
if !ok {
t.Fatal("GetVideo returned false for existing video")
}
if got.ID != "vidTest" || got.Title != "Test Video" {
t.Errorf("GetVideo returned unexpected video: %+v", got)
}
_, ok = s.GetVideo("nonexistent")
if ok {
t.Error("GetVideo returned true for nonexistent video")
}
}
func TestStorageNotifyOnAddChannel(t *testing.T) {
s := newTestStorage(t)
// Drain any pre-existing signals.
for len(s.NotifyCh()) > 0 {
<-s.NotifyCh()
}
if err := s.AddChannel(storage.Channel{ID: "UC1", URL: "u", Name: "c"}); err != nil {
t.Fatal(err)
}
select {
case <-s.NotifyCh():
case <-time.After(200 * time.Millisecond):
t.Error("expected notification after AddChannel")
}
}
func TestStorageNotifyOnRemoveChannel(t *testing.T) {
s := newTestStorage(t)
if err := s.AddChannel(storage.Channel{ID: "UC2", URL: "u", Name: "c"}); err != nil {
t.Fatal(err)
}
// Drain add notification.
select {
case <-s.NotifyCh():
default:
}
if err := s.RemoveChannel("UC2"); err != nil {
t.Fatal(err)
}
select {
case <-s.NotifyCh():
case <-time.After(200 * time.Millisecond):
t.Error("expected notification after RemoveChannel")
}
}
func TestStorageNotifyOnAddVideo(t *testing.T) {
s := newTestStorage(t)
for len(s.NotifyCh()) > 0 {
<-s.NotifyCh()
}
if err := s.AddVideo(storage.Video{ID: "v1", URL: "u", Title: "t"}); err != nil {
t.Fatal(err)
}
select {
case <-s.NotifyCh():
case <-time.After(200 * time.Millisecond):
t.Error("expected notification after AddVideo")
}
}
func TestStorageNotifyOnRemoveVideo(t *testing.T) {
s := newTestStorage(t)
if err := s.AddVideo(storage.Video{ID: "v2", URL: "u", Title: "t"}); err != nil {
t.Fatal(err)
}
select {
case <-s.NotifyCh():
default:
}
if err := s.RemoveVideo("v2"); err != nil {
t.Fatal(err)
}
select {
case <-s.NotifyCh():
case <-time.After(200 * time.Millisecond):
t.Error("expected notification after RemoveVideo")
}
}