| 1 |
package zulip |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"errors" |
| 7 |
"io" |
| 8 |
"net/http" |
| 9 |
"net/url" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"github.com/jarcoal/httpmock" |
| 13 |
"github.com/onsi/gomega" |
| 14 |
"github.com/stretchr/testify/mock" |
| 15 |
|
| 16 |
ginkgo "github.com/onsi/ginkgo/v2" |
| 17 |
|
| 18 |
"github.com/nicholas-fedor/shoutrrr/internal/testutils" |
| 19 |
"github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 20 |
"github.com/nicholas-fedor/shoutrrr/pkg/services/chat/zulip/mocks" |
| 21 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 22 |
) |
| 23 |
|
| 24 |
// mockLogger is a test helper that implements StdLogger interface. |
| 25 |
type mockLogger struct{} |
| 26 |
|
| 27 |
var _ = ginkgo.Describe("Service Unit Tests", func() { |
| 28 |
ginkgo.Describe("NewDefaultHTTPClient", func() { |
| 29 |
ginkgo.It("should create a non-nil client", func() { |
| 30 |
client := NewDefaultHTTPClient() |
| 31 |
|
| 32 |
gomega.Expect(client).NotTo(gomega.BeNil()) |
| 33 |
}) |
| 34 |
|
| 35 |
ginkgo.It("should create a client with the expected timeout", func() { |
| 36 |
client := NewDefaultHTTPClient() |
| 37 |
|
| 38 |
gomega.Expect(client.client.Timeout).To(gomega.Equal(defaultHTTPTimeout)) |
| 39 |
}) |
| 40 |
}) |
| 41 |
|
| 42 |
ginkgo.Describe("DefaultHTTPClient.Do", func() { |
| 43 |
var client *DefaultHTTPClient |
| 44 |
|
| 45 |
ginkgo.BeforeEach(func() { |
| 46 |
client = NewDefaultHTTPClient() |
| 47 |
httpmock.ActivateNonDefault(client.client) |
| 48 |
}) |
| 49 |
|
| 50 |
ginkgo.AfterEach(func() { |
| 51 |
httpmock.DeactivateAndReset() |
| 52 |
}) |
| 53 |
|
| 54 |
ginkgo.It("should successfully make an HTTP request", func() { |
| 55 |
httpmock.RegisterResponder(http.MethodPost, "https://zulip.example.com/api/v1/messages", |
| 56 |
httpmock.NewStringResponder(http.StatusOK, `{"result": "success"}`)) |
| 57 |
|
| 58 |
req, err := http.NewRequest(http.MethodPost, "https://zulip.example.com/api/v1/messages", http.NoBody) |
| 59 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 60 |
|
| 61 |
resp, err := client.Do(req) |
| 62 |
|
| 63 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 64 |
gomega.Expect(resp.StatusCode).To(gomega.Equal(http.StatusOK)) |
| 65 |
}) |
| 66 |
|
| 67 |
ginkgo.It("should return an error when the request fails", func() { |
| 68 |
httpmock.RegisterResponder(http.MethodPost, "https://zulip.example.com/api/v1/messages", |
| 69 |
httpmock.NewErrorResponder(errors.New("network error"))) |
| 70 |
|
| 71 |
req, err := http.NewRequest(http.MethodPost, "https://zulip.example.com/api/v1/messages", http.NoBody) |
| 72 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 73 |
|
| 74 |
resp, err := client.Do(req) |
| 75 |
|
| 76 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 77 |
gomega.Expect(resp).To(gomega.BeNil()) |
| 78 |
gomega.Expect(err.Error()).To(gomega.ContainSubstring("performing HTTP request")) |
| 79 |
}) |
| 80 |
}) |
| 81 |
|
| 82 |
ginkgo.Describe("GetID", func() { |
| 83 |
ginkgo.It("should return the zulip scheme identifier", func() { |
| 84 |
svc := &Service{} |
| 85 |
|
| 86 |
gomega.Expect(svc.GetID()).To(gomega.Equal(Scheme)) |
| 87 |
}) |
| 88 |
|
| 89 |
ginkgo.It("should always return 'zulip' regardless of service state", func() { |
| 90 |
svc := &Service{ |
| 91 |
Config: &Config{ |
| 92 |
Host: "zulip.example.com", |
| 93 |
}, |
| 94 |
} |
| 95 |
|
| 96 |
gomega.Expect(svc.GetID()).To(gomega.Equal("zulip")) |
| 97 |
}) |
| 98 |
}) |
| 99 |
|
| 100 |
ginkgo.Describe("Initialize", func() { |
| 101 |
ginkgo.It("should initialize from a valid URL", func() { |
| 102 |
svc := &Service{} |
| 103 |
serviceURL := testutils.URLMust("zulip://[email protected]:[email protected]?stream=general&topic=announcements") |
| 104 |
|
| 105 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 106 |
|
| 107 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 108 |
gomega.Expect(svc.Config).NotTo(gomega.BeNil()) |
| 109 |
gomega.Expect(svc.Config.BotMail).To(gomega.Equal("[email protected]")) |
| 110 |
gomega.Expect(svc.Config.BotKey).To(gomega.Equal("secret-key")) |
| 111 |
gomega.Expect(svc.Config.Host).To(gomega.Equal("zulip.example.com")) |
| 112 |
gomega.Expect(svc.Config.Stream).To(gomega.Equal("general")) |
| 113 |
gomega.Expect(svc.Config.Topic).To(gomega.Equal("announcements")) |
| 114 |
gomega.Expect(svc.HTTPClient).NotTo(gomega.BeNil()) |
| 115 |
gomega.Expect(svc.contentMaxSize).To(gomega.Equal(contentMaxSize)) |
| 116 |
gomega.Expect(svc.topicMaxLength).To(gomega.Equal(topicMaxLength)) |
| 117 |
}) |
| 118 |
|
| 119 |
ginkgo.It("should set the logger", func() { |
| 120 |
svc := &Service{} |
| 121 |
logger := testutils.TestLogger() |
| 122 |
serviceURL := testutils.URLMust("zulip://[email protected]:[email protected]") |
| 123 |
|
| 124 |
err := svc.Initialize(serviceURL, logger) |
| 125 |
|
| 126 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 127 |
gomega.Expect(svc.Logger).NotTo(gomega.BeNil()) |
| 128 |
}) |
| 129 |
|
| 130 |
ginkgo.It("should return an error for URL with missing bot mail", func() { |
| 131 |
svc := &Service{} |
| 132 |
serviceURL := testutils.URLMust("zulip://:[email protected]") |
| 133 |
|
| 134 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 135 |
|
| 136 |
gomega.Expect(err).To(gomega.MatchError(ErrMissingBotMail)) |
| 137 |
}) |
| 138 |
|
| 139 |
ginkgo.It("should return an error for URL with missing API key", func() { |
| 140 |
svc := &Service{} |
| 141 |
serviceURL := testutils.URLMust("zulip://[email protected]@zulip.example.com") |
| 142 |
|
| 143 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 144 |
|
| 145 |
gomega.Expect(err).To(gomega.MatchError(ErrMissingAPIKey)) |
| 146 |
}) |
| 147 |
|
| 148 |
ginkgo.It("should return an error for URL with missing host", func() { |
| 149 |
svc := &Service{} |
| 150 |
serviceURL := testutils.URLMust("zulip://[email protected]:secret-key@") |
| 151 |
|
| 152 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 153 |
|
| 154 |
gomega.Expect(err).To(gomega.MatchError(ErrMissingHost)) |
| 155 |
}) |
| 156 |
}) |
| 157 |
|
| 158 |
ginkgo.Describe("Send", func() { |
| 159 |
ginkgo.It("should send a message successfully", func() { |
| 160 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 161 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 162 |
StatusCode: http.StatusOK, |
| 163 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 164 |
}, nil).Once() |
| 165 |
|
| 166 |
service := newTestService(mockClient) |
| 167 |
|
| 168 |
err := service.Send("Test message", nil) |
| 169 |
|
| 170 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 171 |
}) |
| 172 |
|
| 173 |
ginkgo.It("should return an error when HTTP client fails", func() { |
| 174 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 175 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(nil, errors.New("network error")).Once() |
| 176 |
|
| 177 |
service := newTestService(mockClient) |
| 178 |
|
| 179 |
err := service.Send("Test message", nil) |
| 180 |
|
| 181 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 182 |
gomega.Expect(err.Error()).To(gomega.ContainSubstring("making HTTP POST request")) |
| 183 |
}) |
| 184 |
|
| 185 |
ginkgo.It("should return an error for non-200 response status", func() { |
| 186 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 187 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 188 |
StatusCode: http.StatusUnauthorized, |
| 189 |
Body: io.NopCloser(strings.NewReader("")), |
| 190 |
}, nil).Once() |
| 191 |
|
| 192 |
service := newTestService(mockClient) |
| 193 |
|
| 194 |
err := service.Send("Test message", nil) |
| 195 |
|
| 196 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 197 |
gomega.Expect(err).To(gomega.MatchError(gomega.ContainSubstring("401"))) |
| 198 |
}) |
| 199 |
|
| 200 |
ginkgo.It("should return an error when topic exceeds max length", func() { |
| 201 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 202 |
|
| 203 |
service := newTestService(mockClient) |
| 204 |
longTopic := strings.Repeat("a", topicMaxLength+1) |
| 205 |
|
| 206 |
err := service.Send("Test message", &types.Params{"topic": longTopic}) |
| 207 |
|
| 208 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 209 |
gomega.Expect(err).To(gomega.MatchError(ErrTopicTooLong)) |
| 210 |
}) |
| 211 |
|
| 212 |
ginkgo.It("should accept topic at exactly max length", func() { |
| 213 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 214 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 215 |
StatusCode: http.StatusOK, |
| 216 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 217 |
}, nil).Once() |
| 218 |
|
| 219 |
service := newTestService(mockClient) |
| 220 |
exactTopic := strings.Repeat("a", topicMaxLength) |
| 221 |
|
| 222 |
err := service.Send("Test message", &types.Params{"topic": exactTopic}) |
| 223 |
|
| 224 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 225 |
}) |
| 226 |
|
| 227 |
ginkgo.It("should count topic length in runes, not bytes", func() { |
| 228 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 229 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 230 |
StatusCode: http.StatusOK, |
| 231 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 232 |
}, nil).Once() |
| 233 |
|
| 234 |
service := newTestService(mockClient) |
| 235 |
// 60 multi-byte characters (3 bytes each = 180 bytes, but only 60 runes) |
| 236 |
unicodeTopic := strings.Repeat("日", topicMaxLength) //nolint:gosmopolitan // unicode topic test |
| 237 |
|
| 238 |
err := service.Send("Test message", &types.Params{"topic": unicodeTopic}) |
| 239 |
|
| 240 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 241 |
}) |
| 242 |
|
| 243 |
ginkgo.It("should reject topic exceeding max length in runes", func() { |
| 244 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 245 |
|
| 246 |
service := newTestService(mockClient) |
| 247 |
// 61 multi-byte characters = 61 runes > 60 max |
| 248 |
unicodeTopic := strings.Repeat("日", topicMaxLength+1) //nolint:gosmopolitan // unicode topic test |
| 249 |
|
| 250 |
err := service.Send("Test message", &types.Params{"topic": unicodeTopic}) |
| 251 |
|
| 252 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 253 |
gomega.Expect(err).To(gomega.MatchError(ErrTopicTooLong)) |
| 254 |
}) |
| 255 |
|
| 256 |
ginkgo.It("should use title as topic when topic is not set", func() { |
| 257 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 258 |
|
| 259 |
var capturedReq *http.Request |
| 260 |
|
| 261 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 262 |
capturedReq = args.Get(0).(*http.Request) |
| 263 |
}).Return(&http.Response{ |
| 264 |
StatusCode: http.StatusOK, |
| 265 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 266 |
}, nil).Once() |
| 267 |
|
| 268 |
service := &Service{ |
| 269 |
Config: &Config{ |
| 270 |
BotMail: "[email protected]", |
| 271 |
BotKey: "secret-key", |
| 272 |
Host: "zulip.example.com", |
| 273 |
Stream: "general", |
| 274 |
}, |
| 275 |
HTTPClient: mockClient, |
| 276 |
} |
| 277 |
service.SetLogger(&mockLogger{}) |
| 278 |
service.pkr = format.NewPropKeyResolver(service.Config) |
| 279 |
service.contentMaxSize = contentMaxSize |
| 280 |
service.topicMaxLength = topicMaxLength |
| 281 |
service.mu.Do(func() {}) |
| 282 |
|
| 283 |
err := service.Send("Test message", &types.Params{"title": "My Topic"}) |
| 284 |
|
| 285 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 286 |
|
| 287 |
body, _ := io.ReadAll(capturedReq.Body) |
| 288 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("topic=My+Topic")) |
| 289 |
|
| 290 |
mockClient.AssertExpectations(ginkgo.GinkgoT()) |
| 291 |
}) |
| 292 |
|
| 293 |
ginkgo.It("should not override topic with title when both are set", func() { |
| 294 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 295 |
|
| 296 |
var capturedReq *http.Request |
| 297 |
|
| 298 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 299 |
capturedReq = args.Get(0).(*http.Request) |
| 300 |
}).Return(&http.Response{ |
| 301 |
StatusCode: http.StatusOK, |
| 302 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 303 |
}, nil).Once() |
| 304 |
|
| 305 |
service := newTestService(mockClient) |
| 306 |
|
| 307 |
err := service.Send("Test message", &types.Params{"title": "Notification Title"}) |
| 308 |
|
| 309 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 310 |
|
| 311 |
body, _ := io.ReadAll(capturedReq.Body) |
| 312 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("topic=announcements")) |
| 313 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("content=Notification+Title")) |
| 314 |
|
| 315 |
mockClient.AssertExpectations(ginkgo.GinkgoT()) |
| 316 |
}) |
| 317 |
|
| 318 |
ginkgo.It("should prepend title to message when both topic and title are set", func() { |
| 319 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 320 |
|
| 321 |
var capturedReq *http.Request |
| 322 |
|
| 323 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 324 |
capturedReq = args.Get(0).(*http.Request) |
| 325 |
}).Return(&http.Response{ |
| 326 |
StatusCode: http.StatusOK, |
| 327 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 328 |
}, nil).Once() |
| 329 |
|
| 330 |
service := newTestService(mockClient) |
| 331 |
|
| 332 |
err := service.Send("body text", &types.Params{"title": "My Title"}) |
| 333 |
|
| 334 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 335 |
|
| 336 |
body, _ := io.ReadAll(capturedReq.Body) |
| 337 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("topic=announcements")) |
| 338 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("content=My+Title%0A%0Abody+text")) |
| 339 |
|
| 340 |
mockClient.AssertExpectations(ginkgo.GinkgoT()) |
| 341 |
}) |
| 342 |
|
| 343 |
ginkgo.It("should return error when title used as topic fallback exceeds max length", func() { |
| 344 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 345 |
|
| 346 |
service := &Service{ |
| 347 |
Config: &Config{ |
| 348 |
BotMail: "[email protected]", |
| 349 |
BotKey: "secret-key", |
| 350 |
Host: "zulip.example.com", |
| 351 |
Stream: "general", |
| 352 |
}, |
| 353 |
HTTPClient: mockClient, |
| 354 |
} |
| 355 |
service.SetLogger(&mockLogger{}) |
| 356 |
service.pkr = format.NewPropKeyResolver(service.Config) |
| 357 |
service.contentMaxSize = contentMaxSize |
| 358 |
service.topicMaxLength = topicMaxLength |
| 359 |
service.mu.Do(func() {}) |
| 360 |
|
| 361 |
longTitle := strings.Repeat("a", topicMaxLength+1) |
| 362 |
err := service.Send("Test message", &types.Params{"title": longTitle}) |
| 363 |
|
| 364 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 365 |
gomega.Expect(err).To(gomega.MatchError(ErrTopicTooLong)) |
| 366 |
}) |
| 367 |
|
| 368 |
ginkgo.It("should handle empty title param gracefully", func() { |
| 369 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 370 |
|
| 371 |
var capturedReq *http.Request |
| 372 |
|
| 373 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 374 |
capturedReq = args.Get(0).(*http.Request) |
| 375 |
}).Return(&http.Response{ |
| 376 |
StatusCode: http.StatusOK, |
| 377 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 378 |
}, nil).Once() |
| 379 |
|
| 380 |
service := newTestService(mockClient) |
| 381 |
|
| 382 |
err := service.Send("Test message", &types.Params{"title": ""}) |
| 383 |
|
| 384 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 385 |
|
| 386 |
body, _ := io.ReadAll(capturedReq.Body) |
| 387 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("topic=announcements")) |
| 388 |
|
| 389 |
mockClient.AssertExpectations(ginkgo.GinkgoT()) |
| 390 |
}) |
| 391 |
|
| 392 |
ginkgo.It("should return an error when message exceeds max size", func() { |
| 393 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 394 |
|
| 395 |
service := newTestService(mockClient) |
| 396 |
longMessage := strings.Repeat("a", contentMaxSize+1) |
| 397 |
|
| 398 |
err := service.Send(longMessage, nil) |
| 399 |
|
| 400 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 401 |
gomega.Expect(err).To(gomega.MatchError(ErrMessageTooLong)) |
| 402 |
}) |
| 403 |
|
| 404 |
ginkgo.It("should accept message at exactly max size", func() { |
| 405 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 406 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 407 |
StatusCode: http.StatusOK, |
| 408 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 409 |
}, nil).Once() |
| 410 |
|
| 411 |
service := newTestService(mockClient) |
| 412 |
exactMessage := strings.Repeat("a", contentMaxSize) |
| 413 |
|
| 414 |
err := service.Send(exactMessage, nil) |
| 415 |
|
| 416 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 417 |
}) |
| 418 |
|
| 419 |
ginkgo.It("should error for invalid message type", func() { |
| 420 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 421 |
|
| 422 |
service := newTestService(mockClient) |
| 423 |
|
| 424 |
err := service.Send("Test message", &types.Params{"type": "invalid"}) |
| 425 |
|
| 426 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 427 |
gomega.Expect(err.Error()).To(gomega.ContainSubstring("invalid message type")) |
| 428 |
}) |
| 429 |
|
| 430 |
ginkgo.It("should error when no stream is set for channel message", func() { |
| 431 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 432 |
|
| 433 |
service := &Service{ |
| 434 |
Config: &Config{ |
| 435 |
BotMail: "[email protected]", |
| 436 |
BotKey: "secret-key", |
| 437 |
Host: "zulip.example.com", |
| 438 |
}, |
| 439 |
HTTPClient: mockClient, |
| 440 |
} |
| 441 |
service.SetLogger(&mockLogger{}) |
| 442 |
service.pkr = format.NewPropKeyResolver(service.Config) |
| 443 |
service.contentMaxSize = contentMaxSize |
| 444 |
service.topicMaxLength = topicMaxLength |
| 445 |
service.mu.Do(func() {}) |
| 446 |
|
| 447 |
err := service.Send("Test message", nil) |
| 448 |
|
| 449 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 450 |
gomega.Expect(err).To(gomega.MatchError(ErrMissingRecipient)) |
| 451 |
}) |
| 452 |
}) |
| 453 |
|
| 454 |
ginkgo.Describe("SendWithContext", func() { |
| 455 |
ginkgo.It("should send a message with background context", func() { |
| 456 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 457 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 458 |
StatusCode: http.StatusOK, |
| 459 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 460 |
}, nil).Once() |
| 461 |
|
| 462 |
service := newTestService(mockClient) |
| 463 |
|
| 464 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 465 |
|
| 466 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 467 |
}) |
| 468 |
|
| 469 |
ginkgo.It("should pass context to the HTTP request", func() { |
| 470 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 471 |
|
| 472 |
var capturedReq *http.Request |
| 473 |
|
| 474 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 475 |
capturedReq = args.Get(0).(*http.Request) |
| 476 |
}).Return(&http.Response{ |
| 477 |
StatusCode: http.StatusOK, |
| 478 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 479 |
}, nil).Once() |
| 480 |
|
| 481 |
service := newTestService(mockClient) |
| 482 |
|
| 483 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 484 |
|
| 485 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 486 |
gomega.Expect(capturedReq).NotTo(gomega.BeNil()) |
| 487 |
}) |
| 488 |
|
| 489 |
ginkgo.It("should return an error when HTTP client returns error", func() { |
| 490 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 491 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(nil, errors.New("context canceled")).Once() |
| 492 |
|
| 493 |
service := newTestService(mockClient) |
| 494 |
|
| 495 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 496 |
|
| 497 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 498 |
}) |
| 499 |
|
| 500 |
ginkgo.It("should not modify the original config", func() { |
| 501 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 502 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 503 |
StatusCode: http.StatusOK, |
| 504 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 505 |
}, nil).Maybe() |
| 506 |
|
| 507 |
service := newTestService(mockClient) |
| 508 |
originalTopic := service.Config.Topic |
| 509 |
|
| 510 |
err := service.SendWithContext(context.Background(), "Test message", &types.Params{"topic": "different-topic"}) |
| 511 |
|
| 512 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 513 |
gomega.Expect(service.Config.Topic).To(gomega.Equal(originalTopic)) |
| 514 |
}) |
| 515 |
|
| 516 |
ginkgo.It("should return an error for invalid host", func() { |
| 517 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 518 |
|
| 519 |
service := newTestService(mockClient) |
| 520 |
service.Config.Host = "invalid host with spaces" |
| 521 |
|
| 522 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 523 |
|
| 524 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 525 |
gomega.Expect(err).To(gomega.MatchError(ErrInvalidHost)) |
| 526 |
}) |
| 527 |
|
| 528 |
ginkgo.It("should accept host with valid port", func() { |
| 529 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 530 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 531 |
StatusCode: http.StatusOK, |
| 532 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 533 |
}, nil).Once() |
| 534 |
|
| 535 |
service := newTestService(mockClient) |
| 536 |
service.Config.Host = "zulip.example.com:8443" |
| 537 |
|
| 538 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 539 |
|
| 540 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 541 |
}) |
| 542 |
|
| 543 |
ginkgo.It("should reject host with invalid port format", func() { |
| 544 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 545 |
|
| 546 |
service := newTestService(mockClient) |
| 547 |
service.Config.Host = "zulip.example.com:abc" |
| 548 |
|
| 549 |
err := service.SendWithContext(context.Background(), "Test message", nil) |
| 550 |
|
| 551 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 552 |
gomega.Expect(err).To(gomega.MatchError(ErrInvalidHost)) |
| 553 |
}) |
| 554 |
|
| 555 |
ginkgo.It("should send direct message with type=direct and to param as JSON", func() { |
| 556 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 557 |
|
| 558 |
var capturedReq *http.Request |
| 559 |
|
| 560 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 561 |
capturedReq = args.Get(0).(*http.Request) |
| 562 |
}).Return(&http.Response{ |
| 563 |
StatusCode: http.StatusOK, |
| 564 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 565 |
}, nil).Once() |
| 566 |
|
| 567 |
service := newTestService(mockClient) |
| 568 |
service.Config.Stream = "" // no stream, use to |
| 569 |
|
| 570 |
err := service.SendWithContext(context.Background(), "Test direct", &types.Params{ |
| 571 |
"type": "direct", |
| 572 |
"to": "[email protected],[email protected]", |
| 573 |
}) |
| 574 |
|
| 575 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 576 |
|
| 577 |
body, _ := io.ReadAll(capturedReq.Body) |
| 578 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("type=direct")) |
| 579 |
gomega.Expect(string(body)).To(gomega.ContainSubstring(`to=%5B%22user1%40example.com%22%2C%22user2%40example.com%22%5D`)) |
| 580 |
}) |
| 581 |
|
| 582 |
ginkgo.It("should error when no recipient for direct message", func() { |
| 583 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 584 |
|
| 585 |
service := newTestService(mockClient) |
| 586 |
service.Config.Stream = "" |
| 587 |
|
| 588 |
err := service.SendWithContext(context.Background(), "Test message", &types.Params{"type": "direct"}) |
| 589 |
|
| 590 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 591 |
gomega.Expect(err).To(gomega.MatchError(ErrMissingRecipient)) |
| 592 |
}) |
| 593 |
}) |
| 594 |
|
| 595 |
ginkgo.Describe("doSend", func() { |
| 596 |
ginkgo.It("should send to the correct API URL path", func() { |
| 597 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 598 |
|
| 599 |
var capturedReq *http.Request |
| 600 |
|
| 601 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 602 |
capturedReq = args.Get(0).(*http.Request) |
| 603 |
}).Return(&http.Response{ |
| 604 |
StatusCode: http.StatusOK, |
| 605 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 606 |
}, nil).Once() |
| 607 |
|
| 608 |
service := newTestService(mockClient) |
| 609 |
|
| 610 |
err := service.doSend(context.Background(), service.Config, "Test message") |
| 611 |
|
| 612 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 613 |
gomega.Expect(capturedReq).NotTo(gomega.BeNil()) |
| 614 |
gomega.Expect(capturedReq.URL.Path).To(gomega.Equal("/api/v1/messages")) |
| 615 |
}) |
| 616 |
|
| 617 |
ginkgo.It("should set content type header", func() { |
| 618 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 619 |
|
| 620 |
var capturedReq *http.Request |
| 621 |
|
| 622 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 623 |
capturedReq = args.Get(0).(*http.Request) |
| 624 |
}).Return(&http.Response{ |
| 625 |
StatusCode: http.StatusOK, |
| 626 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 627 |
}, nil).Once() |
| 628 |
|
| 629 |
service := newTestService(mockClient) |
| 630 |
|
| 631 |
err := service.doSend(context.Background(), service.Config, "Test message") |
| 632 |
|
| 633 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 634 |
gomega.Expect(capturedReq.Header.Get("Content-Type")).To( |
| 635 |
gomega.Equal("application/x-www-form-urlencoded"), |
| 636 |
) |
| 637 |
}) |
| 638 |
|
| 639 |
ginkgo.It("should send form-encoded payload", func() { |
| 640 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 641 |
|
| 642 |
var capturedReq *http.Request |
| 643 |
|
| 644 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Run(func(args mock.Arguments) { |
| 645 |
capturedReq = args.Get(0).(*http.Request) |
| 646 |
}).Return(&http.Response{ |
| 647 |
StatusCode: http.StatusOK, |
| 648 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 649 |
}, nil).Once() |
| 650 |
|
| 651 |
service := newTestService(mockClient) |
| 652 |
|
| 653 |
err := service.doSend(context.Background(), service.Config, "Hello World") |
| 654 |
|
| 655 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 656 |
|
| 657 |
body, readErr := io.ReadAll(capturedReq.Body) |
| 658 |
gomega.Expect(readErr).NotTo(gomega.HaveOccurred()) |
| 659 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("type=channel")) |
| 660 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("to=general")) |
| 661 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("content=Hello+World")) |
| 662 |
gomega.Expect(string(body)).To(gomega.ContainSubstring("topic=announcements")) |
| 663 |
}) |
| 664 |
|
| 665 |
ginkgo.It("should proceed with host validation already done by caller", func() { |
| 666 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 667 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 668 |
StatusCode: http.StatusOK, |
| 669 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 670 |
}, nil).Once() |
| 671 |
|
| 672 |
service := newTestService(mockClient) |
| 673 |
cfg := &Config{ |
| 674 |
BotMail: "[email protected]", |
| 675 |
BotKey: "secret-key", |
| 676 |
Host: "zulip.example.com", |
| 677 |
Stream: "general", |
| 678 |
} |
| 679 |
|
| 680 |
err := service.doSend(context.Background(), cfg, "Test message") |
| 681 |
|
| 682 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 683 |
}) |
| 684 |
|
| 685 |
ginkgo.It("should return an error for non-200 response", func() { |
| 686 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 687 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 688 |
StatusCode: http.StatusInternalServerError, |
| 689 |
Body: io.NopCloser(strings.NewReader("")), |
| 690 |
}, nil).Once() |
| 691 |
|
| 692 |
service := newTestService(mockClient) |
| 693 |
|
| 694 |
err := service.doSend(context.Background(), service.Config, "Test message") |
| 695 |
|
| 696 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 697 |
gomega.Expect(err).To(gomega.MatchError(ErrResponseStatusFailure)) |
| 698 |
}) |
| 699 |
|
| 700 |
ginkgo.It("should return an error when HTTP client fails", func() { |
| 701 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 702 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(nil, errors.New("connection refused")).Once() |
| 703 |
|
| 704 |
service := newTestService(mockClient) |
| 705 |
|
| 706 |
err := service.doSend(context.Background(), service.Config, "Test message") |
| 707 |
|
| 708 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 709 |
gomega.Expect(err.Error()).To(gomega.ContainSubstring("making HTTP POST request")) |
| 710 |
}) |
| 711 |
}) |
| 712 |
|
| 713 |
ginkgo.Describe("getAPIURL", func() { |
| 714 |
ginkgo.It("should construct the correct API URL", func() { |
| 715 |
svc := &Service{} |
| 716 |
cfg := &Config{ |
| 717 |
BotMail: "[email protected]", |
| 718 |
BotKey: "secret-key", |
| 719 |
Host: "zulip.example.com", |
| 720 |
} |
| 721 |
|
| 722 |
apiURL := svc.getAPIURL(cfg) |
| 723 |
|
| 724 |
parsed, err := url.Parse(apiURL) |
| 725 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 726 |
gomega.Expect(parsed.Scheme).To(gomega.Equal("https")) |
| 727 |
gomega.Expect(parsed.Host).To(gomega.Equal("zulip.example.com")) |
| 728 |
gomega.Expect(parsed.Path).To(gomega.Equal("/api/v1/messages")) |
| 729 |
gomega.Expect(parsed.User.Username()).To(gomega.Equal("[email protected]")) |
| 730 |
password, isSet := parsed.User.Password() |
| 731 |
gomega.Expect(isSet).To(gomega.BeTrue()) |
| 732 |
gomega.Expect(password).To(gomega.Equal("secret-key")) |
| 733 |
}) |
| 734 |
|
| 735 |
ginkgo.It("should use https scheme", func() { |
| 736 |
svc := &Service{} |
| 737 |
cfg := &Config{ |
| 738 |
BotMail: "[email protected]", |
| 739 |
BotKey: "secret-key", |
| 740 |
Host: "zulip.example.com", |
| 741 |
} |
| 742 |
|
| 743 |
apiURL := svc.getAPIURL(cfg) |
| 744 |
|
| 745 |
gomega.Expect(apiURL).To(gomega.HavePrefix("https://")) |
| 746 |
}) |
| 747 |
|
| 748 |
ginkgo.It("should include credentials in the URL", func() { |
| 749 |
svc := &Service{} |
| 750 |
cfg := &Config{ |
| 751 |
BotMail: "[email protected]", |
| 752 |
BotKey: "secret-key", |
| 753 |
Host: "zulip.example.com", |
| 754 |
} |
| 755 |
|
| 756 |
apiURL := svc.getAPIURL(cfg) |
| 757 |
|
| 758 |
parsed, err := url.Parse(apiURL) |
| 759 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 760 |
gomega.Expect(parsed.User.Username()).To(gomega.Equal("[email protected]")) |
| 761 |
password, isSet := parsed.User.Password() |
| 762 |
gomega.Expect(isSet).To(gomega.BeTrue()) |
| 763 |
gomega.Expect(password).To(gomega.Equal("secret-key")) |
| 764 |
}) |
| 765 |
|
| 766 |
ginkgo.It("should always use /api/v1/messages path", func() { |
| 767 |
svc := &Service{} |
| 768 |
cfg := &Config{ |
| 769 |
BotMail: "[email protected]", |
| 770 |
BotKey: "secret-key", |
| 771 |
Host: "zulip.example.com", |
| 772 |
} |
| 773 |
|
| 774 |
apiURL := svc.getAPIURL(cfg) |
| 775 |
|
| 776 |
parsed, err := url.Parse(apiURL) |
| 777 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 778 |
gomega.Expect(parsed.Path).To(gomega.Equal("/api/v1/messages")) |
| 779 |
}) |
| 780 |
|
| 781 |
ginkgo.It("should use server-side size limits from register endpoint", func() { |
| 782 |
httpmock.Activate() |
| 783 |
|
| 784 |
defer httpmock.DeactivateAndReset() |
| 785 |
|
| 786 |
registerURL := (&url.URL{ |
| 787 |
User: url.UserPassword("[email protected]", "secret-key"), |
| 788 |
Host: "zulip.example.com", |
| 789 |
Path: "/api/v1/register", |
| 790 |
Scheme: "https", |
| 791 |
}).String() |
| 792 |
httpmock.RegisterResponder( |
| 793 |
"POST", |
| 794 |
registerURL, |
| 795 |
httpmock.NewStringResponder(http.StatusOK, `{"max_message_length":5000,"max_topic_length":30}`), |
| 796 |
) |
| 797 |
|
| 798 |
apiURL := (&url.URL{ |
| 799 |
Host: "zulip.example.com", |
| 800 |
Path: "/api/v1/messages", |
| 801 |
Scheme: "https", |
| 802 |
User: url.UserPassword("[email protected]", "secret-key"), |
| 803 |
}).String() |
| 804 |
httpmock.RegisterResponder( |
| 805 |
"POST", |
| 806 |
apiURL, |
| 807 |
httpmock.NewStringResponder(http.StatusOK, ""), |
| 808 |
) |
| 809 |
|
| 810 |
svc := &Service{} |
| 811 |
serviceURL := testutils.URLMust("zulip://[email protected]:[email protected]?stream=general") |
| 812 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 813 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 814 |
|
| 815 |
longMessage := strings.Repeat("a", 5001) |
| 816 |
err = svc.Send(longMessage, nil) |
| 817 |
gomega.Expect(err).To(gomega.HaveOccurred()) |
| 818 |
gomega.Expect(err.Error()).To(gomega.Equal("message exceeds max size: 5000 bytes, got 5001 bytes")) |
| 819 |
}) |
| 820 |
|
| 821 |
ginkgo.It("should fall back to defaults when register fails", func() { |
| 822 |
httpmock.Activate() |
| 823 |
|
| 824 |
defer httpmock.DeactivateAndReset() |
| 825 |
|
| 826 |
registerURL := (&url.URL{ |
| 827 |
User: url.UserPassword("[email protected]", "secret-key"), |
| 828 |
Host: "zulip.example.com", |
| 829 |
Path: "/api/v1/register", |
| 830 |
Scheme: "https", |
| 831 |
}).String() |
| 832 |
httpmock.RegisterResponder( |
| 833 |
"POST", |
| 834 |
registerURL, |
| 835 |
httpmock.NewStringResponder(http.StatusServiceUnavailable, ""), |
| 836 |
) |
| 837 |
|
| 838 |
apiURL := (&url.URL{ |
| 839 |
Host: "zulip.example.com", |
| 840 |
Path: "/api/v1/messages", |
| 841 |
Scheme: "https", |
| 842 |
User: url.UserPassword("[email protected]", "secret-key"), |
| 843 |
}).String() |
| 844 |
httpmock.RegisterResponder( |
| 845 |
"POST", |
| 846 |
apiURL, |
| 847 |
httpmock.NewStringResponder(http.StatusOK, ""), |
| 848 |
) |
| 849 |
|
| 850 |
svc := &Service{} |
| 851 |
serviceURL := testutils.URLMust("zulip://[email protected]:[email protected]?stream=general") |
| 852 |
err := svc.Initialize(serviceURL, testutils.TestLogger()) |
| 853 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 854 |
|
| 855 |
err = svc.Send("test message", nil) |
| 856 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 857 |
}) |
| 858 |
}) |
| 859 |
|
| 860 |
ginkgo.Describe("Params update", func() { |
| 861 |
ginkgo.It("should update config from params without mutating original", func() { |
| 862 |
mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 863 |
mockClient.On("Do", mock.AnythingOfType("*http.Request")).Return(&http.Response{ |
| 864 |
StatusCode: http.StatusOK, |
| 865 |
Body: io.NopCloser(bytes.NewReader([]byte(`{"result": "success"}`))), |
| 866 |
}, nil).Maybe() |
| 867 |
|
| 868 |
service := newTestService(mockClient) |
| 869 |
originalTopic := service.Config.Topic |
| 870 |
|
| 871 |
params := types.Params{"topic": "new-topic"} |
| 872 |
|
| 873 |
err := service.Send("Test message", ¶ms) |
| 874 |
|
| 875 |
gomega.Expect(err).NotTo(gomega.HaveOccurred()) |
| 876 |
gomega.Expect(service.Config.Topic).To(gomega.Equal(originalTopic)) |
| 877 |
}) |
| 878 |
}) |
| 879 |
}) |
| 880 |
|
| 881 |
func (m *mockLogger) Print(_ ...any) {} |
| 882 |
func (m *mockLogger) Printf(_ string, _ ...any) {} |
| 883 |
func (m *mockLogger) Println(_ ...any) {} |
| 884 |
|
| 885 |
func newTestService(mockClient *mocks.MockHTTPClient) *Service { |
| 886 |
service := &Service{ |
| 887 |
Config: &Config{ |
| 888 |
BotMail: "[email protected]", |
| 889 |
BotKey: "secret-key", |
| 890 |
Host: "zulip.example.com", |
| 891 |
Stream: "general", |
| 892 |
Topic: "announcements", |
| 893 |
}, |
| 894 |
HTTPClient: mockClient, |
| 895 |
} |
| 896 |
service.SetLogger(&mockLogger{}) |
| 897 |
service.pkr = format.NewPropKeyResolver(service.Config) |
| 898 |
service.contentMaxSize = contentMaxSize |
| 899 |
service.topicMaxLength = topicMaxLength |
| 900 |
// Prime the Once so fetchLimits (which would call HTTPClient) is skipped in mock-based unit tests. |
| 901 |
service.mu.Do(func() {}) |
| 902 |
|
| 903 |
return service |
| 904 |
} |