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*")
52 require.NoError(t, err)
54 require.Equal(t, map[string]any{
55 "chat_id": float64(testOwner),
57 }, server.Calls()[0].params)
60 func TestSendMessageTimesOutOnAStalledConnection(t *testing.T) {
61 server := newFakeBot(t)
62 server.stall = func(call fakeBotCall) bool {
63 return call.method == "sendMessage"
66 api := newBotAPI(server.URL, testBotToken)
67 api.sendTimeout = 50 * time.Millisecond
69 err := api.SendMessage(t.Context(), testOwner, "hi")
70 require.ErrorIs(t, err, errBotNetwork)
71 require.Less(t, time.Since(start), 5*time.Second)
72 require.NotContains(t, err.Error(), testBotToken)
73 require.NotContains(t, err.Error(), server.URL)
75 retry, _ := retryable(err)
76 require.True(t, retry)
78 api.sendTimeout = time.Hour
79 ctx, cancel := context.WithCancel(t.Context())
80 time.AfterFunc(50*time.Millisecond, cancel)
82 err = api.SendMessage(ctx, testOwner, "hi")
84 require.Less(t, time.Since(start), 5*time.Second)
87 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
88 testCases := []struct {
90 reply func(w http.ResponseWriter)
96 name: "refused connection is retried",
97 reply: func(w http.ResponseWriter) {
98 conn, _, err := http.NewResponseController(w).Hijack()
104 errorText: "no valid answer",
107 name: "rate limit waits as asked",
108 reply: func(w http.ResponseWriter) {
109 w.WriteHeader(http.StatusTooManyRequests)
110 _, _ = io.WriteString(w, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`)
113 wait: 3 * time.Second,
114 errorText: "answered 429",
117 name: "server error page is retried",
118 reply: func(w http.ResponseWriter) {
119 w.WriteHeader(http.StatusBadGateway)
120 _, _ = io.WriteString(w, "<html>bad gateway</html>")
123 errorText: "answered 502: Bad Gateway",
126 name: "token echoed in a description is hidden",
127 reply: func(w http.ResponseWriter) {
128 w.WriteHeader(http.StatusUnauthorized)
129 _, _ = io.WriteString(w, `{"ok":false,"error_code":401,"description":"Unauthorized: bot`+testBotToken+`"}`)
132 errorText: "Unauthorized: botTOKEN",
135 name: "broken answer is retried",
136 reply: func(w http.ResponseWriter) {
137 _, _ = io.WriteString(w, `{"ok":`)
140 errorText: "decode answer",
144 for _, tc := range testCases {
145 t.Run(tc.name, func(t *testing.T) {
146 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
149 t.Cleanup(server.Close)
151 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi")
152 require.ErrorContains(t, err, tc.errorText)
153 require.NotContains(t, err.Error(), testBotToken)
154 require.NotContains(t, err.Error(), server.URL)
156 retry, wait := retryable(err)
157 require.Equal(t, tc.retry, retry)
158 require.Equal(t, tc.wait, wait)
162 server := httptest.NewServer(http.NotFoundHandler())
165 _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0)
166 require.ErrorIs(t, err, errBotNetwork)
167 require.NotContains(t, err.Error(), testBotToken)
170 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
171 // added updates from the offset on, or waits a short time when there are none.
172 // The other methods succeed, unless fail gives an error answer for a call. An
173 // answer with HTTP 429 asks for a wait of one second. When stall is true for a
174 // call, the call gets no answer until the client gives it up or the test ends.
175 // Fail and stall run with the mutex held.
176 type fakeBot struct {
182 fail func(call fakeBotCall) (int, string)
183 stall func(call fakeBotCall) bool
185 stopped chan struct{}
188 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
190 type fakeBotCall struct {
192 params map[string]any
196 // newFakeBot starts a fake Bot API server that stops at the end of the test.
197 func newFakeBot(t *testing.T) *fakeBot {
201 added: make(chan struct{}, 1),
202 stopped: make(chan struct{}),
205 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
214 // Add makes update available to getUpdates.
215 func (f *fakeBot) Add(update botUpdate) {
217 f.updates = append(f.updates, update)
221 case f.added <- struct{}{}:
226 // Calls returns the calls so far.
227 func (f *fakeBot) Calls() []fakeBotCall {
229 defer f.mutex.Unlock()
231 return append([]fakeBotCall(nil), f.calls...)
234 // Sent returns the texts of the sendMessage calls that succeeded.
235 func (f *fakeBot) Sent() []string {
237 for _, call := range f.Calls() {
238 if call.method == "sendMessage" && call.ok {
239 texts = append(texts, call.params["text"].(string))
246 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
247 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
249 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
253 var params map[string]any
254 err := json.NewDecoder(r.Body).Decode(¶ms)
256 http.Error(w, err.Error(), http.StatusBadRequest)
266 status, description := 0, ""
268 status, description = f.fail(call)
271 stall := f.stall != nil && f.stall(call)
277 case <-r.Context().Done():
286 w.WriteHeader(status)
288 if status == http.StatusTooManyRequests {
292 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
299 if method != "getUpdates" {
300 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
304 offset := int64(params["offset"].(float64))
305 updates := f.from(offset)
306 if len(updates) == 0 {
309 case <-time.After(50 * time.Millisecond):
310 case <-r.Context().Done():
313 updates = f.from(offset)
316 _ = json.NewEncoder(w).Encode(map[string]any{
322 // record keeps call.
323 func (f *fakeBot) record(call fakeBotCall) {
325 defer f.mutex.Unlock()
327 f.calls = append(f.calls, call)
330 // from returns the updates from offset on, and forgets the ones before it, as
332 func (f *fakeBot) from(offset int64) []botUpdate {
334 defer f.mutex.Unlock()
336 var updates []botUpdate
337 kept := f.updates[:0]
338 for _, update := range f.updates {
339 if update.UpdateID >= offset {
340 updates = append(updates, update)
341 kept = append(kept, update)
350 // ownerMessage returns a text message of the owner in the private chat.
351 func ownerMessage(text string) *botMessage {