-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmail_test.go
More file actions
784 lines (654 loc) · 21.8 KB
/
Copy pathmail_test.go
File metadata and controls
784 lines (654 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
package mail
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"math/rand"
"net"
"strings"
"sync"
"testing"
"github.com/nativebpm/compress"
)
// MockStore is an in-memory implementation of AttachmentStore for testing.
type MockStore struct {
mu sync.Mutex
store map[string][]byte
}
func NewMockStore() *MockStore {
return &MockStore{
store: make(map[string][]byte),
}
}
func (s *MockStore) UploadAttachment(key string, data []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
s.store[key] = data
return nil
}
func (s *MockStore) DownloadAttachment(key string) ([]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
data, exists := s.store[key]
if !exists {
return nil, fmt.Errorf("key not found: %s", key)
}
return data, nil
}
func (s *MockStore) DeleteAttachment(key string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.store, key)
return nil
}
func TestMessageBuilder(t *testing.T) {
builder := NewMessage().
From("sender@example.com", "Sender Name").
To("receiver@example.com").
Subject("Test Subject").
Body("Hello World")
if builder.Error() != nil {
t.Fatalf("unexpected builder error: %v", builder.Error())
}
if builder.fromEmail != "sender@example.com" {
t.Errorf("expected sender email sender@example.com, got %s", builder.fromEmail)
}
if builder.fromName != "Sender Name" {
t.Errorf("expected sender name 'Sender Name', got %s", builder.fromName)
}
if len(builder.to) != 1 || builder.to[0] != "receiver@example.com" {
t.Errorf("expected receiver receiver@example.com, got %v", builder.to)
}
if builder.subject != "Test Subject" {
t.Errorf("expected subject 'Test Subject', got %s", builder.subject)
}
if builder.body != "Hello World" {
t.Errorf("expected body 'Hello World', got %s", builder.body)
}
if builder.isHTML {
t.Error("expected isHTML to be false for Body call")
}
}
func TestMessageBuilderHTMLAndAttachments(t *testing.T) {
builder := NewMessage().
From("sender@example.com", "Sender").
To("receiver@example.com").
Subject("HTML Test").
HTML("<h1>Hello HTML</h1>").
EmbedBytes([]byte("dummy-png-data"), "banner.png", "image/png", "main_banner").
AttachBytes([]byte("dummy-pdf-data"), "invoice.pdf", "application/pdf")
if builder.Error() != nil {
t.Fatalf("unexpected builder error: %v", builder.Error())
}
if !builder.isHTML {
t.Error("expected isHTML to be true after HTML call")
}
if builder.body != "<h1>Hello HTML</h1>" {
t.Errorf("expected body '<h1>Hello HTML</h1>', got %s", builder.body)
}
if len(builder.attachments) != 2 {
t.Fatalf("expected 2 attachments, got %d", len(builder.attachments))
}
att1 := builder.attachments[0]
if att1.Filename != "banner.png" || att1.ContentType != "image/png" || att1.ContentID != "main_banner" || !att1.IsInline {
t.Errorf("incorrect inline attachment configuration: %+v", att1)
}
att2 := builder.attachments[1]
if att2.Filename != "invoice.pdf" || att2.ContentType != "application/pdf" || att2.ContentID != "" || att2.IsInline {
t.Errorf("incorrect standard attachment configuration: %+v", att2)
}
}
func TestMessageBuilderErrors(t *testing.T) {
builder := NewMessage().
From("", "Sender").
To("receiver@example.com")
if builder.Error() == nil {
t.Fatal("expected error for empty from email")
}
builder = NewMessage().
From("sender@example.com", "Sender").
To()
if builder.Error() == nil {
t.Fatal("expected error for empty recipients list")
}
}
func TestAESEncryptionDecryption(t *testing.T) {
key := []byte("a_very_secret_32_bytes_key_12345") // 32 bytes
plaintext := []byte("Hello, this is a secure BPMN transaction payload!")
ciphertext, err := EncryptAES(key, plaintext)
if err != nil {
t.Fatalf("encryption failed: %v", err)
}
if bytes.Equal(plaintext, ciphertext) {
t.Fatal("expected ciphertext to be different from plaintext")
}
decrypted, err := DecryptAES(key, ciphertext)
if err != nil {
t.Fatalf("decryption failed: %v", err)
}
if !bytes.Equal(plaintext, decrypted) {
t.Errorf("expected decrypted text %s, got %s", string(plaintext), string(decrypted))
}
}
func TestGzipCompressionDecompression(t *testing.T) {
plaintext := []byte("Hello, this is a very long text to compress using gzip. Go packages handle this natively.")
compressed, err := compress.GzipCompress(plaintext)
if err != nil {
t.Fatalf("compression failed: %v", err)
}
if len(compressed) == 0 {
t.Fatal("expected compressed bytes to be non-empty")
}
decompressed, err := compress.GzipDecompress(compressed)
if err != nil {
t.Fatalf("decompression failed: %v", err)
}
if !bytes.Equal(plaintext, decompressed) {
t.Errorf("expected decompressed %s, got %s", string(plaintext), string(decompressed))
}
}
func TestS3EncryptedQueueDelivery(t *testing.T) {
// Start a mock SMTP server locally
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to start mock smtp server: %v", err)
}
defer listener.Close()
addr := listener.Addr().String()
parts := strings.Split(addr, ":")
host := parts[0]
var port int
_, _ = fmt.Sscanf(parts[1], "%d", &port)
smtpConfig := SMTPConfig{
Host: host,
Port: port,
Username: "",
Password: "",
From: "sender@example.com",
FromName: "Sender Name",
UseSSL: false,
}
var capturedBody []string
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
writer.WriteString("220 mock.smtp.server.local\r\n")
writer.Flush()
line, _ := reader.ReadString('\n')
if !strings.HasPrefix(line, "EHLO") && !strings.HasPrefix(line, "HELO") {
return
}
writer.WriteString("250-mock.smtp.server.local\r\n250 HELP\r\n")
writer.Flush()
line, _ = reader.ReadString('\n')
writer.WriteString("250 OK\r\n")
writer.Flush()
line, _ = reader.ReadString('\n')
writer.WriteString("250 OK\r\n")
writer.Flush()
line, _ = reader.ReadString('\n')
writer.WriteString("354 Start mail input\r\n")
writer.Flush()
for {
line, _ = reader.ReadString('\n')
if line == ".\r\n" {
break
}
capturedBody = append(capturedBody, strings.TrimRight(line, "\r\n"))
}
writer.WriteString("250 OK: queued\r\n")
writer.Flush()
line, _ = reader.ReadString('\n')
writer.WriteString("221 Bye\r\n")
writer.Flush()
}()
store := NewMockStore()
aesKey := []byte("aes_encryption_key_size_32_bytes") // 32 bytes
payload := []byte("important_pdf_invoice_report_data")
m := NewMessage().
From("sender@example.com", "Sender Name").
To("receiver@example.com").
Subject("S3 Attachment Queue Test").
WithStore(store).
HTML("<h1>Open attached report</h1>")
// 1. Queue attachment (encrypts and uploads)
s3Key, err := m.QueueAttachment(store, aesKey, "invoice.pdf", "application/pdf", payload, false, "")
if err != nil {
t.Fatalf("failed to queue attachment: %v", err)
}
if s3Key == "" {
t.Fatal("expected returned s3Key to be non-empty")
}
// 2. Check that store holds the encrypted data, not plain text
storedData, err := store.DownloadAttachment(s3Key)
if err != nil {
t.Fatalf("failed to download from mock store: %v", err)
}
if bytes.Equal(storedData, payload) {
t.Fatal("expected S3 stored payload to be encrypted, got raw plaintext")
}
// 3. Send the message (downloads, decrypts, sends, and deletes)
err = m.Send(smtpConfig)
if err != nil {
t.Fatalf("Send failed: %v", err)
}
// 4. Verify SMTP content
rawMail := strings.Join(capturedBody, "\n")
if !strings.Contains(rawMail, "Content-Disposition: attachment; filename=\"invoice.pdf\"") {
t.Error("expected SMTP body to contain the attachment filename headers")
}
// 5. Verify the temporary S3 key has been auto-deleted upon successful delivery
_, err = store.DownloadAttachment(s3Key)
if err == nil {
t.Error("expected S3 key to be deleted automatically after Send call, but it still exists")
}
}
func TestSMTPDeliveryMock(t *testing.T) {
// Start a mock SMTP server locally
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to start mock smtp server: %v", err)
}
defer listener.Close()
addr := listener.Addr().String()
parts := strings.Split(addr, ":")
host := parts[0]
var port int
_, _ = fmt.Sscanf(parts[1], "%d", &port)
smtpConfig := SMTPConfig{
Host: host,
Port: port,
Username: "",
Password: "",
From: "sender@example.com",
FromName: "Sender Name",
UseSSL: false,
}
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
// 1. Send greeting
writer.WriteString("220 mock.smtp.server.local\r\n")
writer.Flush()
// 2. Read EHLO/HELO
line, _ := reader.ReadString('\n')
if !strings.HasPrefix(line, "EHLO") && !strings.HasPrefix(line, "HELO") {
return
}
writer.WriteString("250-mock.smtp.server.local\r\n250 HELP\r\n")
writer.Flush()
// 3. Read MAIL FROM
line, _ = reader.ReadString('\n')
if !strings.HasPrefix(line, "MAIL FROM") {
return
}
writer.WriteString("250 2.1.0 OK\r\n")
writer.Flush()
// 4. Read RCPT TO
line, _ = reader.ReadString('\n')
if !strings.HasPrefix(line, "RCPT TO") {
return
}
writer.WriteString("250 2.1.5 OK\r\n")
writer.Flush()
// 5. Read DATA
line, _ = reader.ReadString('\n')
if !strings.HasPrefix(line, "DATA") {
return
}
writer.WriteString("354 Start mail input; end with <CR><LF>.<CR><LF>\r\n")
writer.Flush()
// 6. Read mail body until "."
for {
line, _ = reader.ReadString('\n')
if line == ".\r\n" {
break
}
}
writer.WriteString("250 2.0.0 OK: queued\r\n")
writer.Flush()
// 7. Read QUIT
line, _ = reader.ReadString('\n')
if strings.HasPrefix(line, "QUIT") {
writer.WriteString("221 2.0.0 Bye\r\n")
writer.Flush()
}
}()
err = NewMessage().
From("sender@example.com", "Sender Name").
To("receiver@example.com").
Subject("Mock Test").
Body("Body content").
Send(smtpConfig)
if err != nil {
t.Fatalf("Send failed: %v", err)
}
}
func TestSMTPDeliveryMockMultipart(t *testing.T) {
// Start a mock SMTP server locally
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to start mock smtp server: %v", err)
}
defer listener.Close()
addr := listener.Addr().String()
parts := strings.Split(addr, ":")
host := parts[0]
var port int
_, _ = fmt.Sscanf(parts[1], "%d", &port)
smtpConfig := SMTPConfig{
Host: host,
Port: port,
Username: "",
Password: "",
From: "sender@example.com",
FromName: "Sender Name",
UseSSL: false,
}
var capturedBody []string
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
// 1. Greeting
writer.WriteString("220 mock.smtp.server.local\r\n")
writer.Flush()
// 2. EHLO
line, _ := reader.ReadString('\n')
if !strings.HasPrefix(line, "EHLO") && !strings.HasPrefix(line, "HELO") {
return
}
writer.WriteString("250-mock.smtp.server.local\r\n250 HELP\r\n")
writer.Flush()
// 3. MAIL FROM
line, _ = reader.ReadString('\n')
writer.WriteString("250 OK\r\n")
writer.Flush()
// 4. RCPT TO
line, _ = reader.ReadString('\n')
writer.WriteString("250 OK\r\n")
writer.Flush()
// 5. DATA
line, _ = reader.ReadString('\n')
writer.WriteString("354 Start mail input\r\n")
writer.Flush()
// 6. Read raw email MIME lines
for {
line, _ = reader.ReadString('\n')
if line == ".\r\n" {
break
}
capturedBody = append(capturedBody, strings.TrimRight(line, "\r\n"))
}
writer.WriteString("250 OK: queued\r\n")
writer.Flush()
// 7. QUIT
line, _ = reader.ReadString('\n')
writer.WriteString("221 Bye\r\n")
writer.Flush()
}()
err = NewMessage().
From("sender@example.com", "Sender Name").
To("receiver@example.com").
Subject("HTML Multipart Mock Test").
HTML("<h1>Mock HTML Body</h1>").
EmbedBytes([]byte("inline-banner-data"), "banner.png", "image/png", "my_banner").
AttachBytes([]byte("standard-attach-data"), "docs.pdf", "application/pdf").
Send(smtpConfig)
if err != nil {
t.Fatalf("Send failed: %v", err)
}
rawMail := strings.Join(capturedBody, "\n")
// Validate SMTP message structure
if !strings.Contains(rawMail, "Content-Type: multipart/related;") {
t.Error("expected Content-Type to be multipart/related")
}
if !strings.Contains(rawMail, "Content-Type: text/html; charset=\"utf-8\"") {
t.Error("expected HTML content-type part")
}
if !strings.Contains(rawMail, "<h1>Mock HTML Body</h1>") {
t.Error("expected HTML body inside captured email content")
}
if !strings.Contains(rawMail, "Content-ID: <my_banner>") {
t.Error("expected Content-ID header for embedded banner")
}
if !strings.Contains(rawMail, "Content-Disposition: inline; filename=\"banner.png\"") {
t.Error("expected Content-Disposition inline for embedded banner")
}
if !strings.Contains(rawMail, "Content-Disposition: attachment; filename=\"docs.pdf\"") {
t.Error("expected Content-Disposition attachment for docs.pdf")
}
}
func generateLargeImage(width, height int, isPNG bool, transparent bool) []byte {
img := image.NewRGBA(image.Rect(0, 0, width, height))
r := rand.New(rand.NewSource(42))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if transparent && x < 10 && y < 10 {
img.Set(x, y, color.RGBA{R: 0, G: 0, B: 0, A: 128})
} else {
img.Set(x, y, color.RGBA{
R: uint8(r.Intn(256)),
G: uint8(r.Intn(256)),
B: uint8(r.Intn(256)),
A: 255,
})
}
}
}
var buf bytes.Buffer
if isPNG {
_ = png.Encode(&buf, img)
} else {
_ = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 95})
}
return buf.Bytes()
}
func TestImageOptimization(t *testing.T) {
// 1. Opaque JPEG > 100KB, width > 600px
opaqueData := generateLargeImage(800, 600, false, false)
if len(opaqueData) <= 100*1024 {
t.Fatalf("test setup error: generated opaque JPEG must be > 100KB, got %d bytes", len(opaqueData))
}
optData, _, optType := optimizeImage(opaqueData, "photo.jpg", "image/jpeg")
if len(optData) >= len(opaqueData) {
t.Errorf("expected optimization to reduce size, got original %d vs optimized %d", len(opaqueData), len(optData))
}
if optType != "image/jpeg" {
t.Errorf("expected content type image/jpeg, got %s", optType)
}
// Verify it was resized
decodedImg, _, err := image.Decode(bytes.NewReader(optData))
if err != nil {
t.Fatalf("failed to decode optimized image: %v", err)
}
if decodedImg.Bounds().Dx() != 600 {
t.Errorf("expected resized width 600, got %d", decodedImg.Bounds().Dx())
}
// 2. Transparent PNG > 100KB, width > 600px
transData := generateLargeImage(800, 600, true, true)
if len(transData) <= 100*1024 {
t.Fatalf("test setup error: generated transparent PNG must be > 100KB, got %d bytes", len(transData))
}
optDataPNG, _, optTypePNG := optimizeImage(transData, "logo.png", "image/png")
if len(optDataPNG) >= len(transData) {
t.Errorf("expected optimization to reduce size for PNG, got original %d vs optimized %d", len(transData), len(optDataPNG))
}
if optTypePNG != "image/png" {
t.Errorf("expected transparent PNG to keep image/png content type, got %s", optTypePNG)
}
// 3. Opaque PNG > 100KB, width > 600px -> should be converted to JPEG
opaquePNGData := generateLargeImage(800, 600, true, false)
if len(opaquePNGData) <= 100*1024 {
t.Fatalf("test setup error: generated opaque PNG must be > 100KB, got %d bytes", len(opaquePNGData))
}
_, optNameOpaquePNG, optTypeOpaquePNG := optimizeImage(opaquePNGData, "chart.png", "image/png")
if optTypeOpaquePNG != "image/jpeg" {
t.Errorf("expected opaque PNG to be optimized to image/jpeg, got %s", optTypeOpaquePNG)
}
if !strings.HasSuffix(optNameOpaquePNG, ".jpg") {
t.Errorf("expected filename to have .jpg suffix, got %s", optNameOpaquePNG)
}
}
func TestAttachmentSizeLimits(t *testing.T) {
// Test eager verification: individual attachment limit
builder := NewMessage().
WithMaxAttachmentSize(50).
WithMaxTotalAttachmentsSize(150)
// Adding a small attachment (10 bytes) - should pass
builder.AttachBytes(make([]byte, 10), "small.txt", "text/plain")
if builder.Error() != nil {
t.Fatalf("unexpected error adding small attachment: %v", builder.Error())
}
// Adding a large attachment (60 bytes) - should trigger eager error
builder.AttachBytes(make([]byte, 60), "large.txt", "text/plain")
if builder.Error() == nil {
t.Fatal("expected eager limit error for attachment exceeding 50 bytes limit")
}
if !strings.Contains(builder.Error().Error(), "exceeds the maximum allowed individual limit") {
t.Errorf("unexpected error message: %v", builder.Error())
}
// Reset builder and test total attachments size limit
builder = NewMessage().
WithMaxAttachmentSize(100).
WithMaxTotalAttachmentsSize(150)
builder.AttachBytes(make([]byte, 80), "file1.txt", "text/plain")
if builder.Error() != nil {
t.Fatalf("unexpected error adding file1: %v", builder.Error())
}
// Adding file2 of size 80 would make total 160 > 150
builder.AttachBytes(make([]byte, 80), "file2.txt", "text/plain")
if builder.Error() == nil {
t.Fatal("expected eager limit error for total attachments exceeding 150 bytes limit")
}
// Test late size limit validation in Send() after S3 resolution
store := NewMockStore()
smtpConfig := SMTPConfig{
Host: "localhost",
Port: 25,
}
builder = NewMessage().
From("sender@example.com", "Sender").
To("receiver@example.com").
WithStore(store).
WithMaxAttachmentSize(50)
// Simulate a pre-existing 60-byte encrypted S3 attachment manually uploaded
aesKey := []byte("aes_encryption_key_size_32_bytes") // 32 bytes
plaintext := make([]byte, 60)
encrypted, _ := EncryptAES(aesKey, plaintext)
_ = store.UploadAttachment("s3key_large", encrypted)
builder.AddQueuedAttachment("s3key_large", aesKey, "invoice.pdf", "application/pdf", false, "")
if builder.Error() != nil {
t.Fatalf("unexpected error from AddQueuedAttachment: %v", builder.Error())
}
// Send should fail due to decrypted size (60 bytes) > individual limit (50 bytes)
err := builder.Send(smtpConfig)
if err == nil {
t.Fatal("expected Send to fail because downloaded attachment exceeds individual limit")
}
if !strings.Contains(err.Error(), "exceeds the maximum allowed individual limit") {
t.Errorf("unexpected error message from Send: %v", err)
}
}
func TestProviderPresets(t *testing.T) {
// 1. Verify presets builder config
m := NewMessage().WithPreset(YandexPreset)
if m.maxAttachmentSize != YandexPreset.MaxAttachmentSize {
t.Errorf("expected maxAttachmentSize to be Yandex value %d, got %d", YandexPreset.MaxAttachmentSize, m.maxAttachmentSize)
}
if m.maxTotalAttachmentsSize != YandexPreset.MaxTotalAttachmentsSize {
t.Errorf("expected maxTotalAttachmentsSize to be Yandex value %d, got %d", YandexPreset.MaxTotalAttachmentsSize, m.maxTotalAttachmentsSize)
}
// 2. Verify config generation
cfg := YandexPreset.SMTPConfig("user@yandex.ru", "my-password")
if cfg.Host != "smtp.yandex.ru" || cfg.Port != 465 || cfg.UseSSL != true || cfg.Username != "user@yandex.ru" || cfg.Password != "my-password" {
t.Errorf("incorrect Yandex SMTPConfig: %+v", cfg)
}
// 3. Verify Gmail preset config
m2 := NewMessage().WithPreset(GmailPreset)
if m2.maxAttachmentSize != GmailPreset.MaxAttachmentSize {
t.Errorf("expected maxAttachmentSize to be Gmail value %d, got %d", GmailPreset.MaxAttachmentSize, m2.maxAttachmentSize)
}
cfg2 := GmailPreset.SMTPConfig("user@gmail.com", "pass")
if cfg2.Host != "smtp.gmail.com" || cfg2.Port != 587 || cfg2.UseSSL != false || cfg2.Username != "user@gmail.com" || cfg2.Password != "pass" {
t.Errorf("incorrect Gmail SMTPConfig: %+v", cfg2)
}
}
func TestHTMLSizeLimits(t *testing.T) {
// 1. Eager HTML limit validation
builder := NewMessage().WithMaxHTMLSize(10)
builder.HTML("1234567890") // 10 bytes (valid)
if builder.Error() != nil {
t.Fatalf("unexpected error setting valid HTML: %v", builder.Error())
}
builder = NewMessage().WithMaxHTMLSize(10)
builder.HTML("12345678901") // 11 bytes (invalid)
if builder.Error() == nil {
t.Fatal("expected error for HTML size exceeding 10 bytes limit")
}
if !strings.Contains(builder.Error().Error(), "exceeds the maximum allowed limit") {
t.Errorf("unexpected error message: %v", builder.Error())
}
// 2. Late HTML limit validation in Send()
builder = NewMessage().
From("sender@example.com", "Sender").
To("receiver@example.com").
WithMaxHTMLSize(10)
// Circumvent eager checks (e.g. modify body directly for testing purposes)
builder.body = "12345678901"
builder.isHTML = true
smtpConfig := SMTPConfig{
Host: "localhost",
Port: 25,
}
err := builder.Send(smtpConfig)
if err == nil {
t.Fatal("expected Send to fail because body exceeds HTML limit")
}
if !strings.Contains(err.Error(), "exceeds the maximum allowed limit") {
t.Errorf("unexpected error message from Send: %v", err)
}
}
func TestBase64ImageCompressionInHTML(t *testing.T) {
opaqueData := generateLargeImage(800, 600, false, false)
base64Opaque := base64.StdEncoding.EncodeToString(opaqueData)
htmlInput := `<html><body><img src="data:image/jpeg;base64,` + base64Opaque + `" /></body></html>`
// Set maxHTMLSize to a larger value so it doesn't fail eager validation
builder := NewMessage().WithMaxHTMLSize(10 * 1024 * 1024)
builder.HTML(htmlInput)
if builder.Error() != nil {
t.Fatalf("unexpected error: %v", builder.Error())
}
// Check that the body is HTML and the base64 string was compressed
if !builder.isHTML {
t.Error("expected body to be HTML")
}
// Extract the new base64 data and verify it is shorter
matches := base64ImageRegexp.FindStringSubmatch(builder.body)
if len(matches) < 3 {
t.Fatalf("could not find base64 image in compressed HTML: %s", builder.body)
}
compressedBase64 := matches[2]
if len(compressedBase64) >= len(base64Opaque) {
t.Errorf("expected base64 length to decrease: original %d, compressed %d", len(base64Opaque), len(compressedBase64))
}
}