test_clearattachments.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from datetime import timedelta
  2. from django.core.management import call_command
  3. from django.test import TestCase
  4. from django.utils import timezone
  5. from django.utils.six import StringIO
  6. from misago.categories.models import Category
  7. from misago.conf import settings
  8. from misago.threads import testutils
  9. from misago.threads.management.commands import clearattachments
  10. from misago.threads.models import Attachment, AttachmentType
  11. class ClearAttachmentsTests(TestCase):
  12. def test_no_attachments_sync(self):
  13. """command works when there are no attachments"""
  14. command = clearattachments.Command()
  15. out = StringIO()
  16. call_command(command, stdout=out)
  17. command_output = out.getvalue().strip()
  18. self.assertEqual(command_output, "No attachments were found")
  19. def test_attachments_sync(self):
  20. """command synchronizes attachments"""
  21. filetype = AttachmentType.objects.order_by('id').last()
  22. # create 5 expired orphaned attachments
  23. cutoff = timezone.now() - timedelta(minutes=settings.MISAGO_ATTACHMENT_ORPHANED_EXPIRE)
  24. cutoff -= timedelta(minutes=5)
  25. for _ in range(5):
  26. Attachment.objects.create(
  27. secret=Attachment.generate_new_secret(),
  28. filetype=filetype,
  29. size=1000,
  30. uploaded_on=cutoff,
  31. uploader_name='bob',
  32. uploader_slug='bob',
  33. uploader_ip='127.0.0.1',
  34. filename='testfile_{}.zip'.format(Attachment.objects.count() + 1),
  35. )
  36. # create 5 expired non-orphaned attachments
  37. category = Category.objects.get(slug='first-category')
  38. post = testutils.post_thread(category).first_post
  39. for _ in range(5):
  40. Attachment.objects.create(
  41. secret=Attachment.generate_new_secret(),
  42. filetype=filetype,
  43. size=1000,
  44. uploaded_on=cutoff,
  45. post=post,
  46. uploader_name='bob',
  47. uploader_slug='bob',
  48. uploader_ip='127.0.0.1',
  49. filename='testfile_{}.zip'.format(Attachment.objects.count() + 1),
  50. )
  51. # create 5 fresh orphaned attachments
  52. for _ in range(5):
  53. Attachment.objects.create(
  54. secret=Attachment.generate_new_secret(),
  55. filetype=filetype,
  56. size=1000,
  57. uploader_name='bob',
  58. uploader_slug='bob',
  59. uploader_ip='127.0.0.1',
  60. filename='testfile_{}.zip'.format(Attachment.objects.count() + 1),
  61. )
  62. command = clearattachments.Command()
  63. out = StringIO()
  64. call_command(command, stdout=out)
  65. command_output = out.getvalue().splitlines()[-1].strip()
  66. self.assertEqual(command_output, "Cleared 5 attachments")
  67. self.assertEqual(Attachment.objects.count(), 10)