tgbot_add_client_picker_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package tgbot
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "slices"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mymmrac/telego"
  11. "github.com/nicksnyder/go-i18n/v2/i18n"
  12. )
  13. func seedPickerInbounds(t *testing.T, protocols ...model.Protocol) {
  14. t.Helper()
  15. dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
  16. for i, protocol := range protocols {
  17. port := 20000 + i
  18. ib := &model.Inbound{Remark: string(protocol), Enable: true, Port: port, Protocol: protocol, Tag: fmt.Sprintf("inbound-%d", port), Settings: `{}`}
  19. if err := database.GetDB().Create(ib).Error; err != nil {
  20. t.Fatalf("seed %s inbound: %v", protocol, err)
  21. }
  22. }
  23. }
  24. func pickerLabels(keyboard *telego.InlineKeyboardMarkup) []string {
  25. var labels []string
  26. for _, row := range keyboard.InlineKeyboard {
  27. for _, button := range row {
  28. labels = append(labels, button.Text)
  29. }
  30. }
  31. slices.Sort(labels)
  32. return labels
  33. }
  34. // WireGuard and AmneziaWG clients get a generated keypair and address on Create,
  35. // so the wizard offers them; Mixed authenticates per inbound and has no clients.
  36. func TestAddClientPickerOffersWireGuardAndAmneziaWG(t *testing.T) {
  37. seedPickerInbounds(t, model.VLESS, model.WireGuard, model.AmneziaWG, model.Mixed)
  38. keyboard, err := (&Tgbot{}).getInboundsAddClient()
  39. if err != nil {
  40. t.Fatalf("getInboundsAddClient: %v", err)
  41. }
  42. want := []string{"amneziawg - ✅", "vless - ✅", "wireguard - ✅"}
  43. if got := pickerLabels(keyboard); !slices.Equal(got, want) {
  44. t.Fatalf("picker buttons = %q, want %q", got, want)
  45. }
  46. }
  47. // An empty keyboard sent the admin a "choose inbound" prompt with nothing to tap.
  48. func TestAddClientPickerFailsWhenNoInboundTakesClients(t *testing.T) {
  49. draftLocalizer(t, &i18n.Message{ID: "tgbot.answers.getInboundsFailed", Other: "Failed to get inbounds."})
  50. seedPickerInbounds(t, model.Mixed, model.HTTP, model.Tunnel)
  51. keyboard, err := (&Tgbot{}).getInboundsAddClient()
  52. if err == nil || err.Error() != "Failed to get inbounds." {
  53. t.Fatalf("getInboundsAddClient = (%v, %v), want the getInboundsFailed error", keyboard, err)
  54. }
  55. }