Files
Media-download-telegram-bot/internal/bot/result_test.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

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

222 lines
7.4 KiB
Go

package bot
import (
"context"
"io"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/tg"
"github.com/noderunners/dlbot/locales"
)
// testBot is a Bot with just enough set up for the pure parts: texts,
// captions, keyboards and the status throttle.
func testBot(t *testing.T, api tg.API) *Bot {
t.Helper()
log := slog.New(slog.NewTextHandler(io.Discard, nil))
tr, err := i18n.Load(locales.FS, log)
if err != nil {
t.Fatal(err)
}
return &Bot{
api: api, cfg: config.Default(), tr: tr, log: log, username: "nr_bot",
statuses: map[string]*statusState{}, live: map[string]*liveJob{}, liveTried: map[string]int{},
statusMinGap: 2500 * time.Millisecond,
}
}
func info(title, uploader string) *service.CardInfo {
return &service.CardInfo{
VideoID: "abc123", Title: title, Uploader: uploader, Duration: 75, Site: "instagram.com",
UploadDate: "20250503", HasAudio: true, Thumbnail: "https://img.example.com/t.jpg",
}
}
func TestCaption(t *testing.T) {
b := testBot(t, nil)
url := "https://www.instagram.com/reel/C1x/?igsh=MWQ1&utm_source=ig_web"
got := b.caption("en", info("Sunset over the bay", "nasa"), url, media.Best)
want := "<b>Sunset over the bay</b>\nnasa · 1:15\n" +
`<a href="https://www.instagram.com/reel/C1x/">instagram.com/reel/C1x</a>` + "\nvia @nr_bot"
if got != want {
t.Fatalf("caption =\n%s\nwant\n%s", got, want)
}
// A generic title becomes the uploader and the date; the uploader is
// then not repeated on the next line.
got = b.caption("en", info("Video by nasa", "nasa"), url, media.Best)
if !strings.HasPrefix(got, "<b>nasa · 3 May 2025</b>\n1:15\n") {
t.Fatalf("generic title caption = %q", got)
}
got = b.caption("nl", info("", "nasa"), url, media.Best)
if !strings.HasPrefix(got, "<b>nasa · 3 mei 2025</b>") {
t.Fatalf("Dutch generic title caption = %q", got)
}
// Titles from the web cannot inject markup.
got = b.caption("en", info("<script>&", "a<b"), "https://example.com/a?x=<1>", media.Best)
if strings.Contains(got, "<script>") || !strings.Contains(got, "&lt;script&gt;&amp;") || !strings.Contains(got, "a&lt;b") {
t.Fatalf("caption is not escaped: %q", got)
}
// The attribution line can be turned off; a thumbnail has no length.
b.cfg.CaptionAttribution = false
got = b.caption("en", info("Sunset", "nasa"), "https://example.com/v", media.Thumb)
if strings.Contains(got, "via @") || strings.Contains(got, "1:15") {
t.Fatalf("caption = %q", got)
}
}
func TestGenericTitles(t *testing.T) {
generic := []string{"", " ", "abc123", "Video", "Instagram", "Video by nasa", "Reel by someone", "nasa", "@nasa", "TikTok video #7412"}
for _, title := range generic {
if !isGenericTitle(info(title, "nasa")) {
t.Errorf("%q is not seen as generic", title)
}
}
for _, title := range []string{"Sunset over the bay", "Videos of cats", "nasa launches a rocket"} {
if isGenericTitle(info(title, "nasa")) {
t.Errorf("%q is seen as generic", title)
}
}
b := testBot(t, nil)
// Without an uploader or a date the site has to do.
in := info("Video", "")
in.UploadDate = ""
if got, _ := b.displayTitle("en", in); got != "instagram.com" {
t.Errorf("displayTitle = %q", got)
}
}
func TestQueueNoiseThreshold(t *testing.T) {
b := testBot(t, nil)
b.cfg.QueueNoticeThresholdSeconds = 10
cases := []struct {
ahead int
wait time.Duration
quiet bool
}{
{0, 0, true},
{0, 10 * time.Second, true},
{0, 11 * time.Second, false}, // a long wait is worth saying
{1, 2 * time.Second, false}, // so is anybody ahead
{3, 0, false},
}
for _, c := range cases {
if got := b.quietQueue(sched.Position{Ahead: c.ahead, Wait: c.wait}); got != c.quiet {
t.Errorf("ahead %d, wait %s: quiet = %v, want %v", c.ahead, c.wait, got, c.quiet)
}
}
b.cfg.QueueNoticeThresholdSeconds = 0
if b.quietQueue(sched.Position{Wait: time.Second}) {
t.Error("with a threshold of 0 any wait is shown")
}
}
func TestReplyQuotesOnlyInGroups(t *testing.T) {
if replyParams(42, 7) != nil {
t.Error("a private chat quotes")
}
if rp := replyParams(-100123, 7); rp == nil || rp.MessageID != 7 {
t.Error("a group does not quote")
}
if replyParams(-100123, 0) != nil {
t.Error("nothing to quote, but a quote")
}
}
func TestResultKeyboard(t *testing.T) {
b := testBot(t, nil)
req := &db.Request{ID: "01REQ"}
labels := func(kb *telego.InlineKeyboardMarkup) string {
var out []string
for _, row := range kb.InlineKeyboard {
for _, btn := range row {
out = append(out, btn.Text+"="+btn.CallbackData)
}
}
return strings.Join(out, " ")
}
in := info("Sunset", "nasa")
if got := labels(b.resultKeyboard("en", req, in, media.P720)); got !=
"Audio (MP3)=fa:01REQ Other quality=fq:01REQ Thumbnail=ft:01REQ Delete=fx:01REQ" {
t.Errorf("video buttons = %s", got)
}
if got := labels(b.resultKeyboard("en", req, in, media.MP3)); got != "Other quality=fq:01REQ Delete=fx:01REQ" {
t.Errorf("audio buttons = %s", got)
}
if got := labels(b.resultKeyboard("es", req, in, media.Thumb)); got != "Eliminar=fx:01REQ" {
t.Errorf("thumbnail buttons = %s", got)
}
silent := info("Sunset", "nasa")
silent.HasAudio, silent.Thumbnail = false, ""
if got := labels(b.resultKeyboard("en", req, silent, media.Best)); got != "Other quality=fq:01REQ Delete=fx:01REQ" {
t.Errorf("buttons without audio or thumbnail = %s", got)
}
}
// editRecorder is a Bot API that only records message edits.
type editRecorder struct {
tg.API
mu sync.Mutex
texts []string
at []time.Time
}
func (r *editRecorder) EditMessageText(_ context.Context, p *telego.EditMessageTextParams) (*telego.Message, error) {
r.mu.Lock()
defer r.mu.Unlock()
r.texts = append(r.texts, p.Text)
r.at = append(r.at, time.Now())
return &telego.Message{}, nil
}
func (r *editRecorder) edits() ([]string, []time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
return append([]string(nil), r.texts...), append([]time.Time(nil), r.at...)
}
func TestStatusEditsAreThrottledButNotLost(t *testing.T) {
api := &editRecorder{}
b := testBot(t, api)
b.statusMinGap = 150 * time.Millisecond
d := &db.Delivery{ID: "d1", ChatID: -100, ChatType: "supergroup", StatusMessageID: 5}
ctx := context.Background()
b.setStatus(ctx, d, "one", nil, "queued", false)
b.setStatus(ctx, d, "two", nil, "downloading", false) // too soon
b.setStatus(ctx, d, "three", nil, "downloading", false) // too soon, replaces two
b.setStatus(ctx, d, "three", nil, "downloading", false) // no change
time.Sleep(400 * time.Millisecond)
texts, at := api.edits()
if strings.Join(texts, ",") != "one,three" {
t.Fatalf("edits = %v, want the first and then the newest", texts)
}
if gap := at[1].Sub(at[0]); gap < b.statusMinGap-10*time.Millisecond {
t.Fatalf("two edits %s apart, the minimum is %s", gap, b.statusMinGap)
}
// A state waiting for the gap is dropped when the delivery ends.
b.setStatus(ctx, d, "four", nil, "uploading", false) // the gap is over: shown
b.setStatus(ctx, d, "five", nil, "uploading", false) // waits
b.forgetStatus(d.ID)
time.Sleep(300 * time.Millisecond)
if texts, _ := api.edits(); strings.Join(texts, ",") != "one,three,four" {
t.Fatalf("edits = %v, want nothing after the delivery ended", texts)
}
}