From 5e0ea95d9cd6dfe345d0a21d867b7d0a33072a4f Mon Sep 17 00:00:00 2001 From: Daniel Gray Date: Thu, 18 Jul 2024 18:18:11 +0200 Subject: [PATCH] backup of code --- app/accounts/service/active_email.py | 4 +- app/accounts/tests/test_active_email.py | 54 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 app/accounts/tests/test_active_email.py diff --git a/app/accounts/service/active_email.py b/app/accounts/service/active_email.py index f5ee9b0d..d43181a9 100644 --- a/app/accounts/service/active_email.py +++ b/app/accounts/service/active_email.py @@ -8,9 +8,7 @@ class SendActiveEmailService: - def __init__(self, user): - self.user = user - + @staticmethod def send_activation_email(request, user): if user and request: current_site = get_current_site(request) diff --git a/app/accounts/tests/test_active_email.py b/app/accounts/tests/test_active_email.py new file mode 100644 index 00000000..64312842 --- /dev/null +++ b/app/accounts/tests/test_active_email.py @@ -0,0 +1,54 @@ +from unittest.mock import MagicMock, patch + +from django.contrib.sites.shortcuts import get_current_site +from django.core import mail +from django.test import RequestFactory, TestCase +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode + +from accounts.service.active_email import ( # Adjust the import path as necessary + SendActiveEmailService, +) +from accounts.tokens import account_activation_token +from users.models import CustomUser # Import your custom user model + + +class SendActiveEmailServiceTest(TestCase): + def setUp(self): + self.factory = RequestFactory() + self.user = CustomUser.objects.create_user( + username="testuser", email="test@example.com", password="password123" + ) + self.request = self.factory.get("/fake-path") + self.service = SendActiveEmailService() + + def test_send_activation_email(self): + with patch("accounts.service.active_email.render_to_string") as mock_render: + # Set up the mocks + mock_render.return_value = "mocked template" + + # # Call the method + self.service.send_activation_email(self.request, self.user) + + # Check that render_to_string was called with the correct parameters + mock_render.assert_called_once_with( + "accounts/email/activation_email.html", + { + "user": self.user, + "domain": get_current_site(self.request).domain, + "uid": urlsafe_base64_encode(force_bytes(self.user.pk)), + "token": account_activation_token.make_token(self.user), + }, + ) + + # Check that an email was sent + self.assertEqual(len(mail.outbox), 1) + sent_email = mail.outbox[0] + self.assertEqual(sent_email.subject, "Activate your account.") + self.assertEqual(sent_email.to, [self.user.email]) + self.assertIn("mocked template", sent_email.alternatives[0][0]) + self.assertEqual(sent_email.alternatives[0][1], "text/html") + self.assertIn( + "Please activate your account by clicking the link provided in the email.", + sent_email.body, + )