test_email_service.py 8.0 KB

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