test_email_service.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. """Unit tests for email service.
  2. These tests verify email template rendering, HTML formatting,
  3. password generation, and SMTP settings persistence.
  4. """
  5. import string
  6. from unittest.mock import AsyncMock, patch
  7. import pytest
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.models.notification_template import NotificationTemplate
  10. from backend.app.services.email_service import (
  11. create_welcome_email_from_template,
  12. generate_secure_password,
  13. render_template,
  14. )
  15. class TestEmailTemplateFormatting:
  16. """Tests for email template formatting."""
  17. @pytest.mark.asyncio
  18. async def test_welcome_email_newlines_converted_to_br(self):
  19. """Verify that newlines in welcome email body are converted to <br> tags."""
  20. # Mock database session
  21. db = AsyncMock(spec=AsyncSession)
  22. # Mock template with newlines
  23. template = NotificationTemplate(
  24. event_type="user_created",
  25. name="Welcome Email",
  26. title_template="Welcome to {app_name}",
  27. body_template="Hello {username}!\n\nYour password is: {password}\n\nPlease login at: {login_url}",
  28. is_default=True,
  29. )
  30. # Patch get_notification_template to return our template
  31. with patch("backend.app.services.email_service.get_notification_template", return_value=template):
  32. # Generate email
  33. subject, text_body, html_body = await create_welcome_email_from_template(
  34. db=db,
  35. username="testuser",
  36. password="testpass123",
  37. login_url="http://example.com/login",
  38. app_name="TestApp",
  39. )
  40. # Verify subject
  41. assert subject == "Welcome to TestApp"
  42. # Verify text body has newlines
  43. assert "\n\n" in text_body
  44. assert "Hello testuser!" in text_body
  45. assert "Your password is: testpass123" in text_body
  46. # Verify HTML body has <br> tags instead of relying on CSS
  47. assert "<br>" in html_body
  48. # Should not use white-space: pre-wrap
  49. assert "white-space: pre-wrap" not in html_body
  50. # Should have proper structure
  51. assert "<!DOCTYPE html>" in html_body
  52. assert '<div style="font-size: 16px;">' in html_body
  53. # Verify that escaped content is present (XSS protection)
  54. assert "Hello testuser!<br>" in html_body
  55. assert "Your password is: testpass123<br>" in html_body
  56. @pytest.mark.asyncio
  57. async def test_email_header_padding(self):
  58. """Verify that email header has proper padding to prevent cutoff."""
  59. # Mock database session
  60. db = AsyncMock(spec=AsyncSession)
  61. # Mock template
  62. template = NotificationTemplate(
  63. event_type="user_created",
  64. name="Welcome Email",
  65. title_template="Welcome",
  66. body_template="Test body",
  67. is_default=True,
  68. )
  69. # Patch get_notification_template to return our template
  70. with patch("backend.app.services.email_service.get_notification_template", return_value=template):
  71. # Generate email
  72. subject, text_body, html_body = await create_welcome_email_from_template(
  73. db=db,
  74. username="testuser",
  75. password="testpass123",
  76. login_url="http://example.com/login",
  77. )
  78. # Verify header has 30px padding (not 20px which was cutting off)
  79. assert "padding: 30px; border-radius: 8px 8px 0 0;" in html_body
  80. @pytest.mark.asyncio
  81. async def test_email_xss_protection(self):
  82. """Verify that HTML escaping is applied to prevent XSS attacks."""
  83. # Mock database session
  84. db = AsyncMock(spec=AsyncSession)
  85. # Mock template with potential XSS content
  86. template = NotificationTemplate(
  87. event_type="user_created",
  88. name="Welcome Email",
  89. title_template="Welcome <script>alert('xss')</script>",
  90. body_template="Hello <script>alert('xss')</script>\nTest",
  91. is_default=True,
  92. )
  93. # Patch get_notification_template to return our template
  94. with patch("backend.app.services.email_service.get_notification_template", return_value=template):
  95. # Generate email
  96. subject, text_body, html_body = await create_welcome_email_from_template(
  97. db=db,
  98. username="testuser",
  99. password="testpass123",
  100. login_url="http://example.com/login",
  101. )
  102. # Verify that script tags are escaped
  103. assert "&lt;script&gt;" in html_body
  104. # Verify no unescaped script tags
  105. assert "<script>" not in html_body
  106. class TestGenerateSecurePassword:
  107. """Tests for generate_secure_password()."""
  108. def test_password_default_length(self):
  109. """Default password is 16 characters."""
  110. password = generate_secure_password()
  111. assert len(password) == 16
  112. def test_password_custom_length(self):
  113. """Custom length is respected."""
  114. password = generate_secure_password(24)
  115. assert len(password) == 24
  116. def test_password_has_required_char_types(self):
  117. """Password contains uppercase, lowercase, digit, and special character."""
  118. # Run multiple times to reduce flakiness from random shuffling
  119. for _ in range(5):
  120. password = generate_secure_password()
  121. assert any(c in string.ascii_uppercase for c in password), "Missing uppercase"
  122. assert any(c in string.ascii_lowercase for c in password), "Missing lowercase"
  123. assert any(c in string.digits for c in password), "Missing digit"
  124. assert any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password), "Missing special"
  125. class TestRenderTemplate:
  126. """Tests for render_template()."""
  127. def test_render_template_basic(self):
  128. """Placeholders are replaced correctly."""
  129. result = render_template("Hello {name}, welcome to {app}!", {"name": "Alice", "app": "BamBuddy"})
  130. assert result == "Hello Alice, welcome to BamBuddy!"
  131. def test_render_template_removes_unreplaced(self):
  132. """Unreplaced placeholders are removed."""
  133. result = render_template("Hello {name}, your code is {code}", {"name": "Bob"})
  134. assert result == "Hello Bob, your code is "
  135. class TestSMTPSettingsPersistence:
  136. """Tests for save_smtp_settings() and get_smtp_settings() round-trip."""
  137. @pytest.mark.asyncio
  138. async def test_save_and_retrieve_smtp_settings(self, db_session):
  139. """Save SMTP settings, then retrieve them and verify values match."""
  140. from backend.app.schemas.auth import SMTPSettings
  141. from backend.app.services.email_service import get_smtp_settings, save_smtp_settings
  142. settings = SMTPSettings(
  143. smtp_host="mail.example.com",
  144. smtp_port=465,
  145. smtp_username="user@example.com",
  146. smtp_password="secret",
  147. smtp_security="ssl",
  148. smtp_auth_enabled=True,
  149. smtp_from_email="noreply@example.com",
  150. )
  151. await save_smtp_settings(db_session, settings)
  152. await db_session.commit()
  153. retrieved = await get_smtp_settings(db_session)
  154. assert retrieved is not None
  155. assert retrieved.smtp_host == "mail.example.com"
  156. assert retrieved.smtp_port == 465
  157. assert retrieved.smtp_username == "user@example.com"
  158. assert retrieved.smtp_password == "secret"
  159. assert retrieved.smtp_security == "ssl"
  160. assert retrieved.smtp_auth_enabled is True
  161. assert retrieved.smtp_from_email == "noreply@example.com"
  162. @pytest.mark.asyncio
  163. async def test_get_smtp_settings_returns_none_when_unconfigured(self, db_session):
  164. """Empty DB returns None for SMTP settings."""
  165. from backend.app.services.email_service import get_smtp_settings
  166. result = await get_smtp_settings(db_session)
  167. assert result is None