18 // telegramTestToken is the bot token of the tests. It has the form of a
20 telegramTestToken = "123456:TEST-secret_token"
22 // telegramTestOwner is the user ID of the owner of the test bot.
23 telegramTestOwner = 4242
26 // TelegramFakeCall is one call of the fake Bot API. OK tells if the call got a
28 type TelegramFakeCall struct {
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 {
44 updates []TelegramUpdate
45 calls []TelegramFakeCall
46 fail func(call TelegramFakeCall) (int, string)
47 stall func(call TelegramFakeCall) bool
50 images map[string][]byte
53 // newTelegramFake starts a fake Bot API server that stops at the end of the
55 func newTelegramFake(t *testing.T) *TelegramFake {
59 added: make(chan struct{}, 1),
60 stopped: make(chan struct{}),
63 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
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 {
78 Server: &httptest.Server{URL: "https://example.com"},
79 added: make(chan struct{}, 1),
80 stopped: make(chan struct{}),
89 // Add makes update available to getUpdates.
90 func (f *TelegramFake) Add(update TelegramUpdate) {
93 f.updates = append(f.updates, update)
97 case f.added <- struct{}{}:
102 // Calls returns the calls so far.
103 func (f *TelegramFake) Calls() []TelegramFakeCall {
105 defer f.mutex.Unlock()
107 return append([]TelegramFakeCall(nil), f.calls...)
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 {
115 for _, call := range f.Calls() {
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))
128 func (f *TelegramFake) Image(id string, data []byte) {
130 defer f.mutex.Unlock()
133 f.images = make(map[string][]byte)
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)
144 ctx := request.Context()
145 if ctx.Err() != nil {
146 return nil, ctx.Err()
149 return response.Result(), nil
152 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
153 id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
157 data, exists := f.images[id]
171 method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
173 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
178 var params map[string]any
182 if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data;") {
183 err = r.ParseMultipartForm(imageMaxBytes + (1 << 20))
185 params = make(map[string]any)
186 for key, values := range r.MultipartForm.Value {
187 params[key] = values[0]
190 for key, files := range r.MultipartForm.File {
191 var file multipart.File
193 file, err = files[0].Open()
198 params[key], err = io.ReadAll(file)
199 err = errors.Join(err, file.Close())
200 params[key+"_name"] = files[0].Filename
206 err = errors.Join(err, r.MultipartForm.RemoveAll())
209 err = json.NewDecoder(r.Body).Decode(¶ms)
213 http.Error(w, err.Error(), http.StatusBadRequest)
218 call := TelegramFakeCall{
225 status, description := 0, ""
227 status, description = f.fail(call)
230 stall := f.stall != nil && f.stall(call)
237 case <-r.Context().Done():
246 w.WriteHeader(status)
249 if status == http.StatusTooManyRequests {
253 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
261 if method == "getFile" {
262 _ = json.NewEncoder(w).Encode(map[string]any{
264 "result": map[string]any{"file_path": params["file_id"]},
270 if method != "getUpdates" {
271 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
275 offset := int64(params["offset"].(float64))
276 updates := f.from(offset)
277 if len(updates) == 0 {
280 case <-time.After(50 * time.Millisecond):
281 case <-r.Context().Done():
284 updates = f.from(offset)
287 _ = json.NewEncoder(w).Encode(map[string]any{
293 // record keeps call.
294 func (f *TelegramFake) record(call TelegramFakeCall) {
296 defer f.mutex.Unlock()
298 f.calls = append(f.calls, call)
301 // from returns the updates from offset on, and forgets the ones before it, as
303 func (f *TelegramFake) from(offset int64) []TelegramUpdate {
305 defer f.mutex.Unlock()
307 var updates []TelegramUpdate
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)
322 // telegramOwnerMessage returns a text message of the owner in the private chat.
323 func telegramOwnerMessage(text string) *TelegramMessage {
324 return &TelegramMessage{
326 ID: telegramTestOwner,
330 ID: telegramTestOwner,