feat(mail): RFC822 message parsing (headers, body, attachments)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func loadFixture(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(filepath.Join("testdata", name))
|
||||
if err != nil {
|
||||
t.Fatalf("read fixture: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestParseMessage(t *testing.T) {
|
||||
raw := loadFixture(t, "with_attachment.eml")
|
||||
m, err := ParseMessage(42, raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseMessage: %v", err)
|
||||
}
|
||||
if m.Header.UID != 42 {
|
||||
t.Fatalf("uid: %d", m.Header.UID)
|
||||
}
|
||||
if m.Header.Subject != "Your Invoice #5" {
|
||||
t.Fatalf("subject: %q", m.Header.Subject)
|
||||
}
|
||||
if m.Header.From != `"Bob" <bob@trusted.com>` && m.Header.From != "Bob <bob@trusted.com>" {
|
||||
t.Fatalf("from: %q", m.Header.From)
|
||||
}
|
||||
if m.Header.MessageID != "abc123@trusted.com" && m.Header.MessageID != "<abc123@trusted.com>" {
|
||||
t.Fatalf("message-id: %q", m.Header.MessageID)
|
||||
}
|
||||
if want := "Hello, here is your invoice."; !contains(m.BodyText, want) {
|
||||
t.Fatalf("body=%q want contains %q", m.BodyText, want)
|
||||
}
|
||||
if !m.Header.HasAttachments {
|
||||
t.Fatal("HasAttachments should be true")
|
||||
}
|
||||
if len(m.Attachments) != 1 || m.Attachments[0].Name != "invoice.txt" {
|
||||
t.Fatalf("attachments: %+v", m.Attachments)
|
||||
}
|
||||
if !contains(string(m.Attachments[0].Content), "LINE-ITEM 1") {
|
||||
t.Fatalf("attachment content: %q", m.Attachments[0].Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseHeaderOnly(t *testing.T) {
|
||||
raw := loadFixture(t, "with_attachment.eml")
|
||||
h, err := ParseHeaderOnly(7, raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseHeaderOnly: %v", err)
|
||||
}
|
||||
if h.Subject != "Your Invoice #5" || !h.HasAttachments {
|
||||
t.Fatalf("header: %+v", h)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (func() bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}())
|
||||
}
|
||||
Reference in New Issue
Block a user