Skip to content

chore: refactor promo activation, update lint rules, and expand test coverage #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 26, 2025
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
32 changes: 32 additions & 0 deletions promo_code/business/tests/auth/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ def test_short_company_name(self):
rest_framework.status.HTTP_400_BAD_REQUEST,
)

def test_create_company_missing_email_fiels(self):
with self.assertRaisesMessage(
ValueError,
'The Email must be set',
):
business.models.Company.objects.create_company(
name=self.valid_data['name'],
password=self.valid_data['password'],
email=None,
)


class InvalidCompanyAuthenticationTestCase(
business.tests.auth.base.BaseBusinessAuthTestCase,
Expand Down Expand Up @@ -132,3 +143,24 @@ def test_signin_invalid_password(self):
response.status_code,
rest_framework.status.HTTP_401_UNAUTHORIZED,
)

def test_signin_invalid_email(self):
business.models.Company.objects.create_company(
email=self.valid_data['email'],
name=self.valid_data['name'],
password=self.valid_data['password'],
)

data = {
'email': '[email protected]',
'password': self.valid_data['password'],
}
response = self.client.post(
self.company_signin_url,
data,
format='json',
)
self.assertEqual(
response.status_code,
rest_framework.status.HTTP_400_BAD_REQUEST,
)
53 changes: 53 additions & 0 deletions promo_code/business/tests/promocodes/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import django.test

import business.constants
import business.models


class CompanyModelTests(django.test.TestCase):
def test_company_str_representation(self):
company = business.models.Company.objects.create(
email='[email protected]',
name='My Awesome Company',
)
self.assertEqual(str(company), 'My Awesome Company')


class PromoModelTests(django.test.TestCase):
def setUp(self):
self.company = business.models.Company.objects.create(
email='[email protected]',
name='TestCorp',
)
self.common_promo = business.models.Promo.objects.create(
company=self.company,
description='A common promo',
max_count=100,
used_count=50,
mode=business.constants.PROMO_MODE_COMMON,
)

def test_promo_str_representation(self):
expected_str = (
f'Promo {self.common_promo.id} ({self.common_promo.mode})'
)
self.assertEqual(str(self.common_promo), expected_str)


class PromoCodeModelTests(django.test.TestCase):
def test_promo_code_str_representation(self):
company = business.models.Company.objects.create(
email='[email protected]',
name='TestCorp',
)
promo = business.models.Promo.objects.create(
company=company,
description='Unique codes promo',
max_count=10,
mode=business.constants.PROMO_MODE_UNIQUE,
)
promo_code = business.models.PromoCode.objects.create(
promo=promo,
code='UNIQUE123',
)
self.assertEqual(str(promo_code), 'UNIQUE123')
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,42 @@ def test_too_short_promo_common(self):
rest_framework.status.HTTP_400_BAD_REQUEST,
)

def test_missing_promo_common_field_for_common_promo(self):
payload = {
'description': 'Increased cashback 40% for new bank clients!',
'max_count': 100,
'target': {},
'active_from': '2028-12-20',
'mode': 'COMMON',
}
response = self.client.post(
self.promo_list_create_url,
payload,
format='json',
)
self.assertEqual(
response.status_code,
rest_framework.status.HTTP_400_BAD_REQUEST,
)

def test_missing_promo_unique_field_for_unique_promo(self):
payload = {
'description': 'Increased cashback 40% for new bank clients!',
'max_count': 100,
'target': {},
'active_from': '2028-12-20',
'mode': 'UNIQUE',
}
response = self.client.post(
self.promo_list_create_url,
payload,
format='json',
)
self.assertEqual(
response.status_code,
rest_framework.status.HTTP_400_BAD_REQUEST,
)

