Files
Media-download-telegram-bot/internal/ytdlp/exec_test.go
T
MichilisandClaude Fable 5.2 3b361c17a1 Phase 1: core bot
Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 07:33:32 +00:00

322 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package ytdlp
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// fakeExec returns an Exec that runs the shell stand-in for yt-dlp.
func fakeExec(t *testing.T, mode string, env ...string) *Exec {
t.Helper()
script, err := filepath.Abs("testdata/fake-yt-dlp.sh")
if err != nil {
t.Fatal(err)
}
if err := os.Chmod(script, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("FAKE_MODE", mode)
for _, kv := range env {
k, v, _ := strings.Cut(kv, "=")
t.Setenv(k, v)
}
return &Exec{Path: script, ProbeTimeout: 5 * time.Second, DownloadTimeout: 5 * time.Second}
}
func TestExecProbeParsesLooseJSON(t *testing.T) {
e := fakeExec(t, "ok")
info, err := e.Probe(context.Background(), "https://example.com/watch?v=abc")
if err != nil {
t.Fatal(err)
}
if info.ID != "abc" || info.Title != "Fake Title" || info.Extractor != "youtube" || info.Type != "video" {
t.Fatalf("info = %+v", info)
}
if info.Duration != 61.4 || info.FilesizeAprx != 1234 || info.Filesize != 0 {
t.Fatalf("loose numbers: duration=%v approx=%v size=%v", info.Duration, info.FilesizeAprx, info.Filesize)
}
if len(info.Formats) != 2 || info.Formats[1].Width != 1280 || info.Formats[1].FilesizeAprx != 9000000 {
t.Fatalf("formats = %+v", info.Formats)
}
if info.MaxHeight() != 720 || !info.HasAudio() || info.IsPlaylist() || info.Live() {
t.Fatalf("derived facts wrong: height=%d", info.MaxHeight())
}
manual, auto := info.SubtitleLangs()
if len(manual) != 1 || manual[0] != "en" || len(auto) != 1 || auto[0] != "es" {
t.Fatalf("subtitle langs: manual=%v auto=%v", manual, auto)
}
// 720p video (9000000) plus the audio track (1000000).
if got := info.EstimateSize(media.P720); got != 10000000 {
t.Fatalf("EstimateSize(720) = %d", got)
}
if got := info.EstimateSize(media.MP3); got != 1000000 {
t.Fatalf("EstimateSize(mp3) = %d", got)
}
}
func TestExecProbePlaylist(t *testing.T) {
e := fakeExec(t, "playlist")
info, err := e.Probe(context.Background(), "https://example.com/list")
if err != nil {
t.Fatal(err)
}
if !info.IsPlaylist() || len(info.Entries) != 2 || info.Entries[1].URL != "https://example.com/b" {
t.Fatalf("playlist info = %+v", info)
}
}
func TestExecProbeErrors(t *testing.T) {
tests := []struct {
mode string
want Code
retryable bool
}{
{"error_private", CodePrivate, false},
{"error_bot", CodeSiteBlocked, false},
{"error_with_secret", CodeNetwork, true},
}
for _, tc := range tests {
t.Run(tc.mode, func(t *testing.T) {
e := fakeExec(t, tc.mode)
_, err := e.Probe(context.Background(), "https://example.com/x")
var ye *Error
if !errors.As(err, &ye) {
t.Fatalf("error = %v, want *Error", err)
}
if ye.Code != tc.want || ye.Retryable != tc.retryable {
t.Fatalf("got %s retryable=%v, want %s retryable=%v", ye.Code, ye.Retryable, tc.want, tc.retryable)
}
if strings.Contains(ye.Raw, "TOPSECRET") {
t.Fatalf("raw error leaks a credential: %q", ye.Raw)
}
})
}
}
func TestExecProbeTimeout(t *testing.T) {
e := fakeExec(t, "hang")
e.ProbeTimeout = 200 * time.Millisecond
start := time.Now()
_, err := e.Probe(context.Background(), "https://example.com/x")
if CodeOf(err) != CodeTimeout {
t.Fatalf("error = %v, want timeout", err)
}
if time.Since(start) > 4*time.Second {
t.Fatal("the hung process was not killed promptly")
}
}
func TestExecDownload(t *testing.T) {
argsFile := filepath.Join(t.TempDir(), "args")
e := fakeExec(t, "ok", "FAKE_ARGS_FILE="+argsFile)
dir := filepath.Join(t.TempDir(), "job")
var seen []Progress
res, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/watch?v=abc", Profile: media.P720, Dir: dir,
MaxSize: 50 << 20, MaxDuration: 10 * time.Minute,
}, func(p Progress) { seen = append(seen, p) })
if err != nil {
t.Fatal(err)
}
if res.Path != filepath.Join(dir, "media.mp4") || res.Size != 4000 || res.Ext != "mp4" {
t.Fatalf("result = %+v", res)
}
if res.ID != "abc" || res.Title != "Fake Title" || res.Extractor != "youtube" || res.Uploader != "Someone" {
t.Fatalf("metadata = %+v", res)
}
if res.Width != 1280 || res.Height != 720 || res.Duration != 61.4 {
t.Fatalf("dimensions = %+v", res)
}
if len(seen) < 3 {
t.Fatalf("progress callbacks = %+v", seen)
}
if seen[0].Downloaded != 1000 || seen[0].Total != 4000 || seen[0].Stage != StageDownloading {
t.Fatalf("first progress = %+v", seen[0])
}
// total_bytes was NA on the second line, so the estimate is used.
if seen[1].Total != 4000 {
t.Fatalf("second progress = %+v", seen[1])
}
if last := seen[len(seen)-1]; last.Stage != StageProcessing {
t.Fatalf("last progress = %+v, want processing", last)
}
raw, err := os.ReadFile(argsFile)
if err != nil {
t.Fatal(err)
}
args := strings.Split(strings.TrimSpace(string(raw)), "\n")
mustHave := func(flag, value string) {
t.Helper()
for i, a := range args {
if a == flag && (value == "" || (i+1 < len(args) && args[i+1] == value)) {
return
}
}
t.Errorf("args lack %s %s\n%v", flag, value, args)
}
mustHave("--ignore-config", "")
mustHave("--no-playlist", "")
mustHave("--max-filesize", "52428800")
mustHave("--match-filters", "!is_live & duration<=?600")
mustHave("-S", "vcodec:h264,res:720,acodec:m4a")
mustHave("--merge-output-format", "mp4/mkv")
mustHave("-P", dir)
if args[len(args)-2] != "--" || args[len(args)-1] != "https://example.com/watch?v=abc" {
t.Errorf("the URL must come last after --, got %v", args[len(args)-2:])
}
}
func TestExecDownloadNoFileOutcomes(t *testing.T) {
tests := []struct {
name string
mode string
env []string
profile media.Profile
maxDur time.Duration
want Code
}{
{"filter rejected a long video", "filtered", nil, media.Best, 30 * time.Second, CodeTooLong},
{"filter rejected a live stream", "filtered", []string{"FAKE_IS_LIVE=true"}, media.Best, 0, CodeLive},
{"size cap hit during download", "max_filesize", nil, media.Best, 0, CodeTooLarge},
{"no subtitles", "no_subs", nil, media.Subs("en"), 0, CodeNoSubtitles},
{"private video", "error_private", nil, media.Best, 0, CodePrivate},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
e := fakeExec(t, tc.mode, tc.env...)
_, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: tc.profile, Dir: t.TempDir(), MaxDuration: tc.maxDur,
}, nil)
if got := CodeOf(err); got != tc.want {
t.Fatalf("code = %s (%v), want %s", got, err, tc.want)
}
})
}
}
func TestExecDownloadEnforcesCapOnRealFile(t *testing.T) {
// The metadata promised nothing, the file turned out too big.
e := fakeExec(t, "ok", "FAKE_SIZE=5000")
_, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: media.Best, Dir: t.TempDir(), MaxSize: 4999,
}, nil)
if CodeOf(err) != CodeTooLarge {
t.Fatalf("error = %v, want too_large", err)
}
}
func TestExecDownloadThumbFindsFile(t *testing.T) {
e := fakeExec(t, "thumb")
dir := t.TempDir()
res, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: media.Thumb, Dir: dir,
}, nil)
if err != nil {
t.Fatal(err)
}
if res.Ext != "jpg" || res.Size != 300 {
t.Fatalf("result = %+v", res)
}
}
func TestExecDownloadCancel(t *testing.T) {
e := fakeExec(t, "hang")
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(150 * time.Millisecond)
cancel()
}()
start := time.Now()
_, err := e.Download(ctx, DownloadRequest{URL: "https://example.com/x", Profile: media.Best, Dir: t.TempDir()}, nil)
if CodeOf(err) != CodeCancelled {
t.Fatalf("error = %v, want cancelled", err)
}
if time.Since(start) > 4*time.Second {
t.Fatal("cancel did not stop the process promptly")
}
}
func TestProfileArgs(t *testing.T) {
join := func(p media.Profile) string { return strings.Join(profileArgs(p), " ") }
tests := map[media.Profile]string{
media.Best: "-S vcodec:h264,res,acodec:m4a -f bv*+ba/b --merge-output-format mp4/mkv",
media.P480: "-S vcodec:h264,res:480,acodec:m4a -f bv*+ba/b --merge-output-format mp4/mkv",
media.MP3: "-f ba/b -x --audio-format mp3 --audio-quality 192K",
media.M4A: "-f ba[ext=m4a]/ba/b -x --audio-format m4a",
media.Thumb: "--skip-download --write-thumbnail --convert-thumbnails jpg",
media.Subs("es"): "--skip-download --write-subs --write-auto-subs --sub-langs es --convert-subs srt",
}
for p, want := range tests {
if got := join(p); got != want {
t.Errorf("profileArgs(%s) = %q, want %q", p, got, want)
}
}
}
func TestClassify(t *testing.T) {
tests := []struct {
raw string
want Code
retryable bool
}{
{"ERROR: Unsupported URL: https://example.com/", CodeUnsupported, false},
{"ERROR: [youtube] x: Sign in to confirm you’re not a bot. Use --cookies", CodeSiteBlocked, false},
{"ERROR: [youtube] x: Private video. Sign in if you've been granted access", CodePrivate, false},
{"ERROR: [vimeo] 1: The web client only works when logged-in. Use --cookies", CodeLoginRequired, false},
{"ERROR: [youtube] x: Sign in to confirm your age. This video may be inappropriate for some users.", CodeLoginRequired, false},
{"ERROR: [youtube] x: Video unavailable. This video is not available in your country", CodeGeoBlocked, false},
{"ERROR: [generic] x: Unable to download webpage: HTTP Error 404: Not Found", CodeNotFound, false},
{"ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader", CodeNotFound, false},
{"ERROR: unable to download video data: HTTP Error 429: Too Many Requests", CodeRateLimited, true},
{"ERROR: [youtube] x: This live event will begin in 3 hours.", CodeLive, false},
{"ERROR: [x] 1: This video is DRM protected", CodeDRM, false},
{"ERROR: [youtube] x: Requested format is not available. Use --list-formats", CodeNoMedia, false},
{"ERROR: Postprocessing: WARNING: unable to obtain file audio codec with ffprobe", CodeNoMedia, false},
{"ERROR: Postprocessing: Conversion failed!", CodeProcessing, false},
{"ERROR: unable to download video data: The read operation timed out", CodeNetwork, true},
{"ERROR: unable to write data: [Errno 28] No space left on device", CodeInternal, true},
{"ERROR: something nobody has seen before", CodeUnknown, true},
}
for _, tc := range tests {
got := Classify(tc.raw)
if got.Code != tc.want || got.Retryable != tc.retryable {
t.Errorf("Classify(%q) = %s retryable=%v, want %s retryable=%v", tc.raw, got.Code, got.Retryable, tc.want, tc.retryable)
}
}
}
func TestEstimateSizeEdgeCases(t *testing.T) {
// Sparse metadata, as archive.org returns it: no codecs, sizes known.
sparse := &Info{Duration: 596, Formats: []Format{
{FormatID: "0", Ext: "ogv", Height: 300, Filesize: 46 << 20},
{FormatID: "1", Ext: "mp4", Height: 360, Filesize: 61 << 20},
{FormatID: "2", Ext: "avi", Height: 720, Filesize: 332 << 20},
}}
if got := sparse.EstimateSize(media.Best); got != 332<<20 {
t.Errorf("best = %d", got)
}
if got := sparse.EstimateSize(media.P480); got != 61<<20 {
t.Errorf("480 = %d, want the 360p file", got)
}
// Bitrate fallback: 1000 kbit/s for 80 seconds is 10 MB.
rate := &Info{Duration: 80, Formats: []Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 720, TBR: 1000}}}
if got := rate.EstimateSize(media.Best); got != 10_000_000 {
t.Errorf("bitrate estimate = %d", got)
}
// Nothing to go on.
if got := (&Info{}).EstimateSize(media.Best); got != 0 {
t.Errorf("empty info = %d, want 0", got)
}
if got := sparse.EstimateSize(media.Thumb); got != 0 {
t.Errorf("thumb = %d, want 0", got)
}
}