]> git.giacomolli.uk - onechat/blob - telegram_test.go
d18e7948e2b27f430b4fec071a6fe7a1391aa6ae
[onechat] / telegram_test.go
1 package main
2
3 import (
4 "log"
5 "net/http"
6 "os"
7 "path/filepath"
8 "slices"
9 "strings"
10 "testing"
11 "time"
12
13 "github.com/stretchr/testify/require"
14 )
15
16 func TestOwnerTalksToTheAgentThroughTelegram(t *testing.T) {
17 server := newFakeResponses(t)
18 server.reply = func(w http.ResponseWriter, call fakeCall) {
19 writeEvents(w, completedEvent([]any{messageItem("Hello from the agent.")}, 100, 0, 5))
20 }
21
22 telegram := newFakeBot(t)
23 bot, _ := startTestBot(t, telegram)
24 socket := startTestDaemonWithBot(t, server, bot)
25 terminal := startTestClient(t, socket)
26 terminal.WaitFor(t, "[connected to OneChat]")
27
28 telegram.Add(botUpdate{
29 UpdateID: 1,
30 Message: ownerMessage("hi from the phone"),
31 })
32
33 terminal.WaitFor(t, "[telegram] hi from the phone\n[working]\nHello from the agent.\n[done]")
34 waitForSent(t, telegram, "Hello from the agent.")
35 require.True(t, slices.ContainsFunc(telegram.Calls(), func(call fakeBotCall) bool {
36 return call.method == "sendChatAction" && call.params["action"] == "typing"
37 }))
38
39 terminal.Type("hi from the desk")
40 require.Equal(t, []string{"Hello from the agent.", "[terminal] hi from the desk", "Hello from the agent."}, waitForSent(t, telegram, "Hello from the agent.", "[terminal] hi from the desk", "Hello from the agent."))
41 }
42
43 func TestBotIgnoresEveryoneButTheOwner(t *testing.T) {
44 telegram := newFakeBot(t)
45 bot, logs := startTestBot(t, telegram)
46 socket := startTestDaemonWithBot(t, newFakeResponses(t), bot)
47 terminal := startTestClient(t, socket)
48 terminal.WaitFor(t, "[connected to OneChat]")
49
50 group := ownerMessage("secret in a group")
51 group.Chat = botChat{
52 ID: -100,
53 Type: "group",
54 }
55
56 stranger := ownerMessage("secret of a stranger")
57 stranger.Chat.ID = 77
58 stranger.From.ID = 77
59
60 unsigned := ownerMessage("secret with no sender")
61 unsigned.From = nil
62
63 for id, message := range []*botMessage{group, stranger, unsigned, nil} {
64 telegram.Add(botUpdate{
65 UpdateID: int64(10 + id),
66 Message: message,
67 })
68 }
69
70 require.Eventually(t, func() bool {
71 offset, err := loadOffset(bot.offsetPath)
72 return err == nil && offset == 14
73 }, 10*time.Second, time.Millisecond)
74
75 require.Empty(t, telegram.Sent())
76 require.NotContains(t, terminal.Output(), "secret")
77 require.NotContains(t, logs.String(), "secret")
78 require.Contains(t, logs.String(), "update ignored")
79 }
80
81 func TestBotAnswersThatOnlyTextIsSupported(t *testing.T) {
82 telegram := newFakeBot(t)
83 bot, _ := startTestBot(t, telegram)
84 startTestDaemonWithBot(t, newFakeResponses(t), bot)
85
86 telegram.Add(botUpdate{
87 UpdateID: 1,
88 Message: ownerMessage(""),
89 })
90
91 waitForSent(t, telegram, textOnly)
92 }
93
94 func TestStopFromTelegramInterruptsTheTurn(t *testing.T) {
95 server := newFakeResponses(t)
96 arrived := make(chan struct{})
97 release := make(chan struct{})
98 t.Cleanup(func() {
99 close(release)
100 })
101
102 server.reply = func(w http.ResponseWriter, call fakeCall) {
103 close(arrived)
104 <-release
105 }
106
107 telegram := newFakeBot(t)
108 bot, _ := startTestBot(t, telegram)
109 startTestDaemonWithBot(t, server, bot)
110
111 telegram.Add(botUpdate{
112 UpdateID: 1,
113 Message: ownerMessage("a long task"),
114 })
115
116 <-arrived
117 telegram.Add(botUpdate{
118 UpdateID: 2,
119 Message: ownerMessage(stopCommand),
120 })
121
122 waitForSent(t, telegram, "Error: interrupted")
123
124 telegram.Add(botUpdate{
125 UpdateID: 3,
126 Message: ownerMessage(stopCommand),
127 })
128
129 waitForSent(t, telegram, "Error: interrupted", "No turn runs.")
130 }
131
132 func TestBotStartsAtTheStoredOffset(t *testing.T) {
133 server := newFakeResponses(t)
134 server.reply = func(w http.ResponseWriter, call fakeCall) {
135 writeEvents(w, completedEvent([]any{messageItem("ok")}, 100, 0, 5))
136 }
137
138 telegram := newFakeBot(t)
139 bot, _ := startTestBot(t, telegram)
140 require.NoError(t, saveOffset(bot.offsetPath, 10))
141
142 telegram.Add(botUpdate{
143 UpdateID: 9,
144 Message: ownerMessage("handled before the restart"),
145 })
146
147 telegram.Add(botUpdate{
148 UpdateID: 10,
149 Message: ownerMessage("new after the restart"),
150 })
151
152 socket := startTestDaemonWithBot(t, server, bot)
153 terminal := startTestClient(t, socket)
154 terminal.WaitFor(t, "[connected to OneChat]")
155 waitForSent(t, telegram, "ok")
156
157 require.Equal(t, float64(10), telegram.Calls()[0].params["offset"])
158 require.NotContains(t, terminal.Output(), "handled before the restart")
159
160 require.Eventually(t, func() bool {
161 offset, err := loadOffset(bot.offsetPath)
162 return err == nil && offset == 11
163 }, 10*time.Second, time.Millisecond)
164 }
165
166 func TestBotTriesAgainAfterFailures(t *testing.T) {
167 server := newFakeResponses(t)
168 server.reply = func(w http.ResponseWriter, call fakeCall) {
169 writeEvents(w, completedEvent([]any{messageItem("ok")}, 100, 0, 5))
170 }
171
172 telegram := newFakeBot(t)
173 failures := map[string]int{
174 "getUpdates": 2,
175 "sendMessage": 1,
176 }
177
178 telegram.fail = func(call fakeBotCall) (int, string) {
179 if failures[call.method] == 0 {
180 return 0, ""
181 }
182
183 failures[call.method]--
184 if call.method == "sendMessage" {
185 return http.StatusTooManyRequests, "Too Many Requests: retry after 1"
186 }
187
188 return http.StatusBadGateway, "Bad Gateway"
189 }
190
191 bot, logs := startTestBot(t, telegram)
192 startTestDaemonWithBot(t, server, bot)
193
194 telegram.Add(botUpdate{
195 UpdateID: 1,
196 Message: ownerMessage("hello"),
197 })
198
199 waitForSent(t, telegram, "ok")
200 require.Contains(t, logs.String(), "answered 502")
201 require.Contains(t, logs.String(), "answered 429")
202 require.NotContains(t, logs.String(), testBotToken)
203 }
204
205 func TestBotLogsNoTokenWhenTheNetworkFails(t *testing.T) {
206 telegram := newFakeBot(t)
207 telegram.Close()
208
209 bot, logs := startTestBot(t, telegram)
210 startTestDaemonWithBot(t, newFakeResponses(t), bot)
211
212 require.Eventually(t, func() bool {
213 return strings.Count(logs.String(), "no valid answer") >= 2
214 }, 10*time.Second, time.Millisecond)
215 require.NotContains(t, logs.String(), testBotToken)
216 }
217
218 func TestSplitMessage(t *testing.T) {
219 testCases := []struct {
220 name string
221 text string
222 limit int
223 parts []string
224 }{
225 {
226 name: "short text stays whole",
227 text: "one two",
228 limit: 10,
229 parts: []string{"one two"},
230 },
231 {
232 name: "cut after the last line break",
233 text: "first line\nsecond line",
234 limit: 16,
235 parts: []string{"first line\n", "second line"},
236 },
237 {
238 name: "cut after the last space without a line break",
239 text: "aaaa bbbb cccc",
240 limit: 12,
241 parts: []string{"aaaa bbbb ", "cccc"},
242 },
243 {
244 name: "hard cut of one long word",
245 text: "abcdefghij",
246 limit: 4,
247 parts: []string{"abcd", "efgh", "ij"},
248 },
249 {
250 name: "a character outside the BMP counts two units and is not cut",
251 text: "ab\U0001F600cd",
252 limit: 3,
253 parts: []string{"ab", "\U0001F600c", "d"},
254 },
255 }
256
257 for _, tc := range testCases {
258 t.Run(tc.name, func(t *testing.T) {
259 require.Equal(t, tc.parts, splitMessage(tc.text, tc.limit))
260 })
261 }
262
263 long := strings.Repeat("word ", 2000)
264 parts := splitMessage(long, messageUnits)
265 require.Len(t, parts, 3)
266 require.Equal(t, long, strings.Join(parts, ""))
267 }
268
269 func TestLoadBotConfig(t *testing.T) {
270 testCases := []struct {
271 name string
272 content string
273 mode os.FileMode
274 errorText string
275 }{
276 {
277 name: "owner file is read",
278 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
279 mode: 0o600,
280 },
281 {
282 name: "file that others can read is refused",
283 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
284 mode: 0o640,
285 errorText: "mode must be 0600",
286 },
287 {
288 name: "token with a path character is refused",
289 content: `{"token": "123:abc/../x", "owner": 4242}`,
290 mode: 0o600,
291 errorText: "form of a bot token",
292 },
293 {
294 name: "missing owner is refused",
295 content: `{"token": "` + testBotToken + `"}`,
296 mode: 0o600,
297 errorText: "numeric Telegram user ID",
298 },
299 {
300 name: "unknown field is refused",
301 content: `{"token": "` + testBotToken + `", "owner": 4242, "chat": 1}`,
302 mode: 0o600,
303 errorText: "not valid JSON",
304 },
305 }
306
307 for _, tc := range testCases {
308 t.Run(tc.name, func(t *testing.T) {
309 dir := t.TempDir()
310 path := filepath.Join(dir, botConfigFileName)
311 require.NoError(t, os.WriteFile(path, []byte(tc.content), tc.mode))
312 require.NoError(t, os.Chmod(path, tc.mode))
313
314 config, found, err := loadBotConfig(dir)
315 if tc.errorText != "" {
316 require.ErrorContains(t, err, tc.errorText)
317 require.NotContains(t, err.Error(), testBotToken)
318
319 return
320 }
321
322 require.NoError(t, err)
323 require.True(t, found)
324 require.Equal(t, botConfig{
325 Token: testBotToken,
326 Owner: testOwner,
327 }, config)
328 })
329 }
330
331 _, found, err := loadBotConfig(t.TempDir())
332 require.NoError(t, err)
333 require.False(t, found)
334 }
335
336 // startTestBot returns a bot of testOwner on server, with its offset file in a
337 // temporary directory and short waits, and the buffer of its log.
338 func startTestBot(t *testing.T, server *fakeBot) (*telegramBot, *syncBuffer) {
339 t.Helper()
340
341 logs := &syncBuffer{}
342 bot := newTelegramBot(newBotAPI(server.URL, testBotToken), testOwner, filepath.Join(t.TempDir(), offsetFileName), log.New(logs, "", 0))
343 bot.minWait = time.Millisecond
344 bot.maxWait = 10 * time.Millisecond
345
346 return bot, logs
347 }
348
349 // waitForSent waits until the bot sent the texts in order, and returns them.
350 func waitForSent(t *testing.T, server *fakeBot, texts ...string) []string {
351 t.Helper()
352
353 require.Eventually(t, func() bool {
354 sent := server.Sent()
355 return len(sent) >= len(texts) && slices.Equal(sent[len(sent)-len(texts):], texts)
356 }, 10*time.Second, time.Millisecond, "sent so far: %q", server.Sent())
357
358 return server.Sent()
359 }