package main import ( "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "github.com/stretchr/testify/require" ) const ( // testBotToken is the bot token of the tests. It has the form of a real // token. testBotToken = "123456:TEST-secret_token" // testOwner is the user ID of the owner of the test bot. testOwner = 4242 ) func TestGetUpdatesAsksForMessagesFromTheOffset(t *testing.T) { server := newFakeBot(t) server.Add(botUpdate{ UpdateID: 7, Message: ownerMessage("hello"), }) updates, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 7) require.NoError(t, err) require.Len(t, updates, 1) require.Equal(t, int64(7), updates[0].UpdateID) require.Equal(t, "hello", updates[0].Message.Text) call := server.Calls()[0] require.Equal(t, "getUpdates", call.method) require.Equal(t, map[string]any{ "offset": float64(7), "timeout": float64(pollSeconds), "allowed_updates": []any{"message"}, }, call.params) } func TestSendMessageSendsPlainText(t *testing.T) { server := newFakeBot(t) err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "*not bold*", nil) require.NoError(t, err) require.Equal(t, map[string]any{ "chat_id": float64(testOwner), "text": "*not bold*", }, server.Calls()[0].params) } func TestSendMessageSendsTheEntities(t *testing.T) { server := newFakeBot(t) err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "a link", []botEntity{ { Type: "text_link", Offset: 2, Length: 4, URL: "https://example.com", }, }) require.NoError(t, err) require.Equal(t, []any{ map[string]any{ "type": "text_link", "offset": float64(2), "length": float64(4), "url": "https://example.com", }, }, server.Calls()[0].params["entities"]) } func TestSendRichMessageSendsTheMarkdownUnchanged(t *testing.T) { server := newFakeBot(t) markdown := "| a | b |\n|---|---|\n| **1** | `2` |" err := newBotAPI(server.URL, testBotToken).SendRichMessage(t.Context(), testOwner, markdown) require.NoError(t, err) call := server.Calls()[0] require.Equal(t, "sendRichMessage", call.method) require.Equal(t, map[string]any{ "chat_id": float64(testOwner), "rich_message": map[string]any{ "markdown": markdown, }, }, call.params) } func TestSendCallsTimeOutOnAStalledConnection(t *testing.T) { testCases := []struct { method string send func(ctx context.Context, api *botAPI) error }{ { method: "sendMessage", send: func(ctx context.Context, api *botAPI) error { return api.SendMessage(ctx, testOwner, "hi", nil) }, }, { method: "sendRichMessage", send: func(ctx context.Context, api *botAPI) error { return api.SendRichMessage(ctx, testOwner, "hi") }, }, } for _, tc := range testCases { t.Run(tc.method, func(t *testing.T) { server := newFakeBot(t) server.stall = func(call fakeBotCall) bool { return call.method == tc.method } api := newBotAPI(server.URL, testBotToken) api.sendTimeout = 50 * time.Millisecond start := time.Now() err := tc.send(t.Context(), api) require.ErrorIs(t, err, errBotNetwork) require.Less(t, time.Since(start), 5*time.Second) require.NotContains(t, err.Error(), testBotToken) require.NotContains(t, err.Error(), server.URL) retry, _ := retryable(err) require.True(t, retry) api.sendTimeout = time.Hour ctx, cancel := context.WithCancel(t.Context()) time.AfterFunc(50*time.Millisecond, cancel) start = time.Now() err = tc.send(ctx, api) require.Error(t, err) require.Less(t, time.Since(start), 5*time.Second) }) } } func TestBotErrorsDoNotHoldTheToken(t *testing.T) { testCases := []struct { name string reply func(w http.ResponseWriter) retry bool wait time.Duration rejected bool errorText string }{ { name: "refused connection is retried", reply: func(w http.ResponseWriter) { conn, _, err := http.NewResponseController(w).Hijack() if err == nil { _ = conn.Close() } }, retry: true, errorText: "no valid answer", }, { name: "rate limit waits as asked", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(w, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`) }, retry: true, wait: 3 * time.Second, errorText: "answered 429", }, { name: "server error page is retried", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusBadGateway) _, _ = io.WriteString(w, "bad gateway") }, retry: true, errorText: "answered 502: Bad Gateway", }, { name: "token echoed in a description is hidden", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusUnauthorized) _, _ = io.WriteString(w, `{"ok":false,"error_code":401,"description":"Unauthorized: bot`+testBotToken+`"}`) }, retry: false, errorText: "Unauthorized: botTOKEN", }, { name: "bad request is a refusal", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusBadRequest) _, _ = io.WriteString(w, `{"ok":false,"error_code":400,"description":"Bad Request: can't parse"}`) }, retry: false, rejected: true, errorText: "answered 400: Bad Request: can't parse", }, { name: "unknown method is a refusal", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusNotFound) _, _ = io.WriteString(w, `{"ok":false,"error_code":404,"description":"Not Found"}`) }, retry: false, rejected: true, errorText: "answered 404: Not Found", }, { name: "not found page of a proxy is not a refusal", reply: func(w http.ResponseWriter) { w.WriteHeader(http.StatusNotFound) _, _ = io.WriteString(w, "not found") }, retry: false, errorText: "answered 404: Not Found", }, { name: "broken answer is retried", reply: func(w http.ResponseWriter) { _, _ = io.WriteString(w, `{"ok":`) }, retry: true, errorText: "decode answer", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tc.reply(w) })) t.Cleanup(server.Close) err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi", nil) require.ErrorContains(t, err, tc.errorText) require.NotContains(t, err.Error(), testBotToken) require.NotContains(t, err.Error(), server.URL) retry, wait := retryable(err) require.Equal(t, tc.retry, retry) require.Equal(t, tc.wait, wait) require.Equal(t, tc.rejected, rejected(err)) }) } server := httptest.NewServer(http.NotFoundHandler()) server.Close() _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0) require.ErrorIs(t, err, errBotNetwork) require.NotContains(t, err.Error(), testBotToken) } // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the // added updates from the offset on, or waits a short time when there are none. // The other methods succeed, unless fail gives an error answer for a call. An // answer with HTTP 429 asks for a wait of one second. When stall is true for a // call, the call gets no answer until the client gives it up or the test ends. // Fail and stall run with the mutex held. type fakeBot struct { *httptest.Server mutex sync.Mutex updates []botUpdate calls []fakeBotCall fail func(call fakeBotCall) (int, string) stall func(call fakeBotCall) bool added chan struct{} stopped chan struct{} } // fakeBotCall is one call of the fake Bot API. OK tells if the call got a // success answer. type fakeBotCall struct { method string params map[string]any ok bool } // newFakeBot starts a fake Bot API server that stops at the end of the test. func newFakeBot(t *testing.T) *fakeBot { t.Helper() f := &fakeBot{ added: make(chan struct{}, 1), stopped: make(chan struct{}), } f.Server = httptest.NewServer(http.HandlerFunc(f.serve)) t.Cleanup(f.Close) t.Cleanup(func() { close(f.stopped) }) return f } // Add makes update available to getUpdates. func (f *fakeBot) Add(update botUpdate) { f.mutex.Lock() f.updates = append(f.updates, update) f.mutex.Unlock() select { case f.added <- struct{}{}: default: } } // Calls returns the calls so far. func (f *fakeBot) Calls() []fakeBotCall { f.mutex.Lock() defer f.mutex.Unlock() return append([]fakeBotCall(nil), f.calls...) } // Sent returns the texts of the sendMessage calls that succeeded. func (f *fakeBot) Sent() []string { var texts []string for _, call := range f.Calls() { if call.method == "sendMessage" && call.ok { texts = append(texts, call.params["text"].(string)) } } return texts } func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) { method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/") if !found { http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound) return } var params map[string]any err := json.NewDecoder(r.Body).Decode(¶ms) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } call := fakeBotCall{ method: method, params: params, } f.mutex.Lock() status, description := 0, "" if f.fail != nil { status, description = f.fail(call) } stall := f.stall != nil && f.stall(call) f.mutex.Unlock() if stall { f.record(call) select { case <-r.Context().Done(): case <-f.stopped: } return } if status != 0 { f.record(call) w.WriteHeader(status) wait := 0 if status == http.StatusTooManyRequests { wait = 1 } _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait) return } call.ok = true f.record(call) if method != "getUpdates" { _, _ = io.WriteString(w, `{"ok":true,"result":true}`) return } offset := int64(params["offset"].(float64)) updates := f.from(offset) if len(updates) == 0 { select { case <-f.added: case <-time.After(50 * time.Millisecond): case <-r.Context().Done(): } updates = f.from(offset) } _ = json.NewEncoder(w).Encode(map[string]any{ "ok": true, "result": updates, }) } // record keeps call. func (f *fakeBot) record(call fakeBotCall) { f.mutex.Lock() defer f.mutex.Unlock() f.calls = append(f.calls, call) } // from returns the updates from offset on, and forgets the ones before it, as // Telegram does. func (f *fakeBot) from(offset int64) []botUpdate { f.mutex.Lock() defer f.mutex.Unlock() var updates []botUpdate kept := f.updates[:0] for _, update := range f.updates { if update.UpdateID >= offset { updates = append(updates, update) kept = append(kept, update) } } f.updates = kept return updates } // ownerMessage returns a text message of the owner in the private chat. func ownerMessage(text string) *botMessage { return &botMessage{ Chat: botChat{ ID: testOwner, Type: "private", }, From: &botUser{ ID: testOwner, }, Text: text, } }