Files
dobotai-platform/internal/channels/dingtalk/stream_test.go

740 lines
21 KiB
Go

package dingtalk
import (
"context"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
)
type blockingCallbackHandler struct {
started chan struct{}
release chan struct{}
mu sync.Mutex
calls int
}
func (h *blockingCallbackHandler) Handle(_ context.Context, _ BotCallback) error {
h.mu.Lock()
h.calls++
if h.calls == 1 {
close(h.started)
}
h.mu.Unlock()
<-h.release
return nil
}
func (h *blockingCallbackHandler) callCount() int {
h.mu.Lock()
defer h.mu.Unlock()
return h.calls
}
func TestAsyncChatCallbackAcknowledgesBeforeWorkAndDeduplicatesInflightMessage(t *testing.T) {
handler := &blockingCallbackHandler{started: make(chan struct{}), release: make(chan struct{})}
router := newAsyncChatCallbackRouter(handler)
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "text",
MsgId: "same-message",
SenderStaffId: "staff-1",
SessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession?session=test",
Text: chatbot.BotCallbackDataTextModel{Content: "hello"},
}
done := make(chan error, 1)
go func() {
_, err := router(context.Background(), data)
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(100 * time.Millisecond):
t.Fatal("callback ACK waited for slow QA work")
}
select {
case <-handler.started:
case <-time.After(time.Second):
t.Fatal("async handler did not start")
}
if _, err := router(context.Background(), data); err != nil {
t.Fatal(err)
}
time.Sleep(20 * time.Millisecond)
if got := handler.callCount(); got != 1 {
t.Fatalf("same in-flight MsgID handled %d times, want 1", got)
}
close(handler.release)
}
func TestStreamConfigValidate(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cfg StreamConfig
wantErr bool
wantOn bool
errSubstr string
}{
{
name: "all empty is disabled without error",
cfg: StreamConfig{},
wantErr: false,
wantOn: false,
},
{
name: "whitespace only is disabled without error",
cfg: StreamConfig{ClientID: " ", ClientSecret: "\t", TenantKey: " "},
wantErr: false,
wantOn: false,
},
{
name: "client id only is an error",
cfg: StreamConfig{ClientID: "id"},
wantErr: true,
errSubstr: "client secret",
},
{
name: "client secret only is an error",
cfg: StreamConfig{ClientSecret: "secret"},
wantErr: true,
errSubstr: "client id",
},
{
name: "credentials without tenant key is an error",
cfg: StreamConfig{ClientID: "id", ClientSecret: "secret"},
wantErr: true,
errSubstr: "tenant key",
},
{
name: "tenant key without credentials is an error",
cfg: StreamConfig{TenantKey: "acme"},
wantErr: true,
errSubstr: "client id",
},
{
name: "all three present is enabled",
cfg: StreamConfig{ClientID: "id", ClientSecret: "secret", TenantKey: "acme"},
wantErr: false,
wantOn: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := tt.cfg.Validate()
if tt.wantErr && err == nil {
t.Fatalf("Validate() = nil, want error containing %q", tt.errSubstr)
}
if !tt.wantErr && err != nil {
t.Fatalf("Validate() = %v, want nil", err)
}
if tt.wantErr && tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {
t.Fatalf("Validate() error = %q, want substring %q", err.Error(), tt.errSubstr)
}
if got := tt.cfg.Enabled(); got != tt.wantOn {
t.Fatalf("Enabled() = %v, want %v", got, tt.wantOn)
}
})
}
}
func TestBotCallbackFromSDK(t *testing.T) {
t.Parallel()
t.Run("nil data returns error", func(t *testing.T) {
t.Parallel()
if _, err := BotCallbackFromSDK(nil); err == nil {
t.Fatal("BotCallbackFromSDK(nil) = nil error, want error")
}
})
t.Run("maps every field one to one", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "2",
ConversationId: "cid123",
Msgtype: "text",
MsgId: "msg-9",
SenderNick: "Alice",
SenderStaffId: "staff-1",
SenderId: "sender-1",
IsInAtList: true,
SessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession?session=abc",
Text: chatbot.BotCallbackDataTextModel{Content: " 你好 "},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v, want nil", err)
}
want := BotCallback{
ConversationType: "2",
ConversationID: "cid123",
Msgtype: "text",
MsgID: "msg-9",
SenderNick: "Alice",
SenderStaffID: "staff-1",
SenderID: "sender-1",
IsInAtList: true,
SessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession?session=abc",
Text: " 你好 ",
}
if !reflect.DeepEqual(cb, want) {
t.Fatalf("BotCallbackFromSDK() = %+v, want %+v", cb, want)
}
})
t.Run("text content is not trimmed by conversion", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "text",
MsgId: "m",
Text: chatbot.BotCallbackDataTextModel{Content: ""},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Text != "" {
t.Fatalf("Text = %q, want empty", cb.Text)
}
})
}
func TestBotCallbackFromSDKLinkCardPromotesTrustedURLToText(t *testing.T) {
t.Parallel()
const notableURL = "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view"
tests := []struct {
name string
content interface{}
}{
{name: "direct content", content: map[string]interface{}{"title": "FAQ表", "messageUrl": notableURL}},
{name: "nested callback envelope", content: map[string]interface{}{"content": map[string]interface{}{"messageUrl": notableURL}}},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
cb, err := BotCallbackFromSDK(&chatbot.BotCallbackDataModel{Msgtype: "link", MsgId: "link-1", Content: tt.content})
if err != nil {
t.Fatal(err)
}
if cb.Msgtype != "text" || cb.Text != notableURL {
t.Fatalf("callback=%+v, want promoted text URL", cb)
}
})
}
}
func TestBotCallbackFromSDKLinkCardRejectsUnsafeURL(t *testing.T) {
t.Parallel()
cb, err := BotCallbackFromSDK(&chatbot.BotCallbackDataModel{
Msgtype: "link",
MsgId: "link-unsafe",
Content: map[string]interface{}{"messageUrl": "javascript:alert(1)"},
})
if err != nil {
t.Fatal(err)
}
if cb.Msgtype != "link" || cb.Text != "" {
t.Fatalf("unsafe link must not be promoted: %+v", cb)
}
}
func TestBotCallbackFromSDKPicture(t *testing.T) {
t.Parallel()
t.Run("extracts downloadCode from picture content", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "picture",
MsgId: "msg-pic-1",
Content: map[string]interface{}{
"downloadCode": " abc123 ",
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "abc123" {
t.Fatalf("DownloadCode = %q, want trimmed abc123", cb.DownloadCode)
}
if cb.Text != "" {
t.Fatalf("Text = %q, want empty for picture", cb.Text)
}
})
t.Run("malformed content keeps picture with empty downloadCode", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "picture",
MsgId: "msg-pic-2",
Content: "not-a-map",
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture (never downgrade)", cb.Msgtype)
}
if cb.DownloadCode != "" {
t.Fatalf("DownloadCode = %q, want empty", cb.DownloadCode)
}
})
t.Run("missing downloadCode keeps picture", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "picture",
MsgId: "msg-pic-3",
Content: map[string]interface{}{
"content": map[string]interface{}{},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "" {
t.Fatalf("DownloadCode = %q, want empty", cb.DownloadCode)
}
})
t.Run("text regression: Msgtype normalized", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: " TEXT ",
MsgId: "msg-t-1",
Text: chatbot.BotCallbackDataTextModel{Content: "hello"},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "text" {
t.Fatalf("Msgtype = %q, want normalized text", cb.Msgtype)
}
if cb.Text != "hello" {
t.Fatalf("Text = %q, want hello", cb.Text)
}
})
t.Run("nil content keeps picture", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "picture",
MsgId: "msg-pic-4",
Content: nil,
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "" {
t.Fatalf("DownloadCode = %q, want empty", cb.DownloadCode)
}
})
}
func mustTestHandler(t *testing.T) *Handler {
t.Helper()
return newTestHandler(t, &fakeQA{}, &fakeReply{})
}
func TestBotCallbackFromSDKRichText(t *testing.T) {
t.Parallel()
t.Run("direct Content richText text+picture", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-1",
Content: map[string]interface{}{
"richText": []interface{}{
map[string]interface{}{"text": " 问题描述 "},
map[string]interface{}{"type": "picture", "downloadCode": " code-abc "},
},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "code-abc" {
t.Fatalf("DownloadCode = %q, want code-abc", cb.DownloadCode)
}
if cb.Text != "问题描述" {
t.Fatalf("Text = %q, want 问题描述 (trimmed text segments joined)", cb.Text)
}
})
t.Run("nested content envelope richText", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-2",
Content: map[string]interface{}{
"content": map[string]interface{}{
"richText": []interface{}{
map[string]interface{}{"text": "描述"},
map[string]interface{}{"type": "picture", "downloadCode": "code-xyz"},
},
},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "code-xyz" {
t.Fatalf("DownloadCode = %q, want code-xyz", cb.DownloadCode)
}
if cb.Text != "描述" {
t.Fatalf("Text = %q, want 描述", cb.Text)
}
})
t.Run("multi text segments preserve order", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-3",
Content: []interface{}{
map[string]interface{}{"text": "第一段"},
map[string]interface{}{"text": " 第二段 "},
map[string]interface{}{"type": "picture", "downloadCode": "code-multi"},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.Text != "第一段\n第二段" {
t.Fatalf("Text = %q, want joined with newline", cb.Text)
}
})
t.Run("all picture downloadCodes collected in order", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-4",
Content: []interface{}{
map[string]interface{}{"type": "picture", "downloadCode": " code-first "},
map[string]interface{}{"type": "picture", "downloadCode": "code-second"},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.DownloadCode != "code-first" {
t.Fatalf("DownloadCode = %q, want first code-first", cb.DownloadCode)
}
if len(cb.DownloadCodes) != 2 || cb.DownloadCodes[0] != "code-first" || cb.DownloadCodes[1] != "code-second" {
t.Fatalf("DownloadCodes = %+v, want [code-first code-second]", cb.DownloadCodes)
}
})
t.Run("picture item missing downloadCode still picture", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-5",
Content: []interface{}{
map[string]interface{}{"text": "看看这张图"},
map[string]interface{}{"type": "picture"},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture (never downgrade)", cb.Msgtype)
}
if cb.DownloadCode != "" {
t.Fatalf("DownloadCode = %q, want empty", cb.DownloadCode)
}
if cb.Text != "看看这张图" {
t.Fatalf("Text = %q, want 看看这张图", cb.Text)
}
})
t.Run("pure text richText becomes text", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-6",
Content: []interface{}{
map[string]interface{}{"text": "你好"},
map[string]interface{}{"text": " 世界 "},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "text" {
t.Fatalf("Msgtype = %q, want text", cb.Msgtype)
}
if cb.Text != "你好\n世界" {
t.Fatalf("Text = %q, want joined text", cb.Text)
}
if cb.DownloadCode != "" {
t.Fatalf("DownloadCode = %q, want empty", cb.DownloadCode)
}
})
t.Run("malformed richText keeps richtext", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-7",
Content: "not-a-list",
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "richtext" {
t.Fatalf("Msgtype = %q, want richtext (malformed, keep original)", cb.Msgtype)
}
})
t.Run("empty richText keeps richtext", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-8",
Content: []interface{}{},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "richtext" {
t.Fatalf("Msgtype = %q, want richtext (empty, keep original)", cb.Msgtype)
}
})
t.Run("richText with type case normalization", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: " RICHTEXT ",
MsgId: "msg-rt-9",
Content: []interface{}{
map[string]interface{}{"text": "hello"},
map[string]interface{}{"TYPE": " PICTURE ", "DOWNLOADCODE": "code-case"},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "code-case" {
t.Fatalf("DownloadCode = %q, want code-case", cb.DownloadCode)
}
if cb.Text != "hello" {
t.Fatalf("Text = %q, want hello", cb.Text)
}
})
t.Run("richText skips empty text segments", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "richText",
MsgId: "msg-rt-10",
Content: []interface{}{
map[string]interface{}{"text": " "},
map[string]interface{}{"text": "有效内容"},
map[string]interface{}{"text": ""},
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "text" {
t.Fatalf("Msgtype = %q, want text", cb.Msgtype)
}
if cb.Text != "有效内容" {
t.Fatalf("Text = %q, want 有效内容 (empty segments skipped)", cb.Text)
}
})
t.Run("text regression still works", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "text",
MsgId: "msg-t-2",
Text: chatbot.BotCallbackDataTextModel{Content: "hello"},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "text" {
t.Fatalf("Msgtype = %q, want text", cb.Msgtype)
}
if cb.Text != "hello" {
t.Fatalf("Text = %q, want hello", cb.Text)
}
})
t.Run("picture regression still works", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "picture",
MsgId: "msg-p-2",
Content: map[string]interface{}{
"downloadCode": "regression-code",
},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.Msgtype != "picture" {
t.Fatalf("Msgtype = %q, want picture", cb.Msgtype)
}
if cb.DownloadCode != "regression-code" {
t.Fatalf("DownloadCode = %q, want regression-code", cb.DownloadCode)
}
})
}
func TestBotCallbackFromSDKConversationTitle(t *testing.T) {
t.Parallel()
t.Run("conversation title survives conversion", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "2",
ConversationId: "cid123",
Msgtype: "text",
MsgId: "msg-1",
ConversationTitle: "项目讨论群",
Text: chatbot.BotCallbackDataTextModel{Content: "hello"},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.ConversationTitle != "项目讨论群" {
t.Fatalf("ConversationTitle = %q, want 项目讨论群", cb.ConversationTitle)
}
})
t.Run("conversation title empty for direct", func(t *testing.T) {
t.Parallel()
data := &chatbot.BotCallbackDataModel{
ConversationType: "1",
Msgtype: "text",
MsgId: "msg-2",
Text: chatbot.BotCallbackDataTextModel{Content: "hi"},
}
cb, err := BotCallbackFromSDK(data)
if err != nil {
t.Fatalf("BotCallbackFromSDK() error = %v", err)
}
if cb.ConversationTitle != "" {
t.Fatalf("ConversationTitle = %q, want empty for direct", cb.ConversationTitle)
}
})
}
func TestNewStreamClientValidation(t *testing.T) {
t.Parallel()
h := mustTestHandler(t)
t.Run("nil handler is an error", func(t *testing.T) {
t.Parallel()
cfg := StreamConfig{ClientID: "id", ClientSecret: "secret", TenantKey: "acme"}
if _, err := NewStreamClient(cfg, nil); err == nil {
t.Fatal("NewStreamClient with nil handler = nil error, want error")
}
})
t.Run("invalid config is an error", func(t *testing.T) {
t.Parallel()
if _, err := NewStreamClient(StreamConfig{}, h); err == nil {
t.Fatal("NewStreamClient with empty config = nil error, want error")
}
})
t.Run("valid config keeps SDK auto reconnect on until Close disables it", func(t *testing.T) {
t.Parallel()
cfg := StreamConfig{ClientID: "id", ClientSecret: "secret", TenantKey: "acme"}
sc, err := NewStreamClient(cfg, h)
if err != nil {
t.Fatalf("NewStreamClient() error = %v, want nil", err)
}
if sc == nil || sc.inner == nil {
t.Fatal("NewStreamClient() returned nil client")
}
// The SDK default is AutoReconnect=true; keep it so runtime
// disconnects reconnect automatically.
if !sc.inner.AutoReconnect {
t.Fatal("AutoReconnect = false after NewStreamClient, want true (SDK default must be kept)")
}
// Close must flip AutoReconnect off first so the SDK processLoop
// does not reconnect a closed connection.
sc.Close()
if sc.inner.AutoReconnect {
t.Fatal("AutoReconnect = true after Close, want false (Close must stay closed)")
}
// Closing again must remain a safe no-op.
sc.Close()
})
}