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