16 // telegramTestToken is the bot token of the tests. It has the form of a
18 telegramTestToken = "123456:TEST-secret_token"
20 // telegramTestOwner is the user ID of the owner of the test bot.
21 telegramTestOwner = 4242
24 // TelegramFakeCall is one call of the fake Bot API. OK tells if the call got a
26 type TelegramFakeCall struct {
32 // TelegramFake is a fake Bot API server for telegramTestToken. getUpdates
33 // returns the added updates from the offset on, or waits a short time when
34 // there are none. The other methods succeed, unless fail gives an error answer
35 // for a call. An answer with HTTP 429 asks for a wait of one second. When stall
36 // is true for a call, the call gets no answer until the client gives it up or
37 // the test ends. Fail and stall run with the mutex held.
38 type TelegramFake struct {
42 updates []TelegramUpdate
43 calls []TelegramFakeCall
44 fail func(call TelegramFakeCall) (int, string)
45 stall func(call TelegramFakeCall) bool
48 images map[string][]byte
51 // Add makes update available to getUpdates.
52 func (f *TelegramFake) Add(update TelegramUpdate) {
55 f.updates = append(f.updates, update)
59 case f.added <- struct{}{}:
64 // Calls returns the calls so far.
65 func (f *TelegramFake) Calls() []TelegramFakeCall {
67 defer f.mutex.Unlock()
69 return append([]TelegramFakeCall(nil), f.calls...)
72 // Sent returns the texts of the sendMessage calls and the Markdown of the
73 // sendRichMessage calls that succeeded, in order.
74 func (f *TelegramFake) Sent() []string {
77 for _, call := range f.Calls() {
80 case call.method == "sendMessage":
81 texts = append(texts, call.params["text"].(string))
82 case call.method == "sendRichMessage":
83 texts = append(texts, call.params["rich_message"].(map[string]any)["markdown"].(string))
90 func (f *TelegramFake) Image(id string, data []byte) {
92 defer f.mutex.Unlock()
95 f.images = make(map[string][]byte)
101 // RoundTrip handles a request in memory, so synctest can control its timers.
102 func (f *TelegramFake) RoundTrip(request *http.Request) (*http.Response, error) {
103 response := httptest.NewRecorder()
104 f.serve(response, request)
106 ctx := request.Context()
107 if ctx.Err() != nil {
108 return nil, ctx.Err()
111 return response.Result(), nil
114 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
115 id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
119 data, exists := f.images[id]
133 method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
135 http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
140 var params map[string]any
142 err := json.NewDecoder(r.Body).Decode(¶ms)
144 http.Error(w, err.Error(), http.StatusBadRequest)
149 call := TelegramFakeCall{
156 status, description := 0, ""
158 status, description = f.fail(call)
161 stall := f.stall != nil && f.stall(call)
168 case <-r.Context().Done():
177 w.WriteHeader(status)
180 if status == http.StatusTooManyRequests {
184 _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
192 if method == "getFile" {
193 _ = json.NewEncoder(w).Encode(map[string]any{
195 "result": map[string]any{"file_path": params["file_id"]},
201 if method != "getUpdates" {
202 _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
206 offset := int64(params["offset"].(float64))
207 updates := f.from(offset)
208 if len(updates) == 0 {
211 case <-time.After(50 * time.Millisecond):
212 case <-r.Context().Done():
215 updates = f.from(offset)
218 _ = json.NewEncoder(w).Encode(map[string]any{
224 // record keeps call.
225 func (f *TelegramFake) record(call TelegramFakeCall) {
227 defer f.mutex.Unlock()
229 f.calls = append(f.calls, call)
232 // from returns the updates from offset on, and forgets the ones before it, as
234 func (f *TelegramFake) from(offset int64) []TelegramUpdate {
236 defer f.mutex.Unlock()
238 var updates []TelegramUpdate
240 kept := f.updates[:0]
241 for _, update := range f.updates {
242 if update.UpdateID >= offset {
243 updates = append(updates, update)
244 kept = append(kept, update)
253 // newTelegramFake starts a fake Bot API server that stops at the end of the
255 func newTelegramFake(t *testing.T) *TelegramFake {
259 added: make(chan struct{}, 1),
260 stopped: make(chan struct{}),
263 f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
272 // newTelegramLocalFake returns the same fake API without network goroutines.
273 // Its RoundTrip handles requests directly for tests with fake time.
274 func newTelegramLocalFake(t *testing.T) *TelegramFake {
278 Server: &httptest.Server{URL: "https://example.com"},
279 added: make(chan struct{}, 1),
280 stopped: make(chan struct{}),
289 // telegramOwnerMessage returns a text message of the owner in the private chat.
290 func telegramOwnerMessage(text string) *TelegramMessage {
291 return &TelegramMessage{
293 ID: telegramTestOwner,
297 ID: telegramTestOwner,