Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 49 additions & 52 deletions push_notifications/admin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from django.apps import apps
from django.contrib import admin, messages
from django.db.models import QuerySet
from django.http import HttpRequest
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
from django.http import HttpRequest
from django.db.models import QuerySet

from .exceptions import APNSServerError, GCMError, WebPushError
from .models import APNSDevice, GCMDevice, WebPushDevice, WNSDevice
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
from .wns import WNSError


User = apps.get_model(*SETTINGS["USER_MODEL"].split("."))
Expand All @@ -24,7 +25,9 @@ class DeviceAdmin(admin.ModelAdmin):
else:
search_fields = ("name", "device_id", "")

def send_messages(self, request: HttpRequest, queryset: QuerySet, bulk: bool = False) -> None:
def send_messages(
self, request: HttpRequest, queryset: QuerySet, bulk: bool = False
) -> None:
"""
Provides error handling for DeviceAdmin send_message and send_bulk_message methods.
"""
Expand All @@ -46,65 +49,57 @@ def send_messages(self, request: HttpRequest, queryset: QuerySet, bulk: bool = F
errors.append(e.status)
except WebPushError as e:
errors.append(force_str(e))
except WNSError as e:
errors.append(force_str(e))

if bulk:
break

if bulk:
success = 0
for response in ret[0] if ret else []:
if isinstance(response, str):
success += 1 # WNS returns response text.
elif "results" in response:
success += response.get("success", 0)
errors.extend(
force_str(item["error"])
for item in response["results"] if "error" in item
)
else:
for value in response.values():
if force_str(value).lower() == "success":
success += 1
else:
errors.append(force_str(value))
if errors:
self.message_user(
request, _("Some messages could not be processed: %r" % (", ".join(errors))),
level=messages.ERROR
)
if success:
msg = (
_("Some messages were sent: %s" % (ret)) if errors
else _("All messages were sent: %s" % (ret))
)
self.message_user(request, msg)
return

# Because NotRegistered and InvalidRegistration do not throw GCMError
# catch them here to display error msg.
if not bulk:
for r in ret:
if "error" in r["results"][0]:
errors.append(r["results"][0]["error"])
else:
if "results" in ret[0][0]:
try:
errors = [r["error"] for r in ret[0][0]["results"] if "error" in r]
except TypeError:
for entry in ret[0][0]:
errors = errors + [r["error"] for r in entry["results"] if "error" in r]
except IndexError:
pass
else:
# different format, e.g.:
# [{'some_token1': 'Success',
# 'some_token2': 'BadDeviceToken'}]
for key, value in ret[0][0].items():
if value.lower() != "success":
errors.append(value)
for r in ret:
if "error" in r["results"][0]:
errors.append(r["results"][0]["error"])
if errors:
self.message_user(
request, _("Some messages could not be processed: %r" % (", ".join(errors))),
level=messages.ERROR
)
if ret:
if bulk:
# When the queryset exceeds the max_recipients value, the
# send_message method returns a list of dicts, one per chunk
if "results" in ret[0][0]:
try:
success = ret[0][0]["success"]
except TypeError:
success = 0
for entry in ret[0][0]:
success = success + entry["success"]
if success == 0:
return
else:
# different format, e.g.:
# [{'some_token1': 'Success',
# 'some_token2': 'BadDeviceToken'}]
success = []
for key, value in ret[0][0].items():
if value.lower() == "success":
success.append(key)

elif len(errors) == len(ret):
return
if errors:
msg = _("Some messages were sent: %s" % (ret))
else:
msg = _("All messages were sent: %s" % (ret))
if ret and len(errors) != len(ret):
msg = (
_("Some messages were sent: %s" % (ret)) if errors
else _("All messages were sent: %s" % (ret))
)
self.message_user(request, msg)

def send_message(self, request: HttpRequest, queryset: QuerySet) -> None:
Expand Down Expand Up @@ -134,7 +129,9 @@ class GCMDeviceAdmin(DeviceAdmin):
)
list_filter = ("active", "cloud_message_type")

def send_messages(self, request: HttpRequest, queryset: QuerySet, bulk: bool = False) -> None:
def send_messages(
self, request: HttpRequest, queryset: QuerySet, bulk: bool = False
) -> None:
"""
Provides error handling for DeviceAdmin send_message and send_bulk_message methods.
"""
Expand Down
91 changes: 84 additions & 7 deletions tests/test_admin.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,95 @@
from unittest import mock
import sys
from unittest import mock, skipIf


