test_clearattachments.py 2.8 KB

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