]> git.giacomolli.uk - onechat/blob - botapi_test.go
b571c6ae0e625fc1d6b1704ad40f9f60be901a82
[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. An
145 // answer with HTTP 429 asks for a wait of one second. Fail runs with the mutex
146 // held.
147 type fakeBot struct {
148 *httptest.Server
149
150 mutex sync.Mutex
151 updates []botUpdate
152 calls []fakeBotCall
153 fail func(call fakeBotCall) (int, string)
154 added chan struct{}
155 }
156
157 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
158 // success answer.
159 type fakeBotCall struct {
160 method string
161 params map[string]any
162 ok bool
163 }
164
165 // newFakeBot starts a fake Bot API server that stops at the end of the test.
166 func newFakeBot(t *testing.T) *fakeBot {
167 t.Helper()
168
169 f := &fakeBot{
170 added: make(chan struct{}, 1),
171 }
172
173 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
174 t.Cleanup(f.Close)
175
176 return f
177 }
178
179 // Add makes update available to getUpdates.
180 func (f *fakeBot) Add(update botUpdate) {
181 f.mutex.Lock()
182 f.updates = append(f.updates, update)
183 f.mutex.Unlock()
184
185 select {
186 case f.added <- struct{}{}:
187 default:
188 }
189 }
190
191 // Calls returns the calls so far.
192 func (f *fakeBot) Calls() []fakeBotCall {
193 f.mutex.Lock()
194 defer f.mutex.Unlock()
195
196 return append([]fakeBotCall(nil), f.calls...)
197 }
198
199 // Sent returns the texts of the sendMessage calls that succeeded.
200 func (f *fakeBot) Sent() []string {
201 var texts []string
202 for _, call := range f.Calls() {
203 if call.method == "sendMessage" && call.ok {
204 texts = append(texts, call.params["text"].(string))
205 }
206 }
207
208 return texts
209 }
210
211 func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
212 method, found := strings.CutPrefix(r.URL.Path, "/bot"+testBotToken+"/")
213 if !found {
214 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
215 return
216 }
217
218 var params map[string]any
219 err := json.NewDecoder(r.Body).Decode(&params)
220 if err != nil {
221 http.Error(w, err.Error(), http.StatusBadRequest)
222 return
223 }
224
225 call := fakeBotCall{
226 method: method,
227 params: params,
228 }
229
230 f.mutex.Lock()
231 status, description := 0, ""
232 if f.fail != nil {
233 status, description = f.fail(call)
234 }
235
236 f.mutex.Unlock()
237
238 if status != 0 {
239 f.record(call)
240 w.WriteHeader(status)
241 wait := 0
242 if status == http.StatusTooManyRequests {
243 wait = 1
244 }
245
246 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
247
248 return
249 }
250
251 call.ok = true
252 f.record(call)
253 if method != "getUpdates" {
254 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
255 return
256 }
257
258 offset := int64(params["offset"].(float64))
259 updates := f.from(offset)
260 if len(updates) == 0 {
261 select {
262 case <-f.added:
263 case <-time.After(50 * time.Millisecond):
264 case <-r.Context().Done():
265 }
266
267 updates = f.from(offset)
268 }
269
270 _ = json.NewEncoder(w).Encode(map[string]any{
271 "ok": true,
272 "result": updates,
273 })
274 }
275
276 // record keeps call.
277 func (f *fakeBot) record(call fakeBotCall) {
278 f.mutex.Lock()
279 defer f.mutex.Unlock()
280
281 f.calls = append(f.calls, call)
282 }
283
284 // from returns the updates from offset on, and forgets the ones before it, as
285 // Telegram does.
286 func (f *fakeBot) from(offset int64) []botUpdate {
287 f.mutex.Lock()
288 defer f.mutex.Unlock()
289
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)
296 }
297 }
298
299 f.updates = kept
300
301 return updates
302 }
303
304 // ownerMessage returns a text message of the owner in the private chat.
305 func ownerMessage(text string) *botMessage {
306 return &botMessage{
307 Chat: botChat{
308 ID: testOwner,
309 Type: "private",
310 },
311 From: &botUser{
312 ID: testOwner,
313 },
314 Text: text,
315 }
316 }