Files
Media-download-telegram-bot/internal/widget/widget_test.go
T
MichilisandClaude Opus 5.5 3c153af97f Phase 8: widgets and polish
- Live job card widget (progress bar, in-widget cancel via widget_query)
  and live invoice widget (QR drawn from a bitmap, countdown, paid state),
  Bot API 10.4 sendWidget, private chats only
- Automatic fallback to the ordinary message when sendWidget fails, with
  a breaker that pauses widgets after repeated failures or on servers
  without the method; TELEGRAM_WIDGETS
- Prometheus metrics on the core (/metrics) and on every worker: queue
  depth and wait, slots, heartbeats, job outcomes, errors per site,
  deliveries, cache, invoices, Lightning, ledger check, widgets
- Example Prometheus config and alert rules, Caddyfile, dashboard notes
- Load test: cmd/loadtest and deploy/loadtest (make loadtest)
- Browser check of the widgets' HTML, including decoding a drawn QR
- docs/DEPLOY.md (production in under an hour) and docs/MONITORING.md

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

136 lines
4.5 KiB
Go

package widget
import (
"encoding/base64"
"encoding/json"
"os"
"strings"
"testing"
"time"
)
func TestHTMLIsWithinTelegramsLimits(t *testing.T) {
for name, html := range map[string]string{"job": JobHTML(), "invoice": InvoiceHTML()} {
if err := CheckHTML(html); err != nil {
t.Errorf("%s: %v", name, err)
}
t.Logf("%s: %d bytes, %d compressed", name, len(html), CompressedSize(html))
// The sandbox has no network and no logical CSS properties, and
// draws no form controls but buttons.
for _, bad := range []string{"http://", "https://", "fetch(", "XMLHttpRequest", "<input", "<select", "-inline", "inset-block", "-block-", "color-mix(", ":has(", "@import", "\u2014"} {
if strings.Contains(html, bad) {
t.Errorf("%s uses %q, which widgets do not support", name, bad)
}
}
if !strings.Contains(html, "TelegramWidget") || !strings.Contains(html, "chatDataChanged") {
t.Errorf("%s does not follow its state", name)
}
}
}
func TestCheckHTMLRefusesTooMuch(t *testing.T) {
if CheckHTML("") == nil || CheckHTML(strings.Repeat("a", MaxHTML+1)) == nil {
t.Fatal("empty or oversized html accepted")
}
// Random-looking text does not compress.
var sb strings.Builder
x := uint32(2463534242)
for i := 0; i < 12000; i++ {
x ^= x << 13
x ^= x >> 17
x ^= x << 5
sb.WriteByte(byte('!' + x%90))
}
if CheckHTML(sb.String()) == nil {
t.Fatal("html over the compressed limit accepted")
}
}
func TestEncodeStaysWithinTheDataLimit(t *testing.T) {
long := strings.Repeat("ñ", 2000)
got, err := Encode(Job{Kind: "running", Message: long, Detail: long, Progress: 0.5})
if err != nil || len(got) > MaxData {
t.Fatalf("job: %d bytes, %v", len(got), err)
}
var back Job
if err := json.Unmarshal([]byte(got), &back); err != nil || back.Kind != "running" || back.Progress != 0.5 {
t.Fatalf("job state did not survive: %+v %v", back, err)
}
info := InvoiceInfo{Title: "Day pass", Amount: "700 sats", QR: strings.Repeat("A", 1500), N: 99}
got, err = Encode(info)
if err != nil || strings.Contains(got, `"q"`) {
t.Fatalf("an oversized QR must be dropped, not the invoice: %q %v", got, err)
}
}
// A real invoice must leave room for its QR code in the widget's data.
func TestQRFitsForARealInvoice(t *testing.T) {
bolt11 := "LNBC30U1PNXYZ3QPP5" + strings.Repeat("Q8ZJ7W3K", 33) + "CQZPGXQYZ5VQSP5"
n, b64, err := QRBits("LIGHTNING:" + bolt11)
if err != nil {
t.Fatal(err)
}
raw, _ := base64.StdEncoding.DecodeString(b64)
if len(raw) != (n*n+7)/8 {
t.Fatalf("%d bytes for %d modules", len(raw), n)
}
data, err := Encode(InvoiceInfo{
Title: "Pase semanal", Amount: "3.000 sats", Expires: time.Now().Unix(), Waiting: "Esperando el pago · {T}",
Checking: "Verificando el pago…", QR: b64, N: n,
})
if err != nil || !strings.Contains(data, `"q"`) {
t.Fatalf("a %d character invoice does not fit with its QR (%d modules): %d bytes, %v", len(bolt11), n, len(data), err)
}
t.Logf("%d modules, %d bytes of public data", n, len(data))
}
func TestBreaker(t *testing.T) {
var off *Breaker
if off.Allow() {
t.Fatal("a nil breaker means widgets are off")
}
now := time.Unix(1000, 0)
b := NewBreaker()
b.now = func() time.Time { return now }
b.Failed(false)
b.Failed(false)
b.Worked()
b.Failed(false)
if !b.Allow() {
t.Fatal("a success resets the count")
}
b.Failed(false)
if d := b.Failed(false); d != 10*time.Minute || b.Allow() {
t.Fatalf("three in a row: pause %s, allowed %v", d, b.Allow())
}
now = now.Add(11 * time.Minute)
if !b.Allow() {
t.Fatal("the pause ends")
}
if d := b.Failed(true); d != time.Hour || b.Allow() {
t.Fatal("an unsupported server pauses for an hour")
}
}
// testdata/qr.json is a real invoice QR as the widget receives it. The
// browser check (web/miniapp/e2e/widgets.mjs) draws it with the widget's
// own code and decodes the picture. This test keeps the file in step with
// QRBits; DLBOT_UPDATE_FIXTURES=1 rewrites it.
func TestQRFixture(t *testing.T) {
text := "LIGHTNING:LNBC7000N1PNXYZ3QPP5" + strings.Repeat("Q8ZJ7W3KX4", 24) + "CQZPGXQYZ5VQSP5"
n, b64, err := QRBits(text)
if err != nil {
t.Fatal(err)
}
want, _ := json.MarshalIndent(map[string]any{"text": text, "n": n, "q": b64}, "", " ")
if os.Getenv("DLBOT_UPDATE_FIXTURES") != "" {
if err := os.WriteFile("testdata/qr.json", append(want, '\n'), 0o644); err != nil {
t.Fatal(err)
}
}
got, err := os.ReadFile("testdata/qr.json")
if err != nil || strings.TrimSpace(string(got)) != string(want) {
t.Fatalf("testdata/qr.json is out of date; run with DLBOT_UPDATE_FIXTURES=1 (%v)", err)
}
}