tgbot_draft_render_test.go 4.5 KB

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