Skip to content

Commit

Permalink
added test for notification resend
Browse files Browse the repository at this point in the history
  • Loading branch information
KlemenSpruk committed Oct 25, 2023
1 parent d74a2be commit c0926ea
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 40 deletions.
9 changes: 2 additions & 7 deletions django_project_base/licensing/logic.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from typing import List

from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import connections
from django.db.models import Model, Sum
Expand Down Expand Up @@ -49,7 +48,7 @@ def report(self, user: Model) -> dict:
added_types.append(content_type.model_class()._meta.verbose_name)
used_credit = 0
if user_query.exists():
used_credit = round(user_query.aggregate(count=Sum("amount")).get("count", 0), 2)
used_credit = round(user_query.aggregate(count=Sum("amount")).get("count", 0), 4)

credit = self._user_access_user_inflow(user.pk)

Expand All @@ -58,7 +57,7 @@ def report(self, user: Model) -> dict:
"credit": round(credit, 2),
"used_credit": used_credit,
"usage_report": usage_report,
"remaining_credit": round(credit - used_credit, 2),
"remaining_credit": round(credit - used_credit, 4),
}
).data

Expand All @@ -72,10 +71,6 @@ def log(
on_sucess=None,
**kwargs,
) -> int:
if getattr(settings, "TESTING", False) and on_sucess:
on_sucess()
return 1

