package notify import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/require" "github.com/tamakyi/TamaBox/internal/conf" ) // TestSendWebhookPostsJSON 验证 webhook 发送的是带 content/event/title 的 JSON, // 且能正确 POST 到目标 URL。 func TestSendWebhookPostsJSON(t *testing.T) { var got map[string]interface{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { require.Equal(t, http.MethodPost, r.Method) require.Equal(t, "application/json", r.Header.Get("Content-Type")) require.NoError(t, json.NewDecoder(r.Body).Decode(&got)) w.WriteHeader(http.StatusOK) })) defer srv.Close() sendWebhook(t.Context(), srv.URL, event{ Event: "new_question", Title: "新的提问", Body: "你好", Link: "https://example.com/_/box/1", Time: "2026-10-29 19:00:00", }) require.Equal(t, "new_question", got["event"]) require.Equal(t, "新的提问", got["title"]) require.Equal(t, "你好", got["body"]) require.NotEmpty(t, got["content"], "Discord 兼容的 content 字段必须有") } // TestSendWebhookSkipsWhenUnconfigured 未配置 webhook_url 时 Send 静默跳过(不 panic)。 func TestSendWebhookSkipsWhenUnconfigured(t *testing.T) { conf.Notify.WebhookURL = "" defer func() { conf.Notify.WebhookURL = "" }() // 不应 panic,也不应发起任何请求。 Send(t.Context(), "new_question", "t", "b", "l") } // TestSendToTelegramSkipsWhenUnconfigured chatID 或 bot token 为空时静默跳过。 func TestSendToTelegramSkipsWhenUnconfigured(t *testing.T) { conf.Notify.TelegramBotToken = "" defer func() { conf.Notify.TelegramBotToken = "" }() SendToTelegram(t.Context(), "", "hello") // 空 chatID SendToTelegram(t.Context(), "123", "hello") // 空 token }