
    P1ie                     b   d Z ddlmZmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZ  e       Z G d de      Z ed       G d de             Z ed       G d de             Z  G d de      Z! G d de      Z" G d de      Z#y)z
Comprehensive unit tests for AI analysis reporting email system.

Tests cover:
- Admin notification emails
- User resolution notification emails
- Email template rendering
- Permission-based email recipients
- Email failure handling
    )TestCaseoverride_settings)get_user_model)
Permission)mail)timezone)datetime)patch	MagicMockcall)Person)liuyao)get_report_recipientssend_admin_report_notification!send_user_resolution_notificationget_category_displayget_admin_action_displayc                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)EmailRecipientsTestsz/Test email recipient management and permissionsc                    t         j                  j                  dddddd      | _        t         j                  j                  dddd	dd      | _        t         j                  j                  d
ddddd      | _        t        j                  j                  d      j                          t        j                  j                  ddd      | _
        y)Set up test data13800138001admin1@example.comAdminOneT)phoneemail
first_name	last_nameis_staff	is_active13800138002admin2@example.comTwo13800138003user@example.comRegularUserFcan_receive_ai_report_emailscodename%Can receive AI analysis report emails   r,   namecontent_type_idN)r)   objectscreate_useradmin1admin2regular_userr   filterdeletecreate
permissionselfs    Z/home/cursorai/projects/iching/iching/tests/../../tests/ai_report/test_reporting_emails.pysetUpzEmailRecipientsTests.setUp#   s    ll..& / 
 ll..& / 
 !LL44$  5 
 	!!+I!JQQS %,,3338 4 
    c                     ddl m}  |        yzClean up test datar   )cleanup_test_permissionsNtests.test_utilsrB   r<   rB   s     r=   tearDownzEmailRecipientsTests.tearDownJ       = "r?   c                 <    t               }| j                  |g        y)z5Test getting recipients when no users have permissionN)r   assertEqualr<   
recipientss     r=   (test_get_report_recipients_no_permissionz=EmailRecipientsTests.test_get_report_recipients_no_permissionO   s    *,
R(r?   c                 R   | j                   j                  j                  | j                         | j                  j                  j                  | j                         t               }| j                  d|       | j                  d|       | j                  t        |      d       y)z2Test getting recipients when users have permissionr   r$      N)	r4   user_permissionsaddr:   r5   r   assertInrI   lenrJ   s     r=   *test_get_report_recipients_with_permissionz?EmailRecipientsTests.test_get_report_recipients_with_permissionT   sv     	$$((9$$((9*,
*J7*J7Z!,r?   c                     | j                   j                  j                  | j                         t	               }| j                  d|       | j                  t        |      d       y)z;Test that non-staff users are excluded even with permissionr'   r   N)r6   rO   rP   r:   r   assertNotInrI   rR   rJ   s     r=   -test_get_report_recipients_excludes_non_staffzBEmailRecipientsTests.test_get_report_recipients_excludes_non_staff_   sM    **..t?*,
+Z8Z!,r?   c                     | j                   j                  j                  | j                         d| j                   _        | j                   j                          t               }| j                  d|       y)z%Test that inactive users are excludedFr   N)r4   rO   rP   r:   r"   saver   rU   rJ   s     r=   ,test_get_report_recipients_excludes_inactivezAEmailRecipientsTests.test_get_report_recipients_excludes_inactiveg   sS    $$((9 %*,
-z:r?   c                 &   | j                   j                  j                  | j                         d| j                   _        | j                   j                          t               }| j                  d|       | j                  t        |      d       y)z*Test that users without email are excluded r   r   N)
r4   rO   rP   r:   r   rX   r   rU   rI   rR   rJ   s     r=   ,test_get_report_recipients_excludes_no_emailzAEmailRecipientsTests.test_get_report_recipients_excludes_no_emailp   sg    $$((9*,
-z:Z!,r?   c                     t         j                  j                  d      j                          t	               }| j                  |g        y)z+Test handling when permission doesn't existr*   r+   N)r   r2   r7   r8   r   rI   rJ   s     r=   5test_get_report_recipients_handles_missing_permissionzJEmailRecipientsTests.test_get_report_recipients_handles_missing_permissionz   s=     	!!+I!JQQS*,
R(r?   N)__name__
__module____qualname____doc__r>   rF   rL   rS   rV   rY   r\   r^    r?   r=   r   r       s.    9%
N#
)
	--;-)r?   r   -django.core.mail.backends.locmem.EmailBackendEMAIL_BACKENDc                   \    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
 ed	      d
        Zd Zy)AdminNotificationEmailTestsz%Test admin notification email sendingc                 $   ddl m}  |dddd      | _        t        j                  j                  dd	d
