13 "github.com/stretchr/testify/require"
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))
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]")
28 telegram.Add(botUpdate{
30 Message: ownerMessage("hi from the phone"),
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"
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."))
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]")
50 group := ownerMessage("secret in a group")
56 stranger := ownerMessage("secret of a stranger")
60 unsigned := ownerMessage("secret with no sender")
63 for id, message := range []*botMessage{group, stranger, unsigned, nil} {
64 telegram.Add(botUpdate{
65 UpdateID: int64(10 + id),
70 require.Eventually(t, func() bool {
71 offset, err := loadOffset(bot.offsetPath)
72 return err == nil && offset == 14
73 }, 10*time.Second, time.Millisecond)
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")
81 func TestBotAnswersThatOnlyTextIsSupported(t *testing.T) {
82 telegram := newFakeBot(t)
83 bot, _ := startTestBot(t, telegram)
84 startTestDaemonWithBot(t, newFakeResponses(t), bot)
86 telegram.Add(botUpdate{
88 Message: ownerMessage(""),
91 waitForSent(t, telegram, textOnly)
94 func TestStopFromTelegramInterruptsTheTurn(t *testing.T) {
95 server := newFakeResponses(t)
96 arrived := make(chan struct{})
97 release := make(chan struct{})
102 server.reply = func(w http.ResponseWriter, call fakeCall) {
107 telegram := newFakeBot(t)
108 bot, _ := startTestBot(t, telegram)
109 startTestDaemonWithBot(t, server, bot)
111 telegram.Add(botUpdate{
113 Message: ownerMessage("a long task"),
117 telegram.Add(botUpdate{
119 Message: ownerMessage(stopCommand),
122 waitForSent(t, telegram, "Error: interrupted")
124 telegram.Add(botUpdate{
126 Message: ownerMessage(stopCommand),
129 waitForSent(t, telegram, "Error: interrupted", "No turn runs.")
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))
138 telegram := newFakeBot(t)
139 bot, _ := startTestBot(t, telegram)
140 require.NoError(t, saveOffset(bot.offsetPath, 10))
142 telegram.Add(botUpdate{
144 Message: ownerMessage("handled before the restart"),
147 telegram.Add(botUpdate{
149 Message: ownerMessage("new after the restart"),
152 socket := startTestDaemonWithBot(t, server, bot)
153 terminal := startTestClient(t, socket)
154 terminal.WaitFor(t, "[connected to OneChat]")
155 waitForSent(t, telegram, "ok")
157 require.Equal(t, float64(10), telegram.Calls()[0].params["offset"])
158 require.NotContains(t, terminal.Output(), "handled before the restart")
160 require.Eventually(t, func() bool {
161 offset, err := loadOffset(bot.offsetPath)
162 return err == nil && offset == 11
163 }, 10*time.Second, time.Millisecond)
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))
172 telegram := newFakeBot(t)
173 failures := map[string]int{
178 telegram.fail = func(call fakeBotCall) (int, string) {
179 if failures[call.method] == 0 {
183 failures[call.method]--
184 if call.method == "sendMessage" {
185 return http.StatusTooManyRequests, "Too Many Requests: retry after 1"
188 return http.StatusBadGateway, "Bad Gateway"
191 bot, logs := startTestBot(t, telegram)
192 startTestDaemonWithBot(t, server, bot)
194 telegram.Add(botUpdate{
196 Message: ownerMessage("hello"),
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)
205 func TestBotLogsNoTokenWhenTheNetworkFails(t *testing.T) {
206 telegram := newFakeBot(t)
209 bot, logs := startTestBot(t, telegram)
210 startTestDaemonWithBot(t, newFakeResponses(t), bot)
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)
218 func TestSplitMessage(t *testing.T) {
219 testCases := []struct {
226 name: "short text stays whole",
229 parts: []string{"one two"},
232 name: "cut after the last line break",
233 text: "first line\nsecond line",
235 parts: []string{"first line\n", "second line"},
238 name: "cut after the last space without a line break",
239 text: "aaaa bbbb cccc",
241 parts: []string{"aaaa bbbb ", "cccc"},
244 name: "hard cut of one long word",
247 parts: []string{"abcd", "efgh", "ij"},
250 name: "a character outside the BMP counts two units and is not cut",
251 text: "ab\U0001F600cd",
253 parts: []string{"ab", "\U0001F600c", "d"},
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))
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, ""))
269 func TestLoadBotConfig(t *testing.T) {
270 testCases := []struct {
277 name: "owner file is read",
278 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
282 name: "file that others can read is refused",
283 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
285 errorText: "mode must be 0600",
288 name: "token with a path character is refused",
289 content: `{"token": "123:abc/../x", "owner": 4242}`,
291 errorText: "form of a bot token",
294 name: "missing owner is refused",
295 content: `{"token": "` + testBotToken + `"}`,
297 errorText: "numeric Telegram user ID",
300 name: "unknown field is refused",
301 content: `{"token": "` + testBotToken + `", "owner": 4242, "chat": 1}`,
303 errorText: "not valid JSON",
307 for _, tc := range testCases {
308 t.Run(tc.name, func(t *testing.T) {
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))
314 config, found, err := loadBotConfig(dir)
315 if tc.errorText != "" {
316 require.ErrorContains(t, err, tc.errorText)
317 require.NotContains(t, err.Error(), testBotToken)
322 require.NoError(t, err)
323 require.True(t, found)
324 require.Equal(t, botConfig{
331 _, found, err := loadBotConfig(t.TempDir())
332 require.NoError(t, err)
333 require.False(t, found)
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) {
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
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 {
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())