tgbot_stale_button_test.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. package tgbot
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "testing"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mymmrac/telego"
  11. )
  12. // staleButtonServer serves canned Telegram API responses so tests can drive
  13. // bot-dependent paths; the returned func reports per-method call counts.
  14. func staleButtonServer(t *testing.T, responses map[string]any) (*httptest.Server, func(string) int) {
  15. t.Helper()
  16. counts := map[string]int{}
  17. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. for method, body := range responses {
  19. if r.URL.Path == "/bot"+testBotToken+"/"+method {
  20. counts[method]++
  21. w.Header().Set("Content-Type", "application/json")
  22. json.NewEncoder(w).Encode(body)
  23. return
  24. }
  25. }
  26. w.WriteHeader(http.StatusNotFound)
  27. }))
  28. return srv, func(method string) int { return counts[method] }
  29. }
  30. func swapTestBot(t *testing.T, url string) {
  31. t.Helper()
  32. origBot := bot
  33. origPool := messageWorkerPool
  34. t.Cleanup(func() {
  35. bot = origBot
  36. messageWorkerPool = origPool
  37. })
  38. var err error
  39. bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(url))
  40. if err != nil {
  41. t.Fatalf("NewBot: %v", err)
  42. }
  43. messageWorkerPool = make(chan struct{}, 10)
  44. }
  45. func newStaleButtonTgbot(t *testing.T) *Tgbot {
  46. t.Helper()
  47. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  48. t.Fatalf("InitDB: %v", err)
  49. }
  50. t.Cleanup(func() { _ = database.CloseDB() })
  51. return &Tgbot{}
  52. }
  53. // Regression test: a stale get_clients_for_* tap on a deleted inbound must
  54. // answer an error, not panic on inbound.Remark; removing the guard fails here.
  55. func TestChooseInboundClientStaleInbound(t *testing.T) {
  56. mock, calls := staleButtonServer(t, map[string]any{
  57. "answerCallbackQuery": map[string]any{"ok": true, "result": true},
  58. })
  59. swapTestBot(t, mock.URL)
  60. defer mock.Close()
  61. tb := newStaleButtonTgbot(t)
  62. q := &telego.CallbackQuery{
  63. ID: "q1",
  64. From: telego.User{ID: 999999},
  65. Message: &telego.Message{Chat: telego.Chat{ID: 1}},
  66. }
  67. tb.chooseInboundClient(q, 1, 42, "client_sub_links")
  68. if n := calls("answerCallbackQuery"); n != 1 {
  69. t.Errorf("answerCallbackQuery calls = %d, want 1: a stale tap must be answered with an error", n)
  70. }
  71. }
  72. // The keyboard builder must consume the caller's inbound row; a second DB read
  73. // reintroduces the stale-row window the guard closed.
  74. func TestGetInboundClientsForUsesProvidedInbound(t *testing.T) {
  75. mock, _ := staleButtonServer(t, map[string]any{
  76. "answerCallbackQuery": map[string]any{"ok": true, "result": true},
  77. })
  78. swapTestBot(t, mock.URL)
  79. defer mock.Close()
  80. tb := newStaleButtonTgbot(t)
  81. inbound := &model.Inbound{Id: 7, Remark: "in-7", Settings: `{"clients":[{"email":"[email protected]"}]}`}
  82. kb, err := tb.getInboundClientsFor(inbound, "client_sub_links")
  83. if err != nil {
  84. t.Fatalf("getInboundClientsFor: %v", err)
  85. }
  86. if kb == nil || len(kb.InlineKeyboard) == 0 || len(kb.InlineKeyboard[0]) == 0 {
  87. t.Fatalf("getInboundClientsFor returned no keyboard")
  88. }
  89. if email := kb.InlineKeyboard[0][0].Text; email != "[email protected]" {
  90. t.Errorf("keyboard button text = %q, want %q", email, "[email protected]")
  91. }
  92. }
  93. // A panicking handler must be contained by runBotHandler; without the
  94. // recover() the panic escapes and fails this test.
  95. func TestRunBotHandlerRecoversPanic(t *testing.T) {
  96. origPool := messageWorkerPool
  97. t.Cleanup(func() { messageWorkerPool = origPool })
  98. messageWorkerPool = make(chan struct{}, 10)
  99. ran := false
  100. func() {
  101. defer func() {
  102. if r := recover(); r != nil {
  103. t.Fatalf("panic escaped runBotHandler: %v", r)
  104. }
  105. }()
  106. runBotHandler(func() {
  107. ran = true
  108. panic("boom")
  109. })
  110. }()
  111. if !ran {
  112. t.Errorf("handler body did not run")
  113. }
  114. }