Skip to content

Commit

Permalink
strict typing checks for DRF types and attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
groovecoder committed Jul 31, 2024
1 parent beb1266 commit 05041c1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 12 additions & 3 deletions api/tests/serializers_tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.contrib.auth.models import User
from django.urls import reverse

import pytest
Expand All @@ -12,14 +13,22 @@


class PremiumValidatorsTest(APITestCase):
def _get_token_for_user(self, user: User) -> Token:
if not hasattr(Token, "objects"):
raise AttributeError("Token must have objects attribute.")
token = Token.objects.get(user=user)
if not isinstance(token, Token):
raise TypeError("token must be of type Token.")
return token

def test_non_premium_cant_set_block_list_emails(self):
free_user = make_free_test_user()
free_alias = baker.make(RelayAddress, user=free_user)
assert free_alias.block_list_emails is False

url = reverse("relayaddress-detail", args=[free_alias.id])
data = {"block_list_emails": True}
free_token = Token.objects.get(user=free_user)
free_token = self._get_token_for_user(free_user)
self.client.credentials(HTTP_AUTHORIZATION="Token " + free_token.key)
response = self.client.patch(url, data, format="json")

Expand All @@ -33,7 +42,7 @@ def test_non_premium_can_clear_block_list_emails(self):

url = reverse("relayaddress-detail", args=[free_alias.id])
data = {"block_list_emails": False}
free_token = Token.objects.get(user=free_user)
free_token = self._get_token_for_user(free_user)
self.client.credentials(HTTP_AUTHORIZATION="Token " + free_token.key)
response = self.client.patch(url, data, format="json")

Expand All @@ -48,7 +57,7 @@ def test_premium_can_set_block_list_emails(self):

url = reverse("relayaddress-detail", args=[premium_alias.id])
data = {"block_list_emails": True}
free_token = Token.objects.get(user=premium_user)
free_token = self._get_token_for_user(premium_user)
self.client.credentials(HTTP_AUTHORIZATION="Token " + free_token.key)
response = self.client.patch(url, data, format="json")

Expand Down
2 changes: 2 additions & 0 deletions privaterelay/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ def copy_auth_token(
if created and instance is not None:
# baker triggers created during tests
# so first check the user doesn't already have a Token
if not hasattr(Token, "objects"):
raise AttributeError("Token must have objects attribute.")
try:
Token.objects.get(user=instance.user)
return
Expand Down

0 comments on commit 05041c1

Please sign in to comment.