Files
Media-download-telegram-bot/internal/config/config_test.go
T
MichilisandClaude Fable 5.2 0d50f453a0 Phase 2: money
Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 08:09:35 +00:00

251 lines
7.9 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 },
}
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)
}
}