test_invalidatebans.py 2.6 KB

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