Files
Media-download-telegram-bot/internal/config/config_test.go
T
MichilisandClaude Fable 5.2 4f11f939a0 Phase 6: Mini App
A Telegram Mini App served by the core under /app/, embedded in the binary.

- API under /app/api/ with initData validated (HMAC, age) on every call
- Pages: Home, Queue, Buy (target, product, invoice), History, Groups,
  group detail (Overview, Settings, Wallet, Usage) and Me
- Every action runs through the same service, billing and scheduler code
  as the chat, so limits, prices and admin checks are decided on the server
- Texts come from the catalog over the API; layout mirrors for RTL
- Front end in web/miniapp (Vite, React, TypeScript); the build is
  committed and guarded by a source hash test; the Docker image rebuilds it
- MINIAPP_ENABLED with an https PUBLIC_URL; entry points from /app, group
  settings and the over-limit offer
- Browser test (make miniapp-e2e) against a core in test mode
- Fix: each download attempt gets its own scratch directory, so a retry
  cannot lose its file to the cleanup of the failed attempt

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 10:27:20 +00:00

373 lines
12 KiB
Go

package config
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
func lookup(env map[string]string) func(string) (string, bool) {
return func(k string) (string, bool) {
v, ok := env[k]
return v, ok
}
}
func TestDefaultsAreValidOnceTokenIsSet(t *testing.T) {
cfg := Default()
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "BOT_TOKEN") {
t.Fatalf("missing token must be reported, got %v", err)
}
cfg.Telegram.Token = "x"
if err := cfg.Validate(); err != nil {
t.Fatalf("defaults should validate: %v", err)
}
if cfg.Limits.Free.MaxSizeMB != 50 || cfg.Limits.Free.MaxDuration.D() != 10*time.Minute ||
cfg.Limits.Free.ActiveJobs != 1 || cfg.Queue.FreeMaxLen != 20 {
t.Fatalf("free tier defaults changed: %+v %+v", cfg.Limits.Free, cfg.Queue)
}
}
func TestApplyEnv(t *testing.T) {
cfg := Default()
env := map[string]string{
"BOT_TOKEN": "123:abc",
"TELEGRAM_MODE": "webhook",
"WEBHOOK_URL": "https://bot.example.com",
"WORKER_EMBEDDED": "false",
"WORKER_CONCURRENCY": "5",
"DOWNLOAD_TIMEOUT": "45m",
"OWNER_IDS": "11, 22;33",
"DB_DRIVER": "postgres",
"LOG_LEVEL": "",
}
if err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(env)); err != nil {
t.Fatal(err)
}
if cfg.Telegram.Token != "123:abc" || cfg.Telegram.Mode != "webhook" || cfg.Worker.Embedded ||
cfg.Worker.Concurrency != 5 || cfg.Worker.DownloadTimeout.D() != 45*time.Minute ||
cfg.Database.Driver != "postgres" {
t.Fatalf("env not applied: %+v", cfg)
}
if !reflect.DeepEqual(cfg.Owners, []int64{11, 22, 33}) {
t.Fatalf("owners = %v", cfg.Owners)
}
if cfg.Log.Level != "info" {
t.Fatalf("an empty variable must not override the default, got %q", cfg.Log.Level)
}
if !cfg.IsOwner(22) || cfg.IsOwner(44) {
t.Fatal("IsOwner is wrong")
}
if err := applyTierEnv("FREE", &cfg.Limits.Free, lookup(map[string]string{
"FREE_MAX_SIZE_MB": "25", "FREE_MAX_DURATION": "5m", "FREE_ACTIVE_JOBS": "2",
})); err != nil {
t.Fatal(err)
}
if cfg.Limits.Free.MaxSizeMB != 25 || cfg.Limits.Free.MaxDuration.D() != 5*time.Minute || cfg.Limits.Free.ActiveJobs != 2 {
t.Fatalf("tier env not applied: %+v", cfg.Limits.Free)
}
}
func TestApplyEnvRejectsBadValues(t *testing.T) {
for k, v := range map[string]string{
"WORKER_CONCURRENCY": "many", "WORKER_EMBEDDED": "maybe", "DOWNLOAD_TIMEOUT": "soon", "OWNER_IDS": "1,x",
} {
cfg := Default()
err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(map[string]string{k: v}))
if err == nil || !strings.Contains(err.Error(), k) {
t.Errorf("%s=%s: error %v should name the variable", k, v, err)
}
}
}
func TestMoneyDefaultsAndValidation(t *testing.T) {
cfg := Default()
cfg.Telegram.Token = "x"
p := cfg.Prices
if p.PassDay != 700 || p.PassWeek != 3000 || p.PassMonth != 9000 {
t.Fatalf("pass prices changed: %+v", p)
}
if cfg.Limits.Free.DailyDownloads != 5 || cfg.Limits.Paid.MaxSizeMB != 2000 ||
cfg.Limits.Paid.MaxDuration.D() != 3*time.Hour || cfg.Limits.Paid.ActiveJobs != 3 {
t.Fatalf("tier defaults changed: %+v", cfg.Limits)
}
if cfg.LNbits.Enabled() {
t.Fatal("payments must be off until LNbits is configured")
}
if err := cfg.Validate(); err != nil {
t.Fatalf("a config without payments must validate: %v", err)
}
// One of the two LNbits settings alone is a mistake.
cfg.LNbits.URL = "https://lnbits.example.com"
if err := cfg.Validate(); err == nil {
t.Fatal("LNBITS_URL without a key must be rejected")
}
cfg.LNbits.InvoiceKey = "key"
if err := cfg.Validate(); err != nil || !cfg.LNbits.Enabled() {
t.Fatalf("complete LNbits settings: %v", err)
}
cfg.Prices.PassDay = 0
if err := cfg.Validate(); err == nil {
t.Fatal("a zero pass price must be rejected when payments are on")
}
cfg.Prices.PassDay = 700
cfg.LNbits.InvoiceExpiry = Duration(10 * time.Second)
if err := cfg.Validate(); err == nil {
t.Fatal("an invoice expiry under a minute must be rejected")
}
// One-off pricing: base plus one step per started 100 MB.
prices := map[int64]int64{
0: 200, // unknown size is priced as 200 MB
1: 150,
100 << 20: 150,
101 << 20: 200,
1 << 30: 100 + 11*50,
}
for size, want := range prices {
if got := p.OneOffPrice(size); got != want {
t.Errorf("OneOffPrice(%d) = %d, want %d", size, got, want)
}
}
if p.PassPrice("week") != 3000 || p.PassPrice("decade") != 0 {
t.Fatal("PassPrice is wrong")
}
}
func TestMoneyEnv(t *testing.T) {
cfg := Default()
env := map[string]string{
"PRICE_PASS_DAY": "1000", "CREDIT_PACKS": "100, 200", "LNBITS_URL": "https://ln.example.com/",
"RATE_USER_PER_MINUTE": "3", "PUBLIC_URL": "https://bot.example.com/",
}
if err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(env)); err != nil {
t.Fatal(err)
}
if cfg.Prices.PassDay != 1000 || !reflect.DeepEqual(cfg.Prices.CreditPacks, []int64{100, 200}) ||
cfg.Rate.UserPerMinute != 3 || cfg.LNbits.URL != "https://ln.example.com/" {
t.Fatalf("env not applied: %+v %+v", cfg.Prices, cfg.Rate)
}
if err := applyTierEnv("PAID", &cfg.Limits.Paid, lookup(map[string]string{
"PAID_DAILY_DOWNLOADS": "7", "PAID_DAILY_MB": "9",
})); err != nil || cfg.Limits.Paid.DailyDownloads != 7 || cfg.Limits.Paid.DailyMB != 9 {
t.Fatalf("paid tier env: %+v, %v", cfg.Limits.Paid, err)
}
}
func TestValidate(t *testing.T) {
bad := []func(*Config){
func(c *Config) { c.Telegram.Mode = "carrier-pigeon" },
func(c *Config) { c.Telegram.Mode = "webhook" }, // no URL
func(c *Config) { c.Database.Driver = "oracle" },
func(c *Config) { c.Storage.Backend = "tape" },
func(c *Config) { c.Worker.Concurrency = 0 },
func(c *Config) { c.Queue.MaxAttempts = 0 },
func(c *Config) { c.Queue.Heartbeat = c.Queue.Lease },
func(c *Config) { c.MiniApp = true }, // no public URL
func(c *Config) { c.MiniApp, c.PublicURL = true, "http://bot.example.com" },
func(c *Config) { c.MiniApp, c.PublicURL = true, "bot.example.com" },
}
good := []func(*Config){
func(c *Config) { c.MiniApp, c.PublicURL = true, "https://bot.example.com" },
func(c *Config) { c.MiniApp, c.PublicURL = true, "http://127.0.0.1:8080" },
func(c *Config) { c.MiniApp, c.PublicURL = true, "http://localhost:8080" },
func(c *Config) { c.PublicURL = "http://bot.example.com" }, // fine without the Mini App
}
for i, mut := range good {
cfg := Default()
cfg.Telegram.Token = "x"
mut(&cfg)
if err := cfg.Validate(); err != nil {
t.Errorf("good case %d: %v", i, err)
}
}
for i, mut := range bad {
cfg := Default()
cfg.Telegram.Token = "x"
mut(&cfg)
if err := cfg.Validate(); err == nil {
t.Errorf("case %d should not validate", i)
}
}
}
func TestLoadFileThenEnv(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
content := `
owners = [5, 6]
[telegram]
token = "from-file"
max_upload_mb = 2000
[worker]
concurrency = 3
download_timeout = "1h"
[limits.free]
max_size_mb = 30
max_duration = "7m"
active_jobs = 1
`
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
t.Chdir(dir) // keeps a developer's real .env out of the test
t.Setenv("BOT_TOKEN", "from-env")
t.Setenv("DLBOT_CONFIG", "")
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
if cfg.Telegram.Token != "from-env" {
t.Errorf("env must override the file, token = %q", cfg.Telegram.Token)
}
if cfg.Worker.Concurrency != 3 || cfg.Worker.DownloadTimeout.D() != time.Hour ||
cfg.Limits.Free.MaxSizeMB != 30 || cfg.Limits.Free.MaxDuration.D() != 7*time.Minute {
t.Errorf("file values not loaded: %+v %+v", cfg.Worker, cfg.Limits.Free)
}
if cfg.MaxUploadBytes() != 2000<<20 || !reflect.DeepEqual(cfg.Owners, []int64{5, 6}) {
t.Errorf("upload cap or owners wrong: %d %v", cfg.MaxUploadBytes(), cfg.Owners)
}
if cfg.HTTP.Listen != ":8080" {
t.Errorf("unset values keep their defaults, listen = %q", cfg.HTTP.Listen)
}
if _, err := Load(filepath.Join(dir, "missing.toml")); err == nil {
t.Error("an explicit config path that does not exist must be an error")
}
}
func TestDotEnvDoesNotOverrideRealEnv(t *testing.T) {
dir := t.TempDir()
env := "# comment\nexport DLBOT_TEST_A=from-dotenv\nDLBOT_TEST_B=\"quoted value\"\nnot a pair\n"
path := filepath.Join(dir, ".env")
if err := os.WriteFile(path, []byte(env), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DLBOT_TEST_A", "from-real-env")
os.Unsetenv("DLBOT_TEST_B")
t.Cleanup(func() { os.Unsetenv("DLBOT_TEST_B") })
if err := loadDotEnv(path); err != nil {
t.Fatal(err)
}
if got := os.Getenv("DLBOT_TEST_A"); got != "from-real-env" {
t.Errorf("A = %q", got)
}
if got := os.Getenv("DLBOT_TEST_B"); got != "quoted value" {
t.Errorf("B = %q", got)
}
if err := loadDotEnv(filepath.Join(dir, "absent")); err != nil {
t.Errorf("a missing .env is fine, got %v", err)
}
}
func TestSiteTagsAndRequiredTags(t *testing.T) {
m, err := ParseSiteTags(" YouTube.com = residential ; example.com=eu, residential ;; x.com=residential")
if err != nil {
t.Fatal(err)
}
cfg := Default()
cfg.SiteTags = m
tests := map[string]string{
"youtube.com": "residential",
"music.youtube.com": "residential", // a rule covers subdomains
"example.com": "eu,residential",
"cdn.eu.example.com": "eu,residential",
"notyoutube.com": "",
"com": "",
"": "",
"vimeo.com": "",
"YOUTUBE.COM": "residential",
}
for site, want := range tests {
if got := cfg.RequiredTags(site); got != want {
t.Errorf("RequiredTags(%q) = %q, want %q", site, got, want)
}
}
// Rules of a host and of its parent add up.
cfg.SiteTags["eu.example.com"] = []string{"fast"}
if got := cfg.RequiredTags("cdn.eu.example.com"); got != "eu,fast,residential" {
t.Errorf("combined rules = %q", got)
}
if _, err := ParseSiteTags("no-equals-sign"); err == nil {
t.Error("a malformed SITE_TAGS must be rejected")
}
if got := Default().RequiredTags("youtube.com"); got != "" {
t.Errorf("without rules nothing is required, got %q", got)
}
}
func TestProbeModeAndScaleOutValidation(t *testing.T) {
cfg := Default()
cfg.Telegram.Token = "x"
if !cfg.ProbeLocally() {
t.Fatal("with the embedded worker, the core probes by itself")
}
cfg.Worker.Embedded = false
if cfg.ProbeLocally() {
t.Fatal("without the embedded worker, probes go to remote workers")
}
cfg.ProbeMode = "local"
if !cfg.ProbeLocally() {
t.Fatal("PROBE_MODE=local forces local probing")
}
cfg.ProbeMode = "sometimes"
if err := cfg.Validate(); err == nil {
t.Fatal("an unknown PROBE_MODE must be rejected")
}
cfg.ProbeMode = "auto"
cfg.WorkerTokens = []string{"eu-1:short"}
if err := cfg.Validate(); err == nil {
t.Fatal("a short worker token must be rejected")
}
cfg.WorkerTokens = []string{"eu-1:dlw_0123456789abcdef"}
if err := cfg.Validate(); err != nil {
t.Fatalf("a good worker token entry: %v", err)
}
cfg.Storage.Backend = "s3"
if err := cfg.Validate(); err == nil {
t.Fatal("s3 without endpoint, bucket and keys must be rejected")
}
cfg.Storage.S3 = S3{Endpoint: "https://s3.example.com", Bucket: "b", AccessKey: "k", SecretKey: "s"}
if err := cfg.Validate(); err != nil {
t.Fatalf("complete s3 settings: %v", err)
}
}
func TestWorkerConfig(t *testing.T) {
cfg := DefaultWorker()
if err := cfg.Validate(); err == nil {
t.Fatal("a worker needs CORE_URL and WORKER_TOKEN")
}
cfg.CoreURL, cfg.Token = "bot.example.com", "dlw_x"
if err := cfg.Validate(); err == nil {
t.Fatal("CORE_URL needs a scheme")
}
cfg.CoreURL = "https://bot.example.com"
if err := cfg.Validate(); err != nil {
t.Fatalf("a complete worker config: %v", err)
}
if cfg.Heartbeat.D() != 10*time.Second || cfg.Concurrency != 2 || cfg.ProbeSlots != 2 {
t.Fatalf("worker defaults changed: %+v", cfg)
}
env := map[string]string{
"CORE_URL": "https://core.example.com/", "WORKER_TOKEN": "dlw_abc", "WORKER_TAGS": "residential, eu",
"YTDLP_EXTRA_ARGS": "--limit-rate 1M", "WORKER_HEALTH_LISTEN": "off", "YTDLP_AUTO_UPDATE": "0",
}
w := DefaultWorker()
if err := applyEnv(reflect.ValueOf(&w).Elem(), lookup(env)); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(w.Tags, []string{"residential", "eu"}) || !reflect.DeepEqual(w.ExtraArgs, []string{"--limit-rate", "1M"}) ||
w.AutoUpdate.D() != 0 {
t.Fatalf("worker env not applied: %+v", w)
}
}