tests.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from django.test import TestCase
  2. from django.utils import timezone
  3. from django.contrib.auth import get_user_model
  4. from django.urls import reverse
  5. from rest_framework import status
  6. from drf_temptoken import utils, models
  7. User = get_user_model()
  8. class ModelsTestCase(TestCase):
  9. def setUp(self):
  10. self.user = User.objects.create_user(username='kapustlo', password='password')
  11. def test_token_expires(self):
  12. token = utils.create_token(self.user)
  13. token = token.expire()
  14. self.assertTrue(token.expired)
  15. class UtilsTestCase(TestCase):
  16. def setUp(self):
  17. self.user = User.objects.create_user(username='kapustlo', password='password')
  18. def test_create_token_generates_token_for_user(self):
  19. token = utils.create_token(self.user)
  20. self.assertEquals(token.user.pk, self.user.pk)
  21. def test_get_user_tokens_returns_quryset_with_3_tokens(self):
  22. for _ in range(3):
  23. utils.create_token(self.user)
  24. tokens = utils.get_user_tokens(self.user)
  25. self.assertEquals(tokens.count(), 3)
  26. class ReceiversTestCase(TestCase):
  27. def setUp(self):
  28. self.user = User.objects.create_user(username='kapustlo', password='password')
  29. self.token = utils.create_token(self.user)
  30. self.expired_pks = []
  31. for _ in range(3):
  32. token = utils.create_token(self.user, expires_on=timezone.now() - utils.get_time_delta())
  33. self.expired_pks.append(token.pk)
  34. def test_expired_tokens_deleted_after_creation_of_another_token(self):
  35. utils.create_token(self.user)
  36. tokens = models.TempToken.objects.filter(pk__in=self.expired_pks)
  37. self.assertEquals(tokens.count(), 0)
  38. def test_exipration_date_added(self):
  39. self.assertNotEquals(self.token.expires_on, None)
  40. class ViewsTestCase(TestCase):
  41. def setUp(self):
  42. self.user = User.objects.create_user(username='kapustlo', password='password')
  43. self.token = utils.create_token(self.user)
  44. def test_check_auth_returns_http_204_no_content(self):
  45. url = reverse('check_auth')
  46. headers = {
  47. 'HTTP_' + utils.TMP_TOKEN_AUTH_HEADER.upper(): utils.get_header_prefix() + self.token.key
  48. }
  49. response = self.client.get(url, **headers)
  50. self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)