package repository import ( "context" "database/sql" "testing" "vidarchive/internal/models" ) func queueDownload(t *testing.T, repo *DownloadRepository, url, status string, subID *int64) *models.Download { t.Helper() d := &models.Download{URL: url, Status: status} if subID != nil { d.SubscriptionID = sql.NullInt64{Int64: *subID, Valid: true} } if err := repo.Create(d); err != nil { t.Fatalf("create %s: %v", url, err) } return d } // The queue checker asks for the oldest queued rows up to the worker buffer // size. Anything else, in any other status, must stay out of the result. func TestGetQueuedOldestFirstWithinLimit(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) first := queueDownload(t, repo, "first", "queued", nil) second := queueDownload(t, repo, "second", "queued", nil) queueDownload(t, repo, "third", "queued", nil) queueDownload(t, repo, "running", "downloading", nil) queueDownload(t, repo, "done", "completed", nil) got, err := repo.GetQueued(2) if err != nil { t.Fatalf("get queued: %v", err) } if len(got) != 2 { t.Fatalf("got %d rows, want 2 (the limit)", len(got)) } if got[0].ID != first.ID || got[1].ID != second.ID { t.Errorf("got ids %d,%d, want the two oldest %d,%d", got[0].ID, got[1].ID, first.ID, second.ID) } } // The queue page filters by status; "" and "all" mean no filter. func TestGetAllStatusFilter(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) queueDownload(t, repo, "a", "queued", nil) queueDownload(t, repo, "b", "error", nil) queueDownload(t, repo, "c", "completed", nil) for _, tc := range []struct { status string want int }{ {"", 3}, {"all", 3}, {"error", 1}, {"cancelled", 0}, } { got, err := repo.GetAll(tc.status, "date", 100, 0) if err != nil { t.Fatalf("get all %q: %v", tc.status, err) } if len(got) != tc.want { t.Errorf("status %q returned %d rows, want %d", tc.status, len(got), tc.want) } } // Sorting by status must not drop rows. got, err := repo.GetAll("", "status", 100, 0) if err != nil { t.Fatalf("get all sorted by status: %v", err) } if len(got) != 3 { t.Errorf("status sort returned %d rows, want 3", len(got)) } } // The health endpoint only needs to know the database answers at all. func TestPing(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) if err := repo.Ping(context.Background()); err != nil { t.Fatalf("ping: %v", err) } db.Close() if err := repo.Ping(context.Background()); err == nil { t.Error("ping on a closed database should fail") } } // Restart recovery: the stalled downloads are found by status and moved back to // queued in one statement. func TestIDsByStatusAndUpdateStatusWhere(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) stalled := queueDownload(t, repo, "stalled", "downloading", nil) queueDownload(t, repo, "done", "completed", nil) ids, err := repo.IDsByStatus("downloading") if err != nil { t.Fatalf("ids by status: %v", err) } if len(ids) != 1 || ids[0] != stalled.ID { t.Fatalf("ids = %v, want [%d]", ids, stalled.ID) } if err := repo.UpdateStatusWhere("downloading", "queued"); err != nil { t.Fatalf("update status: %v", err) } if got, _ := repo.GetByID(stalled.ID); got.Status != "queued" { t.Errorf("status = %q, want queued", got.Status) } if left, _ := repo.IDsByStatus("downloading"); len(left) != 0 { t.Errorf("%d rows still downloading", len(left)) } } // Logs are flushed in slices as yt-dlp produces them, so appends must // accumulate rather than replace — including the first one, onto a NULL column. func TestAppendLogsAccumulates(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) d := queueDownload(t, repo, "a", "downloading", nil) for _, chunk := range []string{"first\n", "second\n"} { if err := repo.AppendLogs(d.ID, chunk); err != nil { t.Fatalf("append %q: %v", chunk, err) } } got, err := repo.GetByID(d.ID) if err != nil { t.Fatal(err) } if got.Logs.String != "first\nsecond\n" { t.Errorf("logs = %q, want both chunks in order", got.Logs.String) } } func TestMarkErrorAndCompleted(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) failed := queueDownload(t, repo, "bad", "downloading", nil) if err := repo.MarkError(failed.ID, "yt-dlp exploded"); err != nil { t.Fatalf("mark error: %v", err) } got, _ := repo.GetByID(failed.ID) if got.Status != "error" || got.ErrorMessage.String != "yt-dlp exploded" { t.Errorf("got status=%q message=%q", got.Status, got.ErrorMessage.String) } ok := queueDownload(t, repo, "good", "downloading", nil) if err := repo.MarkCompleted(ok.ID, "cancelled"); err != nil { t.Fatalf("mark completed: %v", err) } got, _ = repo.GetByID(ok.ID) if got.Status != "cancelled" || !got.CompletedAt.Valid { t.Errorf("got status=%q completed_at valid=%v", got.Status, got.CompletedAt.Valid) } } // The scheduler and the manual run button both use this to avoid stacking a // second run on a subscription that is still working. func TestHasActiveForSubscription(t *testing.T) { db := setupTestDB(t) defer db.Close() subRepo := NewSubscriptionRepository(db) repo := NewDownloadRepository(db) sub := &models.Subscription{ Name: "s", URL: "u", Enabled: true, RefreshMode: "overwrite", ScheduleKind: "daily", CronExpr: "0 3 * * *", OutputDir: "dir", } if err := subRepo.Create(sub); err != nil { t.Fatal(err) } if active, err := repo.HasActiveForSubscription(sub.ID); err != nil || active { t.Fatalf("active = %v (err %v), want false with no downloads", active, err) } for _, status := range []string{"queued", "downloading"} { d := queueDownload(t, repo, "u", status, &sub.ID) active, err := repo.HasActiveForSubscription(sub.ID) if err != nil { t.Fatal(err) } if !active { t.Errorf("status %q should count as active", status) } if err := repo.Delete(d.ID); err != nil { t.Fatal(err) } } // A finished run no longer blocks the next one. queueDownload(t, repo, "u", "completed", &sub.ID) if active, _ := repo.HasActiveForSubscription(sub.ID); active { t.Error("a completed run must not count as active") } } func TestDeleteAllClearsQueue(t *testing.T) { db := setupTestDB(t) defer db.Close() repo := NewDownloadRepository(db) queueDownload(t, repo, "a", "queued", nil) queueDownload(t, repo, "b", "completed", nil) if err := repo.DeleteAll(); err != nil { t.Fatalf("delete all: %v", err) } got, err := repo.GetAll("", "date", 100, 0) if err != nil { t.Fatal(err) } if len(got) != 0 { t.Errorf("%d rows left after DeleteAll", len(got)) } }