d      | _        t        j                  j                  dt        ddd      t        dd      | j                  dddit        j                               | _        t        j                  j                  d| j                  t        j                         dddddddddit        j                         t        j                               | _        y)r   r   )$create_admin_with_report_permissionsr   admin@example.comr   r)   r   r   r   r    13800138000r'   Test   测试用户  r.      	completedbazi_analysiszTest BaZi analysis content)r0   
birth_date
birth_time
created_byanalysis_statusai_analysisbazi_report_timestamp   测试问题10responsezTest LiuYao analysis)questionuserqdatey1y2y3y4y5y6rw   rx   report_timestampreport_resolved_atN)rD   rj   adminr)   r2   r3   r   r   r9   r	   r
   r   nowpersonr   liuyao_entry)r<   rj   s     r=   r>   z!AdminNotificationEmailTests.setUp   s     	J9%	

 LL,,$	 - 
	 nn++D!Q'B{yy'(*FG"*,,. , 
 #NN11#,,.sssss'#%;<%\\^'||~ 2 	
r?   c                     ddl m}  |        yrA   rC   rE   s     r=   rF   z$AdminNotificationEmailTests.tearDown   rG   r?   c                     t        | j                  ddd      }| j                  |       | j                  t	        t
        j                        d       t
        j                  d   }| j                  |j                  dg       | j                  d|j                         | j                  d|j                         | j                  d	|j                         | j                  d|j                         | j                  d
|j                         y)z2Test successful admin notification for BaZi reportbaziinappropriate_contentzThis analysis is inappropriater.   r   rk   u   新的AI分析举报BAZI   内容不当ro   N)r   r   
assertTruerI   rR   r   outboxtorQ   subjectbodyr<   resultr   s      r=   )test_send_admin_notification_bazi_successzEAdminNotificationEmailTests.test_send_admin_notification_bazi_success   s    /KK#,	
 	T[[)1-A$7#89,emm<femm,nejj16

Cnejj1r?   c                 v   t        | j                  ddd      }| j                  |       | j                  t	        t
        j                        d       t
        j                  d   }| j                  d|j                         | j                  d|j                         | j                  d|j                         y	)
