15 "github.com/stretchr/testify/require"
19 // testBotToken is the bot token of the tests. It has the form of a real
21 testBotToken = "123456:TEST-secret_token"
23 // testOwner is the user ID of the owner of the test bot.
27 func TestGetUpdatesAsksForMessagesFromTheOffset(t *testing.T) {
28 server := newFakeBot(t)
31 Message: ownerMessage("hello"),
34 updates, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 7)
35 require.NoError(t, err)
36 require.Len(t, updates, 1)
37 require.Equal(t, int64(7), updates[0].UpdateID)
38 require.Equal(t, "hello", updates[0].Message.Text)
40 call := server.Calls()[0]
41 require.Equal(t, "getUpdates", call.method)
42 require.Equal(t, map[string]any{
44 "timeout": float64(pollSeconds),
45 "allowed_updates": []any{"message"},
49 func TestSendMessageSendsPlainText(t *testing.T) {
50 server := newFakeBot(t)
51 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "*not bold*", nil)
52 require.NoError(t, err)
54 require.Equal(t, map[string]any{
55 "chat_id": float64(testOwner),
57 }, server.Calls()[0].params)
60 func TestSendMessageSendsTheEntities(t *testing.T) {
61 server := newFakeBot(t)
62 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "a link", []botEntity{
67 URL: "https://example.com",
70 require.NoError(t, err)
72 require.Equal(t, []any{
77 "url": "https://example.com",
79 }, server.Calls()[0].params["entities"])
82 func TestSendRichMessageSendsTheMarkdownUnchanged(t *testing.T) {
83 server := newFakeBot(t)
84 markdown := "| a | b |\n|---|---|\n| **1** | `2` |"
85 err := newBotAPI(server.URL, testBotToken).SendRichMessage(t.Context(), testOwner, markdown)
86 require.NoError(t, err)
88 call := server.Calls()[0]
89 require.Equal(t, "sendRichMessage", call.method)
90 require.Equal(t, map[string]any{
91 "chat_id": float64(testOwner),
92 "rich_message": map[string]any{
98 func TestSendCallsTimeOutOnAStalledConnection(t *testing.T) {
99 testCases := []struct {
101 send func(ctx context.Context, api *botAPI) error
104 method: "sendMessage",
105 send: func(ctx context.Context, api *botAPI) error {
106 return api.SendMessage(ctx, testOwner, "hi", nil)
110 method: "sendRichMessage",
111 send: func(ctx context.Context, api *botAPI) error {
112 return api.SendRichMessage(ctx, testOwner, "hi")
117 for _, tc := range testCases {
118 t.Run(tc.method, func(t *testing.T) {
119 server := newFakeBot(t)
120 server.stall = func(call fakeBotCall) bool {
121 return call.method == tc.method
124 api := newBotAPI(server.URL, testBotToken)
125 api.sendTimeout = 50 * time.Millisecond
127 err := tc.send(t.Context(), api)
128 require.ErrorIs(t, err, errBotNetwork)
129 require.Less(t, time.Since(start), 5*time.Second)
130 require.NotContains(t, err.Error(), testBotToken)
131 require.NotContains(t, err.Error(), server.URL)
133 retry, _ := retryable(err)
134 require.True(t, retry)
136 api.sendTimeout = time.Hour
137 ctx, cancel := context.WithCancel(t.Context())
138 time.AfterFunc(50*time.Millisecond, cancel)
140 err = tc.send(ctx, api)
141 require.Error(t, err)
142 require.Less(t, time.Since(start), 5*time.Second)
147 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
148 testCases := []struct {
150 reply func(w http.ResponseWriter)
157 name: "refused connection is retried",
158 reply: func(w http.ResponseWriter) {
159 conn, _, err := http.NewResponseController(w).Hijack()
165 errorText: "no valid answer",
168 name: "rate limit waits as asked",
169 reply: func(w http.ResponseWriter) {
170 w.WriteHeader(http.StatusTooManyRequests)
171 _, _ = io.WriteString(w, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`)
174 wait: 3 * time.Second,
175 errorText: "answered 429",
178 name: "server error page is retried",
179 reply: func(w http.ResponseWriter) {
180 w.WriteHeader(http.StatusBadGateway)
181 _, _ = io.WriteString(w, "<html>bad gateway</html>")
184 errorText: "answered 502: Bad Gateway",
187 name: "token echoed in a description is hidden",
188 reply: func(w http.ResponseWriter) {
189 w.WriteHeader(http.StatusUnauthorized)
190 _, _ = io.WriteString(w, `{"ok":false,"error_code":401,"description":"Unauthorized: bot`+testBotToken+`"}`)
193 errorText: "Unauthorized: botTOKEN",
196 name: "bad request is a refusal",
197 reply: func(w http.ResponseWriter) {
198 w.WriteHeader(http.StatusBadRequest)
199 _, _ = io.WriteString(w, `{"ok":false,"error_code":400,"description":"Bad Request: can't parse"}`)
203 errorText: "answered 400: Bad Request: can't parse",
206 name: "unknown method is a refusal",
207 reply: func(w http.ResponseWriter) {
208 w.WriteHeader(http.StatusNotFound)
209 _, _ = io.WriteString(w, `{"ok":false,"error_code":404,"description":"Not Found"}`)
213 errorText: "answered 404: Not Found",
216 name: "not found page of a proxy is not a refusal",
217 reply: func(w http.ResponseWriter) {
218 w.WriteHeader(http.StatusNotFound)
219 _, _ = io.WriteString(w, "<html>not found</html>")
222 errorText: "answered 404: Not Found",
225 name: "broken answer is retried",
226 reply: func(w http.ResponseWriter) {
227 _, _ = io.WriteString(w, `{"ok":`)
230 errorText: "decode answer",
234 for _, tc := range testCases {
235 t.Run(tc.name, func(t *testing.T) {
236 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
239 t.Cleanup(server.Close)
241 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi", nil)
242 require.ErrorContains(t, err, tc.errorText)
243 require.NotContains(t, err.Error(), testBotToken)
244 require.NotContains(t, err.Error(), server.URL)
246 retry, wait := retryable(err)
247 require.Equal(t, tc.retry, retry)
248 require.Equal(t, tc.wait, wait)
249 require.Equal(t, tc.rejected, rejected(err))
253 server := httptest.NewServer(http.NotFoundHandler())
256 _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0)
257 require.ErrorIs(t, err, errBotNetwork)
258 require.NotContains(t, err.Error(), testBotToken)
261 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
262 // added updates from the offset on, or waits a short time when there are none.
263 // The other methods succeed, unless fail gives an error answer for a call. An
264 // answer with HTTP 429 asks for a wait of one second. When stall is true for a
265 // call, the call gets no answer until the client gives it up or the test ends.
266 // Fail and stall run with the mutex held.
267 type fakeBot struct {
273 fail func(call fakeBotCall) (int, string)
274 stall func(call fakeBotCall) bool
276 stopped chan struct{}
279 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
281 type fakeBotCall struct {
283 params map[string]any
287 // newFakeBot starts a fake Bot API server that stops at the end of the test.
288 func newFakeBot(t *testing.T) *fakeBot {
292 added: make(chan struct{}, 1),
293 stopped: make(chan struct{}),
296 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
305 // Add makes update available to getUpdates.
306 func (f *fakeBot) Add(update botUpdate) {
308 f.updates = append(f.updates, update)
312 case f.added <- struct{}{}:
317 // Calls returns the calls so far.
318 func (f *fakeBot) Calls() []fakeBotCall {
320 defer f.mutex.Unlock()
322 return append([]fakeBotCall(nil), f.calls...)
325 // Sent returns the texts of the sendMessage calls and the Markdown of the
326 // sendRichMessage calls that succeeded, in order.
327 func (f *fakeBot) Sent() []string {
329 for _, call := range f.Calls() {
332 case call.method == "sendMessage":
333 texts = append(texts, call.params["text"].(string))
334 case call.method == "sendRichMessage":
335 texts = append(texts, call.params["rich_message"].(map[string]any)["markdown"].(string))
342 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
343 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
345 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
349 var params map[string]any
350 err := json.NewDecoder(r.Body).Decode(¶ms)
352 http.Error(w, err.Error(), http.StatusBadRequest)
362 status, description := 0, ""
364 status, description = f.fail(call)
367 stall := f.stall != nil && f.stall(call)
373 case <-r.Context().Done():
382 w.WriteHeader(status)
384 if status == http.StatusTooManyRequests {
388 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
395 if method != "getUpdates" {
396 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
400 offset := int64(params["offset"].(float64))
401 updates := f.from(offset)
402 if len(updates) == 0 {
405 case <-time.After(50 * time.Millisecond):
406 case <-r.Context().Done():
409 updates = f.from(offset)
412 _ = json.NewEncoder(w).Encode(map[string]any{
418 // record keeps call.
419 func (f *fakeBot) record(call fakeBotCall) {
421 defer f.mutex.Unlock()
423 f.calls = append(f.calls, call)
426 // from returns the updates from offset on, and forgets the ones before it, as
428 func (f *fakeBot) from(offset int64) []botUpdate {
430 defer f.mutex.Unlock()
432 var updates []botUpdate
433 kept := f.updates[:0]
434 for _, update := range f.updates {
435 if update.UpdateID >= offset {
436 updates = append(updates, update)
437 kept = append(kept, update)
446 // ownerMessage returns a text message of the owner in the private chat.
447 func ownerMessage(text string) *botMessage {