forked from agentic-review-benchmarks/dify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_mail_send_task.py
More file actions
1504 lines (1180 loc) · 53.6 KB
/
test_mail_send_task.py
File metadata and controls
1504 lines (1180 loc) · 53.6 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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit tests for mail send tasks.
This module tests the mail sending functionality including:
- Email template rendering with internationalization
- SMTP integration with various configurations
- Retry logic for failed email sends
- Error handling and logging
"""
import smtplib
from unittest.mock import ANY, MagicMock, patch
import pytest
from configs import dify_config
from configs.feature import TemplateMode
from libs.email_i18n import EmailType
from tasks.mail_inner_task import _render_template_with_strategy, send_inner_email_task
from tasks.mail_register_task import (
send_email_register_mail_task,
send_email_register_mail_task_when_account_exist,
)
from tasks.mail_reset_password_task import (
send_reset_password_mail_task,
send_reset_password_mail_task_when_account_not_exist,
)
class TestEmailTemplateRendering:
"""Test email template rendering with various scenarios."""
def test_render_template_unsafe_mode(self):
"""Test template rendering in unsafe mode with Jinja2 syntax."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "John", "code": "123456"}
# Act
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.UNSAFE):
result = _render_template_with_strategy(body, substitutions)
# Assert
assert result == "Hello John, your code is 123456"
def test_render_template_sandbox_mode(self):
"""Test template rendering in sandbox mode for security."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "Alice", "code": "654321"}
# Act
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
with patch.object(dify_config, "MAIL_TEMPLATING_TIMEOUT", 3):
result = _render_template_with_strategy(body, substitutions)
# Assert
assert result == "Hello Alice, your code is 654321"
def test_render_template_disabled_mode(self):
"""Test template rendering when templating is disabled."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "Bob", "code": "999999"}
# Act
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.DISABLED):
result = _render_template_with_strategy(body, substitutions)
# Assert - should return body unchanged
assert result == "Hello {{ name }}, your code is {{ code }}"
def test_render_template_sandbox_timeout(self):
"""Test that sandbox mode respects timeout settings and range limits."""
# Arrange - template with very large range (exceeds sandbox MAX_RANGE)
body = "{% for i in range(1000000) %}{{ i }}{% endfor %}"
substitutions: dict[str, str] = {}
# Act & Assert - sandbox blocks ranges larger than MAX_RANGE (100000)
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
with patch.object(dify_config, "MAIL_TEMPLATING_TIMEOUT", 1):
# Should raise OverflowError for range too big
with pytest.raises((TimeoutError, RuntimeError, OverflowError)):
_render_template_with_strategy(body, substitutions)
def test_render_template_invalid_mode(self):
"""Test that invalid template mode raises ValueError."""
# Arrange
body = "Test"
substitutions: dict[str, str] = {}
# Act & Assert
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", "invalid_mode"):
with pytest.raises(ValueError, match="Unsupported mail templating mode"):
_render_template_with_strategy(body, substitutions)
def test_render_template_with_special_characters(self):
"""Test template rendering with special characters and HTML."""
# Arrange
body = "<h1>Hello {{ name }}</h1><p>Code: {{ code }}</p>"
substitutions = {"name": "Test<User>", "code": "ABC&123"}
# Act
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
result = _render_template_with_strategy(body, substitutions)
# Assert
assert "Test<User>" in result
assert "ABC&123" in result
def test_render_template_missing_variable_sandbox(self):
"""Test sandbox mode handles missing variables gracefully."""
# Arrange
body = "Hello {{ name }}, your code is {{ missing_var }}"
substitutions = {"name": "John"}
# Act - sandbox mode renders undefined variables as empty strings by default
with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
result = _render_template_with_strategy(body, substitutions)
# Assert - undefined variable is rendered as empty string
assert "Hello John" in result
assert "missing_var" not in result # Variable name should not appear in output
class TestSMTPIntegration:
"""Test SMTP client integration with various configurations."""
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_with_tls_ssl(self, mock_smtp_ssl):
"""Test SMTP send with TLS using SMTP_SSL."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp_ssl.return_value = mock_server
client = SMTPClient(
server="smtp.example.com",
port=465,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test Subject", "html": "<p>Test Content</p>"}
# Act
client.send(mail_data)
# Assert
mock_smtp_ssl.assert_called_once_with("smtp.example.com", 465, timeout=10, local_hostname=ANY)
mock_server.login.assert_called_once_with("user@example.com", "password123")
mock_server.sendmail.assert_called_once()
mock_server.quit.assert_called_once()
@patch("libs.smtp.smtplib.SMTP")
def test_smtp_send_with_opportunistic_tls(self, mock_smtp):
"""Test SMTP send with opportunistic TLS (STARTTLS)."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp.return_value = mock_server
client = SMTPClient(
server="smtp.example.com",
port=587,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=True,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act
client.send(mail_data)
# Assert
mock_smtp.assert_called_once_with("smtp.example.com", 587, timeout=10, local_hostname=ANY)
mock_server.ehlo.assert_called()
mock_server.starttls.assert_called_once()
assert mock_server.ehlo.call_count == 2 # Before and after STARTTLS
mock_server.sendmail.assert_called_once()
mock_server.quit.assert_called_once()
@patch("libs.smtp.smtplib.SMTP")
def test_smtp_send_without_tls(self, mock_smtp):
"""Test SMTP send without TLS encryption."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp.return_value = mock_server
client = SMTPClient(
server="smtp.example.com",
port=25,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=False,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act
client.send(mail_data)
# Assert
mock_smtp.assert_called_once_with("smtp.example.com", 25, timeout=10, local_hostname=ANY)
mock_server.login.assert_called_once()
mock_server.sendmail.assert_called_once()
mock_server.quit.assert_called_once()
@patch("libs.smtp.smtplib.SMTP")
def test_smtp_send_without_authentication(self, mock_smtp):
"""Test SMTP send without authentication (empty credentials)."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp.return_value = mock_server
client = SMTPClient(
server="smtp.example.com",
port=25,
username="",
password="",
_from="noreply@example.com",
use_tls=False,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act
client.send(mail_data)
# Assert
mock_server.login.assert_not_called() # Should skip login with empty credentials
mock_server.sendmail.assert_called_once()
mock_server.quit.assert_called_once()
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_authentication_failure(self, mock_smtp_ssl):
"""Test SMTP send handles authentication failure."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp_ssl.return_value = mock_server
mock_server.login.side_effect = smtplib.SMTPAuthenticationError(535, b"Authentication failed")
client = SMTPClient(
server="smtp.example.com",
port=465,
username="user@example.com",
password="wrong_password",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(smtplib.SMTPAuthenticationError):
client.send(mail_data)
mock_server.quit.assert_called_once() # Should still cleanup
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_timeout_error(self, mock_smtp_ssl):
"""Test SMTP send handles timeout errors."""
# Arrange
from libs.smtp import SMTPClient
mock_smtp_ssl.side_effect = TimeoutError("Connection timeout")
client = SMTPClient(
server="smtp.example.com",
port=465,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(TimeoutError):
client.send(mail_data)
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_connection_refused(self, mock_smtp_ssl):
"""Test SMTP send handles connection refused errors."""
# Arrange
from libs.smtp import SMTPClient
mock_smtp_ssl.side_effect = ConnectionRefusedError("Connection refused")
client = SMTPClient(
server="smtp.example.com",
port=465,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises((ConnectionRefusedError, OSError)):
client.send(mail_data)
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_ensures_cleanup_on_error(self, mock_smtp_ssl):
"""Test SMTP send ensures cleanup even when errors occur."""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()
mock_smtp_ssl.return_value = mock_server
mock_server.sendmail.side_effect = smtplib.SMTPException("Send failed")
client = SMTPClient(
server="smtp.example.com",
port=465,
username="user@example.com",
password="password123",
_from="noreply@example.com",
use_tls=True,
opportunistic_tls=False,
)
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(smtplib.SMTPException):
client.send(mail_data)
# Verify cleanup was called
mock_server.quit.assert_called_once()
class TestMailTaskRetryLogic:
"""Test retry logic for mail sending tasks."""
@patch("tasks.mail_register_task.mail")
def test_mail_task_skips_when_not_initialized(self, mock_mail):
"""Test that mail tasks skip execution when mail is not initialized."""
# Arrange
mock_mail.is_inited.return_value = False
# Act
result = send_email_register_mail_task(language="en-US", to="test@example.com", code="123456")
# Assert
assert result is None
mock_mail.is_inited.assert_called_once()
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
@patch("tasks.mail_register_task.logger")
def test_mail_task_logs_success(self, mock_logger, mock_mail, mock_email_service):
"""Test that successful mail sends are logged properly."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_email_register_mail_task(language="en-US", to="test@example.com", code="123456")
# Assert
mock_service.send_email.assert_called_once_with(
email_type=EmailType.EMAIL_REGISTER,
language_code="en-US",
to="test@example.com",
template_context={"to": "test@example.com", "code": "123456"},
)
# Verify logging calls
assert mock_logger.info.call_count == 2 # Start and success logs
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
@patch("tasks.mail_register_task.logger")
def test_mail_task_logs_failure(self, mock_logger, mock_mail, mock_email_service):
"""Test that failed mail sends are logged with exception details."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_service.send_email.side_effect = Exception("SMTP connection failed")
mock_email_service.return_value = mock_service
# Act
send_email_register_mail_task(language="en-US", to="test@example.com", code="123456")
# Assert
mock_logger.exception.assert_called_once_with("Send email register mail to %s failed", "test@example.com")
@patch("tasks.mail_reset_password_task.get_email_i18n_service")
@patch("tasks.mail_reset_password_task.mail")
def test_reset_password_task_success(self, mock_mail, mock_email_service):
"""Test reset password task sends email successfully."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_reset_password_mail_task(language="zh-Hans", to="user@example.com", code="RESET123")
# Assert
mock_service.send_email.assert_called_once_with(
email_type=EmailType.RESET_PASSWORD,
language_code="zh-Hans",
to="user@example.com",
template_context={"to": "user@example.com", "code": "RESET123"},
)
@patch("tasks.mail_reset_password_task.get_email_i18n_service")
@patch("tasks.mail_reset_password_task.mail")
@patch("tasks.mail_reset_password_task.dify_config")
def test_reset_password_when_account_not_exist_with_register(self, mock_config, mock_mail, mock_email_service):
"""Test reset password task when account doesn't exist and registration is allowed."""
# Arrange
mock_mail.is_inited.return_value = True
mock_config.CONSOLE_WEB_URL = "https://console.example.com"
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_reset_password_mail_task_when_account_not_exist(
language="en-US", to="newuser@example.com", is_allow_register=True
)
# Assert
mock_service.send_email.assert_called_once()
call_args = mock_service.send_email.call_args
assert call_args[1]["email_type"] == EmailType.RESET_PASSWORD_WHEN_ACCOUNT_NOT_EXIST
assert call_args[1]["to"] == "newuser@example.com"
assert "sign_up_url" in call_args[1]["template_context"]
@patch("tasks.mail_reset_password_task.get_email_i18n_service")
@patch("tasks.mail_reset_password_task.mail")
def test_reset_password_when_account_not_exist_without_register(self, mock_mail, mock_email_service):
"""Test reset password task when account doesn't exist and registration is not allowed."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_reset_password_mail_task_when_account_not_exist(
language="en-US", to="newuser@example.com", is_allow_register=False
)
# Assert
mock_service.send_email.assert_called_once()
call_args = mock_service.send_email.call_args
assert call_args[1]["email_type"] == EmailType.RESET_PASSWORD_WHEN_ACCOUNT_NOT_EXIST_NO_REGISTER
class TestMailTaskInternationalization:
"""Test internationalization support in mail tasks."""
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
def test_mail_task_with_english_language(self, mock_mail, mock_email_service):
"""Test mail task with English language code."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_email_register_mail_task(language="en-US", to="test@example.com", code="123456")
# Assert
call_args = mock_service.send_email.call_args
assert call_args[1]["language_code"] == "en-US"
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
def test_mail_task_with_chinese_language(self, mock_mail, mock_email_service):
"""Test mail task with Chinese language code."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_email_register_mail_task(language="zh-Hans", to="test@example.com", code="123456")
# Assert
call_args = mock_service.send_email.call_args
assert call_args[1]["language_code"] == "zh-Hans"
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
@patch("tasks.mail_register_task.dify_config")
def test_account_exist_task_includes_urls(self, mock_config, mock_mail, mock_email_service):
"""Test account exist task includes proper URLs in template context."""
# Arrange
mock_mail.is_inited.return_value = True
mock_config.CONSOLE_WEB_URL = "https://console.example.com"
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Act
send_email_register_mail_task_when_account_exist(
language="en-US", to="existing@example.com", account_name="John Doe"
)
# Assert
call_args = mock_service.send_email.call_args
context = call_args[1]["template_context"]
assert context["login_url"] == "https://console.example.com/signin"
assert context["reset_password_url"] == "https://console.example.com/reset-password"
assert context["account_name"] == "John Doe"
class TestInnerEmailTask:
"""Test inner email task with template rendering."""
@patch("tasks.mail_inner_task.get_email_i18n_service")
@patch("tasks.mail_inner_task.mail")
@patch("tasks.mail_inner_task._render_template_with_strategy")
def test_inner_email_task_renders_and_sends(self, mock_render, mock_mail, mock_email_service):
"""Test inner email task renders template and sends email."""
# Arrange
mock_mail.is_inited.return_value = True
mock_render.return_value = "<p>Hello John, your code is 123456</p>"
mock_service = MagicMock()
mock_email_service.return_value = mock_service
to_list = ["user1@example.com", "user2@example.com"]
subject = "Test Subject"
body = "<p>Hello {{ name }}, your code is {{ code }}</p>"
substitutions = {"name": "John", "code": "123456"}
# Act
send_inner_email_task(to=to_list, subject=subject, body=body, substitutions=substitutions)
# Assert
mock_render.assert_called_once_with(body, substitutions)
mock_service.send_raw_email.assert_called_once_with(
to=to_list, subject=subject, html_content="<p>Hello John, your code is 123456</p>"
)
@patch("tasks.mail_inner_task.mail")
def test_inner_email_task_skips_when_not_initialized(self, mock_mail):
"""Test inner email task skips when mail is not initialized."""
# Arrange
mock_mail.is_inited.return_value = False
# Act
result = send_inner_email_task(to=["test@example.com"], subject="Test", body="Body", substitutions={})
# Assert
assert result is None
@patch("tasks.mail_inner_task.get_email_i18n_service")
@patch("tasks.mail_inner_task.mail")
@patch("tasks.mail_inner_task._render_template_with_strategy")
@patch("tasks.mail_inner_task.logger")
def test_inner_email_task_logs_failure(self, mock_logger, mock_render, mock_mail, mock_email_service):
"""Test inner email task logs failures properly."""
# Arrange
mock_mail.is_inited.return_value = True
mock_render.return_value = "<p>Content</p>"
mock_service = MagicMock()
mock_service.send_raw_email.side_effect = Exception("Send failed")
mock_email_service.return_value = mock_service
to_list = ["user@example.com"]
# Act
send_inner_email_task(to=to_list, subject="Test", body="Body", substitutions={})
# Assert
mock_logger.exception.assert_called_once()
class TestSendGridIntegration:
"""Test SendGrid client integration."""
@patch("libs.sendgrid.sendgrid.SendGridAPIClient")
def test_sendgrid_send_success(self, mock_sg_client):
"""Test SendGrid client sends email successfully."""
# Arrange
from libs.sendgrid import SendGridClient
mock_client_instance = MagicMock()
mock_sg_client.return_value = mock_client_instance
mock_response = MagicMock()
mock_response.status_code = 202
mock_client_instance.client.mail.send.post.return_value = mock_response
client = SendGridClient(sendgrid_api_key="test_api_key", _from="noreply@example.com")
mail_data = {"to": "recipient@example.com", "subject": "Test Subject", "html": "<p>Test Content</p>"}
# Act
client.send(mail_data)
# Assert
mock_sg_client.assert_called_once_with(api_key="test_api_key")
mock_client_instance.client.mail.send.post.assert_called_once()
@patch("libs.sendgrid.sendgrid.SendGridAPIClient")
def test_sendgrid_send_missing_recipient(self, mock_sg_client):
"""Test SendGrid client raises error when recipient is missing."""
# Arrange
from libs.sendgrid import SendGridClient
client = SendGridClient(sendgrid_api_key="test_api_key", _from="noreply@example.com")
mail_data = {"to": "", "subject": "Test Subject", "html": "<p>Test Content</p>"}
# Act & Assert
with pytest.raises(ValueError, match="recipient address is missing"):
client.send(mail_data)
@patch("libs.sendgrid.sendgrid.SendGridAPIClient")
def test_sendgrid_send_unauthorized_error(self, mock_sg_client):
"""Test SendGrid client handles unauthorized errors."""
# Arrange
from python_http_client.exceptions import UnauthorizedError
from libs.sendgrid import SendGridClient
mock_client_instance = MagicMock()
mock_sg_client.return_value = mock_client_instance
mock_client_instance.client.mail.send.post.side_effect = UnauthorizedError(
MagicMock(status_code=401), "Unauthorized"
)
client = SendGridClient(sendgrid_api_key="invalid_key", _from="noreply@example.com")
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(UnauthorizedError):
client.send(mail_data)
@patch("libs.sendgrid.sendgrid.SendGridAPIClient")
def test_sendgrid_send_forbidden_error(self, mock_sg_client):
"""Test SendGrid client handles forbidden errors."""
# Arrange
from python_http_client.exceptions import ForbiddenError
from libs.sendgrid import SendGridClient
mock_client_instance = MagicMock()
mock_sg_client.return_value = mock_client_instance
mock_client_instance.client.mail.send.post.side_effect = ForbiddenError(MagicMock(status_code=403), "Forbidden")
client = SendGridClient(sendgrid_api_key="test_api_key", _from="invalid@example.com")
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(ForbiddenError):
client.send(mail_data)
@patch("libs.sendgrid.sendgrid.SendGridAPIClient")
def test_sendgrid_send_timeout_error(self, mock_sg_client):
"""Test SendGrid client handles timeout errors."""
# Arrange
from libs.sendgrid import SendGridClient
mock_client_instance = MagicMock()
mock_sg_client.return_value = mock_client_instance
mock_client_instance.client.mail.send.post.side_effect = TimeoutError("Request timeout")
client = SendGridClient(sendgrid_api_key="test_api_key", _from="noreply@example.com")
mail_data = {"to": "recipient@example.com", "subject": "Test", "html": "<p>Content</p>"}
# Act & Assert
with pytest.raises(TimeoutError):
client.send(mail_data)
class TestMailExtension:
"""Test mail extension initialization and configuration."""
@patch("extensions.ext_mail.dify_config")
def test_mail_init_smtp_configuration(self, mock_config):
"""Test mail extension initializes SMTP client correctly."""
# Arrange
from extensions.ext_mail import Mail
mock_config.MAIL_TYPE = "smtp"
mock_config.SMTP_SERVER = "smtp.example.com"
mock_config.SMTP_PORT = 465
mock_config.SMTP_USERNAME = "user@example.com"
mock_config.SMTP_PASSWORD = "password123"
mock_config.SMTP_USE_TLS = True
mock_config.SMTP_OPPORTUNISTIC_TLS = False
mock_config.MAIL_DEFAULT_SEND_FROM = "noreply@example.com"
mail = Mail()
mock_app = MagicMock()
# Act
mail.init_app(mock_app)
# Assert
assert mail.is_inited() is True
assert mail._client is not None
@patch("extensions.ext_mail.dify_config")
def test_mail_init_without_mail_type(self, mock_config):
"""Test mail extension skips initialization when MAIL_TYPE is not set."""
# Arrange
from extensions.ext_mail import Mail
mock_config.MAIL_TYPE = None
mail = Mail()
mock_app = MagicMock()
# Act
mail.init_app(mock_app)
# Assert
assert mail.is_inited() is False
@patch("extensions.ext_mail.dify_config")
def test_mail_send_validates_parameters(self, mock_config):
"""Test mail send validates required parameters."""
# Arrange
from extensions.ext_mail import Mail
mail = Mail()
mail._client = MagicMock()
mail._default_send_from = "noreply@example.com"
# Act & Assert - missing to
with pytest.raises(ValueError, match="mail to is not set"):
mail.send(to="", subject="Test", html="<p>Content</p>")
# Act & Assert - missing subject
with pytest.raises(ValueError, match="mail subject is not set"):
mail.send(to="test@example.com", subject="", html="<p>Content</p>")
# Act & Assert - missing html
with pytest.raises(ValueError, match="mail html is not set"):
mail.send(to="test@example.com", subject="Test", html="")
@patch("extensions.ext_mail.dify_config")
def test_mail_send_uses_default_from(self, mock_config):
"""Test mail send uses default from address when not provided."""
# Arrange
from extensions.ext_mail import Mail
mail = Mail()
mock_client = MagicMock()
mail._client = mock_client
mail._default_send_from = "default@example.com"
# Act
mail.send(to="test@example.com", subject="Test", html="<p>Content</p>")
# Assert
mock_client.send.assert_called_once()
call_args = mock_client.send.call_args[0][0]
assert call_args["from"] == "default@example.com"
class TestEmailI18nService:
"""Test email internationalization service."""
@patch("libs.email_i18n.FlaskMailSender")
@patch("libs.email_i18n.FeatureBrandingService")
@patch("libs.email_i18n.FlaskEmailRenderer")
def test_email_service_sends_with_branding(self, mock_renderer_class, mock_branding_class, mock_sender_class):
"""Test email service sends email with branding support."""
# Arrange
from libs.email_i18n import EmailI18nConfig, EmailI18nService, EmailLanguage, EmailTemplate, EmailType
from services.feature_service import BrandingModel
mock_renderer = MagicMock()
mock_renderer.render_template.return_value = "<html>Rendered content</html>"
mock_renderer_class.return_value = mock_renderer
mock_branding = MagicMock()
mock_branding.get_branding_config.return_value = BrandingModel(
enabled=True, application_title="Custom App", logo="logo.png"
)
mock_branding_class.return_value = mock_branding
mock_sender = MagicMock()
mock_sender_class.return_value = mock_sender
template = EmailTemplate(
subject="Test {application_title}",
template_path="templates/test.html",
branded_template_path="templates/branded/test.html",
)
config = EmailI18nConfig(templates={EmailType.EMAIL_REGISTER: {EmailLanguage.EN_US: template}})
service = EmailI18nService(
config=config, renderer=mock_renderer, branding_service=mock_branding, sender=mock_sender
)
# Act
service.send_email(
email_type=EmailType.EMAIL_REGISTER,
language_code="en-US",
to="test@example.com",
template_context={"code": "123456"},
)
# Assert
mock_renderer.render_template.assert_called_once()
# Should use branded template
assert mock_renderer.render_template.call_args[0][0] == "templates/branded/test.html"
mock_sender.send_email.assert_called_once_with(
to="test@example.com", subject="Test Custom App", html_content="<html>Rendered content</html>"
)
@patch("libs.email_i18n.FlaskMailSender")
def test_email_service_send_raw_email_single_recipient(self, mock_sender_class):
"""Test email service sends raw email to single recipient."""
# Arrange
from libs.email_i18n import EmailI18nConfig, EmailI18nService
mock_sender = MagicMock()
mock_sender_class.return_value = mock_sender
service = EmailI18nService(
config=EmailI18nConfig(),
renderer=MagicMock(),
branding_service=MagicMock(),
sender=mock_sender,
)
# Act
service.send_raw_email(to="test@example.com", subject="Test", html_content="<p>Content</p>")
# Assert
mock_sender.send_email.assert_called_once_with(
to="test@example.com", subject="Test", html_content="<p>Content</p>"
)
@patch("libs.email_i18n.FlaskMailSender")
def test_email_service_send_raw_email_multiple_recipients(self, mock_sender_class):
"""Test email service sends raw email to multiple recipients."""
# Arrange
from libs.email_i18n import EmailI18nConfig, EmailI18nService
mock_sender = MagicMock()
mock_sender_class.return_value = mock_sender
service = EmailI18nService(
config=EmailI18nConfig(),
renderer=MagicMock(),
branding_service=MagicMock(),
sender=mock_sender,
)
# Act
service.send_raw_email(
to=["user1@example.com", "user2@example.com"], subject="Test", html_content="<p>Content</p>"
)
# Assert
assert mock_sender.send_email.call_count == 2
mock_sender.send_email.assert_any_call(to="user1@example.com", subject="Test", html_content="<p>Content</p>")
mock_sender.send_email.assert_any_call(to="user2@example.com", subject="Test", html_content="<p>Content</p>")
class TestPerformanceAndTiming:
"""Test performance tracking and timing in mail tasks."""
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
@patch("tasks.mail_register_task.logger")
@patch("tasks.mail_register_task.time")
def test_mail_task_tracks_execution_time(self, mock_time, mock_logger, mock_mail, mock_email_service):
"""Test that mail tasks track and log execution time."""
# Arrange
mock_mail.is_inited.return_value = True
mock_service = MagicMock()
mock_email_service.return_value = mock_service
# Simulate time progression
mock_time.perf_counter.side_effect = [100.0, 100.5] # 0.5 second execution
# Act
send_email_register_mail_task(language="en-US", to="test@example.com", code="123456")
# Assert
assert mock_time.perf_counter.call_count == 2
# Verify latency is logged
success_log_call = mock_logger.info.call_args_list[1]
assert "latency" in str(success_log_call)
class TestEdgeCasesAndErrorHandling:
"""
Test edge cases and error handling scenarios.
This test class covers unusual inputs, boundary conditions,
and various error scenarios to ensure robust error handling.
"""
@patch("extensions.ext_mail.dify_config")
def test_mail_init_invalid_smtp_config_missing_server(self, mock_config):
"""
Test mail initialization fails when SMTP server is missing.
Validates that proper error is raised when required SMTP
configuration parameters are not provided.
"""
# Arrange
from extensions.ext_mail import Mail
mock_config.MAIL_TYPE = "smtp"
mock_config.SMTP_SERVER = None # Missing required parameter
mock_config.SMTP_PORT = 465
mail = Mail()
mock_app = MagicMock()
# Act & Assert
with pytest.raises(ValueError, match="SMTP_SERVER and SMTP_PORT are required"):
mail.init_app(mock_app)
@patch("extensions.ext_mail.dify_config")
def test_mail_init_invalid_smtp_opportunistic_tls_without_tls(self, mock_config):
"""
Test mail initialization fails with opportunistic TLS but TLS disabled.
Opportunistic TLS (STARTTLS) requires TLS to be enabled.
This test ensures the configuration is validated properly.
"""
# Arrange
from extensions.ext_mail import Mail
mock_config.MAIL_TYPE = "smtp"
mock_config.SMTP_SERVER = "smtp.example.com"
mock_config.SMTP_PORT = 587
mock_config.SMTP_USE_TLS = False # TLS disabled
mock_config.SMTP_OPPORTUNISTIC_TLS = True # But opportunistic TLS enabled
mail = Mail()
mock_app = MagicMock()
# Act & Assert
with pytest.raises(ValueError, match="SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS"):
mail.init_app(mock_app)
@patch("extensions.ext_mail.dify_config")
def test_mail_init_unsupported_mail_type(self, mock_config):
"""
Test mail initialization fails with unsupported mail type.
Ensures that only supported mail providers (smtp, sendgrid, resend)
are accepted and invalid types are rejected.
"""
# Arrange
from extensions.ext_mail import Mail
mock_config.MAIL_TYPE = "unsupported_provider"
mail = Mail()
mock_app = MagicMock()
# Act & Assert
with pytest.raises(ValueError, match="Unsupported mail type"):
mail.init_app(mock_app)
@patch("libs.smtp.smtplib.SMTP_SSL")
def test_smtp_send_with_empty_subject(self, mock_smtp_ssl):
"""
Test SMTP client handles empty subject gracefully.
While not ideal, the SMTP client should be able to send
emails with empty subjects without crashing.
"""
# Arrange
from libs.smtp import SMTPClient
mock_server = MagicMock()