14 "github.com/stretchr/testify/require"
18 // testBotToken is the bot token of the tests. It has the form of a real
20 testBotToken = "123456:TEST-secret_token"
22 // testOwner is the user ID of the owner of the test bot.
26 func TestGetUpdatesAsksForMessagesFromTheOffset(t *testing.T) {
27 server := newFakeBot(t)
30 Message: ownerMessage("hello"),
33 updates, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 7)
34 require.NoError(t, err)
35 require.Len(t, updates, 1)
36 require.Equal(t, int64(7), updates[0].UpdateID)
37 require.Equal(t, "hello", updates[0].Message.Text)
39 call := server.Calls()[0]
40 require.Equal(t, "getUpdates", call.method)
41 require.Equal(t, map[string]any{
43 "timeout": float64(pollSeconds),
44 "allowed_updates": []any{"message"},
48 func TestSendMessageSendsPlainText(t *testing.T) {
49 server := newFakeBot(t)
50 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "*not bold*")
51 require.NoError(t, err)
53 require.Equal(t, map[string]any{
54 "chat_id": float64(testOwner),
56 }, server.Calls()[0].params)
59 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
60 testCases := []struct {
62 reply func(w http.ResponseWriter)
68 name: "refused connection is retried",
69 reply: func(w http.ResponseWriter) {
70 conn, _, err := http.NewResponseController(w).Hijack()
76 errorText: "no valid answer",
79 name: "rate limit waits as asked",
80 reply: func(w http.ResponseWriter) {
81 w.WriteHeader(http.StatusTooManyRequests)
82 _, _ = io.WriteString(w, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`)
85 wait: 3 * time.Second,
86 errorText: "answered 429",
89 name: "server error page is retried",
90 reply: func(w http.ResponseWriter) {
91 w.WriteHeader(http.StatusBadGateway)
92 _, _ = io.WriteString(w, "<html>bad gateway</html>")
95 errorText: "answered 502: Bad Gateway",
98 name: "token echoed in a description is hidden",
99 reply: func(w http.ResponseWriter) {
100 w.WriteHeader(http.StatusUnauthorized)
101 _, _ = io.WriteString(w, `{"ok":false,"error_code":401,"description":"Unauthorized: bot`+testBotToken+`"}`)
104 errorText: "Unauthorized: botTOKEN",
107 name: "broken answer is retried",
108 reply: func(w http.ResponseWriter) {
109 _, _ = io.WriteString(w, `{"ok":`)
112 errorText: "decode answer",
116 for _, tc := range testCases {
117 t.Run(tc.name, func(t *testing.T) {
118 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
121 t.Cleanup(server.Close)
123 err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi")
124 require.ErrorContains(t, err, tc.errorText)
125 require.NotContains(t, err.Error(), testBotToken)
126 require.NotContains(t, err.Error(), server.URL)
128 retry, wait := retryable(err)
129 require.Equal(t, tc.retry, retry)
130 require.Equal(t, tc.wait, wait)
134 server := httptest.NewServer(http.NotFoundHandler())
137 _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0)
138 require.ErrorIs(t, err, errBotNetwork)
139 require.NotContains(t, err.Error(), testBotToken)
142 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
143 // added updates from the offset on, or waits a short time when there are none.
144 // The other methods succeed, unless fail gives an error answer for a call. An
145 // answer with HTTP 429 asks for a wait of one second. Fail runs with the mutex
147 type fakeBot struct {
153 fail func(call fakeBotCall) (int, string)
157 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
159 type fakeBotCall struct {
161 params map[string]any
165 // newFakeBot starts a fake Bot API server that stops at the end of the test.
166 func newFakeBot(t *testing.T) *fakeBot {
170 added: make(chan struct{}, 1),
173 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
179 // Add makes update available to getUpdates.
180 func (f *fakeBot) Add(update botUpdate) {
182 f.updates = append(f.updates, update)
186 case f.added <- struct{}{}:
191 // Calls returns the calls so far.
192 func (f *fakeBot) Calls() []fakeBotCall {
194 defer f.mutex.Unlock()
196 return append([]fakeBotCall(nil), f.calls...)
199 // Sent returns the texts of the sendMessage calls that succeeded.
200 func (f *fakeBot) Sent() []string {
202 for _, call := range f.Calls() {
203 if call.method == "sendMessage" && call.ok {
204 texts = append(texts, call.params["text"].(string))
211 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
212 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
214 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
218 var params map[string]any
219 err := json.NewDecoder(r.Body).Decode(¶ms)
221 http.Error(w, err.Error(), http.StatusBadRequest)
231 status, description := 0, ""
233 status, description = f.fail(call)
240 w.WriteHeader(status)
242 if status == http.StatusTooManyRequests {
246 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
253 if method != "getUpdates" {
254 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
258 offset := int64(params["offset"].(float64))
259 updates := f.from(offset)
260 if len(updates) == 0 {
263 case <-time.After(50 * time.Millisecond):
264 case <-r.Context().Done():
267 updates = f.from(offset)
270 _ = json.NewEncoder(w).Encode(map[string]any{
276 // record keeps call.
277 func (f *fakeBot) record(call fakeBotCall) {
279 defer f.mutex.Unlock()
281 f.calls = append(f.calls, call)
284 // from returns the updates from offset on, and forgets the ones before it, as
286 func (f *fakeBot) from(offset int64) []botUpdate {
288 defer f.mutex.Unlock()
290 var updates []botUpdate
291 kept := f.updates[:0]
292 for _, update := range f.updates {
293 if update.UpdateID >= offset {
294 updates = append(updates, update)
295 kept = append(kept, update)
304 // ownerMessage returns a text message of the owner in the private chat.
305 func ownerMessage(text string) *botMessage {