@parameterized.parameterized.expand(
[
(
Expand Down
17 changes: 3 additions & 14 deletions promo_code/user/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,10 @@ def _validate_targeting(self):
if target.get('country') and user_country != target['country'].lower():
raise TargetingError('Country mismatch.')

if target.get('age_from') and (
user_age is None or user_age < target['age_from']
):
if target.get('age_from') and user_age < target['age_from']:
raise TargetingError('Age mismatch.')

if target.get('age_until') and (
user_age is None or user_age > target['age_until']
):
if target.get('age_until') and user_age > target['age_until']:
raise TargetingError('Age mismatch.')

def _validate_is_active(self):
Expand Down Expand Up @@ -127,10 +123,7 @@ def _issue_promo_code(self) -> str:
)
promo_locked.save(update_fields=['used_count'])
promo_code_value = promo_locked.promo_common
else:
raise PromoUnavailableError()

elif promo_locked.mode == business.constants.PROMO_MODE_UNIQUE:
else:
unique_code = promo_locked.unique_codes.filter(
is_used=False,
).first()
Expand All @@ -139,8 +132,6 @@ def _issue_promo_code(self) -> str:
unique_code.used_at = django.utils.timezone.now()
unique_code.save(update_fields=['is_used', 'used_at'])
promo_code_value = unique_code.code
else:
raise PromoUnavailableError()

if promo_code_value:
user.models.PromoActivationHistory.objects.create(
Expand All @@ -149,7 +140,5 @@ def _issue_promo_code(self) -> str:
)
return promo_code_value

raise PromoActivationError('Invalid promotion type.')

except business.models.Promo.DoesNotExist:
raise PromoActivationError('Promo not found.')
94 changes: 94 additions & 0 deletions promo_code/user/tests/auth/test_authentication.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import uuid

import django.test
import rest_framework.status
import rest_framework_simplejwt.exceptions
import rest_framework_simplejwt.tokens

import business.models
import user.authentication
import user.models
import user.tests.auth.base

Expand Down Expand Up @@ -27,3 +34,90 @@ def test_signin_success(self):
response.status_code,
rest_framework.status.HTTP_200_OK,
)


class CustomJWTAuthenticationTest(django.test.TestCase):
def setUp(self):
self.factory = django.test.RequestFactory()
self.authenticator = user.authentication.CustomJWTAuthentication()
self.user = user.models.User.objects.create(
name='testuser_uuid',
token_version=1,
)
self.company = business.models.Company.objects.create(
name='testcompany_uuid',
token_version=1,
)

def _get_token_with_payload(self, payload):
token = rest_framework_simplejwt.tokens.AccessToken()
token.payload.update(payload)
return str(token)

def test_authenticate_invalid_user_type(self):
payload = {
'user_type': 'admin',
'user_id': str(self.user.id),
'token_version': self.user.token_version,
}
token = self._get_token_with_payload(payload)
request = self.factory.get('/api/test/')
request.META['HTTP_AUTHORIZATION'] = f'Bearer {token}'
with self.assertRaisesMessage(
rest_framework_simplejwt.exceptions.AuthenticationFailed,
'Invalid user type',
):
self.authenticator.authenticate(request)

def test_authenticate_missing_id_in_token(self):
payload = {
'user_type': 'user',
'token_version': self.user.token_version,
}
token = self._get_token_with_payload(payload)
request = self.factory.get('/api/test/')
request.META['HTTP_AUTHORIZATION'] = f'Bearer {token}'
with self.assertRaisesMessage(
rest_framework_simplejwt.exceptions.AuthenticationFailed,
'Missing user_id in token',
):
self.authenticator.authenticate(request)

def test_authenticate_mismatched_token_version(self):
payload = {
'user_type': 'user',
'user_id': str(self.user.id),
'token_version': 1,
}
token = self._get_token_with_payload(payload)
self.user.token_version = 2
self.user.save()
request = self.factory.get('/api/test/')
request.META['HTTP_AUTHORIZATION'] = f'Bearer {token}'
with self.assertRaisesMessage(
rest_framework_simplejwt.exceptions.AuthenticationFailed,
'Token invalid',
):
self.authenticator.authenticate(request)

def test_authenticate_user_or_company_not_found(self):
non_existent_uuid = str(uuid.uuid4())
payload = {
'user_type': 'user',
'user_id': non_existent_uuid,
'token_version': 1,
}
token = self._get_token_with_payload(payload)
request = self.factory.get('/api/test/')
request.META['HTTP_AUTHORIZATION'] = f'Bearer {token}'
with self.assertRaisesMessage(
rest_framework_simplejwt.exceptions.AuthenticationFailed,
'User or Company not found',
):
self.authenticator.authenticate(request)

def test_authenticate_raw_token_none(self):
request = self.factory.get('/api/test/')
request.META['HTTP_AUTHORIZATION'] = 'Token abcdefg'
result = self.authenticator.authenticate(request)
self.assertIsNone(result)
56 changes: 56 additions & 0 deletions promo_code/user/tests/user/operations/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,59 @@ def test_auth_sign_in_new_password_succeeds(self):
response.status_code,
rest_framework.status.HTTP_200_OK,
)

def test_patch_profile_update_other(self):
new_other = {'age': 30, 'country': 'ca'}
response = self.client.patch(
self.user_profile_url,
{'other': new_other},
format='json',
)

self.assertEqual(
response.status_code,
rest_framework.status.HTTP_200_OK,
)

self.assertEqual(
response.data.get('other'),
new_other,
)

get_resp = self.client.get(self.user_profile_url, format='json')
self.assertEqual(
get_resp.status_code,
rest_framework.status.HTTP_200_OK,
)
self.assertEqual(
get_resp.data.get('other'),
new_other,
)

def test_patch_profile_update_mail(self):
new_email = '[email protected]'
response = self.client.patch(
self.user_profile_url,
{'email': new_email},
format='json',
)

self.assertEqual(
response.status_code,
rest_framework.status.HTTP_200_OK,
)

self.assertEqual(
response.data.get('email'),
new_email,
)

get_resp = self.client.get(self.user_profile_url, format='json')
self.assertEqual(
get_resp.status_code,
rest_framework.status.HTTP_200_OK,
)
self.assertEqual(
get_resp.data.get('email'),
new_email,
)
8 changes: 8 additions & 0 deletions promo_code/user/tests/user/test_antifraud_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,11 @@ def test_handles_api_http_error(self, mock_cache, mock_post):
result,
{'ok': False, 'error': 'Anti-fraud service unavailable'},
)

def test_calculate_cache_timeout_none_when_missing(self):
self.assertIsNone(
self.service._calculate_cache_timeout(None),
)
self.assertIsNone(
self.service._calculate_cache_timeout(''),
)
Loading