|
| 1 | +from datetime import timedelta |
| 2 | + |
| 3 | +from django.core.exceptions import ValidationError |
1 | 4 | from django.test import TestCase |
| 5 | +from django.utils import timezone |
| 6 | + |
| 7 | +from users.models import User, Token |
| 8 | +from utilities.testing import create_test_user |
| 9 | + |
2 | 10 |
|
3 | | -from users.models import User |
| 11 | +class TokenTest(TestCase): |
| 12 | + """ |
| 13 | + Test class for testing the functionality of the Token model. |
| 14 | + """ |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def setUpTestData(cls): |
| 18 | + """ |
| 19 | + Set up test data for the Token model. |
| 20 | + """ |
| 21 | + cls.user = create_test_user('User 1') |
| 22 | + |
| 23 | + def test_is_expired(self): |
| 24 | + """ |
| 25 | + Test the is_expired property. |
| 26 | + """ |
| 27 | + # Token with no expiration |
| 28 | + token = Token(user=self.user, expires=None) |
| 29 | + self.assertFalse(token.is_expired) |
| 30 | + |
| 31 | + # Token with future expiration |
| 32 | + token.expires = timezone.now() + timedelta(days=1) |
| 33 | + self.assertFalse(token.is_expired) |
| 34 | + |
| 35 | + # Token with past expiration |
| 36 | + token.expires = timezone.now() - timedelta(days=1) |
| 37 | + self.assertTrue(token.is_expired) |
| 38 | + |
| 39 | + def test_cannot_create_token_with_past_expiration(self): |
| 40 | + """ |
| 41 | + Test that creating a token with an expiration date in the past raises a ValidationError. |
| 42 | + """ |
| 43 | + past_date = timezone.now() - timedelta(days=1) |
| 44 | + token = Token(user=self.user, expires=past_date) |
| 45 | + |
| 46 | + with self.assertRaises(ValidationError) as cm: |
| 47 | + token.clean() |
| 48 | + self.assertIn('expires', cm.exception.error_dict) |
| 49 | + |
| 50 | + def test_can_update_existing_expired_token(self): |
| 51 | + """ |
| 52 | + Test that updating an already expired token does NOT raise a ValidationError. |
| 53 | + """ |
| 54 | + # Create a valid token first with an expiration date in the past |
| 55 | + # bypasses the clean() method |
| 56 | + token = Token.objects.create(user=self.user) |
| 57 | + token.expires = timezone.now() - timedelta(days=1) |
| 58 | + token.save() |
| 59 | + |
| 60 | + # Try to update the description |
| 61 | + token.description = 'New Description' |
| 62 | + try: |
| 63 | + token.clean() |
| 64 | + token.save() |
| 65 | + except ValidationError: |
| 66 | + self.fail('Updating an expired token should not raise ValidationError') |
| 67 | + |
| 68 | + token.refresh_from_db() |
| 69 | + self.assertEqual(token.description, 'New Description') |
4 | 70 |
|
5 | 71 |
|
6 | 72 | class UserConfigTest(TestCase): |
|
0 commit comments