z4Test successful admin notification for LiuYao reportr   inaccurate_analysisz Hexagram interpretation is wrongr.   r   LIUYAOrz      分析不准确N)
r   r   r   rI   rR   r   r   rQ   r   r   r   s      r=   +test_send_admin_notification_liuyao_successzGAdminNotificationEmailTests.test_send_admin_notification_liuyao_success   s    /!.	
 	T[[)1-Ah.nejj1'4r?   c                     | j                   j                  j                          t        | j                  dddd      }| j                  |       | j                  t        t        j                        d       y)z4Test admin notification when no recipients availabler   technical_errorTest messageT)silentr   N)
r   rO   clearr   r   assertFalserI   rR   r   r   r<   r   s     r=   *test_send_admin_notification_no_recipientszFAdminNotificationEmailTests.test_send_admin_notification_no_recipients   s`     	

##))+/KK
 	 T[[)1-r?   c                     t        | j                  ddd      }| j                  |       t        j                  d   }| j                  d|j                         y)z/Test admin notification with empty user messager   otherr[   r   u   用户未留言Nr   r   r   r   r   rQ   r   r   s      r=   *test_send_admin_notification_empty_messagezFAdminNotificationEmailTests.test_send_admin_notification_empty_message   sJ    /KK	
 	A'4r?   c                     d}t        | j                  dd|      }| j                  |       t        j                  d   }| j                  ||j                         y)z,Test admin notification with Unicode contentu.   这是一个包含中文和emoji的消息 🚨r   r   r   Nr   )r<   unicode_messager   r   s       r=   ,test_send_admin_notification_unicode_contentzHAdminNotificationEmailTests.test_send_admin_notification_unicode_content   sN    J/KK#	
 	Aouzz2r?   api.utils.send_mailc                 v    t        d      |_        t        | j                  ddd      }| j	                  |       y)z&Test handling of email sending failurezSMTP server downr   r   r   N)	Exceptionside_effectr   r   r   r<   mock_send_mailr   s      r=   *test_send_admin_notification_email_failurezFAdminNotificationEmailTests.test_send_admin_notification_email_failure  s<     &//A%B"/KK	
 	 r?   c                     t        | j                  ddd      }| j                  |       t        j                  d   }| j                  |j                         | j                  t        |d             y)z4Test that both HTML and plain text versions are sentr   r   zTest HTML emailr   alternativesN)r   r   r   r   r   assertIsNotNoner   hasattrr   s      r=   *test_send_admin_notification_html_and_textzFAdminNotificationEmailTests.test_send_admin_notification_html_and_text  s^    /KK#	
 	 AUZZ(~67r?   N)r_   r`   ra   rb   r>   rF   r   r   r   r   r   r   r   r   rc   r?   r=   rh   rh      sH    /&
P#
2(5". 53  !! "!8r?   rh   c                   V    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
 ed	      d
        Zy)UserResolutionEmailTestsz(Test user resolution notification emailsc                    t         j                  j                  dddd      | _        t         j                  j                  dddd	d
      | _        t
        j                  j                  dt        ddd      | j                  dddid
ddd| j                  t        j                         t        j                               | _
        y)r   rm   r'      测试   用户rl   r   rk   r   r)   Tr   r   r   r    r!   u   测试人员rp   r.   rr   rs   Test contentr   zTest reportresolved)r0   rt   rv   rw   rx   bazi_analysis_reportedbazi_report_categorybazi_report_messagebazi_report_statusbazi_report_resolved_bybazi_report_resolved_atry   N)r)   r2   r3   r   r   r   r9   r	   r   r   r   r;   s    r=   r>   zUserResolutionEmailTests.setUp)  s    LL,,$	 - 
	 \\--% . 

 nn++D!Q'yy'(.9#'!8 -)$(JJ$,LLN"*,,. , 
r?   c                     ddl m}  |        yrA   rC   rE   s     r=   rF   z!UserResolutionEmailTests.tearDownI  rG   r?   c                    t        | j                  | j                  ddd      }| j                  |       | j	                  t        t        j                        d       t        j                  d   }| j	                  |j                  dg       | j                  d|j                         | j                  d|j                         | j                  d|j                         | j                  d	|j                         y
)z,Test successful user resolution notificationr   r   z:We have reviewed your report and taken appropriate action.r.   r   r'      举报处理结果   测试 用户zWe have reviewedN)r   r   r   r   rI   rR   r   r   r   rQ   r   r   r   s      r=   .test_send_user_resolution_notification_successzGUserResolutionEmailTests.test_send_user_resolution_notification_successN  s    2IIKKH
 	T[[)1-A$6#78*EMM:*EMM:ouzz2(%**5r?   c                    d| j                   _        | j                   j                          t        | j                   | j                  ddd      }| j                  |       | j                  t        t        j                        d       y)z8Test user resolution notification when user has no emailr[   r   r   zAdmin notesr   N)
r   r   rX   r   r   r   rI   rR   r   r   r   s     r=   /test_send_user_resolution_notification_no_emailzHUserResolutionEmailTests.test_send_user_resolution_notification_no_emailb  se    				2IIKK
 	 T[[)1-r?   c                     t        d| j                  ddd      }| j                  |       | j                  t	        t
        j                        d       y)z3Test user resolution notification when user is NoneNr   dismisszReport dismissedr   )r   r   r   rI   rR   r   r   r   s     r=   .test_send_user_resolution_notification_no_userzGUserResolutionEmailTests.test_send_user_resolution_notification_no_userr  sH    2KK
 	 T[[)1-r?   c           	         g d}|D ]  }t         j                  j                          t        | j                  | j
                  d|d|       }| j                  |       | j                  t        t         j                        d        t         j                  j                          t        | j                  | j
                  ddd      }| j                  |       | j                  t        t         j                        d       y)	z7Test user resolution notification for all admin actions)r   
