]> git.giacomolli.uk - onechat/blob - telegram_fake_helper_test.go
Separate multiline Go statements
[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
83 t.Cleanup(func() {
84 close(f.stopped)
85 })
86
87 return f
88 }
89
90 // Add makes update available to getUpdates.
91 func (f *TelegramFake) Add(update TelegramUpdate) {
92 f.mutex.Lock()
93
94 f.updates = append(f.updates, update)
95 f.mutex.Unlock()
96
97 select {
98 case f.added <- struct{}{}:
99 default:
100 }
101 }
102
103 // Calls returns the calls so far.
104 func (f *TelegramFake) Calls() []TelegramFakeCall {
105 f.mutex.Lock()
106 defer f.mutex.Unlock()
107
108 return append([]TelegramFakeCall(nil), f.calls...)
109 }
110
111 // Sent returns the texts of the sendMessage calls and the Markdown of the
112 // sendRichMessage calls that succeeded, in order.
113 func (f *TelegramFake) Sent() []string {
114 var texts []string
115
116 for _, call := range f.Calls() {
117 switch {
118 case !call.ok:
119 case call.method == "sendMessage":
120 texts = append(texts, call.params["text"].(string))
121 case call.method == "sendRichMessage":
122 texts = append(texts, call.params["rich_message"].(map[string]any)["markdown"].(string))
123 }
124 }
125
126 return texts
127 }
128
129 func (f *TelegramFake) Image(id string, data []byte) {
130 f.mutex.Lock()
131 defer f.mutex.Unlock()
132
133 if f.images == nil {
134 f.images = make(map[string][]byte)
135 }
136
137 f.images[id] = data
138 }
139
140 // RoundTrip handles a request in memory, so synctest can control its timers.
141 func (f *TelegramFake) RoundTrip(request *http.Request) (*http.Response, error) {
142 response := httptest.NewRecorder()
143 f.serve(response, request)
144
145 ctx := request.Context()
146 if ctx.Err() != nil {
147 return nil, ctx.Err()
148 }
149
150 return response.Result(), nil
151 }
152
153 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
154 id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
155 if file {
156 f.mutex.Lock()
157
158 data, exists := f.images[id]
159 f.mutex.Unlock()
160
161 if !exists {
162 http.NotFound(w, r)
163
164 return
165 }
166
167 _, _ = w.Write(data)
168
169 return
170 }
171
172 method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
173 if !found {
174 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
175
176 return
177 }
178
179 var params map[string]any
180
181 var err error
182
183 if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data;") {
184 err = r.ParseMultipartForm(imageMaxBytes + (1 << 20))
185 if err == nil {
186 params = make(map[string]any)
187 for key, values := range r.MultipartForm.Value {
188 params[key] = values[0]
189 }
190
191 for key, files := range r.MultipartForm.File {
192 var file multipart.File
193
194 file, err = files[0].Open()
195 if err != nil {
196 break
197 }
198
199 params[key], err = io.ReadAll(file)
200 err = errors.Join(err, file.Close())
201 params[key+"_name"] = files[0].Filename
202 if err != nil {
203 break
204 }
205 }
206
207 err = errors.Join(err, r.MultipartForm.RemoveAll())
208 }
209 } else {
210 err = json.NewDecoder(r.Body).Decode(&params)
211 }
212
213 if err != nil {
214 http.Error(w, err.Error(), http.StatusBadRequest)
215
216 return
217 }
218
219 call := TelegramFakeCall{
220 method: method,
221 params: params,
222 }
223
224 f.mutex.Lock()
225
226 status, description := 0, ""
227 if f.fail != nil {
228 status, description = f.fail(call)
229 }
230
231 stall := f.stall != nil && f.stall(call)
232 f.mutex.Unlock()
233
234 if stall {
235 f.record(call)
236
237 select {
238 case <-r.Context().Done():
239 case <-f.stopped:
240 }
241
242 return
243 }
244
245 if status != 0 {
246 f.record(call)
247 w.WriteHeader(status)
248
249 wait := 0
250 if status == http.StatusTooManyRequests {
251 wait = 1
252 }
253
254 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
255
256 return
257 }
258
259 call.ok = true
260 f.record(call)
261
262 if method == "getFile" {
263 _ = json.NewEncoder(w).Encode(map[string]any{
264 "ok": true,
265 "result": map[string]any{"file_path": params["file_id"]},
266 })
267
268 return
269 }
270
271 if method != "getUpdates" {
272 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
273 return
274 }
275
276 offset := int64(params["offset"].(float64))
277 updates := f.from(offset)
278 if len(updates) == 0 {
279 select {
280 case <-f.added:
281 case <-time.After(50 * time.Millisecond):
282 case <-r.Context().Done():
283 }
284
285 updates = f.from(offset)
286 }
287
288 _ = json.NewEncoder(w).Encode(map[string]any{
289 "ok": true,
290 "result": updates,
291 })
292 }
293
294 // record keeps call.
295 func (f *TelegramFake) record(call TelegramFakeCall) {
296 f.mutex.Lock()
297 defer f.mutex.Unlock()
298
299 f.calls = append(f.calls, call)
300 }
301
302 // from returns the updates from offset on, and forgets the ones before it, as
303 // Telegram does.
304 func (f *TelegramFake) from(offset int64) []TelegramUpdate {
305 f.mutex.Lock()
306 defer f.mutex.Unlock()
307
308 var updates []TelegramUpdate
309
310 kept := f.updates[:0]
311 for _, update := range f.updates {
312 if update.UpdateID >= offset {
313 updates = append(updates, update)
314 kept = append(kept, update)
315 }
316 }
317
318 f.updates = kept
319
320 return updates
321 }
322
323 // telegramOwnerMessage returns a text message of the owner in the private chat.
324 func telegramOwnerMessage(text string) *TelegramMessage {
325 return &TelegramMessage{
326 Chat: TelegramChat{
327 ID: telegramTestOwner,
328 Type: "private",
329 },
330 From: &TelegramUser{
331 ID: telegramTestOwner,
332 },
333 Text: text,
334 }
335 }