Files
Media-download-telegram-bot/internal/app/app_test.go
T
MichilisandClaude Opus 5.5 123cede7f3 Phase 2: command screens
- /help: a short introduction with the user's default format, how to be
  asked every time and the limits on one line, plus buttons Commands,
  Account, Groups, Open app and Upgrade that switch the same message to
  a section. Group commands are hidden in private chats; "Add me to a
  group" takes their place.
- /quality: Ask every time, Best that fits my limit, Best, 1080p, 720p,
  480p and Audio only, with the active one checked. Free users see which
  qualities may go over their limit.
- /history: pages of five compact buttons (site, title, format, when),
  a view per download with Send again, Thumbnail, Remove from history,
  and Clear history with a confirmation. Thumbnails are grouped under
  their video. Migration 00007 stores extractor, title, uploader and
  profile on deliveries and adds a hidden flag.
- docs/SCREENS.md shows every screen in en, es and nl, generated by the
  language test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:46:13 +00:00

951 lines
32 KiB
Go

package app_test
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/app"
"github.com/noderunners/dlbot/internal/bot"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/db/dbtest"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
// harness runs the real core against a fake Bot API and a scripted yt-dlp.
type harness struct {
t *testing.T
srv *fakeserver.Server
fake *ytdlptest.Fake
runner ytdlp.Runner
trans ffmpeg.Transcoder
app *app.App
cfg config.Config
cancel context.CancelFunc
done chan error
}
const (
alice = int64(42)
bob = int64(43)
group = int64(-1001234567890)
link = "https://example.com/watch?v=1"
)
func start(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *harness {
t.Helper()
if fake == nil {
fake = &ytdlptest.Fake{}
}
h := startWithRunner(t, fake, mut)
h.fake = fake
return h
}
// startWith starts a core with a scripted yt-dlp and a scripted ffmpeg.
func startWith(t *testing.T, fake *ytdlptest.Fake, trans ffmpeg.Transcoder, mut func(*config.Config)) *harness {
t.Helper()
pendingTranscoder = trans
defer func() { pendingTranscoder = nil }()
return start(t, fake, mut)
}
// pendingTranscoder hands a transcoder to the next harness that starts.
var pendingTranscoder ffmpeg.Transcoder
func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)) *harness {
t.Helper()
dir := t.TempDir()
srv := fakeserver.New()
cfg := config.Default()
cfg.Telegram.Token = fakeserver.Token
cfg.Telegram.APIURL = srv.URL()
cfg.HTTP.Listen = "127.0.0.1:0"
// Widgets have their own tests; the others check ordinary messages.
cfg.Telegram.Widgets = false
cfg.Database.Driver, cfg.Database.DSN = dbtest.NewDSN(t)
cfg.Storage.LocalDir = filepath.Join(dir, "files")
cfg.Worker.TempDir = filepath.Join(dir, "tmp")
cfg.Queue.Lease = config.Duration(2 * time.Second)
cfg.Queue.Heartbeat = config.Duration(40 * time.Millisecond)
if mut != nil {
mut(&cfg)
}
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg, trans: pendingTranscoder}
h.boot()
t.Cleanup(func() {
h.stop()
srv.Close()
})
return h
}
// boot starts (or restarts) the core on the same database and storage.
func (h *harness) boot() {
h.t.Helper()
ctx, cancel := context.WithCancel(context.Background())
// DLBOT_TEST_LOG=1 prints the core's log, which helps with a failing test.
var logOut io.Writer = io.Discard
if os.Getenv("DLBOT_TEST_LOG") != "" {
logOut = os.Stderr
}
base := slog.NewTextHandler(logOut, &slog.HandlerOptions{Level: slog.LevelDebug})
a, err := app.New(ctx, app.Options{
Config: h.cfg,
Log: slog.New(&guardHandler{Handler: base, t: h.t}),
Runner: h.runner, Transcoder: h.trans,
Tune: func(b *bot.Bot) {
b.SetTimings(60*time.Millisecond, 0)
b.SetThumbnails(testThumbs{})
},
})
if err != nil {
cancel()
h.t.Fatalf("app.New: %v", err)
}
h.app, h.cancel, h.done = a, cancel, make(chan error, 1)
go func() { h.done <- a.Run(ctx) }()
select {
case <-a.Ready():
case err := <-h.done:
h.t.Fatalf("app.Run stopped during startup: %v", err)
case <-time.After(10 * time.Second):
h.t.Fatal("the core did not become ready")
}
}
// testThumbs stands in for fetching thumbnails from the web: the fake
// yt-dlp's thumbnail URL gives a fixed small JPEG, anything else none.
type testThumbs struct{}
// testThumbJPEG is what testThumbs returns.
var testThumbJPEG = []byte("\xff\xd8\xff\xe0test-thumbnail\xff\xd9")
func (testThumbs) Fetch(_ context.Context, url string) []byte {
if url == "https://img.example.com/t.jpg" {
return testThumbJPEG
}
return nil
}
// guardHandler fails the test when the core logs something that is always
// a bug: a message ID that is missing from the catalog, or a panic.
type guardHandler struct {
slog.Handler
t *testing.T
}
func (g *guardHandler) Handle(ctx context.Context, r slog.Record) error {
if strings.HasPrefix(r.Message, "i18n: missing message") || r.Message == "panic recovered" {
var sb strings.Builder
r.Attrs(func(a slog.Attr) bool {
if a.Key != "stack" {
fmt.Fprintf(&sb, " %s=%v", a.Key, a.Value)
}
return true
})
g.t.Errorf("core logged a bug: %s%s", r.Message, sb.String())
}
return g.Handler.Handle(ctx, r)
}
func (g *guardHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &guardHandler{Handler: g.Handler.WithAttrs(attrs), t: g.t}
}
func (g *guardHandler) WithGroup(name string) slog.Handler {
return &guardHandler{Handler: g.Handler.WithGroup(name), t: g.t}
}
func (h *harness) stop() {
if h.cancel == nil {
return
}
h.cancel()
h.cancel = nil
select {
case err := <-h.done:
if err != nil {
h.t.Errorf("app.Run: %v", err)
}
case <-time.After(15 * time.Second):
h.t.Error("the core did not shut down")
}
}
// wait blocks until the bot makes a matching call after sequence "after".
func (h *harness) wait(after int, method string, match func(fakeserver.Call) bool) fakeserver.Call {
h.t.Helper()
c, ok := h.srv.WaitFor(after, 10*time.Second, method, match)
if !ok {
var sb strings.Builder
for _, c := range h.srv.Calls("") {
if c.Seq > after {
fmt.Fprintf(&sb, "\n #%d %s chat=%s text=%q", c.Seq, c.Method, c.Params["chat_id"], c.Text())
}
}
h.t.Fatalf("no %s call matched. Calls since #%d:%s", method, after, sb.String())
}
return c
}
// never asserts that no matching call shows up for a short while.
func (h *harness) never(after int, method string, match func(fakeserver.Call) bool) {
h.t.Helper()
if c, ok := h.srv.WaitFor(after, 400*time.Millisecond, method, match); ok {
h.t.Fatalf("unexpected %s call: %+v", method, c.Params)
}
}
// fileMethods are the calls that send a downloaded file.
const fileMethods = "sendVideo|sendAudio|sendDocument|sendPhoto"
// isResult matches a delivered file: it carries the buttons for the next
// step, among them Delete. A card, which is also a photo, has format
// buttons instead.
func isResult(chat int64) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool {
_, ok := c.Button("fx:")
return ok && !c.Failed && (chat == 0 || c.ChatID() == chat)
}
}
// finished waits for a download to end the way it should: the file in the
// chat, then the status message deleted so the file is the only message
// left. chat 0 matches any chat. It returns the file call.
func (h *harness) finished(after int, chat int64) fakeserver.Call {
h.t.Helper()
file := h.wait(after, fileMethods, isResult(chat))
h.wait(file.Seq, "deleteMessage", func(c fakeserver.Call) bool { return c.ChatID() == file.ChatID() })
return file
}
func textHas(sub string) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool { return strings.Contains(c.Text(), sub) }
}
func textIs(want string) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool { return c.Text() == want }
}
const edits = "editMessageText|editMessageCaption"
// card sends a link and returns the card call. The user is set to "ask
// every time" first, the setting under which every link shows a card.
func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) fakeserver.Call {
h.t.Helper()
h.askEveryTime(user)
seq := h.srv.Seq()
h.srv.PushMessage(chat, user, text, opts...)
return h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool {
_, ok := c.Button("dl:")
return ok
})
}
// askEveryTime makes sure a user sees the card for every link. A user who
// never chose a default gets the card once and "best that fits" after it.
func (h *harness) askEveryTime(user int64) {
h.t.Helper()
ctx := context.Background()
u, err := h.app.Store.GetUser(ctx, user)
if err == db.ErrNotFound {
if u, err = h.app.Store.UpsertUser(ctx, user, "", "User", "en"); err != nil {
h.t.Fatal(err)
}
} else if err != nil {
h.t.Fatal(err)
}
if u.Quality == "" {
if err := h.app.Store.SetUserQuality(ctx, user, "ask"); err != nil {
h.t.Fatal(err)
}
}
}
func (h *harness) press(chat, user int64, card fakeserver.Call, prefix string) (seq int) {
h.t.Helper()
btn, ok := card.Button(prefix)
if !ok {
h.t.Fatalf("no button starting with %q in %+v", prefix, card.Buttons())
}
seq = h.srv.Seq()
h.srv.PushCallback(chat, user, card.MessageID, btn.Data)
return seq
}
func replyTarget(c fakeserver.Call) int {
var rp struct {
MessageID int `json:"message_id"`
}
_ = json.Unmarshal([]byte(c.Params["reply_parameters"]), &rp)
return rp.MessageID
}
func (h *harness) jobs(status string) []*db.Job {
h.t.Helper()
js, err := h.app.Store.JobsByStatus(context.Background(), status, 100)
if err != nil {
h.t.Fatal(err)
}
return js
}
func (h *harness) waitJobs(status string, n int) []*db.Job {
h.t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
js := h.jobs(status)
if len(js) == n {
return js
}
if time.Now().After(deadline) {
h.t.Fatalf("%d jobs in %s, want %d", len(js), status, n)
}
time.Sleep(20 * time.Millisecond)
}
}
func (h *harness) storedFiles() int {
n := 0
_ = h.app.Storage.List(context.Background(), "", func(storage.Object) error { n++; return nil })
return n
}
// --- acceptance: pasting a link returns the file ---------------------------
func TestPrivateLinkReturnsFile(t *testing.T) {
h := start(t, &ytdlptest.Fake{FileSize: 4096}, nil)
seq := h.srv.Seq()
msgID := h.srv.PushMessage(alice, alice, "look at this "+link)
looking := h.wait(seq, "sendMessage", textHas("Looking up"))
card := h.wait(seq, "sendPhoto", nil)
if !strings.Contains(card.Text(), "<b>Test Video</b>") || !strings.Contains(card.Text(), "1:00") ||
!strings.Contains(card.Text(), "example.com") {
t.Fatalf("card text = %q", card.Text())
}
// The first link of a new user shows the card once and says what
// happens from now on.
if !strings.Contains(card.Text(), "best quality that fits your limit") {
t.Fatalf("the first card does not explain the new default: %q", card.Text())
}
if card.Params["photo"] != "https://img.example.com/t.jpg" {
t.Fatalf("card photo = %q", card.Params["photo"])
}
// A private chat has one conversation: nothing is quoted.
if replyTarget(card) != 0 || replyTarget(looking) != 0 {
t.Fatalf("a private answer quotes the link message")
}
var labels []string
for _, b := range card.Buttons() {
labels = append(labels, b.Text)
// Callback data carries identifiers only, never translated text.
if strings.ContainsAny(b.Data, " ") || len(b.Data) > 64 {
t.Errorf("bad callback data %q", b.Data)
}
}
want := []string{"Best · 10 MB", "480p · 5 MB", "MP3 · 1 MB", "Thumbnail", "Cancel"}
if strings.Join(labels, "|") != strings.Join(want, "|") {
t.Fatalf("buttons = %v, want %v", labels, want)
}
// The placeholder is replaced by the photo card.
h.wait(seq, "deleteMessage", nil)
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "answerCallbackQuery", nil)
video := h.wait(seq, "sendVideo", nil)
if video.ChatID() != alice || video.Files["video"].Size != 4096 {
t.Fatalf("sendVideo = %+v files=%+v", video.Params, video.Files)
}
if video.Files["video"].Name != "Test Video.mp4" {
t.Fatalf("file name = %q", video.Files["video"].Name)
}
if video.Params["supports_streaming"] != "true" || video.Params["width"] != "1280" || video.Params["duration"] != "60" {
t.Fatalf("video params = %+v", video.Params)
}
if replyTarget(video) != 0 {
t.Fatalf("the file quotes the link message in a private chat")
}
// Forwarding works: the content is not protected.
if video.Params["protect_content"] == "true" {
t.Fatal("the video is protected")
}
// The caption: title, uploader and length, a clean link, the bot.
wantCaption := "<b>Test Video</b>\nTester · 1:00\n" +
`<a href="https://example.com/watch?v=1">example.com/watch?v=1</a>` + "\nvia @" + fakeserver.BotUsername
if video.Text() != wantCaption {
t.Fatalf("caption = %q, want %q", video.Text(), wantCaption)
}
// The thumbnail is uploaded with the video.
if f, ok := video.Files["thumbnail"]; !ok || f.Size != int64(len(testThumbJPEG)) {
t.Fatalf("thumbnail = %+v, %v", f, ok)
}
var next []string
for _, b := range video.Buttons() {
next = append(next, b.Text)
}
if strings.Join(next, "|") != "Audio (MP3)|Other quality|Thumbnail|Delete" {
t.Fatalf("buttons under the file = %v", next)
}
// One message per job: the card that showed the status is gone, and
// nothing says "Done" under the file.
gone := h.wait(video.Seq, "deleteMessage", nil)
if gone.MessageID != card.MessageID {
t.Fatalf("deleted message %d, want the card %d", gone.MessageID, card.MessageID)
}
h.never(video.Seq, edits, textHas("Done"))
_ = msgID
// The user's default is now "best that fits": the next link starts
// right away, with one status message that becomes the file.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "https://example.com/watch?v=2")
status := h.wait(seq, "sendMessage", textHas("Looking up"))
h.never(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
second := h.finished(seq, alice)
if gone := h.wait(second.Seq, "deleteMessage", nil); gone.MessageID != status.MessageID {
t.Fatalf("deleted %d, want the status %d", gone.MessageID, status.MessageID)
}
h.waitJobs(db.JobDone, 2)
// The delivered files stay as the cache's stored copies.
if n := h.storedFiles(); n != 2 {
t.Fatalf("%d files in storage after delivery, want the two cached copies", n)
}
if n := len(h.fake.Probes()); n != 2 {
t.Fatalf("probes = %d, want 2", n)
}
}
func TestStatusGoesThroughDownloadingAndUploading(t *testing.T) {
block := make(chan struct{})
h := start(t, &ytdlptest.Fake{Block: block, FileSize: 2000}, nil)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
// The fake reports half of the file before it blocks.
down := h.wait(seq, edits, textHas("50%"))
if !strings.Contains(down.Text(), "Downloading") || !strings.Contains(down.Text(), "▰▰▰▰▰▱▱▱▱▱") ||
!strings.Contains(down.Text(), "1,000 B of 2 KB") {
t.Fatalf("progress text = %q", down.Text())
}
if _, ok := down.Button("jc:"); !ok {
t.Fatal("a running job must offer Cancel")
}
close(block)
h.wait(seq, edits, textHas("Sending it to Telegram"))
h.wait(seq, "sendChatAction", func(c fakeserver.Call) bool { return c.Params["action"] == "upload_video" })
h.wait(seq, "sendVideo", nil)
h.finished(seq, 0)
}
// --- acceptance: groups work with /dl --------------------------------------
func TestGroupDlCommand(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
cmdID := h.srv.PushMessage(group, alice, "/dl@"+fakeserver.BotUsername+" "+link)
card := h.wait(seq, "sendPhoto", nil)
if card.ChatID() != group || replyTarget(card) != cmdID {
t.Fatalf("the card must reply to the command in the group: %+v", card.Params)
}
// Somebody else presses a button: a short notice, no job.
seq = h.press(group, bob, card, "dl:")
notice := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(notice.Params["text"], "belong to the person who asked") {
t.Fatalf("notice = %q", notice.Params["text"])
}
h.never(seq, "sendVideo", nil)
if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)); n != 0 {
t.Fatalf("a stranger's press created %d jobs", n)
}
// The stranger cannot dismiss the card either.
seq = h.press(group, bob, card, "cx:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "belong to the person who asked")
})
h.never(seq, "deleteMessage", nil)
seq = h.press(group, alice, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480")
video := h.wait(seq, "sendVideo", nil)
if video.ChatID() != group || replyTarget(video) != cmdID {
t.Fatalf("the file must reply to the original message: %+v", video.Params)
}
if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "480" {
t.Fatalf("downloads = %+v", dl)
}
}
func TestGroupReplyDlUsesTheRepliedMessage(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(group, alice, "/dl", fakeserver.ReplyTo(555, "watch "+link+" tonight"))
card := h.wait(seq, "sendPhoto", nil)
if replyTarget(card) != 555 {
t.Fatalf("card replies to %d, want the message with the link (555)", replyTarget(card))
}
if got := h.fake.Probes(); len(got) != 1 || got[0] != link {
t.Fatalf("probed %v", got)
}
}
func TestGroupIgnoresPlainLinksAndForeignCommands(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(group, alice, "check "+link)
h.srv.PushMessage(group, alice, "/dl@some_other_bot "+link)
h.srv.PushMessage(group, alice, "/unknowncommand")
h.never(seq, "", nil)
if n := len(h.fake.Probes()); n != 0 {
t.Fatalf("probes = %d, want 0", n)
}
// /dl without a link explains itself.
seq = h.srv.Seq()
h.srv.PushMessage(group, alice, "/dl")
h.wait(seq, "sendMessage", textHas("Add a link after the command"))
}
// --- acceptance: cancel works ----------------------------------------------
func TestCancelCardBeforeChoosing(t *testing.T) {
h := start(t, nil, nil)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "cx:")
h.wait(seq, "answerCallbackQuery", textIs("Cancelled."))
h.wait(0, "deleteMessage", func(c fakeserver.Call) bool {
return c.Params["message_id"] == fmt.Sprint(card.MessageID)
})
// The card is dead: its format buttons no longer start anything.
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "answerCallbackQuery", nil)
h.never(seq, "sendVideo", nil)
}
func TestCancelRunningJob(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := start(t, &ytdlptest.Fake{Block: block}, nil)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
status := h.wait(seq, edits, textHas("Downloading"))
// Bob cannot cancel Alice's download.
seq = h.press(alice, bob, status, "jc:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "belong to the person who asked")
})
if len(h.jobs(db.JobRunning)) != 1 {
t.Fatal("the job must keep running")
}
seq = h.press(alice, alice, status, "jc:")
cancelled := h.wait(seq, edits, textHas("Cancelled"))
if len(cancelled.Buttons()) != 0 {
t.Fatal("a cancelled status must have no buttons")
}
h.waitJobs(db.JobCancelled, 1)
h.never(seq, "sendVideo", nil)
if n := h.storedFiles(); n != 0 {
t.Fatalf("%d files left in storage after cancel", n)
}
}
func TestCancelCommandCancelsQueuedAndRunning(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) {
c.Worker.Concurrency = 1
c.Limits.Free.ActiveJobs = 3
})
for i := 0; i < 2; i++ {
card := h.card(alice, alice, fmt.Sprintf("https://example.com/v%d", i))
h.press(alice, alice, card, "dl:")
}
h.waitJobs(db.JobRunning, 1)
h.waitJobs(db.JobQueued, 1)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/queue")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "2 downloads in progress") && strings.Contains(c.Text(), "In the queue. Position 1")
})
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/cancel")
h.wait(seq, "sendMessage", textHas("Cancelled 2 downloads."))
h.waitJobs(db.JobCancelled, 2)
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/cancel")
h.wait(seq, "sendMessage", textHas("nothing to cancel"))
}
// --- failures --------------------------------------------------------------
func TestDownloadFailureShowsFriendlyError(t *testing.T) {
raw := "ERROR: [youtube] abc: Private video. token=SECRET"
h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
link: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: raw}},
}}, nil)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
failed := h.wait(seq, edits, textHas("That did not work"))
if !strings.Contains(failed.Text(), "private or for members only") {
t.Fatalf("failure text = %q", failed.Text())
}
for _, c := range h.srv.Calls("") {
if strings.Contains(c.Text(), "SECRET") || strings.Contains(c.Text(), "ERROR:") {
t.Fatalf("raw yt-dlp output reached the user: %q", c.Text())
}
}
h.waitJobs(db.JobFailed, 1)
h.never(seq, "sendVideo", nil)
}
func TestRetryableFailureIsRetriedOnce(t *testing.T) {
h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
link: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "reset"}},
}}, nil)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", nil)
if n := len(h.fake.Downloads()); n != 2 {
t.Fatalf("downloads = %d, want 2 (one retry)", n)
}
}
func TestProbeFailureShowsFriendlyError(t *testing.T) {
h := start(t, &ytdlptest.Fake{ProbeErrs: map[string]error{
link: &ytdlp.Error{Code: ytdlp.CodeUnsupported, Raw: "ERROR: Unsupported URL"},
}}, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, link)
h.wait(seq, "editMessageText", textHas("I cannot download from that link"))
}
func TestPlaylistLinkIsExplained(t *testing.T) {
h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{
link: {Type: "playlist", ID: "PL", Title: "List"},
}}, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, link)
h.wait(seq, "editMessageText", textHas("playlist"))
}
func TestThumbnailFetchFailureFallsBackToTextCard(t *testing.T) {
h := start(t, nil, nil)
h.srv.FailNext("sendPhoto", 400, "Bad Request: wrong file identifier/HTTP URL specified")
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, link)
card := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
// The text card works exactly like the photo card.
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, edits, func(c fakeserver.Call) bool {
return c.MessageID == card.MessageID && !strings.Contains(c.Text(), "Pick a format")
})
h.finished(seq, alice)
if gone := h.wait(seq, "deleteMessage", nil); gone.MessageID != card.MessageID {
t.Fatal("the text card must be the status message, and go once the file is there")
}
}
func TestRejectedVideoIsSentAsDocument(t *testing.T) {
h := start(t, nil, nil)
card := h.card(alice, alice, link)
h.srv.FailNext("sendVideo", 400, "Bad Request: wrong file type")
seq := h.press(alice, alice, card, "dl:")
doc := h.wait(seq, "sendDocument", nil)
if doc.Files["document"].Size != 1024 {
t.Fatalf("document upload = %+v", doc.Files)
}
h.finished(seq, 0)
}
func TestTransientSendFailureIsRetried(t *testing.T) {
h := start(t, nil, nil)
card := h.card(alice, alice, link)
h.srv.FailNext("sendVideo", 500, "Internal Server Error")
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed })
h.finished(seq, 0)
h.waitJobs(db.JobDone, 1)
}
func TestSendGivesUpAfterRepeatedFailures(t *testing.T) {
h := start(t, nil, nil)
card := h.card(alice, alice, link)
for i := 0; i < 3; i++ {
h.srv.FailNext("sendVideo", 500, "Internal Server Error")
}
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("could not send the file to Telegram"))
h.waitJobs(db.JobDone, 1) // the job itself is closed
// The download worked, only the send did not: the file is kept in the
// cache, so the next request does not have to fetch it again.
if n := h.storedFiles(); n != 1 {
t.Fatalf("%d files in storage, want the cached copy", n)
}
}
// --- limits ----------------------------------------------------------------
func TestOverSizeAndOverDurationAreRefused(t *testing.T) {
big := "https://example.com/big"
long := "https://example.com/long"
h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{
big: {Type: "video", ID: "b", Title: "Big", Extractor: "fake", Duration: 60,
Formats: []ytdlp.Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 1080, Filesize: 80 << 20}}},
long: {Type: "video", ID: "l", Title: "Long", Extractor: "fake", Duration: 3600},
}}, nil)
card := h.card(alice, alice, big)
seq := h.press(alice, alice, card, "dl:")
alert := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "larger than your limit of 50 MB") || alert.Params["show_alert"] != "true" {
t.Fatalf("alert = %+v", alert.Params)
}
// The card stays usable: the thumbnail-free card still lets the user
// pick something else, here MP3 is absent so we only check no job ran.
h.never(seq, "sendVideo|sendDocument", nil)
card = h.card(alice, alice, long)
seq = h.press(alice, alice, card, "dl:")
alert = h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "longer than your limit of 10 minutes") {
t.Fatalf("alert = %+v", alert.Params)
}
if n := len(h.fake.Downloads()); n != 0 {
t.Fatalf("downloads = %d, want 0", n)
}
}
func TestWorkerEnforcesCapWhenMetadataHasNoSize(t *testing.T) {
// The card cannot know the size, the worker finds out and stops.
h := start(t, &ytdlptest.Fake{FileSize: 3 << 20, Infos: map[string]*ytdlp.Info{
link: {Type: "video", ID: "x", Title: "No Sizes", Extractor: "fake"},
}}, func(c *config.Config) { c.Limits.Free.MaxSizeMB = 2 })
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("larger than your limit"))
h.never(seq, "sendVideo", nil)
}
func TestOneActiveJobPerFreeUser(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := start(t, &ytdlptest.Fake{Block: block}, nil)
first := h.card(alice, alice, "https://example.com/a")
second := h.card(alice, alice, "https://example.com/b")
h.press(alice, alice, first, "dl:")
h.waitJobs(db.JobRunning, 1)
seq := h.press(alice, alice, second, "dl:")
alert := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "already have 1 download running") {
t.Fatalf("alert = %q", alert.Params["text"])
}
// Another user is not affected.
other := h.card(bob, bob, "https://example.com/c")
h.press(bob, bob, other, "dl:")
h.waitJobs(db.JobRunning, 2)
}
func TestDoubleTapStartsOneJob(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Limits.Free.ActiveJobs = 5 })
card := h.card(alice, alice, link)
btn, _ := card.Button("dl:")
for i := 0; i < 4; i++ {
h.srv.PushCallback(alice, alice, card.MessageID, btn.Data)
}
h.waitJobs(db.JobRunning, 1)
time.Sleep(300 * time.Millisecond)
if n := len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobQueued)); n != 1 {
t.Fatalf("%d jobs after a quadruple tap, want 1", n)
}
}
// --- other commands --------------------------------------------------------
func TestAudioCommandSkipsTheCard(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/audio "+link)
audio := h.wait(seq, "sendAudio", nil)
if audio.Files["audio"].Name != "Test Video.mp3" || audio.Params["title"] != "Test Video" || audio.Params["performer"] != "Tester" {
t.Fatalf("sendAudio = %+v files=%+v", audio.Params, audio.Files)
}
h.finished(seq, alice)
if len(h.srv.Calls("sendPhoto")) != 0 {
t.Fatal("/audio must not show a card")
}
}
func TestThumbCommandSendsPhoto(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/thumb "+link)
photo := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, up := c.Files["photo"]; return up })
if photo.Files["photo"].Name != "Test Video.jpg" {
t.Fatalf("photo upload = %+v", photo.Files)
}
}
func TestInfoCommandListsFormatsWithoutDownloading(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/info "+link)
info := h.wait(seq, "sendMessage", textHas("Test Video"))
for _, want := range []string{"Best: 10 MB", "720p: 10 MB", "480p: 5 MB", "MP3: 1 MB", "Tester"} {
if !strings.Contains(info.Text(), want) {
t.Errorf("info text lacks %q: %q", want, info.Text())
}
}
if strings.Contains(info.Text(), "1080p") {
t.Errorf("1080p is above the source height and must not be listed: %q", info.Text())
}
if n := len(h.fake.Downloads()); n != 0 {
t.Fatalf("/info downloaded %d files", n)
}
}
func TestStartHelpAndHints(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/start", fakeserver.From("Ana <b>", "ana"))
welcome := h.wait(seq, "sendMessage", textHas("welcome"))
if !strings.Contains(welcome.Text(), "Ana &lt;b&gt;") {
t.Fatalf("the name must be escaped: %q", welcome.Text())
}
if welcome.Params["parse_mode"] != "HTML" {
t.Fatalf("parse_mode = %q", welcome.Params["parse_mode"])
}
u, err := h.app.Store.GetUser(context.Background(), alice)
if err != nil || u.Username != "ana" || u.FirstName != "Ana <b>" || u.Lang != "en" {
t.Fatalf("user row = %+v, %v", u, err)
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/help")
help := h.wait(seq, "sendMessage", textHas("Your limits: 50 MB and 10 minutes per download, 5 downloads a day."))
if !strings.Contains(help.Text(), "Your default format: <b>Best that fits my limit</b>") {
t.Fatalf("help = %q", help.Text())
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "hello bot")
h.wait(seq, "sendMessage", textHas("Send me a link"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/nope")
h.wait(seq, "sendMessage", textHas("do not know that command"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "http://127.0.0.1:8080/admin")
h.wait(seq, "sendMessage", textHas("Send me a link"))
if n := len(h.fake.Probes()); n != 0 {
t.Fatalf("a private address was probed %d times", n)
}
}
// --- durability ------------------------------------------------------------
func TestRestartResumesQueuedJob(t *testing.T) {
block := make(chan struct{})
fake := &ytdlptest.Fake{Block: block}
h := start(t, fake, nil)
card := h.card(alice, alice, link)
h.press(alice, alice, card, "dl:")
h.waitJobs(db.JobRunning, 1)
// Stop the core in the middle of the download. The worker hands the
// job back, and the next start picks it up and delivers it.
h.stop()
close(block)
seq := h.srv.Seq()
h.boot()
video := h.wait(seq, "sendVideo", nil)
if video.ChatID() != alice {
t.Fatalf("sendVideo after restart = %+v", video.Params)
}
h.finished(seq, 0)
h.waitJobs(db.JobDone, 1)
}
func TestHealthEndpoint(t *testing.T) {
h := start(t, nil, nil)
resp, err := http.Get("http://" + h.app.HTTP.Addr() + "/healthz")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 || !strings.Contains(string(body), `"ok"`) {
t.Fatalf("healthz = %d %s", resp.StatusCode, body)
}
}
// TestRealYtDlp runs the whole path with the real yt-dlp and ffmpeg against
// a small public test file. It needs network access, so it only runs when
// DLBOT_E2E_YTDLP points at a yt-dlp binary:
//
// DLBOT_E2E_YTDLP=$(command -v yt-dlp) go test ./internal/app -run TestRealYtDlp -v
func TestRealYtDlp(t *testing.T) {
bin := os.Getenv("DLBOT_E2E_YTDLP")
if bin == "" {
t.Skip("set DLBOT_E2E_YTDLP to a yt-dlp binary to run this test")
}
url := os.Getenv("DLBOT_E2E_URL")
if url == "" {
url = "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4"
}
real := &ytdlp.Exec{Path: bin, ProbeTimeout: 60 * time.Second, DownloadTimeout: 3 * time.Minute}
h := startWithRunner(t, real, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, url)
card, ok := h.srv.WaitFor(seq, 90*time.Second, "sendPhoto|editMessageText", func(c fakeserver.Call) bool {
_, ok := c.Button("dl:")
return ok
})
if !ok {
t.Fatalf("no card for the real link. Calls: %+v", h.srv.Calls(""))
}
t.Logf("card: %q buttons=%v", card.Text(), card.Buttons())
seq = h.press(alice, alice, card, "dl:")
video, ok := h.srv.WaitFor(seq, 3*time.Minute, "sendVideo|sendDocument", nil)
if !ok {
var last string
for _, c := range h.srv.Calls("") {
if c.Text() != "" {
last = c.Text()
}
}
t.Fatalf("the real download was not delivered. Last status: %q", last)
}
f := video.Files["video"]
t.Logf("delivered via %s: %s (%d bytes), duration=%s %sx%s", video.Method, f.Name, f.Size,
video.Params["duration"], video.Params["width"], video.Params["height"])
if video.Method != "sendVideo" || f.Size < 100_000 || video.Params["duration"] != "10" ||
video.Params["width"] != "640" || video.Params["height"] != "360" {
t.Fatalf("unexpected delivery: %+v %+v", video.Params, video.Files)
}
}