]> git.giacomolli.uk - onechat/blob - botapi_test.go
565f27d061acfbe5d1444b4dab21a4b27c599aa1
[onechat] / botapi_test.go
1 package main
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 "github.com/stretchr/testify/require"
15 )
16
17 const (
18 // testBotToken is the bot token of the tests. It has the form of a real
19 // token.
20 testBotToken = "123456:TEST-secret_token"
21
22 // testOwner is the user ID of the owner of the test bot.
23 testOwner = 4242
24 )
25
26 func TestGetUpdatesAsksForMessagesFromTheOffset(t *testing.T) {
27 server := newFakeBot(t)
28 server.Add(botUpdate{
29 UpdateID: 7,
30 Message: ownerMessage("hello"),
31 })
32
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)
38
39 call := server.Calls()[0]
40 require.Equal(t, "getUpdates", call.method)
41 require.Equal(t, map[string]any{
42 "offset": float64(7),
43 "timeout": float64(pollSeconds),
44 "allowed_updates": []any{"message"},
45 }, call.params)
46 }
47
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)
52
53 require.Equal(t, map[string]any{
54 "chat_id": float64(testOwner),
55 "text": "*not bold*",
56 }, server.Calls()[0].params)
57 }
58
59 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
60 testCases := []struct {
61 name string
62 reply func(w http.ResponseWriter)
63 retry bool
64 wait time.Duration
65 errorText string
66 }{
67 {
68 name: "refused connection is retried",
69 reply: func(w http.ResponseWriter) {
70 conn, _, err := http.NewResponseController(w).Hijack()
71 if err == nil {
72 _ = conn.Close()
73 }
74 },
75 retry: true,
76 errorText: "no valid answer",
77 },
78 {
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}}`)
83 },
84 retry: true,
85 wait: 3 * time.Second,
86 errorText: "answered 429",
87 },
88 {
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>")
93 },
94 retry: true,
95 errorText: "answered 502: Bad Gateway",
96 },
97 {
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+`"}`)
102 },
103 retry: false,
104 errorText: "Unauthorized: botTOKEN",
105 },
106 {
107 name: "broken answer is retried",
108 reply: func(w http.ResponseWriter) {
109 _, _ = io.WriteString(w, `{"ok":`)
110 },
111 retry: true,
112 errorText: "decode answer",
113 },
114 }
115
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) {
119 tc.reply(w)
120 }))
121 t.Cleanup(server.Close)
122
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)
127
128 retry, wait := retryable(err)
129 require.Equal(t, tc.retry, retry)
130 require.Equal(t, tc.wait, wait)
131 })
132 }
133
134 server := httptest.NewServer(http.NotFoundHandler())
135 server.Close()
136
137 _, err := newBotAPI(server.URL, testBotToken).GetUpdates(t.Context(), 0)
138 require.ErrorIs(t, err, errBotNetwork)
139 require.NotContains(t, err.Error(), testBotToken)
140 }
141
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 {
146 *httptest.Server
147
148 mutex sync.Mutex
149 updates []botUpdate
150 calls []fakeBotCall
151 fail func(call fakeBotCall) (int, string)
152 added chan struct{}
153 }
154
155 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
156 // success answer.
157 type fakeBotCall struct {
158 method string
159 params map[string]any
160 ok bool
161 }
162
163 // newFakeBot starts a fake Bot API server that stops at the end of the test.
164 func newFakeBot(t *testing.T) *fakeBot {
165 t.Helper()
166
167 f := &fakeBot{
168 added: make(chan struct{}, 1),
169 }
170
171 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
172 t.Cleanup(f.Close)
173
174 return f
175 }
176
177 // Add makes update available to getUpdates.
178 func (f *fakeBot) Add(update botUpdate) {
179 f.mutex.Lock()
180 f.updates = append(f.updates, update)
181 f.mutex.Unlock()
182
183 select {
184 case f.added <- struct{}{}:
185 default:
186 }
187 }
188
189 // Calls returns the calls so far.
190 func (f *fakeBot) Calls() []fakeBotCall {
191 f.mutex.Lock()
192 defer f.mutex.Unlock()
193
194 return append([]fakeBotCall(nil), f.calls...)
195 }
196
197 // Sent returns the texts of the sendMessage calls that succeeded.
198 func (f *fakeBot) Sent() []string {
199 var texts []string
200 for _, call := range f.Calls() {
201 if call.method == "sendMessage" && call.ok {
202 texts = append(texts, call.params["text"].(string))
203 }
204 }
205
206 return texts
207 }
208
209 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
210 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
211 if !found {
212 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
213 return
214 }
215
216 var params map[string]any
217 err := json.NewDecoder(r.Body).Decode(&params)
218 if err != nil {
219 http.Error(w, err.Error(), http.StatusBadRequest)
220 return
221 }
222
223 call := fakeBotCall{
224 method: method,
225 params: params,
226 }
227
228 f.mutex.Lock()
229 fail := f.fail
230 f.mutex.Unlock()
231
232 status, description := 0, ""
233 if fail != nil {
234 status, description = fail(call)
235 }
236
237 if status != 0 {
238 f.record(call)
239 w.WriteHeader(status)
240 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":1}}`, status, description)
241
242 return
243 }
244
245 call.ok = true
246 f.record(call)
247 if method != "getUpdates" {
248 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
249 return
250 }
251
252 offset := int64(params["offset"].(float64))
253 updates := f.from(offset)
254 if len(updates) == 0 {
255 select {
256 case <-f.added:
257 case <-time.After(50 * time.Millisecond):
258 case <-r.Context().Done():
259 }
260
261 updates = f.from(offset)
262 }
263
264 _ = json.NewEncoder(w).Encode(map[string]any{
265 "ok": true,
266 "result": updates,
267 })
268 }
269
270 // record keeps call.
271 func (f *fakeBot) record(call fakeBotCall) {
272 f.mutex.Lock()
273 defer f.mutex.Unlock()
274
275 f.calls = append(f.calls, call)
276 }
277
278 // from returns the updates from offset on, and forgets the ones before it, as
279 // Telegram does.
280 func (f *fakeBot) from(offset int64) []botUpdate {
281 f.mutex.Lock()
282 defer f.mutex.Unlock()
283
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)
290 }
291 }
292
293 f.updates = kept
294
295 return updates
296 }
297
298 // ownerMessage returns a text message of the owner in the private chat.
299 func ownerMessage(text string) *botMessage {
300 return &botMessage{
301 Chat: botChat{
302 ID: testOwner,
303 Type: "private",
304 },
305 From: &botUser{
306 ID: testOwner,
307 },
308 Text: text,
309 }
310 }