test_chores.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from unittest import mock
  2. from django.conf import settings
  3. from django.core import management
  4. from django.test import override_settings, TestCase
  5. from django.utils import timezone
  6. from desecapi.models import Captcha, User
  7. class ChoresCommandTest(TestCase):
  8. @override_settings(CAPTCHA_VALIDITY_PERIOD=timezone.timedelta(hours=1))
  9. def test_captcha_cleanup(self):
  10. faketime = timezone.now() - settings.CAPTCHA_VALIDITY_PERIOD - timezone.timedelta(seconds=1)
  11. with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
  12. captcha1 = Captcha.objects.create()
  13. captcha2 = Captcha.objects.create()
  14. self.assertGreaterEqual((captcha2.created - captcha1.created).total_seconds(), 3601)
  15. management.call_command('chores')
  16. self.assertEqual(list(Captcha.objects.all()), [captcha2])
  17. @override_settings(VALIDITY_PERIOD_VERIFICATION_SIGNATURE=timezone.timedelta(hours=1))
  18. def test_inactive_user_cleanup(self):
  19. def create_users(kind):
  20. logintime = timezone.now() + timezone.timedelta(seconds=5)
  21. kwargs_list = [
  22. dict(email=f'user1+{kind}@example.com', is_active=False, last_login=None),
  23. dict(email=f'user2+{kind}@example.com', is_active=True, last_login=None),
  24. dict(email=f'user3+{kind}@example.com', is_active=False, last_login=logintime),
  25. dict(email=f'user4+{kind}@example.com', is_active=True, last_login=logintime),
  26. ]
  27. return (User.objects.create(**kwargs) for kwargs in kwargs_list)
  28. # Old users
  29. faketime = timezone.now() - settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE - timezone.timedelta(seconds=1)
  30. with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
  31. expired_user, _, _, _ = create_users('old')
  32. # New users
  33. create_users('new')
  34. all_users = set(User.objects.all())
  35. management.call_command('chores')
  36. # Check that only the expired user was deleted
  37. self.assertEqual(all_users - set(User.objects.all()), {expired_user})