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 // Add makes update available to getUpdates.
54 func (f *TelegramFake) Add(update TelegramUpdate) {
57 f.updates = append(f.updates, update)
61 case f.added <- struct{}{}:
66 // Calls returns the calls so far.
67 func (f *TelegramFake) Calls() []TelegramFakeCall {
69 defer f.mutex.Unlock()
71 return append([]TelegramFakeCall(nil), f.calls...)
74 // Sent returns the texts of the sendMessage calls and the Markdown of the
75 // sendRichMessage calls that succeeded, in order.
76 func (f *TelegramFake) Sent() []string {
79 for _, call := range f.Calls() {
82 case call.method == "sendMessage":
83 texts = append(texts, call.params["text"].(string))
84 case call.method == "sendRichMessage":
85 texts = append(texts, call.params["rich_message"].(map[string]any)["markdown"].(string))
92 func (f *TelegramFake) Image(id string, data []byte) {
94 defer f.mutex.Unlock()
97 f.images = make(map[string][]byte)
103 // RoundTrip handles a request in memory, so synctest can control its timers.
104 func (f *TelegramFake) RoundTrip(request *http.Request) (*http.Response, error) {
105 response := httptest.NewRecorder()
106 f.serve(response, request)
108 ctx := request.Context()
109 if ctx.Err() != nil {
110 return nil, ctx.Err()
113 return response.Result(), nil
116 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
117 id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
121 data, exists := f.images[id]
135 method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
137 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
142 var params map[string]any
146 if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data;") {
147 err = r.ParseMultipartForm(imageMaxBytes + (1 << 20))
149 params = make(map[string]any)
150 for key, values := range r.MultipartForm.Value {
151 params[key] = values[0]
154 for key, files := range r.MultipartForm.File {
155 var file multipart.File
157 file, err = files[0].Open()
162 params[key], err = io.ReadAll(file)
163 err = errors.Join(err, file.Close())
164 params[key+"_name"] = files[0].Filename
170 err = errors.Join(err, r.MultipartForm.RemoveAll())
173 err = json.NewDecoder(r.Body).Decode(¶ms)
177 http.Error(w, err.Error(), http.StatusBadRequest)
182 call := TelegramFakeCall{
189 status, description := 0, ""
191 status, description = f.fail(call)
194 stall := f.stall != nil && f.stall(call)
201 case <-r.Context().Done():
210 w.WriteHeader(status)
213 if status == http.StatusTooManyRequests {
217 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
225 if method == "getFile" {
226 _ = json.NewEncoder(w).Encode(map[string]any{
228 "result": map[string]any{"file_path": params["file_id"]},
234 if method != "getUpdates" {
235 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
239 offset := int64(params["offset"].(float64))
240 updates := f.from(offset)
241 if len(updates) == 0 {
244 case <-time.After(50 * time.Millisecond):
245 case <-r.Context().Done():
248 updates = f.from(offset)
251 _ = json.NewEncoder(w).Encode(map[string]any{
257 // record keeps call.
258 func (f *TelegramFake) record(call TelegramFakeCall) {
260 defer f.mutex.Unlock()
262 f.calls = append(f.calls, call)
265 // from returns the updates from offset on, and forgets the ones before it, as
267 func (f *TelegramFake) from(offset int64) []TelegramUpdate {
269 defer f.mutex.Unlock()
271 var updates []TelegramUpdate
273 kept := f.updates[:0]
274 for _, update := range f.updates {
275 if update.UpdateID >= offset {
276 updates = append(updates, update)
277 kept = append(kept, update)
286 // newTelegramFake starts a fake Bot API server that stops at the end of the
288 func newTelegramFake(t *testing.T) *TelegramFake {
292 added: make(chan struct{}, 1),
293 stopped: make(chan struct{}),
296 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
305 // newTelegramLocalFake returns the same fake API without network goroutines.
306 // Its RoundTrip handles requests directly for tests with fake time.
307 func newTelegramLocalFake(t *testing.T) *TelegramFake {
311 Server: &httptest.Server{URL: "https://example.com"},
312 added: make(chan struct{}, 1),
313 stopped: make(chan struct{}),
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,