regeneratecontent_warningescalater   zAdmin notes for r   r   zAdmin notes for resolvedr.   N)
r   r   r   r   r   r   r   rI   rR   r   )r<   actionsactionr   s       r=   2test_send_user_resolution_notification_all_actionszKUserResolutionEmailTests.test_send_user_resolution_notification_all_actions  s    JFKK6		"6(+F V$S-q1  	2IIKK&
 	T[[)1-r?   c                    t         j                  j                  d| j                  t	        j
                         dddddddddiddd	| j                  t	        j
                         
      }t        | j                  |dd	d      }| j                  |       t        j                  d   }| j                  d|j                         | j                  d|j                         y)z5Test user resolution notification for LiuYao analysiszTest questionr{   r|   rr   r}   r   Tr   r   )r~   r   r   r   r   r   r   r   r   rw   rx   analysis_reportedreport_categoryreport_statusreport_resolved_byr   r   z We have regenerated the analysisr   r   N)r   r2   r9   r   r   r   r   r   r   r   r   rQ   r   r   )r<   r   r   r   s       r=   -test_send_user_resolution_notification_liuyaozFUserResolutionEmailTests.test_send_user_resolution_notification_liuyao  s    ~~,,$,,.sssss'#^4"1$#zz'||~ - 
 3II.
 	A*EMM:ouzz2r?   r   c                     t        d      |_        t        | j                  | j                  ddd      }| j                  |       y)z0Test handling of user notification email failurezEmail service unavailabler   resolvezTest admin notesN)r   r   r   r   r   r   r   s      r=   4test_send_user_resolution_notification_email_failurezMUserResolutionEmailTests.test_send_user_resolution_notification_email_failure  sC     &//J%K"2IIKK
 	 r?   N)r_   r`   ra   rb   r>   rF   r   r   r   r   r   r   r   rc   r?   r=   r   r   %  sC    2
@#
6(. ..<3:  !! "!r?   r   c                       e Zd ZdZd Zd Zy)EmailUtilityFunctionTestszTest email utility functionsc                     ddddddd}|j                         D ]"  \  }}t        |      }| j                  ||       $ y)	z#Test category display name functionr   r   u   语言冒犯u   技术错误u   其他invalid_category)r   r   offensive_languager   r   r   N)itemsr   rI   )r<   
test_casescategoryexpectedr   s        r=   test_get_category_displayz3EmailUtilityFunctionTests.test_get_category_display  sQ     &4#4"0- 2

 #-"2"2"4Hh)(3FVX. #5r?   c                     ddddddd}|j                         D ]"  \  }}t        |      }| j                  ||       $ y)	z'Test admin action display name functionu	   已忽略	   已解决r   r   r   invalid_action)r   r   r   r   r   r   N)r   r   rI   )r<   r   r   r   r   s        r=   test_get_admin_action_displayz7EmailUtilityFunctionTests.test_get_admin_action_display  sQ     #"&0".

 !+ 0 0 2FH-f5FVX. !3r?   N)r_   r`   ra   rb   r   r   rc   r?   r=   r   r     s    &//r?   r   c                       e Zd ZdZd Zd Z ed      d        Z ed      d        Z ed      d        Z	 ed      d	        Z
