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 TestSendMessageTimesOutOnAStalledConnection(t *testing.T) {
83 server := newFakeBot(t)
84 server.stall = func(call fakeBotCall) bool {
85 return call.method == "sendMessage"
88 api := newBotAPI(server.URL, testBotToken)
89 api.sendTimeout = 50 * time.Millisecond
91 err := api.SendMessage(t.Context(), testOwner, "hi", nil)
92 require.ErrorIs(t, err, errBotNetwork)
93 require.Less(t, time.Since(start), 5*time.Second)
94 require.NotContains(t, err.Error(), testBotToken)
95 require.NotContains(t, err.Error(), server.URL)
97 retry, _ := retryable(err)
98 require.True(t, retry)
100 api.sendTimeout = time.Hour
101 ctx, cancel := context.WithCancel(t.Context())
102 time.AfterFunc(50*time.Millisecond, cancel)
104 err = api.SendMessage(ctx, testOwner, "hi", nil)
105 require.Error(t, err)
106 require.Less(t, time.Since(start), 5*time.Second)
109 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
110 testCases := []struct {
112 reply func(w http.ResponseWriter)
118 name: "refused connection is retried",
119 reply: func(w http.ResponseWriter) {
120 conn, _, err := http.NewResponseController(w).Hijack()
126 errorText: "no valid answer",
129 name: "rate limit waits as asked",
130 reply: func(w http.ResponseWriter) {
131 w.WriteHeader(http.StatusTooManyRequests)
132 _, _ = io.WriteString(w, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`)
135 wait: 3 * time.Second,
136 errorText: "answered 429",
139 name: "server error page is retried",
140 reply: func(w http.ResponseWriter) {
141 w.WriteHeader(http.StatusBadGateway)
142 _, _ = io.WriteString(w, "<html>bad gateway</html>")
145 errorText: "answered 502: Bad Gateway",
148 name: "token echoed in a description is hidden",
149 reply: func(w http.ResponseWriter) {
150 w.WriteHeader(http.StatusUnauthorized)
151 _, _ = io.WriteString(w, `{"ok":false,"error_code":401,"description":"Unauthorized: bot`+testBotToken+`"}`)
154 errorText: "Unauthorized: botTOKEN",
157 name: "broken answer is retried",
158 reply: func(w http.ResponseWriter) {
159 _, _ = io.WriteString(w, `{"ok":`)
162 errorText: "decode answer",
166 for _, tc := range testCases {
167 t.Run(tc.name, func(t *testing.T) {
168 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
171 t.Cleanup(server.Close)
173 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi", nil)
174 require.ErrorContains(t, err, tc.errorText)
175 require.NotContains(t, err.Error(), testBotToken)
176 require.NotContains(t, err.Error(), server.URL)
178 retry, wait := retryable(err)
179 require.Equal(t, tc.retry, retry)
180 require.Equal(t, tc.wait, wait)
184 server := httptest.NewServer(http.NotFoundHandler())
187 _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0)
188 require.ErrorIs(t, err, errBotNetwork)
189 require.NotContains(t, err.Error(), testBotToken)
192 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
193 // added updates from the offset on, or waits a short time when there are none.
194 // The other methods succeed, unless fail gives an error answer for a call. An
195 // answer with HTTP 429 asks for a wait of one second. When stall is true for a
196 // call, the call gets no answer until the client gives it up or the test ends.
197 // Fail and stall run with the mutex held.
198 type fakeBot struct {
204 fail func(call fakeBotCall) (int, string)
205 stall func(call fakeBotCall) bool
207 stopped chan struct{}
210 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
212 type fakeBotCall struct {
214 params map[string]any
218 // newFakeBot starts a fake Bot API server that stops at the end of the test.
219 func newFakeBot(t *testing.T) *fakeBot {
223 added: make(chan struct{}, 1),
224 stopped: make(chan struct{}),
227 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
236 // Add makes update available to getUpdates.
237 func (f *fakeBot) Add(update botUpdate) {
239 f.updates = append(f.updates, update)
243 case f.added <- struct{}{}:
248 // Calls returns the calls so far.
249 func (f *fakeBot) Calls() []fakeBotCall {
251 defer f.mutex.Unlock()
253 return append([]fakeBotCall(nil), f.calls...)
256 // Sent returns the texts of the sendMessage calls that succeeded.
257 func (f *fakeBot) Sent() []string {
259 for _, call := range f.Calls() {
260 if call.method == "sendMessage" && call.ok {
261 texts = append(texts, call.params["text"].(string))
268 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
269 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
271 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
275 var params map[string]any
276 err := json.NewDecoder(r.Body).Decode(¶ms)
278 http.Error(w, err.Error(), http.StatusBadRequest)
288 status, description := 0, ""
290 status, description = f.fail(call)
293 stall := f.stall != nil && f.stall(call)
299 case <-r.Context().Done():
308 w.WriteHeader(status)
310 if status == http.StatusTooManyRequests {
314 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
321 if method != "getUpdates" {
322 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
326 offset := int64(params["offset"].(float64))
327 updates := f.from(offset)
328 if len(updates) == 0 {
331 case <-time.After(50 * time.Millisecond):
332 case <-r.Context().Done():
335 updates = f.from(offset)
338 _ = json.NewEncoder(w).Encode(map[string]any{
344 // record keeps call.
345 func (f *fakeBot) record(call fakeBotCall) {
347 defer f.mutex.Unlock()
349 f.calls = append(f.calls, call)
352 // from returns the updates from offset on, and forgets the ones before it, as
354 func (f *fakeBot) from(offset int64) []botUpdate {
356 defer f.mutex.Unlock()
358 var updates []botUpdate
359 kept := f.updates[:0]
360 for _, update := range f.updates {
361 if update.UpdateID >= offset {
362 updates = append(updates, update)
363 kept = append(kept, update)
372 // ownerMessage returns a text message of the owner in the private chat.
373 func ownerMessage(text string) *botMessage {