Skip to content

Commit

Permalink
fixed errors in send_email and in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilJohns1 committed Sep 25, 2024
1 parent 9a156dc commit 418549a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 36 deletions.
26 changes: 14 additions & 12 deletions app/communication/tests/test_send_email.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from unittest.mock import patch

from rest_framework import status
Expand All @@ -10,6 +11,7 @@
from app.util.test_utils import get_api_client

EMAIL_URL = "/send-email/"
EMAIL_API_KEY = os.environ.get("EMAIL_API_KEY")


def _get_email_url():
Expand All @@ -25,18 +27,18 @@ def test_send_email_success(mock_send):
test_user = UserFactory()

data = {
"user_id": test_user.user_id,
"user_id_list": [test_user.user_id],
"notification_type": "KONTRES",
"title": "Test Notification",
"paragraphs": ["This is a test paragraph.", "This is another paragraph."],
}

client = get_api_client(user=test_user)
url = _get_email_url()
headers = {"EMAIL_API_KEY": "your_api_key"}
headers = {"api_key": EMAIL_API_KEY}
response = client.post(url, data, format="json", **headers)

assert response.status_code == status.HTTP_200_OK
assert response.status_code == status.HTTP_201_CREATED
mock_send.assert_called_once()


Expand All @@ -49,14 +51,14 @@ def test_send_email_fails_when_field_missing(mock_send):
test_user = UserFactory()

data = {
"user_id": test_user.user_id,
"user_id_list": [test_user.user_id],
"title": "Test Notification",
"paragraphs": ["This is a test paragraph.", "This is another paragraph."],
}

client = get_api_client(user=test_user)
url = _get_email_url()
headers = {"EMAIL_API_KEY": "your_api_key"}
headers = {"api_key": EMAIL_API_KEY}
response = client.post(url, data, format="json", **headers)

assert response.status_code == status.HTTP_400_BAD_REQUEST
Expand All @@ -72,15 +74,15 @@ def test_send_email_fails_when_wrong_api_key(mock_send):
test_user = UserFactory()

data = {
"user_id": test_user.user_id,
"user_id_list": [test_user.user_id],
"notification_type": "KONTRES",
"title": "Test Notification",
"paragraphs": ["This is a test paragraph.", "This is another paragraph."],
}

client = get_api_client(user=test_user)
url = _get_email_url()
headers = {"EMAIL_API_KEY": "wrong_api_key"}
headers = {"api_key": "wrong_key"}
response = client.post(url, data, format="json", **headers)

assert response.status_code == status.HTTP_403_FORBIDDEN
Expand All @@ -96,15 +98,15 @@ def test_send_email_fails_when_user_id_invalid(mock_send):
test_user = UserFactory()

data = {
"user_id": 999,
"user_id_list": [999],
"notification_type": "KONTRES",
"title": "Test Notification",
"paragraphs": ["This is a test paragraph.", "This is another paragraph."],
}

client = get_api_client(user=test_user)
url = _get_email_url()
headers = {"EMAIL_API_KEY": "your_api_key"}
headers = {"api_key": EMAIL_API_KEY}
response = client.post(url, data, format="json", **headers)

assert response.status_code == status.HTTP_404_NOT_FOUND
Expand All @@ -123,16 +125,16 @@ def test_email_success_with_kontres_and_blitzed(mock_send, notification_type):
test_user = UserFactory()

data = {
"user_id": test_user.user_id,
"user_id_list": [test_user.user_id],
"notification_type": notification_type,
"title": "Test Notification",
"paragraphs": ["This is a test paragraph.", "This is another paragraph."],
}

client = get_api_client(user=test_user)
url = _get_email_url()
headers = {"EMAIL_API_KEY": "your_api_key"}
headers = {"api_key": EMAIL_API_KEY}
response = client.post(url, data, format="json", **headers)

assert response.status_code == status.HTTP_200_OK
assert response.status_code == status.HTTP_201_CREATED
mock_send.assert_called_once()
53 changes: 29 additions & 24 deletions app/content/views/send_email.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import os

from rest_framework import status
from rest_framework.decorators import api_view
Expand All @@ -8,17 +9,14 @@
from app.communication.notifier import Notify
from app.content.models import User

# Temporary fake api key, will be changed to a proper api key in prod
API_KEY = "your_api_key"


@api_view(["POST"])
def send_email(request):
"""
Endpoint for sending a notification and email to a user.
Body should contain:
- 'user_id': The ID of the user to notify.
- 'user_id_list': A list of user ids to send the email to.
- 'notification_type': KONTRES or BLITZED.
- 'title': The title of the notification.
- 'paragraphs': A list of paragraphs to include in the notification.
Expand All @@ -28,53 +26,60 @@ def send_email(request):
"""
try:
# Validate API key
api_key = request.META.get("EMAIL_API_KEY")
if api_key != API_KEY:
EMAIL_API_KEY = os.environ.get("EMAIL_API_KEY")
api_key = request.META.get("api_key")
if api_key != EMAIL_API_KEY:
return Response(
{"detail": "Invalid API key"},
{"detail": "Feil API nøkkel"},
status=status.HTTP_403_FORBIDDEN,
)

# Validate request data
user_id = request.data.get("user_id")
user_id_list = request.data.get("user_id_list")
paragraphs = request.data.get("paragraphs")
title = request.data.get("title")
notification_type = request.data.get("notification_type")

if not user_id or not notification_type or not paragraphs or not title:
if not isinstance(user_id_list, list) or not user_id_list:
return Response(
{"detail": "En ikke-tom liste med bruker id-er må inkluderes"},
status=status.HTTP_400_BAD_REQUEST,
)

if not isinstance(paragraphs, list) or not paragraphs:
return Response(
{"detail": "En ikke-tom liste med paragrafer må inkluderes"},
status=status.HTTP_400_BAD_REQUEST,
)

if not notification_type or not title:
return Response(
{
"detail": "user_id, event_id, paragraphs and title are required fields."
"detail": "Notifikasjonstype (KONTRES/BLITZED) og tittel må være satt"
},
status=status.HTTP_400_BAD_REQUEST,
)

try:
user = User.objects.get(user_id=user_id)
except User.DoesNotExist:
users = list(User.objects.filter(user_id__in=user_id_list))
if not users or len(users) != len(user_id_list):
return Response(
{"detail": "User not found."},
{"detail": "En eller flere brukere ble ikke funnet"},
status=status.HTTP_404_NOT_FOUND,
)

email = Notify(
[user],
users,
f"{title}",
UserNotificationSettingType(notification_type),
).add_paragraph(f"Hei, {user.first_name}!")
)

for paragraph in paragraphs:
email.add_paragraph(paragraph)

email.send()
return Response(
{"detail": "Email sent successfully."},
status=status.HTTP_200_OK,
)
return Response({"detail": "Emailen ble sendt"}, status=status.HTTP_201_CREATED)
except Exception as e:
logging.error("An error occurred while sending email: %s", str(e))
print(e)
return Response(
{"detail": "An internal error has occurred."},
{"detail": "Det oppsto en feil under sending av email"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

0 comments on commit 418549a

Please sign in to comment.