Debian Codegraph @

cmd/send-reminders/main_test.go

raw symbols SCIP
1 package main
2
3 import (
4 "errors"
5 "io"
6 "io/fs"
7 "log"
8 "os"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13
14 "launchpad.net/email-reminder/internal/config"
15 "launchpad.net/email-reminder/internal/events"
16 "launchpad.net/email-reminder/internal/util"
17 )
18
19 var cfg = config.Config{
20 MaxRecipientsPerEvent: 10000,
21 }
22
23 var defaultRecipient = util.EmailRecipient{Email: "[email protected]"}
24
25 // Hide any log output that processEvent may trigger
26 func discardLogs(t *testing.T) {
27 t.Helper()
28 original := log.Writer()
29 log.SetOutput(io.Discard)
30 t.Cleanup(func() {
31 log.SetOutput(original)
32 })
33 }
34
35 type mockNotifier struct {
36 sendFunc func(body, subject string, recipients []util.EmailRecipient) []error
37 sendDebugFunc func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient)
38 }
39
40 func (m *mockNotifier) Send(body, subject string, recipients []util.EmailRecipient) []error {
41 if m.sendFunc != nil {
42 return m.sendFunc(body, subject, recipients)
43 }
44 return nil
45 }
46
47 func (m *mockNotifier) SendDebug(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
48 if m.sendDebugFunc != nil {
49 m.sendDebugFunc(now, event, when, failures, defaultRecipient)
50 }
51 }
52
53 func TestProcessEventSkipsInvalidEvent(t *testing.T) {
54 discardLogs(t)
55
56 now := time.Now()
57 event := events.Event{Type: events.EventTypeBirthday}
58
59 called := false
60 notifier := &mockNotifier{
61 sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
62 called = true
63 return nil
64 },
65 }
66 processEvent(now, event, defaultRecipient, cfg, notifier)
67
68 if called {
69 t.Fatalf("expected invalid event to be skipped")
70 }
71 }
72
73 func TestProcessEventSendsReminderWhenOccurring(t *testing.T) {
74 discardLogs(t)
75
76 now := time.Date(2024, time.March, 10, 9, 0, 0, 0, time.UTC)
77 event := events.Event{
78 Type: events.EventTypeBirthday,
79 Name: "Alice",
80 Month: time.March,
81 Day: 10,
82 Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
83 }
84
85 sendCount := 0
86 debugCount := 0
87 notifier := &mockNotifier{
88 sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
89 sendCount++
90 if body == "" {
91 t.Fatalf("expected body to be populated")
92 }
93 if subject == "" {
94 t.Fatalf("expected subject to be populated")
95 }
96 if len(recipients) == 0 {
97 t.Fatalf("expected at least one recipient")
98 }
99 return nil
100 },
101 sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
102 debugCount++
103 },
104 }
105 processEvent(now, event, defaultRecipient, cfg, notifier)
106
107 if sendCount != 1 {
108 t.Fatalf("expected exactly one reminder to be sent, got %d", sendCount)
109 }
110 if debugCount != 0 {
111 t.Fatalf("expected no debug email to be sent")
112 }
113 }
114
115 func TestProcessEventSendsDebugOnFailure(t *testing.T) {
116 discardLogs(t)
117
118 now := time.Date(2024, time.March, 10, 9, 0, 0, 0, time.UTC)
119 event := events.Event{
120 Type: events.EventTypeBirthday,
121 Name: "Alice",
122 Month: time.March,
123 Day: 10,
124 Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
125 }
126
127 sendCount := 0
128 debugCount := 0
129 notifier := &mockNotifier{
130 sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
131 sendCount++
132 return []error{errors.New("boom")}
133 },
134 sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
135 debugCount++
136 if len(failures) != 1 {
137 t.Fatalf("expected to receive the send errors")
138 }
139 },
140 }
141 processEvent(now, event, defaultRecipient, cfg, notifier)
142
143 if sendCount != 1 {
144 t.Fatalf("expected a send attempt")
145 }
146 if debugCount != 1 {
147 t.Fatalf("expected a debug email to be triggered")
148 }
149 }
150
151 func TestProcessEventSkipsWhenNotOccurring(t *testing.T) {
152 discardLogs(t)
153
154 now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
155 event := events.Event{
156 Type: events.EventTypeBirthday,
157 Name: "Alice",
158 Month: time.March,
159 Day: 10,
160 Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
161 }
162
163 sendCount := 0
164 notifier := &mockNotifier{
165 sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
166 sendCount++
167 return nil
168 },
169 }
170 processEvent(now, event, defaultRecipient, cfg, notifier)
171
172 if sendCount != 0 {
173 t.Fatalf("expected no reminder to be sent, got %d", sendCount)
174 }
175 }
176
177 func TestProcessEventHandlesMultipleRemindersAndRecipients(t *testing.T) {
178 discardLogs(t)
179
180 now := time.Date(2024, time.March, 7, 9, 0, 0, 0, time.UTC)
181 event := events.Event{
182 Type: events.EventTypeBirthday,
183 Name: "Alice",
184 Month: time.March,
185 Day: 10,
186 Reminders: []events.Reminder{
187 {Type: events.ReminderTypeDaysBefore, Days: 3},
188 {Type: events.ReminderTypeSameDay},
189 },
190 Recipients: []events.Recipient{
191 {Name: "Bob", Email: "[email protected]"},
192 {Name: "Carol", Email: "[email protected]"},
193 },
194 }
195
196 sendCount := 0
197 debugCount := 0
198 var gotBody, gotSubject string
199 var gotRecipientsCount int
200 notifier := &mockNotifier{
201 sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
202 sendCount++
203 gotBody = body
204 gotSubject = subject
205 gotRecipientsCount = len(recipients)
206 return nil
207 },
208 sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
209 debugCount++
210 },
211 }
212 processEvent(now, event, defaultRecipient, cfg, notifier)
213
214 if sendCount != 1 {
215 t.Fatalf("expected exactly one reminder to be sent, got %d", sendCount)
216 }
217 if debugCount != 0 {
218 t.Fatalf("expected no debug email to be sent, got %d", debugCount)
219 }
220 if gotSubject == "" {
221 t.Fatalf("expected subject to be populated")
222 }
223 if !strings.Contains(gotBody, "in 3 days") {
224 t.Fatalf("expected body to reference the first matching reminder, got %q", gotBody)
225 }
226 if gotRecipientsCount != 2 {
227 t.Fatalf("expected two recipients, got %d", gotRecipientsCount)
228 }
229 }
230
231 // Minimal testing mock of fs.DirEntry
232 type mockDirEntry struct {
233 name string
234 isDir bool
235 }
236
237 func (m mockDirEntry) Name() string { return m.name }
238 func (m mockDirEntry) IsDir() bool { return m.isDir }
239 func (m mockDirEntry) Type() fs.FileMode { return 0 }
240 func (m mockDirEntry) Info() (fs.FileInfo, error) { return nil, nil }
241
242 func TestShouldProcessPath(t *testing.T) {
243 spoolDir := "/var/spool/reminders"
244
245 tests := []struct {
246 name string
247 path string
248 dirEntry fs.DirEntry
249 walkErr error
250 wantProcess bool
251 wantErr error
252 }{
253 {
254 name: "regular file should be processed",
255 path: "/var/spool/reminders/user1",
256 dirEntry: mockDirEntry{name: "user1", isDir: false},
257 walkErr: nil,
258 wantProcess: true,
259 wantErr: nil,
260 },
261 {
262 name: "hidden file should be skipped",
263 path: "/var/spool/reminders/.hidden",
264 dirEntry: mockDirEntry{name: ".hidden", isDir: false},
265 walkErr: nil,
266 wantProcess: false,
267 wantErr: nil,
268 },
269 {
270 name: "hidden directory should be skipped with SkipDir",
271 path: "/var/spool/reminders/.cache",
272 dirEntry: mockDirEntry{name: ".cache", isDir: true},
273 walkErr: nil,
274 wantProcess: false,
275 wantErr: fs.SkipDir,
276 },
277 {
278 name: "regular directory should not be processed but continue",
279 path: "/var/spool/reminders/subdir",
280 dirEntry: mockDirEntry{name: "subdir", isDir: true},
281 walkErr: nil,
282 wantProcess: false,
283 wantErr: nil,
284 },
285 {
286 name: "error on spool dir should be fatal",
287 path: spoolDir,
288 dirEntry: mockDirEntry{name: "reminders", isDir: true},
289 walkErr: os.ErrPermission,
290 wantProcess: false,
291 wantErr: os.ErrPermission,
292 },
293 {
294 name: "error on file should be skipped",
295 path: "/var/spool/reminders/badfile",
296 dirEntry: mockDirEntry{name: "badfile", isDir: false},
297 walkErr: os.ErrPermission,
298 wantProcess: false,
299 wantErr: nil,
300 },
301 {
302 name: "nested regular file should be processed",
303 path: "/var/spool/reminders/subdir/user 2",
304 dirEntry: mockDirEntry{name: "user 2", isDir: false},
305 walkErr: nil,
306 wantProcess: true,
307 wantErr: nil,
308 },
309 }
310
311 for _, tt := range tests {
312 t.Run(tt.name, func(t *testing.T) {
313 discardLogs(t)
314 conf := config.Config{}
315 gotProcess, gotErr := shouldProcessPath(tt.path, tt.dirEntry, spoolDir, tt.walkErr, conf)
316
317 if gotProcess != tt.wantProcess {
318 t.Errorf("process = %v, want %v", gotProcess, tt.wantProcess)
319 }
320 if tt.wantErr == nil {
321 if gotErr != nil {
322 t.Errorf("err = %v, want nil", gotErr)
323 }
324 } else if !errors.Is(gotErr, tt.wantErr) {
325 t.Errorf("err = %v, wantErr %v", gotErr, tt.wantErr)
326 }
327 })
328 }
329 }
330
331 func TestProcessSpooledFile(t *testing.T) {
332 discardLogs(t)
333
334 // Create a temporary directory and file for testing
335 tmpDir := t.TempDir()
336 testFile := filepath.Join(tmpDir, "testuser")
337
338 // Write valid XML content
339 validContent := `<?xml version="1.0" encoding="UTF-8"?>
340 <user name="Test User" email="[email protected]">
341 <birthday name="Alice" month="3" day="10">
342 <reminder type="sameday"/>
343 </birthday>
344 </user>`
345
346 if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
347 t.Fatalf("failed to create test file: %v", err)
348 }
349
350 now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
351 conf := config.Config{}
352
353 // Process the file (which should delete it)
354 err := processSpooledFile(testFile, tmpDir, now, conf)
355 if err != nil {
356 t.Fatalf("processSpoolFile failed: %v", err)
357 }
358
359 // Verify file was deleted
360 if _, err := os.Stat(testFile); !os.IsNotExist(err) {
361 t.Errorf("expected file to be deleted, but it still exists")
362 }
363 }
364
365 func TestProcessSpooledFileUnreadable(t *testing.T) {
366 discardLogs(t)
367
368 // Use a non-existent file path
369 nonExistentFile := "/tmp/this-file-should-not-exist-" + t.Name()
370
371 now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
372 conf := config.Config{}
373
374 // Should not return an error for unreadable files (logs and skips instead)
375 err := processSpooledFile(nonExistentFile, "/tmp", now, conf)
376 if err != nil {
377 t.Fatalf("expected no error for unreadable file, got: %v", err)
378 }
379 }
380
381 func TestProcessSpooledFileSimulate(t *testing.T) {
382 discardLogs(t)
383
384 tmpDir := t.TempDir()
385 testFile := filepath.Join(tmpDir, "testuser")
386
387 validContent := `<?xml version="1.0" encoding="UTF-8"?>
388 <user name="Test User" email="[email protected]">
389 <birthday name="Alice" month="3" day="10">
390 <reminder type="sameday"/>
391 </birthday>
392 </user>`
393
394 if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
395 t.Fatalf("failed to create test file: %v", err)
396 }
397
398 now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
399 conf := config.Config{Simulate: true}
400
401 err := processSpooledFile(testFile, tmpDir, now, conf)
402 if err != nil {
403 t.Fatalf("processSpoolFile failed: %v", err)
404 }
405
406 // In simulate mode, file should NOT be deleted
407 if _, err := os.Stat(testFile); os.IsNotExist(err) {
408 t.Errorf("expected file to NOT be deleted in simulate mode")
409 }
410 }
411
412 func TestProcessSpooledFilePermissionError(t *testing.T) {
413 if os.Getuid() == 0 {
414 t.Skip("test requires non-root user")
415 }
416
417 discardLogs(t)
418
419 tmpDir := t.TempDir()
420 testFile := filepath.Join(tmpDir, "testuser")
421
422 validContent := `<?xml version="1.0" encoding="UTF-8"?>
423 <user name="Test User" email="[email protected]">
424 <birthday name="Alice" month="3" day="10">
425 <reminder type="sameday"/>
426 </birthday>
427 </user>`
428
429 if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
430 t.Fatalf("failed to create test file: %v", err)
431 }
432
433 // Make directory read-only to prevent deletion
434 if err := os.Chmod(tmpDir, 0555); err != nil {
435 t.Fatalf("failed to change directory permissions: %v", err)
436 }
437 t.Cleanup(func() { os.Chmod(tmpDir, 0755) })
438
439 now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
440 conf := config.Config{}
441
442 // Should return error when unable to delete
443 err := processSpooledFile(testFile, tmpDir, now, conf)
444 if err == nil {
445 t.Fatalf("expected error when unable to delete file")
446 }
447 }