FILE / ScuroNeko/Laniakea
msg_context_test.go
Исходный файл и его история в репозитории.
(fix): harden concurrent lifecycle (tests): add regression coverage (doc): update v1.2 guidance
968 lines
28 KiB
Go
968 lines
28 KiB
Go
package laniakea
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.scuroneko.dev/scuroneko/laniakea/tgapi"
|
|
"git.scuroneko.dev/scuroneko/laniakea/tgrich"
|
|
"git.scuroneko.dev/scuroneko/sneklog/v2"
|
|
)
|
|
|
|
func newMessageContextTestAPI(t *testing.T, transport roundTripFunc) *tgapi.API {
|
|
t.Helper()
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(&http.Client{Transport: transport}),
|
|
)
|
|
t.Cleanup(func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
})
|
|
return api
|
|
}
|
|
|
|
func readMessageContextRequest(t *testing.T, req *http.Request) map[string]any {
|
|
t.Helper()
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
var decoded map[string]any
|
|
if err := json.Unmarshal(body, &decoded); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
return decoded
|
|
}
|
|
|
|
func messageContextResponse(result string) *http.Response {
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":` + result + `}`)),
|
|
}
|
|
}
|
|
|
|
func TestMessageContextPropagatesBusinessConnection(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
wantMethod string
|
|
result string
|
|
invoke func(*MessageContext)
|
|
}{
|
|
{name: "send message", wantMethod: "sendMessage", result: `{"message_id":11,"date":1}`, invoke: func(ctx *MessageContext) { ctx.Answer("text") }},
|
|
{name: "send photo", wantMethod: "sendPhoto", result: `{"message_id":11,"date":1}`, invoke: func(ctx *MessageContext) { ctx.AnswerPhoto("photo-id", "caption") }},
|
|
{name: "edit caption", wantMethod: "editMessageCaption", result: `{"message_id":11,"date":1}`, invoke: func(ctx *MessageContext) { (&AnswerMessage{MessageID: 7, ctx: ctx}).EditCaption("caption") }},
|
|
{name: "send action", wantMethod: "sendChatAction", result: `true`, invoke: func(ctx *MessageContext) { ctx.SendAction(tgapi.ChatActionTyping) }},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
var gotBody map[string]any
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
if !strings.HasSuffix(req.URL.Path, "/"+tt.wantMethod) {
|
|
t.Fatalf("request path = %q, want method %q", req.URL.Path, tt.wantMethod)
|
|
}
|
|
gotBody = readMessageContextRequest(t, req)
|
|
return messageContextResponse(tt.result), nil
|
|
}))
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{
|
|
BusinessConnectionID: "business-1",
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
tt.invoke(ctx)
|
|
if got := gotBody["business_connection_id"]; got != "business-1" {
|
|
t.Fatalf("business_connection_id = %v, want business-1", got)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestMessageContextHelpersRejectMissingChat(t *testing.T) {
|
|
requests := 0
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
requests++
|
|
return nil, errors.New("unexpected request")
|
|
}))
|
|
ctx := &MessageContext{API: api, Msg: &tgapi.Message{}, CallbackMsgID: 7, Logger: sneklog.NewLogger()}
|
|
|
|
if answer := ctx.Answer("text"); answer != nil {
|
|
t.Fatalf("Answer returned %#v for a message without a chat", answer)
|
|
}
|
|
if answer := ctx.EditCallback("text", nil); answer != nil {
|
|
t.Fatalf("EditCallback returned %#v for a message without a chat", answer)
|
|
}
|
|
if requests != 0 {
|
|
t.Fatalf("missing-chat helpers made %d requests", requests)
|
|
}
|
|
}
|
|
|
|
func TestRichAnswerBuildsInputBlocks(t *testing.T) {
|
|
var gotBody map[string]any
|
|
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := json.Unmarshal(body, &gotBody); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":{"message_id":9,"date":1}}`)),
|
|
}, nil
|
|
})}
|
|
api := tgapi.NewAPI(tgapi.NewAPIOpts("token").SetAPIURL("https://example.test").SetHTTPClient(client))
|
|
defer func() { _ = api.Close() }()
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{
|
|
BusinessConnectionID: "business-1",
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
answer := ctx.RichAnswer(tgrich.P(tgrich.Bold(tgrich.Text("ready"))))
|
|
if answer == nil {
|
|
t.Fatal("RichAnswer() returned nil")
|
|
}
|
|
rich, ok := gotBody["rich_message"].(map[string]any)
|
|
if !ok || rich["html"] != "<p><b>ready</b></p>" {
|
|
t.Fatalf("rich_message = %#v", gotBody["rich_message"])
|
|
}
|
|
if _, exists := rich["skip_entity_detection"]; exists {
|
|
t.Fatalf("rich_message unexpectedly disables entity detection: %#v", rich)
|
|
}
|
|
if got := gotBody["business_connection_id"]; got != "business-1" {
|
|
t.Fatalf("business_connection_id = %v, want business-1", got)
|
|
}
|
|
if answer.Text != "<p><b>ready</b></p>" || answer.RichHTML != answer.Text {
|
|
t.Fatalf("unexpected answer content: Text=%q RichHTML=%q", answer.Text, answer.RichHTML)
|
|
}
|
|
}
|
|
|
|
func TestRichAnswerRejectsInvalidBlocksWithoutRequest(t *testing.T) {
|
|
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
t.Fatal("unexpected HTTP request")
|
|
return nil, nil
|
|
})}
|
|
api := tgapi.NewAPI(tgapi.NewAPIOpts("token").SetAPIURL("https://example.test").SetHTTPClient(client))
|
|
defer func() { _ = api.Close() }()
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
if answer := ctx.RichAnswer(tgrich.H(tgrich.Text("invalid"), 0)); answer != nil {
|
|
t.Fatal("RichAnswer() returned an answer for an invalid heading")
|
|
}
|
|
}
|
|
|
|
func TestAnswerMessageEditRich(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
withKeyboard bool
|
|
}{
|
|
{name: "content only"},
|
|
{name: "content and keyboard", withKeyboard: true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
var gotPath string
|
|
var gotBody map[string]any
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
gotPath = req.URL.Path
|
|
gotBody = readMessageContextRequest(t, req)
|
|
return messageContextResponse(`{"message_id":11,"date":1}`), nil
|
|
}))
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{
|
|
BusinessConnectionID: "business-1",
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
original := &AnswerMessage{MessageID: 7, ctx: ctx}
|
|
block := tgrich.P(tgrich.Bold(tgrich.Text("updated")))
|
|
|
|
var answer *AnswerMessage
|
|
if tt.withKeyboard {
|
|
kb := NewInlineKeyboardJSON(1).AddCallbackButton("A", "cmd")
|
|
answer = original.EditRichKeyboard(kb, block)
|
|
} else {
|
|
answer = original.EditRich(block)
|
|
}
|
|
|
|
if answer == nil {
|
|
t.Fatal("rich edit returned nil")
|
|
}
|
|
if gotPath != "/bottoken/editMessageText" {
|
|
t.Fatalf("unexpected request path: %s", gotPath)
|
|
}
|
|
if got := gotBody["chat_id"]; got != float64(42) {
|
|
t.Fatalf("chat_id = %v, want 42", got)
|
|
}
|
|
if got := gotBody["message_id"]; got != float64(7) {
|
|
t.Fatalf("message_id = %v, want 7", got)
|
|
}
|
|
if got := gotBody["business_connection_id"]; got != "business-1" {
|
|
t.Fatalf("business_connection_id = %v, want business-1", got)
|
|
}
|
|
rich, ok := gotBody["rich_message"].(map[string]any)
|
|
if !ok || rich["html"] != "<p><b>updated</b></p>" {
|
|
t.Fatalf("rich_message = %#v", gotBody["rich_message"])
|
|
}
|
|
if _, exists := gotBody["text"]; exists {
|
|
t.Fatalf("edit request unexpectedly contains text: %#v", gotBody)
|
|
}
|
|
_, hasKeyboard := gotBody["reply_markup"]
|
|
if hasKeyboard != tt.withKeyboard {
|
|
t.Fatalf("reply_markup presence = %v, want %v", hasKeyboard, tt.withKeyboard)
|
|
}
|
|
if answer.MessageID != 11 || answer.Text != "<p><b>updated</b></p>" || answer.RichHTML != answer.Text {
|
|
t.Fatalf("unexpected answer: %#v", answer)
|
|
}
|
|
if answer.ctx != ctx {
|
|
t.Fatal("edited answer lost its message context")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEditCallbackRichEditsInlineMessage(t *testing.T) {
|
|
var gotBody map[string]any
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
gotBody = readMessageContextRequest(t, req)
|
|
return messageContextResponse("true"), nil
|
|
}))
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
InlineMsgID: "inline-1",
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
kb := NewInlineKeyboardJSON(1).AddCallbackButton("A", "cmd")
|
|
|
|
answer := ctx.EditCallbackRich(kb, tgrich.P(tgrich.Text("inline")))
|
|
if answer == nil {
|
|
t.Fatal("EditCallbackRich returned nil")
|
|
}
|
|
if got := gotBody["inline_message_id"]; got != "inline-1" {
|
|
t.Fatalf("inline_message_id = %v, want inline-1", got)
|
|
}
|
|
if _, exists := gotBody["chat_id"]; exists {
|
|
t.Fatalf("inline edit unexpectedly contains chat_id: %#v", gotBody)
|
|
}
|
|
if _, exists := gotBody["business_connection_id"]; exists {
|
|
t.Fatalf("inline edit unexpectedly contains business_connection_id: %#v", gotBody)
|
|
}
|
|
rich, ok := gotBody["rich_message"].(map[string]any)
|
|
if !ok || rich["html"] != "<p>inline</p>" {
|
|
t.Fatalf("rich_message = %#v", gotBody["rich_message"])
|
|
}
|
|
if _, exists := gotBody["reply_markup"]; !exists {
|
|
t.Fatal("inline rich edit has no reply_markup")
|
|
}
|
|
if answer.MessageID != 0 || answer.Text != "<p>inline</p>" || answer.RichHTML != answer.Text {
|
|
t.Fatalf("unexpected inline answer: %#v", answer)
|
|
}
|
|
}
|
|
|
|
func TestUpsertKeyboardRichValidatesPhotoBeforeDelete(t *testing.T) {
|
|
requests := 0
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
requests++
|
|
t.Fatalf("unexpected request to %s", req.URL.Path)
|
|
return nil, nil
|
|
}))
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
CallbackMsgID: 7,
|
|
Msg: &tgapi.Message{
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
Photo: []tgapi.PhotoSize{{FileID: "photo-1"}},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
answer := ctx.UpsertKeyboardRich(nil, tgrich.H(tgrich.Text("invalid"), 0))
|
|
if answer != nil {
|
|
t.Fatalf("UpsertKeyboardRich returned an answer for invalid blocks: %#v", answer)
|
|
}
|
|
if requests != 0 {
|
|
t.Fatalf("invalid photo upsert made %d requests", requests)
|
|
}
|
|
}
|
|
|
|
func TestUpsertKeyboardRichReplacesPhotoCallback(t *testing.T) {
|
|
var paths []string
|
|
var sendBody map[string]any
|
|
api := newMessageContextTestAPI(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
paths = append(paths, req.URL.Path)
|
|
switch req.URL.Path {
|
|
case "/bottoken/deleteMessage":
|
|
return messageContextResponse("true"), nil
|
|
case "/bottoken/sendRichMessage":
|
|
sendBody = readMessageContextRequest(t, req)
|
|
return messageContextResponse(`{"message_id":12,"date":1}`), nil
|
|
default:
|
|
t.Fatalf("unexpected request path: %s", req.URL.Path)
|
|
return nil, nil
|
|
}
|
|
}))
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
CallbackMsgID: 7,
|
|
Msg: &tgapi.Message{
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
Photo: []tgapi.PhotoSize{{FileID: "photo-1"}},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
kb := NewInlineKeyboardJSON(1).AddCallbackButton("A", "cmd")
|
|
|
|
answer := ctx.UpsertKeyboardRich(kb, tgrich.P(tgrich.Text("replacement")))
|
|
if answer == nil {
|
|
t.Fatal("UpsertKeyboardRich returned nil")
|
|
}
|
|
wantPaths := []string{"/bottoken/deleteMessage", "/bottoken/sendRichMessage"}
|
|
if !reflect.DeepEqual(paths, wantPaths) {
|
|
t.Fatalf("request paths = %#v, want %#v", paths, wantPaths)
|
|
}
|
|
rich, ok := sendBody["rich_message"].(map[string]any)
|
|
if !ok || rich["html"] != "<p>replacement</p>" {
|
|
t.Fatalf("rich_message = %#v", sendBody["rich_message"])
|
|
}
|
|
if _, exists := sendBody["reply_markup"]; !exists {
|
|
t.Fatal("replacement rich message has no reply_markup")
|
|
}
|
|
if answer.MessageID != 12 || answer.Text != "<p>replacement</p>" || answer.RichHTML != answer.Text {
|
|
t.Fatalf("unexpected replacement answer: %#v", answer)
|
|
}
|
|
}
|
|
|
|
func TestAnswerPhotoIncludesDirectMessagesTopicID(t *testing.T) {
|
|
var gotBody map[string]any
|
|
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
if err := json.Unmarshal(body, &gotBody); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":{"message_id":9,"date":1}}`)),
|
|
}, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{
|
|
Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate},
|
|
DirectMessageTopic: &tgapi.DirectMessageTopic{TopicID: 77},
|
|
},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
answer := ctx.AnswerPhoto("photo-id", "caption")
|
|
if answer == nil {
|
|
t.Fatal("expected answer message")
|
|
return
|
|
}
|
|
if answer.MessageID != 9 {
|
|
t.Fatalf("unexpected message id: %d", answer.MessageID)
|
|
}
|
|
if got := gotBody["direct_messages_topic_id"]; got != float64(77) {
|
|
t.Fatalf("unexpected direct_messages_topic_id: %v", got)
|
|
}
|
|
}
|
|
|
|
func TestBindArgsBindsScalarFields(t *testing.T) {
|
|
type input struct {
|
|
ID int
|
|
Active bool
|
|
Score float64
|
|
Name string
|
|
}
|
|
|
|
ctx := &MessageContext{Args: []string{"42", "true", "3.5", "Ada", "Lovelace"}}
|
|
var got input
|
|
|
|
if err := ctx.BindArgs(&got); err != nil {
|
|
t.Fatalf("BindArgs returned error: %v", err)
|
|
}
|
|
|
|
want := input{
|
|
ID: 42,
|
|
Active: true,
|
|
Score: 3.5,
|
|
Name: "Ada Lovelace",
|
|
}
|
|
if !reflect.DeepEqual(got, want) {
|
|
t.Fatalf("unexpected bound value: got %#v want %#v", got, want)
|
|
}
|
|
}
|
|
|
|
func TestNewInlineKeyboardButtonUsesContextPayloadType(t *testing.T) {
|
|
ctx := &MessageContext{payloadType: BotPayloadBase64}
|
|
|
|
kb := NewInlineKeyboardJSON(1).
|
|
AddButton(ctx.NewInlineKeyboardButton("A").SetCallbackData("cmd", 1, "two"))
|
|
|
|
got, _, err := decodePayload(BotPayloadJSON, kb.Get().InlineKeyboard[0][0].CallbackData, false)
|
|
if err != nil {
|
|
t.Fatalf("decodePayload returned error: %v", err)
|
|
}
|
|
|
|
want := CallbackData{Command: "cmd", Args: []string{"1", "two"}}
|
|
if !reflect.DeepEqual(got, want) {
|
|
t.Fatalf("unexpected payload: got %#v want %#v", got, want)
|
|
}
|
|
}
|
|
|
|
func TestBindArgsLeavesTrailingFieldsZeroWhenArgsRunOut(t *testing.T) {
|
|
type input struct {
|
|
ID int
|
|
Reason string
|
|
Admin bool
|
|
}
|
|
|
|
ctx := &MessageContext{Args: []string{"7"}}
|
|
var got input
|
|
|
|
if err := ctx.BindArgs(&got); err != nil {
|
|
t.Fatalf("BindArgs returned error: %v", err)
|
|
}
|
|
|
|
if got.ID != 7 {
|
|
t.Fatalf("unexpected ID: got %d want 7", got.ID)
|
|
}
|
|
if got.Reason != "" {
|
|
t.Fatalf("expected zero-value Reason, got %q", got.Reason)
|
|
}
|
|
if got.Admin {
|
|
t.Fatal("expected zero-value Admin")
|
|
}
|
|
}
|
|
|
|
func TestBindArgsRejectsInvalidTargets(t *testing.T) {
|
|
ctx := &MessageContext{Args: []string{"1"}}
|
|
|
|
if err := ctx.BindArgs(nil); !errors.Is(err, ErrBindArgsTargetNotPointer) {
|
|
t.Fatalf("expected ErrBindArgsTargetNotPointer for nil target, got %v", err)
|
|
}
|
|
|
|
var notStruct int
|
|
if err := ctx.BindArgs(¬Struct); !errors.Is(err, ErrBindArgsTargetNotStruct) {
|
|
t.Fatalf("expected ErrBindArgsTargetNotStruct for non-struct target, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestBindArgsReportsConversionFailures(t *testing.T) {
|
|
type input struct {
|
|
ID int
|
|
}
|
|
|
|
ctx := &MessageContext{Args: []string{"oops"}}
|
|
var got input
|
|
|
|
err := ctx.BindArgs(&got)
|
|
if err == nil {
|
|
t.Fatal("expected BindArgs to fail")
|
|
}
|
|
if !errors.Is(err, ErrBindArgsConversion) {
|
|
t.Fatalf("expected ErrBindArgsConversion, got %v", err)
|
|
}
|
|
if !strings.Contains(err.Error(), "field ID") {
|
|
t.Fatalf("expected field name in error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestBindArgsRejectsNumericOverflow(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
arg string
|
|
dst any
|
|
}{
|
|
{name: "int8 positive", arg: "128", dst: &struct{ Value int8 }{}},
|
|
{name: "int8 negative", arg: "-129", dst: &struct{ Value int8 }{}},
|
|
{name: "uint8 positive", arg: "256", dst: &struct{ Value uint8 }{}},
|
|
{name: "uint8 negative", arg: "-1", dst: &struct{ Value uint8 }{}},
|
|
{name: "float32", arg: "3.5e39", dst: &struct{ Value float32 }{}},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
ctx := &MessageContext{Args: []string{tt.arg}}
|
|
if err := ctx.BindArgs(tt.dst); !errors.Is(err, ErrBindArgsConversion) {
|
|
t.Fatalf("expected ErrBindArgsConversion, got %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestBindArgsRejectsUnsupportedFieldTypes(t *testing.T) {
|
|
type input struct {
|
|
Tags []string
|
|
}
|
|
|
|
ctx := &MessageContext{Args: []string{"tag"}}
|
|
var got input
|
|
|
|
err := ctx.BindArgs(&got)
|
|
if err == nil {
|
|
t.Fatal("expected BindArgs to fail")
|
|
}
|
|
if !errors.Is(err, ErrBindArgsUnsupportedFieldType) {
|
|
t.Fatalf("expected ErrBindArgsUnsupportedFieldType, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestErrorDefaultStaysInternalForMessageFlow(t *testing.T) {
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
t.Fatal("unexpected HTTP request for unclassified error")
|
|
return nil, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
errorTemplate: "Error: %s",
|
|
}
|
|
|
|
// Unclassified errors must not leak to the user. Only AsUserError replies.
|
|
ctx.error(errors.New("boom"))
|
|
}
|
|
|
|
func TestErrorUserVisibleAnswersForMessageFlow(t *testing.T) {
|
|
var requests int
|
|
var gotBody map[string]any
|
|
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
requests++
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
if err := json.Unmarshal(body, &gotBody); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":{"message_id":9,"date":1}}`)),
|
|
}, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
errorTemplate: "Error: %s",
|
|
}
|
|
|
|
ctx.error(AsUserError(errors.New("boom")))
|
|
|
|
if requests != 1 {
|
|
t.Fatalf("expected one user-facing error reply, got %d requests", requests)
|
|
}
|
|
if got := gotBody["text"]; got != "Error: boom" {
|
|
t.Fatalf("unexpected error reply text: %v", got)
|
|
}
|
|
}
|
|
|
|
func TestErrorInternalSkipsUserReplyForMessageFlow(t *testing.T) {
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
t.Fatal("unexpected HTTP request for internal-only error")
|
|
return nil, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
errorTemplate: "Error: %s",
|
|
}
|
|
|
|
ctx.error(AsInternalError(errors.New("boom")))
|
|
}
|
|
|
|
func TestErrorInternalSkipsCallbackAnswer(t *testing.T) {
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
t.Fatal("unexpected callback answer request for internal-only error")
|
|
return nil, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Logger: sneklog.NewLogger(),
|
|
errorTemplate: "%s",
|
|
CallbackQueryID: "cb-1",
|
|
}
|
|
|
|
ctx.error(AsInternalError(errors.New("boom")))
|
|
}
|
|
|
|
func TestErrorUserVisibleAnswersCallback(t *testing.T) {
|
|
var requests int
|
|
var gotBody map[string]any
|
|
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
requests++
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
if err := json.Unmarshal(body, &gotBody); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":true}`)),
|
|
}, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Logger: sneklog.NewLogger(),
|
|
errorTemplate: "Oops: %s",
|
|
CallbackQueryID: "cb-1",
|
|
}
|
|
|
|
ctx.error(AsUserError(errors.New("boom")))
|
|
|
|
if requests != 1 {
|
|
t.Fatalf("expected one callback error answer, got %d requests", requests)
|
|
}
|
|
if got := gotBody["text"]; got != "Oops: boom" {
|
|
t.Fatalf("unexpected callback error text: %v", got)
|
|
}
|
|
}
|
|
|
|
func TestIsCallbackIncludesInlineCallbackTargets(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
ctx MessageContext
|
|
want bool
|
|
}{
|
|
{name: "callback query id", ctx: MessageContext{CallbackQueryID: "cb-1"}, want: true},
|
|
{name: "callback message id", ctx: MessageContext{CallbackMsgID: 12}, want: true},
|
|
{name: "inline message id", ctx: MessageContext{InlineMsgID: "inline-1"}, want: true},
|
|
{name: "not callback", ctx: MessageContext{}, want: false},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := tt.ctx.IsCallback(); got != tt.want {
|
|
t.Fatalf("IsCallback() = %v, want %v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestUpsertKeyboardEditsInlineCallback(t *testing.T) {
|
|
var requests int
|
|
var gotPath string
|
|
var gotBody map[string]any
|
|
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
requests++
|
|
gotPath = req.URL.Path
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
if err := json.Unmarshal(body, &gotBody); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":true}`)),
|
|
}, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
InlineMsgID: "inline-1",
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
kb := NewInlineKeyboardJSON(1).AddCallbackButton("A", "cmd")
|
|
|
|
answer := ctx.UpsertKeyboard("updated", kb)
|
|
if answer == nil {
|
|
t.Fatal("expected answer message")
|
|
}
|
|
if requests != 1 {
|
|
t.Fatalf("expected one edit request, got %d", requests)
|
|
}
|
|
if gotPath != "/bottoken/editMessageText" {
|
|
t.Fatalf("unexpected request path: %s", gotPath)
|
|
}
|
|
if got := gotBody["inline_message_id"]; got != "inline-1" {
|
|
t.Fatalf("unexpected inline_message_id: %v", got)
|
|
}
|
|
if got := gotBody["text"]; got != "updated" {
|
|
t.Fatalf("unexpected text: %v", got)
|
|
}
|
|
if _, ok := gotBody["reply_markup"]; !ok {
|
|
t.Fatal("expected reply_markup in edit request")
|
|
}
|
|
}
|
|
|
|
func TestAnswerRejectsEmptyMessage(t *testing.T) {
|
|
ctx := &MessageContext{
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
if answer := ctx.Answer(""); answer != nil {
|
|
t.Fatal("expected nil answer for empty message")
|
|
}
|
|
}
|
|
|
|
func TestAnswerRejectsLongMessageWithoutSendingRequest(t *testing.T) {
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
t.Fatal("unexpected HTTP request")
|
|
return nil, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
|
|
if answer := ctx.Answer(strings.Repeat("a", maxMessageTextLen+1)); answer != nil {
|
|
t.Fatal("expected nil answer for long message")
|
|
}
|
|
}
|
|
|
|
func TestValidateMessageText(t *testing.T) {
|
|
if err := validateMessageText(""); !errors.Is(err, ErrEmptyMessage) {
|
|
t.Fatalf("expected ErrEmptyMessage, got %v", err)
|
|
}
|
|
if err := validateMessageText(strings.Repeat("a", maxMessageTextLen+1)); !errors.Is(err, ErrMessageTooLong) {
|
|
t.Fatalf("expected ErrMessageTooLong, got %v", err)
|
|
}
|
|
if err := validateMessageText("ok"); err != nil {
|
|
t.Fatalf("expected nil error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestValidateCaptionText(t *testing.T) {
|
|
if err := validateCaptionText(strings.Repeat("a", maxMessageCaptionLen+1)); !errors.Is(err, ErrCaptionTooLong) {
|
|
t.Fatalf("expected ErrCaptionTooLong, got %v", err)
|
|
}
|
|
if err := validateCaptionText(""); err != nil {
|
|
t.Fatalf("expected nil error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestSplitMessageTextPreservesContent(t *testing.T) {
|
|
text := "alpha beta\n" + strings.Repeat("x", maxMessageTextLen) + " omega"
|
|
|
|
parts := SplitMessageText(text)
|
|
if len(parts) < 2 {
|
|
t.Fatalf("expected multiple parts, got %d", len(parts))
|
|
}
|
|
|
|
for i, part := range parts {
|
|
if got := len([]rune(part)); got > maxMessageTextLen {
|
|
t.Fatalf("part %d exceeded limit: %d", i, got)
|
|
}
|
|
}
|
|
|
|
if got := strings.Join(parts, ""); got != text {
|
|
t.Fatalf("split/join mismatch: got %q want %q", got, text)
|
|
}
|
|
}
|
|
|
|
func TestAnswerLongSplitsRequestsAndAttachesKeyboardToLastChunk(t *testing.T) {
|
|
var requests []map[string]any
|
|
|
|
client := &http.Client{
|
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read request body: %v", err)
|
|
}
|
|
var got map[string]any
|
|
if err := json.Unmarshal(body, &got); err != nil {
|
|
t.Fatalf("failed to decode request body: %v", err)
|
|
}
|
|
requests = append(requests, got)
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(`{"ok":true,"result":{"message_id":9,"date":1}}`)),
|
|
}, nil
|
|
}),
|
|
}
|
|
|
|
api := tgapi.NewAPI(
|
|
tgapi.NewAPIOpts("token").
|
|
SetAPIURL("https://example.test").
|
|
SetHTTPClient(client),
|
|
)
|
|
defer func() {
|
|
if err := api.Close(); err != nil {
|
|
t.Fatalf("Close returned error: %v", err)
|
|
}
|
|
}()
|
|
|
|
ctx := &MessageContext{
|
|
API: api,
|
|
Msg: &tgapi.Message{Chat: &tgapi.Chat{ID: 42, Type: tgapi.ChatTypePrivate}},
|
|
Logger: sneklog.NewLogger(),
|
|
}
|
|
kb := NewInlineKeyboardJSON(1).AddCallbackButton("A", "cmd")
|
|
text := strings.Repeat("a", maxMessageTextLen) + " " + strings.Repeat("b", 32)
|
|
|
|
messages := ctx.KeyboardLong(text, kb)
|
|
if got := len(messages); got != 2 {
|
|
t.Fatalf("expected 2 sent messages, got %d", got)
|
|
}
|
|
if got := len(requests); got != 2 {
|
|
t.Fatalf("expected 2 requests, got %d", got)
|
|
}
|
|
if _, ok := requests[0]["reply_markup"]; ok {
|
|
t.Fatal("did not expect keyboard on first chunk")
|
|
}
|
|
if _, ok := requests[1]["reply_markup"]; !ok {
|
|
t.Fatal("expected keyboard on final chunk")
|
|
}
|
|
|
|
gotTexts := []string{requests[0]["text"].(string), requests[1]["text"].(string)}
|
|
wantTexts := SplitMessageText(text)
|
|
if !reflect.DeepEqual(gotTexts, wantTexts) {
|
|
t.Fatalf("unexpected chunk texts: got %q want %q", gotTexts, wantTexts)
|
|
}
|
|
}
|