]> git.giacomolli.uk - onechat/blob - telegram_fake_helper_test.go
6082d7ddac1b87190475bb6bb583692207b0c293
[onechat] / telegram_fake_helper_test.go
1 package main
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io"
8 "mime/multipart"
9 "net/http"
10 "net/http/httptest"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15 )
16
17 const (
18 // telegramTestToken is the bot token of the tests. It has the form of a
19 // real token.
20 telegramTestToken = "123456:TEST-secret_token"
21
22 // telegramTestOwner is the user ID of the owner of the test bot.
23 telegramTestOwner = 4242
24 )
25
26 // TelegramFakeCall is one call of the fake Bot API. OK tells if the call got a
27 // success answer.
28 type TelegramFakeCall struct {
29 method string
30 params map[string]any
31 ok bool
32 }
33
34 // TelegramFake is a fake Bot API server for telegramTestToken. getUpdates
35 // returns the added updates from the offset on, or waits a short time when
36 // there are none. The other methods succeed, unless fail gives an error answer
37 // for a call. An answer with HTTP 429 asks for a wait of one second. When stall
38 // is true for a call, the call gets no answer until the client gives it up or
39 // the test ends. Fail and stall run with the mutex held.
40 type TelegramFake struct {
41 *httptest.Server
42
43 mutex sync.Mutex
44 updates []TelegramUpdate
45 calls []TelegramFakeCall
46 fail func(call TelegramFakeCall) (int, string)
47 stall func(call TelegramFakeCall) bool
48 added chan struct{}
49 stopped chan struct{}
50 images map[string][]byte
51 }
52
53 // newTelegramFake starts a fake Bot API server that stops at the end of the
54 // test.
55 func newTelegramFake(t *testing.T) *TelegramFake {
56 t.Helper()
57
58 f := &TelegramFake{
59 added: make(chan struct{}, 1),
60 stopped: make(chan struct{}),
61 }
62
63 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
64 t.Cleanup(f.Close)
65 t.Cleanup(func() {
66 close(f.stopped)
67 })
68
69 return f
70 }
71
72 // newTelegramLocalFake returns the same fake API without network goroutines.
73 // Its RoundTrip handles requests directly for tests with fake time.
74 func newTelegramLocalFake(t *testing.T) *TelegramFake {
75 t.Helper()
76
77 f := &TelegramFake{
78 Server: &httptest.Server{URL: "https://example.com"},
79 added: make(chan struct{}, 1),
80 stopped: make(chan struct{}),
81 }
82 t.Cleanup(func() {
83 close(f.stopped)
84 })
85
86 return f
87 }
88
89 // Add makes update available to getUpdates.
90 func (f *TelegramFake) Add(update TelegramUpdate) {
91 f.mutex.Lock()
92
93 f.updates = append(f.updates, update)
94 f.mutex.Unlock()
95
96 select {
97 case f.added <- struct{}{}:
98 default:
99 }
100 }
101
102 // Calls returns the calls so far.
103 func (f *TelegramFake) Calls() []TelegramFakeCall {
104 f.mutex.Lock()
105 defer f.mutex.Unlock()
106
107 return append([]TelegramFakeCall(nil), f.calls...)
108 }
109
110 // Sent returns the texts of the sendMessage calls and the Markdown of the
111 // sendRichMessage calls that succeeded, in order.
112 func (f *TelegramFake) Sent() []string {
113 var texts []string
114
115 for _, call := range f.Calls() {
116 switch {
117 case !call.ok:
118 case call.method == "sendMessage":
119 texts = append(texts, call.params["text"].(string))
120 case call.method == "sendRichMessage":
121 texts = append(texts, call.params["rich_message"].(map[string]any)["markdown"].(string))
122 }
123 }
124
125 return texts
126 }
127
128 func (f *TelegramFake) Image(id string, data []byte) {
129 f.mutex.Lock()
130 defer f.mutex.Unlock()
131
132 if f.images == nil {
133 f.images = make(map[string][]byte)
134 }
135
136 f.images[id] = data
137 }
138
139 // RoundTrip handles a request in memory, so synctest can control its timers.
140 func (f *TelegramFake) RoundTrip(request *http.Request) (*http.Response, error) {
141 response := httptest.NewRecorder()
142 f.serve(response, request)
143
144 ctx := request.Context()
145 if ctx.Err() != nil {
146 return nil, ctx.Err()
147 }
148
149 return response.Result(), nil
150 }
151
152 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
153 id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
154 if file {
155 f.mutex.Lock()
156
157 data, exists := f.images[id]
158 f.mutex.Unlock()
159
160 if !exists {
161 http.NotFound(w, r)
162
163 return
164 }
165
166 _, _ = w.Write(data)
167
168 return
169 }
170
171 method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
172 if !found {
173 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
174
175 return
176 }
177
178 var params map[string]any
179
180 var err error
181
182 if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data;") {
183 err = r.ParseMultipartForm(imageMaxBytes + (1 << 20))
184 if err == nil {
185 params = make(map[string]any)
186 for key, values := range r.MultipartForm.Value {
187 params[key] = values[0]
188 }
189
190 for key, files := range r.MultipartForm.File {
191 var file multipart.File
192
193 file, err = files[0].Open()
194 if err != nil {
195 break
196 }
197
198 params[key], err = io.ReadAll(file)
199 err = errors.Join(err, file.Close())
200 params[key+"_name"] = files[0].Filename
201 if err != nil {
202 break
203 }
204 }
205
206 err = errors.Join(err, r.MultipartForm.RemoveAll())
207 }
208 } else {
209 err = json.NewDecoder(r.Body).Decode(&params)
210 }
211
212 if err != nil {
213 http.Error(w, err.Error(), http.StatusBadRequest)
214
215 return
216 }
217
218 call := TelegramFakeCall{
219 method: method,
220 params: params,
221 }
222
223 f.mutex.Lock()
224
225 status, description := 0, ""
226 if f.fail != nil {
227 status, description = f.fail(call)
228 }
229
230 stall := f.stall != nil && f.stall(call)
231 f.mutex.Unlock()
232
233 if stall {
234 f.record(call)
235
236 select {
237 case <-r.Context().Done():
238 case <-f.stopped:
239 }
240
241 return
242 }
243
244 if status != 0 {
245 f.record(call)
246 w.WriteHeader(status)
247
248 wait := 0
249 if status == http.StatusTooManyRequests {
250 wait = 1
251 }
252
253 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
254
255 return
256 }
257
258 call.ok = true
259 f.record(call)
260
261 if method == "getFile" {
262 _ = json.NewEncoder(w).Encode(map[string]any{
263 "ok": true,
264 "result": map[string]any{"file_path": params["file_id"]},
265 })
266
267 return
268 }
269
270 if method != "getUpdates" {
271 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
272 return
273 }
274
275 offset := int64(params["offset"].(float64))
276 updates := f.from(offset)
277 if len(updates) == 0 {
278 select {
279 case <-f.added:
280 case <-time.After(50 * time.Millisecond):
281 case <-r.Context().Done():
282 }
283
284 updates = f.from(offset)
285 }
286
287 _ = json.NewEncoder(w).Encode(map[string]any{
288 "ok": true,
289 "result": updates,
290 })
291 }
292
293 // record keeps call.
294 func (f *TelegramFake) record(call TelegramFakeCall) {
295 f.mutex.Lock()
296 defer f.mutex.Unlock()
297
298 f.calls = append(f.calls, call)
299 }
300
301 // from returns the updates from offset on, and forgets the ones before it, as
302 // Telegram does.
303 func (f *TelegramFake) from(offset int64) []TelegramUpdate {
304 f.mutex.Lock()
305 defer f.mutex.Unlock()
306
307 var updates []TelegramUpdate
308
309 kept := f.updates[:0]
310 for _, update := range f.updates {
311 if update.UpdateID >= offset {
312 updates = append(updates, update)
313 kept = append(kept, update)
314 }
315 }
316
317 f.updates = kept
318
319 return updates
320 }
321
322 // telegramOwnerMessage returns a text message of the owner in the private chat.
323 func telegramOwnerMessage(text string) *TelegramMessage {
324 return &TelegramMessage{
325 Chat: TelegramChat{
326 ID: telegramTestOwner,
327 Type: "private",
328 },
329 From: &TelegramUser{
330 ID: telegramTestOwner,
331 },
332 Text: text,
333 }
334 }