Skip to content

Commit

Permalink
For #26 add extra tests subscr\unsubscr for exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
lissa3 committed Aug 10, 2023
1 parent 50b0a59 commit 6d1a5f7
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 36 deletions.
16 changes: 16 additions & 0 deletions src/contacts/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,19 @@ class JobError(Exception):
"""

pass


class FailedNewsSubscription(Exception):
"""
get triggered if subscription to news letter failed
"""

pass


class UnsubcribeFail(Exception):
"""
get triggered if subscription to news letter failed
"""

pass
75 changes: 75 additions & 0 deletions src/contacts/tests/test_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from src.accounts.tests.factories import UserFactory
from src.contacts.exceptions import FailedNewsSubscription, UnsubcribeFail
from src.profiles.models import Profile
from src.profiles.tests.factories.profile_factory import ProfileFactory

User = get_user_model()


@override_settings(LANGUAGE_CODE="en", LANGUAGES=(("en", "English"),))
class SubscribeTestCase(TestCase):
def test_ok_subscription_news(self):
"""Auth-ed user can subscribe for a news letter"""
user = UserFactory()
self.client.force_login(user)
profile = Profile.objects.get(user=user)
headers = {"HTTP_HX-Request": "true"}
url = reverse("contacts:subscribe")
resp = self.client.post(url, **headers)
profile.refresh_from_db()

self.assertEqual(resp.status_code, 200)
self.assertIsNotNone(resp.headers["HX-Redirect"])
self.assertTrue(profile.want_news)

def test_failed_subscription_news(self):
"""
Failed subscription if not htmx request
(no header htmx)
"""
user = UserFactory()
profile = user.profile
self.client.force_login(user)
url = reverse("contacts:subscribe")
with self.assertRaises(FailedNewsSubscription) as e:
self.client.post(url) # noqa

profile.refresh_from_db()

self.assertFalse(profile.want_news)
self.assertEqual(str(e.exception), (_("Subscription failed")))


@override_settings(LANGUAGE_CODE="ru", LANGUAGES=(("ru", "Russian"),))
class UnSubscribeTestCase(TestCase):
def test_ok_unsubscribe(self):
"""if profile exists -> via htmx unsubscribe successfull"""
profile = ProfileFactory(want_news=True)
headers = {"HTTP_HX-Request": "true"}
url = reverse("contacts:end_news", kwargs={"uuid": profile.uuid})
resp = self.client.post(url, **headers)
profile.refresh_from_db()
print(resp.items())
self.assertEqual(resp.status_code, 200)
self.assertIsNotNone(resp.headers["HX-Redirect"])
self.assertFalse(profile.want_news)

def test_failed_unsubscribe_no_htmx(self):
"""
Failed un-subscribe if not htmx request
(no header htmx)
"""
profile = ProfileFactory(want_news=True)
url = reverse("contacts:end_news", kwargs={"uuid": profile.uuid})
with self.assertRaises(UnsubcribeFail) as e:
self.client.post(url) # noqa

self.assertTrue(profile.want_news)
self.assertEqual(
str(e.exception), (_("Something went wrong.Can't unsubscribe."))
)
59 changes: 24 additions & 35 deletions src/contacts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from src.profiles.models import Profile

from .exceptions import FailedNewsSubscription, UnsubcribeFail


class Subscribe(LRM, View):
def get(self, request):
Expand All @@ -24,59 +26,46 @@ def post(self, request, **kwargs):
htmx_based request with redirect to home page
and flash msg as a feedback
"""
try:
htmx_req = request.headers.get("hx-request")
if request.user.is_authenticated and htmx_req is not None:
_id = request.user.profile.id
profile = get_object_or_404(Profile, id=_id)
messages.success(request, _("You have subscribed to the news letter"))
profile.want_news = True
profile.save()
return HttpResponse(
headers={
"HX-Redirect": "/",
},
)
except Profile.DoesNotExist():
messages.warning(request, _("Subscription failed"))
htmx_req = request.headers.get("hx-request")

if request.user.is_authenticated and htmx_req is not None:
_id = request.user.profile.id
profile = get_object_or_404(Profile, id=_id)
profile.want_news = True
profile.save()
messages.success(request, _("You have subscribed to the news letter"))
return HttpResponse(
headers={
"HX-Redirect": "/",
},
headers={"HX-Redirect": "/"},
)
elif htmx_req is None:
raise FailedNewsSubscription(_("Subscription failed"))


class UnSubscribe(View):
def get(self, request, **kwargs):
"""
link in newsletter contains profile uuid
get request via link in a newsletter
contains profile uuid
"""
uuid = kwargs.get("uuid")

profile = get_object_or_404(Profile, uuid=uuid)
ctx = {"uuid": profile.uuid}
print("ctx", ctx)
return render(request, "contacts/subscription/unsubscribe.html", ctx)

def post(self, request, **kwargs):
# htmx_based
try:
htmx_req = request.headers.get("hx-request")
uuid = kwargs.get("uuid")
profile = get_object_or_404(Profile, uuid=uuid)
if htmx_req and profile:
messages.success(request, _("You have unsubscribed to the news letter"))
profile.want_news = False
profile.save()
return HttpResponse(
headers={
"HX-Redirect": "/",
},
)
except Profile.DoesNotExist():
messages.warning(request, _("Something went wrong.Subscription failed"))
htmx_req = request.headers.get("hx-request")
uuid = kwargs.get("uuid")
profile = get_object_or_404(Profile, uuid=uuid)
if htmx_req and profile.want_news:
profile.want_news = False
profile.save()
messages.success(request, _("You have unsubscribed to the news letter"))
return HttpResponse(
headers={
"HX-Redirect": "/",
},
)
elif htmx_req is None:
raise UnsubcribeFail(_("Something went wrong.Can't unsubscribe."))
2 changes: 1 addition & 1 deletion src/templates/contacts/subscription/unsubscribe.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<h3>{% trans "Do you really wish to unsubscribe from the newsletter?" %}</h3>
<div class="d-flex">
<button class="btn btn-warning"
hx-post="{% url 'contacts:end-news' uuid=uuid %}"
hx-post="{% url 'contacts:end_news' uuid=uuid %}"
>
{% trans "Unsubscribe" %}
</button>
Expand Down

0 comments on commit 6d1a5f7

Please sign in to comment.