test_invalidatebans.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from datetime import timedelta
  2. from io import StringIO
  3. from django.contrib.auth import get_user_model
  4. from django.core.management import call_command
  5. from django.test import TestCase
  6. from django.utils import timezone
  7. from misago.users import bans
  8. from misago.users.management.commands import invalidatebans
  9. from misago.users.models import Ban, BanCache
  10. UserModel = get_user_model()
  11. class InvalidateBansTests(TestCase):
  12. def test_expired_bans_handling(self):
  13. """expired bans are flagged as such"""
  14. # create 5 bans then update their valid date to past one
  15. for _ in range(5):
  16. Ban.objects.create(banned_value="abcd")
  17. expired_date = timezone.now() - timedelta(days=10)
  18. Ban.objects.all().update(expires_on=expired_date, is_checked=True)
  19. self.assertEqual(Ban.objects.filter(is_checked=True).count(), 5)
  20. command = invalidatebans.Command()
  21. out = StringIO()
  22. call_command(command, stdout=out)
  23. command_output = out.getvalue().splitlines()[0].strip()
  24. self.assertEqual(command_output, 'Bans invalidated: 5')
  25. self.assertEqual(Ban.objects.filter(is_checked=True).count(), 0)
  26. def test_bans_caches_updates(self):
  27. """ban caches are updated"""
  28. user = UserModel.objects.create_user("Bob", "bob@boberson.com", "Pass.123")
  29. # ban user
  30. Ban.objects.create(banned_value="bob")
  31. user_ban = bans.get_user_ban(user)
  32. self.assertIsNotNone(user_ban)
  33. self.assertEqual(Ban.objects.filter(is_checked=True).count(), 1)
  34. # first call didn't touch ban
  35. command = invalidatebans.Command()
  36. out = StringIO()
  37. call_command(command, stdout=out)
  38. command_output = out.getvalue().splitlines()[1].strip()
  39. self.assertEqual(command_output, 'Ban caches emptied: 0')
  40. self.assertEqual(Ban.objects.filter(is_checked=True).count(), 1)
  41. # expire bans
  42. expired_date = timezone.now() - timedelta(days=10)
  43. Ban.objects.all().update(
  44. expires_on=expired_date,
  45. is_checked=True,
  46. )
  47. BanCache.objects.all().update(expires_on=expired_date)
  48. # invalidate expired ban cache
  49. out = StringIO()
  50. call_command(command, stdout=out)
  51. command_output = out.getvalue().splitlines()[1].strip()
  52. self.assertEqual(command_output, 'Ban caches emptied: 1')
  53. self.assertEqual(Ban.objects.filter(is_checked=True).count(), 0)
  54. # see if user is banned anymore
  55. user = UserModel.objects.get(id=user.id)
  56. self.assertIsNone(bans.get_user_ban(user))