y
)EmailTemplateTestsz)Test email template rendering and contentc                    t         j                  j                  dddd      | _        t         j                  j                  ddddd	
      | _        t
        j                  j                  d      j                          t
        j                  j                  ddd      }| j                  j                  j                  |       y)r   rm   r'   r   r   rl   r   rk   u	   管理员Tr   r*   r+   r-   r.   r/   N)r)   r2   r3   r   r   r   r7   r8   r9   rO   rP   )r<   r:   s     r=   r>   zEmailTemplateTests.setUp  s    LL,,$	 - 
	 \\--%" . 

 	!!+I!JQQS''..38 / 


 	

##''
3r?   c                     ddl m}  |        yrA   rC   rE   s     r=   rF   zEmailTemplateTests.tearDown  rG   r?   rd   re   c                 X   t         j                  j                  dt        ddd      d| j                  dddit        j                         t        j                         	      }t        |d
dd       t        j                  d   }g d}|D ]  }| j                  ||j                           y)z?Test that admin email template receives all necessary variables   模板测试rp         Frr   rs   zTemplate test content)r0   rt   genderrv   rw   rx   ry   r   r   r      测试模板变量渲染r   )r   r   r   r   zMay 15, 1990r   r'   Nr   r2   r9   r	   r   r   r   r   r   r   rQ   r   r<   r   r   expected_contentcontents        r=   #test_admin_email_template_variablesz6EmailTemplateTests.test_admin_email_template_variables  s     &&D!R(yy'(*AB"*,,.$,LLN ' 	
 	'#&		
 A
 (GMM'5::. (r?   c                    t         j                  j                  dt        ddd      | j                  dddiddt        j                         t        j                         | j                  	
      }t        | j                  |d
dd       t        j                  d   }g d}|D ]  }| j                  ||j                           y)zITest that user resolution email template receives all necessary variables   解决测试rp   r.   rr   rs   zResolution testTr   )
r0   rt   rv   rw   rx   r   r   ry   r   r   r   r   '   我们已经解决了您报告的问题r   )r   u   八字分析r   r  r  N)r   r2   r9   r	   r   r   r   r   r   r   r   rQ   r   r   s        r=   -test_user_resolution_email_template_variablesz@EmailTemplateTests.test_user_resolution_email_template_variables5  s     &&D!Q'yy'(*;<#'!2"*,,.$,LLN$(JJ ' 
 	*II5	
 A
 (GMM'5::. (r?   c           
         t         j                  j                  dt        ddd      | j                  dddit        j                         t        j                               }d}t        |d	d
|       t        j                  d   }| j                  d|j                         | j                  ||j                         | j                  d|j                         y)z4Test proper encoding of Chinese characters in emailsu   中文测试用户名 🎯rp   r.   rr   rs   u   中文分析内容r0   rt   rv   rw   rx   ry   r   uP   这是一个包含中文字符、标点符号！和emoji 🚨 的测试消息。r   r   r   r   Nr   )r<   r   chinese_messager   s       r=   &test_email_encoding_chinese_charactersz9EmailTemplateTests.test_email_encoding_chinese_charactersZ  s     &&-D!Q'yy'(*>?"*,,.$,LLN ' 
 m&#		
 A2EJJ?ouzz2nejj1r?   c           
      D   t         j                  j                  dt        ddd      | j                  dddit        j                         t        j                               }d}t        |d	d