db_connection = "default"
if kwargs.get("db") and kwargs["db"] != "default":
db_connection = kwargs["db"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ class MailChannel(Channel):

def send(self, notification: DjangoProjectBaseNotification, extra_data, **kwargs) -> int:
if getattr(settings, "TESTING", False):
recipients: List[int] = (
list(map(int, notification.recipients.split(","))) if notification.recipients else []
)
return len(recipients)
return super().send(notification=notification, extra_data=extra_data)
message = self.provider.get_message(notification)
sender = self.sender(notification)
self.provider.client_send(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from typing import List

from django.conf import settings

from django_project_base.notifications.base.channels.channel import Channel, Recipient
from django_project_base.notifications.base.enums import ChannelIdentifier
from django_project_base.notifications.models import DjangoProjectBaseNotification
Expand All @@ -20,9 +18,6 @@ def get_recipients(self, notification: DjangoProjectBaseNotification, unique_ide
return list(set(super().get_recipients(notification, unique_identifier="phone_number")))

def send(self, notification: DjangoProjectBaseNotification, extra_data, **kwargs) -> int: # noqa: F821
recipients: List[int] = list(map(int, notification.recipients.split(","))) if notification.recipients else []
if not recipients or getattr(settings, "TESTING", False):
return len(recipients)
return super().send(notification=notification, extra_data=extra_data)

def clean_sms_recipients(self, recipients: List[Recipient]) -> List[Recipient]:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,13 @@
from django.contrib.contenttypes.models import ContentType

from django_project_base.licensing.logic import LogAccessService
from django_project_base.licensing.models import LicenseAccessUse
from django_project_base.notifications.base.enums import ChannelIdentifier
from django_project_base.notifications.tests.notifications_transaction_test_case import NotificationsTransactionTestCase


class TestRemainingLicense(NotificationsTransactionTestCase):
def test_remaining_license(self):
used_amount = 10
mail = self.create_notification_email_object().send()
LicenseAccessUse.objects.create(
type=LicenseAccessUse.UseType.USE,
user_id=str(self.test_user.pk),
content_type_object_id=str(mail.pk),
content_type=ContentType.objects.get_for_model(mail._meta.model),
amount=-100,
comment=dict(comment="", count=10, item_price=1, sender=""),
)
LicenseAccessUse.objects.create(
type=LicenseAccessUse.UseType.USE,
user_id=str(self.test_user.pk),
content_type_object_id=str(mail.pk),
content_type=ContentType.objects.get_for_model(mail._meta.model),
amount=used_amount,
comment=dict(comment="", count=10, item_price=1, sender=""),
)
log_service = LogAccessService()
usage = log_service.report(user=self.test_user)
credit = log_service._user_access_user_inflow(self.test_user.pk)
self.assertEqual(credit - used_amount, usage["remaining_credit"])
channel = ChannelIdentifier.channel(mail.required_channels.split(",")[0], ensure_dlr_user=False)
self.assertEqual(credit - channel.notification_price, usage["remaining_credit"])
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import socket
import uuid
from typing import List, Type

import swapper
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.test import TransactionTestCase
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

from django_project_base.licensing.models import LicenseAccessUse
from django_project_base.notifications.base.channels.channel import Channel
from django_project_base.notifications.base.channels.mail_channel import MailChannel
from django_project_base.notifications.base.notification import Notification
from django_project_base.notifications.models import DjangoProjectBaseMessage
from django_project_base.notifications.models import DjangoProjectBaseMessage, DjangoProjectBaseNotification


class TestNotificationViaEmail(Notification):
Expand All @@ -33,6 +36,14 @@ def setUp(self) -> None:
name="test", slug="test", owner=self.test_user.userprofile
)
self.api_client = APIClient()
LicenseAccessUse.objects.create(
type=LicenseAccessUse.UseType.USE,
user_id=str(self.test_user.pk),
content_type_object_id=str(uuid.uuid4()),
content_type=ContentType.objects.get_for_model(DjangoProjectBaseNotification._meta.model),
amount=-100,
comment=dict(comment="Test Credit", count=0, item_price=0, sender=""),
)

def _login_to_api_client_with_test_user(self):
user_token, token_created = Token.objects.get_or_create(user=self.test_user)
Expand All @@ -57,5 +68,5 @@ def create_notification_email_object(self) -> TestNotificationViaEmail:
project=swapper.load_model("django_project_base", "Project").objects.first().slug,
recipients=[self.test_user.pk],
persist=True,
user=self.test_user,
user=self.test_user.pk,
)
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
from django_project_base.notifications.models import DjangoProjectBaseNotification
import uuid

from django_project_base.licensing.logic import LogAccessService
from django_project_base.notifications.base.channels.channel import Recipient
from django_project_base.notifications.base.enums import ChannelIdentifier
from django_project_base.notifications.base.notification import Notification
from django_project_base.notifications.models import DeliveryReport, DjangoProjectBaseNotification
from django_project_base.notifications.tests.notifications_transaction_test_case import (
NotificationsTransactionTestCase,
TestNotificationViaEmail,
Expand All @@ -14,6 +20,31 @@ def test_is_email_sent(self):
assert isinstance(notification_db_object.sent_at, int)
self.assertIsNone(notification_db_object.exceptions)

def test_resend_email(self):
lic_start = LogAccessService().report(self.test_user)
notification: DjangoProjectBaseNotification = self.create_notification_email_object().send()
lic_first_sent = LogAccessService().report(self.test_user)
self.assertIsNotNone(notification.sent_at)
self.assertFalse(bool(notification.failed_channels))
self.assertEqual(notification.required_channels, notification.sent_channels)
channel = ChannelIdentifier.channel(notification.required_channels.split(",")[0], ensure_dlr_user=False)
dlr_pk = str(uuid.uuid4())
dlr_count = DeliveryReport.objects.all().count()
resend_data = channel._make_send(
notification_obj=notification,
rec_obj=Recipient(identifier=str(self.test_user.pk), phone_number="+38634000000", email="xyz@xyz.xyz"),
message_str="message",
dlr_pk=dlr_pk,
)
self.assertFalse(resend_data[1])
self.assertIsNone(resend_data[0])
self.assertEqual(dlr_count, DeliveryReport.objects.all().count())
Notification.resend(notification=notification, user_pk=self.test_user.pk)
self.assertEqual(dlr_count, DeliveryReport.objects.all().count())
lic_resend = LogAccessService().report(self.test_user)
self.assertEqual(lic_first_sent["remaining_credit"], lic_resend["remaining_credit"])
self.assertTrue(lic_start["remaining_credit"] > lic_resend["remaining_credit"])

# def test_is_email_queued(self):
# mail_queue: Queue = QueueFactory("mail")
# mail_queue.clear()
Expand Down

0 comments on commit c0926ea

Please sign in to comment.