Files
Media-download-telegram-bot/internal/bot/result_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

254 lines
8.9 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)
}
}
func TestHistoryLabels(t *testing.T) {
b := testBot(t, nil)
now := time.Date(2025, 5, 10, 15, 0, 0, 0, time.UTC)
at := func(daysAgo int) int64 { return now.AddDate(0, 0, -daysAgo).Add(-time.Hour).UnixMilli() }
cases := []struct {
lang string
row db.HistoryRow
want string
}{
{"en", db.HistoryRow{Extractor: "Instagram", Title: "Video by nasa", Uploader: "nasa", Profile: "720", CreatedAt: at(0)}, "Instagram · nasa · 720p · today"},
{"en", db.HistoryRow{Extractor: "youtube:tab", Title: "A very long title that goes on and on", Profile: "best", CreatedAt: at(1)}, "YouTube · A very long title tha… · Best · yesterday"},
{"es", db.HistoryRow{Extractor: "generic", URL: "https://www.example.org/x.mp4", Title: "Clip", Profile: "mp3", CreatedAt: at(3)}, "example.org · Clip · MP3 · hace 3 días"},
{"nl", db.HistoryRow{Extractor: "TikTok", Title: "Dans", Profile: "480", CreatedAt: at(30)}, "TikTok · Dans · 480p · 10 apr 2025"},
}
for _, c := range cases {
if got := b.historyLabel(c.lang, c.row, now); got != c.want {
t.Errorf("%s: label = %q, want %q", c.lang, got, c.want)
}
}
}
func TestSiteNames(t *testing.T) {
for in, want := range map[[2]string]string{
{"youtube", ""}: "YouTube", {"twitter", ""}: "X", {"instagram:story", ""}: "Instagram",
{"generic", "https://m.example.com/v"}: "example.com", {"newsite", ""}: "Newsite", {"", ""}: "?",
} {
if got := siteName(in[0], in[1]); got != want {
t.Errorf("siteName(%q, %q) = %q, want %q", in[0], in[1], got, want)
}
}
}