tgbot_draft_render_test.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package tgbot
  2. import (
  3. "encoding/json"
  4. "html"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "sync"
  10. "testing"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  12. "github.com/mymmrac/telego"
  13. "github.com/nicksnyder/go-i18n/v2/i18n"
  14. "golang.org/x/text/language"
  15. )
  16. // Regression test: the draft is sent with ParseMode HTML, so Markdown markers
  17. // were rendered literally and an unescaped value could break the whole message.
  18. func TestClientDraftMessageRendersHTML(t *testing.T) {
  19. origEmail, origComment, origTgID := client_Email, client_Comment, client_TgID
  20. origTotalGB, origLimitIP, origExpiry := client_TotalGB, client_LimitIP, client_ExpiryTime
  21. origInboundIDs := receiver_inbound_IDs
  22. t.Cleanup(func() {
  23. client_Email, client_Comment, client_TgID = origEmail, origComment, origTgID
  24. client_TotalGB, client_LimitIP, client_ExpiryTime = origTotalGB, origLimitIP, origExpiry
  25. receiver_inbound_IDs = origInboundIDs
  26. })
  27. client_Email = "[email protected]"
  28. client_Comment = "<b>promo</b> & <10 GB>"
  29. client_TgID = "42"
  30. client_TotalGB, client_LimitIP, client_ExpiryTime = 0, 0, 0
  31. receiver_inbound_IDs = nil
  32. out := (&Tgbot{}).BuildClientDraftMessage()
  33. if !strings.Contains(out, "<b>New client draft</b>") {
  34. t.Errorf("draft title is not HTML markup: %q", out)
  35. }
  36. if strings.Contains(out, "*New client draft*") || strings.Contains(out, "`") {
  37. t.Errorf("draft still carries Markdown markers: %q", out)
  38. }
  39. if strings.Contains(out, "<b>promo</b>") {
  40. t.Errorf("raw comment markup reached the message: %q", out)
  41. }
  42. if !strings.Contains(out, html.EscapeString(client_Comment)) {
  43. t.Errorf("comment is not HTML-escaped: %q", out)
  44. }
  45. }
  46. // botPromptLocalizer renders the two prompts the callback tests drive, with the
  47. // templates the translation files carry; without it I18n returns the bare key.
  48. func botPromptLocalizer(t *testing.T) {
  49. t.Helper()
  50. bundle := i18n.NewBundle(language.MustParse("en-US"))
  51. bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
  52. _ = bundle.AddMessages(language.MustParse("en-US"),
  53. &i18n.Message{ID: "tgbot.messages.email_prompt", Other: "📧 Default Email: {{ .ClientEmail }}\n\nEnter your email."},
  54. &i18n.Message{ID: "tgbot.messages.comment_prompt", Other: "💬 Default Comment: {{ .ClientComment }}\n\nEnter your comment."},
  55. )
  56. orig := locale.LocalizerBot
  57. t.Cleanup(func() { locale.LocalizerBot = orig })
  58. locale.LocalizerBot = i18n.NewLocalizer(bundle, "en-US")
  59. }
  60. // promptTexts serves the methods these prompts touch and returns the text of
  61. // every sendMessage, so a test can check what Telegram would actually parse.
  62. func promptTexts(t *testing.T) (string, func() []string) {
  63. t.Helper()
  64. var mu sync.Mutex
  65. var texts []string
  66. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  67. body, _ := io.ReadAll(r.Body)
  68. result := any(true)
  69. if r.URL.Path == "/bot"+testBotToken+"/sendMessage" {
  70. var payload struct {
  71. Text string `json:"text"`
  72. }
  73. _ = json.Unmarshal(body, &payload)
  74. mu.Lock()
  75. texts = append(texts, payload.Text)
  76. mu.Unlock()
  77. result = map[string]any{"message_id": 1, "date": 0, "chat": map[string]any{"id": 1, "type": "private"}}
  78. }
  79. w.Header().Set("Content-Type", "application/json")
  80. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "result": result})
  81. }))
  82. t.Cleanup(srv.Close)
  83. return srv.URL, func() []string {
  84. mu.Lock()
  85. defer mu.Unlock()
  86. return append([]string(nil), texts...)
  87. }
  88. }
  89. // Regression test: the wizard's own prompts are HTML-parsed as well, so the
  90. // draft value they echo has to be escaped exactly like the draft card.
  91. func TestAddClientPromptsEscapeDraftValues(t *testing.T) {
  92. botPromptLocalizer(t)
  93. url, texts := promptTexts(t)
  94. swapTestBot(t, url)
  95. origEmail, origComment := client_Email, client_Comment
  96. origRunning := isRunning
  97. t.Cleanup(func() {
  98. client_Email, client_Comment = origEmail, origComment
  99. isRunning = origRunning
  100. })
  101. isRunning = true
  102. cases := []struct {
  103. name string
  104. data string
  105. value string
  106. }{
  107. {"email prompt", "add_client_ch_default_email", "long<name>@example.com"},
  108. {"comment prompt", "add_client_ch_default_comment", "promo <b>tag</b>"},
  109. }
  110. tb := &Tgbot{}
  111. for _, tc := range cases {
  112. t.Run(tc.name, func(t *testing.T) {
  113. client_Email, client_Comment = tc.value, tc.value
  114. tb.answerCallback(&telego.CallbackQuery{
  115. ID: "q1",
  116. From: telego.User{ID: 1},
  117. Data: tc.data,
  118. Message: &telego.Message{Chat: telego.Chat{ID: 1}},
  119. }, true) // admin
  120. sent := texts()
  121. if len(sent) == 0 {
  122. t.Fatalf("no prompt was sent for %s", tc.data)
  123. }
  124. got := sent[len(sent)-1]
  125. if strings.Contains(got, tc.value) {
  126. t.Errorf("prompt = %q, want the draft value escaped", got)
  127. }
  128. if !strings.Contains(got, html.EscapeString(tc.value)) {
  129. t.Errorf("prompt = %q, want it to contain %q", got, html.EscapeString(tc.value))
  130. }
  131. })
  132. }
  133. }