]> git.giacomolli.uk - onechat/blobdiff - telegram_fake_helper_test.go
Name timeouts for the operations they limit
[onechat] / telegram_fake_helper_test.go
index a70a199c0febbdadc719e37e417236fcfb070653..f6ccd8425d41e36372fc51fb8e8a5afc7f2b2216 100644 (file)
@@ -45,11 +45,13 @@ type TelegramFake struct {
        stall   func(call TelegramFakeCall) bool
        added   chan struct{}
        stopped chan struct{}
        stall   func(call TelegramFakeCall) bool
        added   chan struct{}
        stopped chan struct{}
+       images  map[string][]byte
 }
 
 // Add makes update available to getUpdates.
 func (f *TelegramFake) Add(update TelegramUpdate) {
        f.mutex.Lock()
 }
 
 // Add makes update available to getUpdates.
 func (f *TelegramFake) Add(update TelegramUpdate) {
        f.mutex.Lock()
+
        f.updates = append(f.updates, update)
        f.mutex.Unlock()
 
        f.updates = append(f.updates, update)
        f.mutex.Unlock()
 
@@ -71,6 +73,7 @@ func (f *TelegramFake) Calls() []TelegramFakeCall {
 // sendRichMessage calls that succeeded, in order.
 func (f *TelegramFake) Sent() []string {
        var texts []string
 // sendRichMessage calls that succeeded, in order.
 func (f *TelegramFake) Sent() []string {
        var texts []string
+
        for _, call := range f.Calls() {
                switch {
                case !call.ok:
        for _, call := range f.Calls() {
                switch {
                case !call.ok:
@@ -84,17 +87,62 @@ func (f *TelegramFake) Sent() []string {
        return texts
 }
 
        return texts
 }
 
+func (f *TelegramFake) Image(id string, data []byte) {
+       f.mutex.Lock()
+       defer f.mutex.Unlock()
+
+       if f.images == nil {
+               f.images = make(map[string][]byte)
+       }
+
+       f.images[id] = data
+}
+
+// RoundTrip handles a request in memory, so synctest can control its timers.
+func (f *TelegramFake) RoundTrip(request *http.Request) (*http.Response, error) {
+       response := httptest.NewRecorder()
+       f.serve(response, request)
+
+       ctx := request.Context()
+       if ctx.Err() != nil {
+               return nil, ctx.Err()
+       }
+
+       return response.Result(), nil
+}
+
 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
 func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
+       id, file := strings.CutPrefix(r.URL.Path, "/file/bot"+telegramTestToken+"/")
+       if file {
+               f.mutex.Lock()
+
+               data, exists := f.images[id]
+               f.mutex.Unlock()
+
+               if !exists {
+                       http.NotFound(w, r)
+
+                       return
+               }
+
+               _, _ = w.Write(data)
+
+               return
+       }
+
        method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
        if !found {
                http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
        method, found := strings.CutPrefix(r.URL.Path, "/bot"+telegramTestToken+"/")
        if !found {
                http.Error(w, `{"ok":false,"error_code":404,"description":"Not Found"}`, http.StatusNotFound)
+
                return
        }
 
        var params map[string]any
                return
        }
 
        var params map[string]any
+
        err := json.NewDecoder(r.Body).Decode(&params)
        if err != nil {
                http.Error(w, err.Error(), http.StatusBadRequest)
        err := json.NewDecoder(r.Body).Decode(&params)
        if err != nil {
                http.Error(w, err.Error(), http.StatusBadRequest)
+
                return
        }
 
                return
        }
 
@@ -104,6 +152,7 @@ func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
        }
 
        f.mutex.Lock()
        }
 
        f.mutex.Lock()
+
        status, description := 0, ""
        if f.fail != nil {
                status, description = f.fail(call)
        status, description := 0, ""
        if f.fail != nil {
                status, description = f.fail(call)
@@ -114,6 +163,7 @@ func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
 
        if stall {
                f.record(call)
 
        if stall {
                f.record(call)
+
                select {
                case <-r.Context().Done():
                case <-f.stopped:
                select {
                case <-r.Context().Done():
                case <-f.stopped:
@@ -125,6 +175,7 @@ func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
        if status != 0 {
                f.record(call)
                w.WriteHeader(status)
        if status != 0 {
                f.record(call)
                w.WriteHeader(status)
+
                wait := 0
                if status == http.StatusTooManyRequests {
                        wait = 1
                wait := 0
                if status == http.StatusTooManyRequests {
                        wait = 1
@@ -137,6 +188,16 @@ func (f *TelegramFake) serve(w http.ResponseWriter, r *http.Request) {
 
        call.ok = true
        f.record(call)
 
        call.ok = true
        f.record(call)
+
+       if method == "getFile" {
+               _ = json.NewEncoder(w).Encode(map[string]any{
+                       "ok":     true,
+                       "result": map[string]any{"file_path": params["file_id"]},
+               })
+
+               return
+       }
+
        if method != "getUpdates" {
                _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
                return
        if method != "getUpdates" {
                _, _ = io.WriteString(w, `{"ok":true,"result":true}`)
                return
@@ -175,6 +236,7 @@ func (f *TelegramFake) from(offset int64) []TelegramUpdate {
        defer f.mutex.Unlock()
 
        var updates []TelegramUpdate
        defer f.mutex.Unlock()
 
        var updates []TelegramUpdate
+
        kept := f.updates[:0]
        for _, update := range f.updates {
                if update.UpdateID >= offset {
        kept := f.updates[:0]
        for _, update := range f.updates {
                if update.UpdateID >= offset {
@@ -207,6 +269,23 @@ func newTelegramFake(t *testing.T) *TelegramFake {
        return f
 }
 
        return f
 }
 
+// newTelegramLocalFake returns the same fake API without network goroutines.
+// Its RoundTrip handles requests directly for tests with fake time.
+func newTelegramLocalFake(t *testing.T) *TelegramFake {
+       t.Helper()
+
+       f := &TelegramFake{
+               Server:  &httptest.Server{URL: "https://example.com"},
+               added:   make(chan struct{}, 1),
+               stopped: make(chan struct{}),
+       }
+       t.Cleanup(func() {
+               close(f.stopped)
+       })
+
+       return f
+}
+
 // telegramOwnerMessage returns a text message of the owner in the private chat.
 func telegramOwnerMessage(text string) *TelegramMessage {
        return &TelegramMessage{
 // telegramOwnerMessage returns a text message of the owner in the private chat.
 func telegramOwnerMessage(text string) *TelegramMessage {
        return &TelegramMessage{