from django.contrib.admin import AdminSite
from django.contrib import messages
from django.contrib.admin import AdminSite
from django.http import HttpRequest
from django.test import TestCase
from firebase_admin.messaging import BatchResponse, Message, SendResponse, UnregisteredError

from firebase_admin.messaging import Message, BatchResponse, SendResponse, UnregisteredError

from push_notifications.admin import GCMDeviceAdmin
from push_notifications.models import GCMDevice
from push_notifications.admin import DeviceAdmin, GCMDeviceAdmin, WebPushDeviceAdmin
from push_notifications.models import APNSDevice, GCMDevice, WebPushDevice, WNSDevice
from push_notifications.wns import WNSNotificationResponseError
from tests import responses


class WebPushDeviceAdminTestCase(TestCase):
def test_bulk_action_with_only_inactive_devices_does_not_crash_or_claim_success(self):
WebPushDevice.objects.create(registration_id="inactive", active=False)
admin = WebPushDeviceAdmin(WebPushDevice, AdminSite())
admin.message_user = mock.Mock()

admin.send_messages(HttpRequest(), WebPushDevice.objects.all(), bulk=True)

admin.message_user.assert_not_called()

def test_bulk_action_reports_first_failed_webpush_with_later_success(self):
WebPushDevice.objects.create(registration_id="failed", active=True)
WebPushDevice.objects.create(registration_id="ok", active=True)
admin = WebPushDeviceAdmin(WebPushDevice, AdminSite())
admin.message_user = mock.Mock()

def send(device, message):
if device.registration_id == "failed":
return {"failure": 1, "results": [{"error": "expired"}]}
return {"success": 1, "results": [{}]}

with mock.patch("push_notifications.webpush.webpush_send_message", side_effect=send):
admin.send_messages(HttpRequest(), WebPushDevice.objects.order_by("id"), bulk=True)

self.assertEqual(admin.message_user.call_args_list[0][1]["level"], messages.ERROR)
self.assertIn("expired", str(admin.message_user.call_args_list[0][0][1]))


class WNSDeviceAdminTestCase(TestCase):
def test_bulk_action_reports_string_responses_without_crashing(self):
WNSDevice.objects.create(registration_id="urn:device", application_id="app")
admin = DeviceAdmin(WNSDevice, AdminSite())
admin.message_user = mock.Mock()

with mock.patch("push_notifications.wns.wns_send_bulk_message", return_value=["ok"]):
admin.send_messages(HttpRequest(), WNSDevice.objects.all(), bulk=True)

admin.message_user.assert_called_once()
self.assertNotEqual(admin.message_user.call_args[1].get("level"), messages.ERROR)

def test_bulk_action_reports_wns_failure(self):
WNSDevice.objects.create(registration_id="urn:expired", application_id="app")
admin = DeviceAdmin(WNSDevice, AdminSite())
admin.message_user = mock.Mock()

with mock.patch(
"push_notifications.wns.wns_send_bulk_message",
side_effect=WNSNotificationResponseError("HTTP 410"),
):
admin.send_messages(HttpRequest(), WNSDevice.objects.all(), bulk=True)

admin.message_user.assert_called_once()
self.assertEqual(admin.message_user.call_args[1]["level"], messages.ERROR)
self.assertIn("HTTP 410", str(admin.message_user.call_args[0][1]))


class APNSDeviceAdminTestCase(TestCase):
@skipIf(sys.version_info < (3, 10), "aioapns is unavailable on Python < 3.10")
def test_bulk_action_reports_failures_from_later_application_group(self):
APNSDevice.objects.create(registration_id="first", application_id="a")
APNSDevice.objects.create(registration_id="second", application_id="b")
admin = DeviceAdmin(APNSDevice, AdminSite())
admin.message_user = mock.Mock()

def send_group(registration_ids, **kwargs):
status = "Success" if registration_ids[0] == "first" else "Unregistered"
return {registration_ids[0]: status}

with mock.patch(
"push_notifications.apns_async.apns_send_bulk_message", side_effect=send_group

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apns_async imports aioapns, which the 3.7–3.9 jobs don't have, so this test fails there. It needs a skip like the other APNS tests.

):
admin.send_messages(HttpRequest(), APNSDevice.objects.all(), bulk=True)

self.assertIn("Unregistered", str(admin.message_user.call_args_list[0][0][1]))
self.assertEqual(admin.message_user.call_args_list[0][1]["level"], messages.ERROR)


class GCMDeviceAdminTestCase(TestCase):
def test_send_bulk_messages_action(self):
request = HttpRequest()
Expand Down