]> git.giacomolli.uk - onechat/blob - schedule_test.go
Check error handling and common Go mistakes
[onechat] / schedule_test.go
1 package main
2
3 import (
4         "context"
5         "log"
6         "os"
7         "path/filepath"
8         "strings"
9         "sync"
10         "testing"
11         "time"
12
13         "github.com/stretchr/testify/require"
14 )
15
16 func TestSchedulesSet(t *testing.T) {
17         testCases := []struct {
18                 name   string
19                 text   string
20                 at     *string
21                 cron   *string
22                 answer string
23                 listed string
24         }{
25                 {
26                         name:   "a one-time schedule at a local time",
27                         text:   "Remind the user to drink water.",
28                         at:     new("2026-11-09 09:00"),
29                         answer: "Schedule 1 set. Next: Monday 2026-11-09 09:00 -03:00.",
30                         listed: "1 | Monday 2026-11-09 09:00 -03:00 | once | Remind the user to drink water.",
31                 },
32                 {
33                         name:   "a repeating schedule at the next match",
34                         text:   "Tell the user\nthe time.",
35                         cron:   new("*/5  * * * *"),
36                         answer: "Schedule 1 set. Next: Sunday 2026-11-08 20:05 -03:00.",
37                         listed: "1 | Sunday 2026-11-08 20:05 -03:00 | */5 * * * * | Tell the user the time.",
38                 },
39         }
40
41         for _, tc := range testCases {
42                 t.Run(tc.name, func(t *testing.T) {
43                         schedules, _ := scheduleTestOpen(t)
44
45                         answer, err := schedules.Set(tc.text, tc.at, tc.cron)
46                         require.NoError(t, err)
47                         require.Equal(t, tc.answer, answer)
48                         require.Equal(t, tc.listed, schedules.List())
49                 })
50         }
51 }
52
53 func TestSchedulesSetRefuses(t *testing.T) {
54         testCases := []struct {
55                 name    string
56                 text    string
57                 at      *string
58                 cron    *string
59                 message string
60         }{
61                 {
62                         name:    "an empty text",
63                         text:    " \n",
64                         at:      new("2026-11-09 09:00"),
65                         message: "the text must have 1 to 4096 bytes",
66                 },
67                 {
68                         name:    "a text that is too long",
69                         text:    strings.Repeat("x", scheduleTextBytes+1),
70                         at:      new("2026-11-09 09:00"),
71                         message: "the text must have 1 to 4096 bytes",
72                 },
73                 {
74                         name:    "neither at nor cron",
75                         text:    "Tell the user the time.",
76                         message: "give either at or cron, and null for the other",
77                 },
78                 {
79                         name:    "both at and cron",
80                         text:    "Tell the user the time.",
81                         at:      new("2026-11-09 09:00"),
82                         cron:    new("0 9 * * *"),
83                         message: "give either at or cron, and null for the other",
84                 },
85                 {
86                         name:    "a time in another layout",
87                         text:    "Tell the user the time.",
88                         at:      new("2026-11-09T09:00:00-03:00"),
89                         message: "at must be a local time such as 2026-11-08 20:00",
90                 },
91                 {
92                         name:    "a time that is past",
93                         text:    "Tell the user the time.",
94                         at:      new("2026-11-08 20:00"),
95                         message: "the time Sunday 2026-11-08 20:00 -03:00 is not after now, Sunday 2026-11-08 20:00 -03:00",
96                 },
97                 {
98                         name:    "runs less than 5 minutes apart",
99                         text:    "Tell the user the time.",
100                         cron:    new("* * * * *"),
101                         message: "at least 5 minutes apart",
102                 },
103         }
104
105         for _, tc := range testCases {
106                 t.Run(tc.name, func(t *testing.T) {
107                         schedules, path := scheduleTestOpen(t)
108
109                         _, err := schedules.Set(tc.text, tc.at, tc.cron)
110                         require.ErrorContains(t, err, tc.message)
111                         require.NoFileExists(t, path)
112                 })
113         }
114 }
115
116 func TestSchedulesSurviveARestart(t *testing.T) {
117         schedules, path := scheduleTestOpen(t)
118
119         _, err := schedules.Set("Remind the user to drink water.", new("2026-11-09 09:00"), nil)
120         require.NoError(t, err)
121
122         _, err = schedules.Set("Tell the user the news.", nil, new("0 8 * * 1-5"))
123         require.NoError(t, err)
124
125         _, err = schedules.Remove(1)
126         require.NoError(t, err)
127
128         info, err := os.Stat(path)
129         require.NoError(t, err)
130         require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
131
132         reopened, err := openSchedules(path, schedules.clock, discardLog())
133         require.NoError(t, err)
134         require.Equal(t, "2 | Monday 2026-11-09 08:00 -03:00 | 0 8 * * 1-5 | Tell the user the news.", reopened.List())
135
136         answer, err := reopened.Set("Remind the user to call.", new("2026-11-08 21:00"), nil)
137         require.NoError(t, err)
138         require.Equal(t, "Schedule 3 set. Next: Sunday 2026-11-08 21:00 -03:00.", answer)
139 }
140
141 func TestSchedulesRemove(t *testing.T) {
142         schedules, _ := scheduleTestOpen(t)
143
144         _, err := schedules.Set("Remind the user to drink water.", new("2026-11-09 09:00"), nil)
145         require.NoError(t, err)
146
147         answer, err := schedules.Remove(1)
148         require.NoError(t, err)
149         require.Equal(t, "Schedule 1 removed.", answer)
150         require.Equal(t, "No schedules.", schedules.List())
151
152         _, err = schedules.Remove(1)
153         require.EqualError(t, err, "no schedule 1")
154 }
155
156 func TestSchedulesDone(t *testing.T) {
157         schedules, _ := scheduleTestOpen(t)
158         start := schedules.clock()
159
160         _, err := schedules.Set("Remind the user to drink water.", new("2026-11-08 21:00"), nil)
161         require.NoError(t, err)
162
163         _, err = schedules.Set("Tell the user the time.", nil, new("0 * * * *"))
164         require.NoError(t, err)
165
166         wait, found := schedules.Wait(start)
167         require.True(t, found)
168         require.Equal(t, time.Hour, wait)
169
170         // The daemon was stopped for three hours, so each schedule missed its
171         // times and runs once.
172         now := start.Add(3*time.Hour + 30*time.Minute)
173         due := schedules.Due(now)
174         require.Len(t, due, 2)
175         for _, schedule := range due {
176                 require.NoError(t, schedules.Done(schedule, now))
177         }
178
179         require.Empty(t, schedules.Due(now))
180         require.Equal(t, "2 | Monday 2026-11-09 00:00 -03:00 | 0 * * * * | Tell the user the time.", schedules.List())
181
182         _, err = schedules.Remove(2)
183         require.NoError(t, err)
184         require.NoError(t, schedules.Done(due[1], now))
185         require.Equal(t, "No schedules.", schedules.List())
186
187         _, found = schedules.Wait(now)
188         require.False(t, found)
189 }
190
191 func TestScheduleMessage(t *testing.T) {
192         zone := time.FixedZone("", -3*60*60)
193         due := time.Date(2026, time.November, 9, 9, 0, 0, 0, zone)
194         testCases := []struct {
195                 name     string
196                 schedule Schedule
197                 now      time.Time
198                 message  string
199         }{
200                 {
201                         name: "a one-time run on time",
202                         schedule: Schedule{
203                                 ID:   3,
204                                 Text: "Remind the user to drink water.",
205                                 Due:  due,
206                         },
207                         now:     due.Add(time.Second),
208                         message: "[Schedule 3] Monday 2026-11-09 09:00 -03:00, once\nRemind the user to drink water.\n" + scheduleEmptyReply,
209                 },
210                 {
211                         name: "a late repeating run",
212                         schedule: Schedule{
213                                 ID:   4,
214                                 Text: "Tell the user the news.",
215                                 Cron: "0 9 * * 1-5",
216                                 Due:  due,
217                         },
218                         now:     due.Add(2 * time.Hour),
219                         message: "[Schedule 4] Monday 2026-11-09 09:00 -03:00, repeats 0 9 * * 1-5\nTell the user the news.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
220                 },
221         }
222
223         for _, tc := range testCases {
224                 t.Run(tc.name, func(t *testing.T) {
225                         require.Equal(t, tc.message, tc.schedule.Message(tc.now))
226                 })
227         }
228 }
229
230 func TestOpenSchedulesRefusesABadCron(t *testing.T) {
231         path := filepath.Join(t.TempDir(), scheduleFileName)
232         require.NoError(t, os.WriteFile(path, []byte(`{"next":1,"schedules":[{"id":1,"text":"x","cron":"* * * * *","due":"2026-11-09T09:00:00-03:00"}]}`), 0o600))
233
234         _, err := openSchedules(path, time.Now, discardLog())
235         require.ErrorContains(t, err, "schedule 1: the runs of")
236 }
237
238 func TestSchedulesRunStartsATurnWhenDue(t *testing.T) {
239         clock := &ScheduleTestClock{
240                 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
241         }
242
243         logs := &SyncBuffer{}
244         schedules, err := openSchedules(filepath.Join(t.TempDir(), scheduleFileName), clock.Now, log.New(logs, "", 0))
245         require.NoError(t, err)
246
247         server := newModelFake(t)
248         test := scheduleTestRun(t, schedules, server)
249
250         _, err = schedules.Set("Remind the user to drink water.", new("2026-11-08 20:05"), nil)
251         require.NoError(t, err)
252
253         clock.Set(clock.Now().Add(5 * time.Minute))
254         test.events.WaitFor(t, "idle", 1)
255         require.Equal(t, 1, server.Calls())
256
257         texts := turnInputTexts(t, server.Call(0))
258         require.Equal(t, "[Schedule 1] Sunday 2026-11-08 20:05 -03:00, once\nRemind the user to drink water.\n"+scheduleEmptyReply, texts[len(texts)-1])
259         require.Equal(t, scheduleSource, test.events.LastEvent("work").Source)
260         require.Equal(t, "No schedules.", schedules.List())
261         require.Equal(t, "schedule 1 ran\n", logs.String())
262 }
263
264 func TestSchedulesRunMissedSchedulesOnceAtTheStart(t *testing.T) {
265         path := filepath.Join(t.TempDir(), scheduleFileName)
266         require.NoError(t, os.WriteFile(path, []byte(`{"next":2,"schedules":[{"id":1,"text":"Remind the user to call.","cron":"","due":"2026-11-08T09:00:00-03:00"},{"id":2,"text":"Tell the user the time.","cron":"0 * * * *","due":"2026-11-08T10:00:00-03:00"}]}`), 0o600))
267
268         clock := &ScheduleTestClock{
269                 now: time.Date(2026, time.November, 8, 20, 30, 0, 0, time.FixedZone("", -3*60*60)),
270         }
271
272         logs := &SyncBuffer{}
273         schedules, err := openSchedules(path, clock.Now, log.New(logs, "", 0))
274         require.NoError(t, err)
275
276         server := newModelFake(t)
277         test := scheduleTestRun(t, schedules, server)
278         test.events.WaitFor(t, "idle", 1)
279         require.Equal(t, 1, server.Calls())
280
281         texts := turnInputTexts(t, server.Call(0))
282         require.Equal(t, []string{
283                 "[Schedule 1] Sunday 2026-11-08 09:00 -03:00, once\nRemind the user to call.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
284                 "[Schedule 2] Sunday 2026-11-08 10:00 -03:00, repeats 0 * * * *\nTell the user the time.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
285         }, texts[len(texts)-2:])
286         require.Equal(t, "2 | Sunday 2026-11-08 21:00 -03:00 | 0 * * * * | Tell the user the time.", schedules.List())
287         require.Equal(t, "schedule 1 ran 11h30m0s late\nschedule 2 ran 10h30m0s late\n", logs.String())
288 }
289
290 func TestDaemonRunsADueSchedule(t *testing.T) {
291         clock := &ScheduleTestClock{
292                 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
293         }
294
295         schedules, err := openSchedules(filepath.Join(t.TempDir(), scheduleFileName), clock.Now, discardLog())
296         require.NoError(t, err)
297
298         schedules.check = time.Millisecond
299         whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
300         socket, _ := daemonStartTestWithSchedules(t, newModelFake(t), nil, whatsapp, schedules, clock.Now)
301         client := terminalStartTestClient(t, socket)
302         client.WaitFor(t, "[connected to")
303
304         _, err = schedules.Set("Remind the user to drink water.", new("2026-11-08 20:05"), nil)
305         require.NoError(t, err)
306
307         clock.Set(clock.Now().Add(5 * time.Minute))
308         client.WaitFor(t, "[Schedule 1] Sunday 2026-11-08 20:05 -03:00, once\nRemind the user to drink water.\n"+scheduleEmptyReply+"\n[working]\na line\n[done]")
309 }
310
311 func TestToolboxRunsTheScheduleTools(t *testing.T) {
312         schedules, _ := scheduleTestOpen(t)
313         box := &Toolbox{
314                 schedules: schedules,
315         }
316
317         require.Equal(t, "Schedule 1 set. Next: Monday 2026-11-09 08:00 -03:00.", box.run(t.Context(), "schedule_set", `{"text":"Tell the user the news.","at":null,"cron":"0 8 * * 1-5"}`))
318         require.Equal(t, "Schedule 2 set. Next: Sunday 2026-11-08 20:02 -03:00.", box.run(t.Context(), "schedule_set", `{"text":"Remind the user to drink water.","at":"2026-11-08 20:02","cron":null}`))
319         require.Equal(t, "2 | Sunday 2026-11-08 20:02 -03:00 | once | Remind the user to drink water.\n1 | Monday 2026-11-09 08:00 -03:00 | 0 8 * * 1-5 | Tell the user the news.", box.run(t.Context(), "schedule_list", `{}`))
320         require.Equal(t, "Schedule 1 removed.", box.run(t.Context(), "schedule_remove", `{"id":1}`))
321         require.Equal(t, "error: no schedule 1", box.run(t.Context(), "schedule_remove", `{"id":1}`))
322         require.Equal(t, "error: give either at or cron, and null for the other", box.run(t.Context(), "schedule_set", `{"text":"x","at":null,"cron":null}`))
323 }
324
325 func TestSubagentHasNoScheduleTools(t *testing.T) {
326         box := &Toolbox{}
327         require.Equal(t, `error: unknown tool "schedule_set"`, box.run(t.Context(), "schedule_set", `{"text":"x","at":"2026-11-09 09:00","cron":null}`))
328         require.Equal(t, `error: unknown tool "schedule_list"`, box.run(t.Context(), "schedule_list", `{}`))
329         require.Equal(t, `error: unknown tool "schedule_remove"`, box.run(t.Context(), "schedule_remove", `{"id":1}`))
330 }
331
332 // ScheduleTestClock is a clock that a test sets while Run reads it.
333 type ScheduleTestClock struct {
334         mutex sync.Mutex
335         now   time.Time
336 }
337
338 // Now returns the time of the clock.
339 func (c *ScheduleTestClock) Now() time.Time {
340         c.mutex.Lock()
341         defer c.mutex.Unlock()
342
343         return c.now
344 }
345
346 // Set sets the time of the clock.
347 func (c *ScheduleTestClock) Set(now time.Time) {
348         c.mutex.Lock()
349         defer c.mutex.Unlock()
350
351         c.now = now
352 }
353
354 // scheduleTestOpen opens the schedules of a new file, with a clock at Sunday
355 // 2026-11-08 20:00 -03:00, and returns them and the path of the file.
356 func scheduleTestOpen(t *testing.T) (*Schedules, string) {
357         path := filepath.Join(t.TempDir(), scheduleFileName)
358         clock := &TestClock{
359                 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
360         }
361
362         schedules, err := openSchedules(path, clock.Now, discardLog())
363         require.NoError(t, err)
364
365         return schedules, path
366 }
367
368 // scheduleTestRun runs schedules in a new turn loop that calls server, until
369 // the test ends. Run looks at the times every millisecond.
370 func scheduleTestRun(t *testing.T, schedules *Schedules, server *ModelFake) *TurnTestLoop {
371         t.Helper()
372
373         schedules.check = time.Millisecond
374         test := newTestTurnLoop(t, server)
375         ctx, cancel := context.WithCancel(t.Context())
376         done := make(chan error)
377         go func() {
378                 done <- schedules.Run(ctx, test.loop)
379         }()
380
381         t.Cleanup(func() {
382                 cancel()
383                 require.NoError(t, <-done)
384         })
385
386         return test
387 }