]> git.giacomolli.uk - onechat/blobdiff - botapi_test.go
Send the replies to Telegram with their formats
[onechat] / botapi_test.go
index 565f27d061acfbe5d1444b4dab21a4b27c599aa1..9c4db5461c2d1434be43d0577ff0753b012f498b 100644 (file)
@@ -1,6 +1,7 @@
 package main
 
 import (
 package main
 
 import (
+       "context"
        "encoding/json"
        "fmt"
        "io"
        "encoding/json"
        "fmt"
        "io"
@@ -47,7 +48,7 @@ func TestGetUpdatesAsksForMessagesFromTheOffset(t *testing.T) {
 
 func TestSendMessageSendsPlainText(t *testing.T) {
        server := newFakeBot(t)
 
 func TestSendMessageSendsPlainText(t *testing.T) {
        server := newFakeBot(t)
-       err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "*not bold*")
+       err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "*not bold*", nil)
        require.NoError(t, err)
 
        require.Equal(t, map[string]any{
        require.NoError(t, err)
 
        require.Equal(t, map[string]any{
@@ -56,6 +57,55 @@ func TestSendMessageSendsPlainText(t *testing.T) {
        }, server.Calls()[0].params)
 }
 
        }, server.Calls()[0].params)
 }
 
+func TestSendMessageSendsTheEntities(t *testing.T) {
+       server := newFakeBot(t)
+       err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "a link", []botEntity{
+               {
+                       Type:   "text_link",
+                       Offset: 2,
+                       Length: 4,
+                       URL:    "https://example.com",
+               },
+       })
+       require.NoError(t, err)
+
+       require.Equal(t, []any{
+               map[string]any{
+                       "type":   "text_link",
+                       "offset": float64(2),
+                       "length": float64(4),
+                       "url":    "https://example.com",
+               },
+       }, server.Calls()[0].params["entities"])
+}
+
+func TestSendMessageTimesOutOnAStalledConnection(t *testing.T) {
+       server := newFakeBot(t)
+       server.stall = func(call fakeBotCall) bool {
+               return call.method == "sendMessage"
+       }
+
+       api := newBotAPI(server.URL, testBotToken)
+       api.sendTimeout = 50 * time.Millisecond
+       start := time.Now()
+       err := api.SendMessage(t.Context(), testOwner, "hi", nil)
+       require.ErrorIs(t, err, errBotNetwork)
+       require.Less(t, time.Since(start), 5*time.Second)
+       require.NotContains(t, err.Error(), testBotToken)
+       require.NotContains(t, err.Error(), server.URL)
+
+       retry, _ := retryable(err)
+       require.True(t, retry)
+
+       api.sendTimeout = time.Hour
+       ctx, cancel := context.WithCancel(t.Context())
+       time.AfterFunc(50*time.Millisecond, cancel)
+       start = time.Now()
+       err = api.SendMessage(ctx, testOwner, "hi", nil)
+       require.Error(t, err)
+       require.Less(t, time.Since(start), 5*time.Second)
+}
+
 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
        testCases := []struct {
                name      string
 func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
        testCases := []struct {
                name      string
@@ -120,7 +170,7 @@ func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
                        }))
                        t.Cleanup(server.Close)
 
                        }))
                        t.Cleanup(server.Close)
 
-                       err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi")
+                       err := newBotAPI(server.URL, testBotToken).SendMessage(t.Context(), testOwner, "hi", nil)
                        require.ErrorContains(t, err, tc.errorText)
                        require.NotContains(t, err.Error(), testBotToken)
                        require.NotContains(t, err.Error(), server.URL)
                        require.ErrorContains(t, err, tc.errorText)
                        require.NotContains(t, err.Error(), testBotToken)
                        require.NotContains(t, err.Error(), server.URL)
@@ -141,7 +191,10 @@ func TestBotErrorsDoNotHoldTheToken(t *testing.T) {
 
 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
 // added updates from the offset on, or waits a short time when there are none.
 
 // fakeBot is a fake Bot API server for testBotToken. getUpdates returns the
 // added updates from the offset on, or waits a short time when there are none.
-// The other methods succeed, unless fail gives an error answer for a call.
+// The other methods succeed, unless fail gives an error answer for a call. An
+// answer with HTTP 429 asks for a wait of one second. When stall is true for a
+// call, the call gets no answer until the client gives it up or the test ends.
+// Fail and stall run with the mutex held.
 type fakeBot struct {
        *httptest.Server
 
 type fakeBot struct {
        *httptest.Server
 
@@ -149,7 +202,9 @@ type fakeBot struct {
        updates []botUpdate
        calls   []fakeBotCall
        fail    func(call fakeBotCall) (int, string)
        updates []botUpdate
        calls   []fakeBotCall
        fail    func(call fakeBotCall) (int, string)
+       stall   func(call fakeBotCall) bool
        added   chan struct{}
        added   chan struct{}
+       stopped chan struct{}
 }
 
 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
 }
 
 // fakeBotCall is one call of the fake Bot API. OK tells if the call got a
@@ -165,11 +220,15 @@ func newFakeBot(t *testing.T) *fakeBot {
        t.Helper()
 
        f := &fakeBot{
        t.Helper()
 
        f := &fakeBot{
-               added: make(chan struct{}, 1),
+               added:   make(chan struct{}, 1),
+               stopped: make(chan struct{}),
        }
 
        f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
        t.Cleanup(f.Close)
        }
 
        f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
        t.Cleanup(f.Close)
+       t.Cleanup(func() {
+               close(f.stopped)
+       })
 
        return f
 }
 
        return f
 }
@@ -226,18 +285,33 @@ func (f *fakeBot) serve(w http.ResponseWriter, r *http.Request) {
        }
 
        f.mutex.Lock()
        }
 
        f.mutex.Lock()
-       fail := f.fail
+       status, description := 0, ""
+       if f.fail != nil {
+               status, description = f.fail(call)
+       }
+
+       stall := f.stall != nil && f.stall(call)
        f.mutex.Unlock()
 
        f.mutex.Unlock()
 
-       status, description := 0, ""
-       if fail != nil {
-               status, description = fail(call)
+       if stall {
+               f.record(call)
+               select {
+               case <-r.Context().Done():
+               case <-f.stopped:
+               }
+
+               return
        }
 
        if status != 0 {
                f.record(call)
                w.WriteHeader(status)
        }
 
        if status != 0 {
                f.record(call)
                w.WriteHeader(status)
-               _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":1}}`, status, description)
+               wait := 0
+               if status == http.StatusTooManyRequests {
+                       wait = 1
+               }
+
+               _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":%d,"description":%q,"parameters":{"retry_after":%d}}`, status, description, wait)
 
                return
        }
 
                return
        }