test_clearattachments.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from datetime import timedelta
  2. from io import StringIO
  3. from django.core.management import call_command
  4. from django.test import TestCase
  5. from django.utils import timezone
  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(
  24. minutes=settings.MISAGO_ATTACHMENT_ORPHANED_EXPIRE
  25. )
  26. cutoff -= timedelta(minutes=5)
  27. for _ in range(5):
  28. Attachment.objects.create(
  29. secret=Attachment.generate_new_secret(),
  30. filetype=filetype,
  31. size=1000,
  32. uploaded_on=cutoff,
  33. uploader_name="bob",
  34. uploader_slug="bob",
  35. filename="testfile_%s.zip" % (Attachment.objects.count() + 1),
  36. )
  37. # create 5 expired non-orphaned attachments
  38. category = Category.objects.get(slug="first-category")
  39. post = testutils.post_thread(category).first_post
  40. for _ in range(5):
  41. Attachment.objects.create(
  42. secret=Attachment.generate_new_secret(),
  43. filetype=filetype,
  44. size=1000,
  45. uploaded_on=cutoff,
  46. post=post,
  47. uploader_name="bob",
  48. uploader_slug="bob",
  49. filename="testfile_%s.zip" % (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. filename="testfile_%s.zip" % (Attachment.objects.count() + 1),
  60. )
  61. command = clearattachments.Command()
  62. out = StringIO()
  63. call_command(command, 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)