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.
145 type fakeBot struct {
151 fail func(call fakeBotCall) (int, string)
155 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
157 type fakeBotCall struct {
159 params map[string]any
163 // newFakeBot starts a fake Bot API server that stops at the end of the test.
164 func newFakeBot(t *testing.T) *fakeBot {
168 added: make(chan struct{}, 1),
171 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
177 // Add makes update available to getUpdates.
178 func (f *fakeBot) Add(update botUpdate) {
180 f.updates = append(f.updates, update)
184 case f.added <- struct{}{}:
189 // Calls returns the calls so far.
190 func (f *fakeBot) Calls() []fakeBotCall {
192 defer f.mutex.Unlock()
194 return append([]fakeBotCall(nil), f.calls...)
197 // Sent returns the texts of the sendMessage calls that succeeded.
198 func (f *fakeBot) Sent() []string {
200 for _, call := range f.Calls() {
201 if call.method == "sendMessage" && call.ok {
202 texts = append(texts, call.params["text"].(string))
209 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
210 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
212 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
216 var params map[string]any
217 err := json.NewDecoder(r.Body).Decode(¶ms)
219 http.Error(w, err.Error(), http.StatusBadRequest)
232 status, description := 0, ""
234 status, description = fail(call)
239 w.WriteHeader(status)
240 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":1}}`, status, description)
247 if method != "getUpdates" {
248 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
252 offset := int64(params["offset"].(float64))
253 updates := f.from(offset)
254 if len(updates) == 0 {
257 case <-time.After(50 * time.Millisecond):
258 case <-r.Context().Done():
261 updates = f.from(offset)
264 _ = json.NewEncoder(w).Encode(map[string]any{
270 // record keeps call.
271 func (f *fakeBot) record(call fakeBotCall) {
273 defer f.mutex.Unlock()
275 f.calls = append(f.calls, call)
278 // from returns the updates from offset on, and forgets the ones before it, as
280 func (f *fakeBot) from(offset int64) []botUpdate {
282 defer f.mutex.Unlock()
284 var updates []botUpdate
285 kept := f.updates[:0]
286 for _, update := range f.updates {
287 if update.UpdateID >= offset {
288 updates = append(updates, update)
289 kept = append(kept, update)
298 // ownerMessage returns a text message of the owner in the private chat.
299 func ownerMessage(text string) *botMessage {