|       t        j                  d   }| j                  d|j                         y)z4Test that HTML content is properly handled in emailsz	HTML Testrp   r.   rr   rs   zHTML test contentr  z-<script>alert("XSS")</script><b>Bold text</b>r   r   r   zO&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;&lt;b&gt;Bold text&lt;/b&gt;Nr   )r<   r   html_messager   s       r=   test_email_html_content_safetyz1EmailTemplateTests.test_email_html_content_safetyu  s     &&D!Q'yy'(*=>"*,,.$,LLN ' 
 G&		
 Aginisistr?   N)r_   r`   ra   rb   r>   rF   r   r   r  r  r  rc   r?   r=   r   r     s    348#
 %TU"/ V"/H %TU"/ V"/H %TU2 V24 %TUu Vur?   r   c                   D    e Zd ZdZd Zd Z ed      d        Zd Zd Z	y)	EmailEdgeCaseTestsz4Test edge cases and error scenarios for email systemc                 P    t         j                  j                  dd      | _        y)r   rm   r'   )r   r   N)r)   r2   r3   r   r;   s    r=   r>   zEmailEdgeCaseTests.setUp  s#    LL,,$ - 
	r?   c                     ddl m}  |        yrA   rC   rE   s     r=   rF   zEmailEdgeCaseTests.tearDown  rG   r?   zapi.utils.loggerc           	         t         j                  j                  ddddd      }t        j                  j	                  d      j                          t        j                  j                  dd	d
      }|j                  j                  |       t        j                  j                  dt        dd
d
      | j                  dddit        j                               }t        dt        d            5  t!        |ddd      }| j#                  |       |j$                  j'                          ddd       y# 1 sw Y   yxY w)z,Test that email failures are properly loggedr   rk   r   r)   Tr   r*   r+   r-   r.   r/   zLogging Testrp   rr   testdata)r0   rt   rv   rw   rx   ry   r   z
SMTP Error)r   r   r   zLogging testN)r)   r2   r3   r   r7   r8   r9   rO   rP   r   r	   r   r   r   r   r   r   r   errorassert_called)r<   mock_loggerr   r:   r   r   s         r=   test_email_logging_on_failurez0EmailEdgeCaseTests.test_email_logging_on_failure  s#    ((% ) 
 	!!+I!JQQS''..38 / 


 	"":.&&D!Q'yy'("*,,. ' 
 (i6MN3!	F V$++- ONNs   4:D77E c                 B    t        dddd      }| j                  |       y)z,Test email sending with None analysis objectNr   r   zNone object test)r   r   r   s     r=   $test_email_with_none_analysis_objectz7EmailEdgeCaseTests.test_email_with_none_analysis_object  s(    /	
 	 r?   c                      G d d      } |       }	 t        |ddd      }y# t        $ r}| j                  d|        Y d}~yd}~ww xY w)z>Test email sending when analysis object has missing attributesc                       e Zd Zd Zy)KEmailEdgeCaseTests.test_email_with_missing_attributes.<locals>.MockAnalysisc                      d| _         d| _        y )Nr.   zMock Analysis)idr0   r;   s    r=   __init__zTEmailEdgeCaseTests.test_email_with_missing_attributes.<locals>.MockAnalysis.__init__  s    +	r?   N)r_   r`   ra   r  rc   r?   r=   MockAnalysisr    s    ,r?   r  r   r   zMissing attributes testz/Email sending crashed with missing attributes: N)r   r   fail)r<   r  mock_objr   es        r=   "test_email_with_missing_attributesz5EmailEdgeCaseTests.test_email_with_missing_attributes  s\    	, 	,  >		M3!)	F  	MIIGsKLL	Ms   " 	A	AA	N)
r_   r`   ra   rb   r>   rF   r   r  r  r#  rc   r?   r=   r  r    s5    >
#
 '. '.R
!Mr?   r  N)$rb   django.testr   r   django.contrib.authr   django.contrib.auth.modelsr   django.corer   django.utilsr   datetimer	   r
   unittest.mockr   r   r   bazi.modelsr   liuyao.modelsr   	api.utilsr   r   r   r   r   r)   r   rh   r   r   r   r  rc   r?   r=   <module>r.     s   	 4 . 1  !  0 0     `)8 `)F !PQ^8( ^8 R^8B !PQa!x a! Ra!H/ /Dau auHZM ZMr?   