Files
mailgoserver/internal/db/logs_test.go
T

78 lines
2.6 KiB
Go

package db
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestPruneEmailLogsOlderThanDeletesOldRowsAndKeepsRecentAndQueued(t *testing.T) {
database := openMonitoringTestDB(t)
now := time.Now().UTC()
oldID, err := database.InsertEmailLog(EmailLog{MessageID: "old@x", Timestamp: now.Add(-48 * time.Hour), MailFrom: "a@sender.example", EmailHeaders: "h", Status: "relayed"})
if err != nil {
t.Fatal(err)
}
if err := database.InsertEmailRecipientLog(EmailRecipientLog{EmailLogID: oldID, Recipient: "r@x", RecipientType: "to", Status: "success"}); err != nil {
t.Fatal(err)
}
attachPath := filepath.Join(t.TempDir(), "attach.bin")
if err := os.WriteFile(attachPath, []byte("data"), 0o644); err != nil {
t.Fatal(err)
}
if err := database.InsertEmailAttachment(EmailAttachment{EmailLogID: oldID, Filename: "attach.bin", FilePath: attachPath, Size: 4}); err != nil {
t.Fatal(err)
}
recentID, err := database.InsertEmailLog(EmailLog{MessageID: "recent@x", Timestamp: now, MailFrom: "a@sender.example", EmailHeaders: "h", Status: "relayed"})
if err != nil {
t.Fatal(err)
}
queuedOldID, err := database.InsertEmailLog(EmailLog{MessageID: "queued@x", Timestamp: now.Add(-48 * time.Hour), MailFrom: "a@sender.example", EmailHeaders: "h", Status: "queued"})
if err != nil {
t.Fatal(err)
}
paths, deleted, err := database.PruneEmailLogsOlderThan(now.Add(-24 * time.Hour))
if err != nil {
t.Fatal(err)
}
if deleted != 1 {
t.Fatalf("expected exactly 1 email log deleted, got %d", deleted)
}
if len(paths) != 1 || paths[0] != attachPath {
t.Fatalf("expected the old attachment's path returned, got %v", paths)
}
var count int
if err := database.QueryRow(`SELECT COUNT(*) FROM esrv_email_logs WHERE id = ?`, oldID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 0 {
t.Error("expected the old email log row to be deleted")
}
if err := database.QueryRow(`SELECT COUNT(*) FROM esrv_email_recipient_logs WHERE email_log_id = ?`, oldID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 0 {
t.Error("expected the old email log's recipient log row to be deleted")
}
if err := database.QueryRow(`SELECT COUNT(*) FROM esrv_email_logs WHERE id = ?`, recentID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Error("expected the recent email log to survive pruning")
}
if err := database.QueryRow(`SELECT COUNT(*) FROM esrv_email_logs WHERE id = ?`, queuedOldID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Error("expected an old but still-'queued' email log to survive pruning (the relay worker isn't done with it)")
}
}