test_clearattachments.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from datetime import timedelta
  2. from io import StringIO
  3. import pytest
  4. from django.core import management
  5. from django.utils import timezone
  6. from ...conf.test import override_dynamic_settings
  7. from ..management.commands import clearattachments
  8. from ..models import Attachment, AttachmentType
  9. @pytest.fixture
  10. def attachment_type(db):
  11. return AttachmentType.objects.order_by("id").last()
  12. def create_attachment(attachment_type, uploaded_on, post=None):
  13. return Attachment.objects.create(
  14. secret=Attachment.generate_new_secret(),
  15. post=post,
  16. filetype=attachment_type,
  17. size=1000,
  18. uploaded_on=uploaded_on,
  19. uploader_name="User",
  20. uploader_slug="user",
  21. filename="testfile_%s.zip" % (Attachment.objects.count() + 1),
  22. )
  23. def call_command():
  24. command = clearattachments.Command()
  25. out = StringIO()
  26. management.call_command(command, stdout=out)
  27. return out.getvalue().strip().splitlines()[-1].strip()
  28. def test_command_works_if_there_are_no_attachments(db):
  29. command_output = call_command()
  30. assert command_output == "No unused attachments were cleared"
  31. @override_dynamic_settings(unused_attachments_lifetime=2)
  32. def test_recent_attachment_is_not_cleared(attachment_type):
  33. attachment = create_attachment(attachment_type, timezone.now())
  34. command_output = call_command()
  35. assert command_output == "No unused attachments were cleared"
  36. @override_dynamic_settings(unused_attachments_lifetime=2)
  37. def test_old_used_attachment_is_not_cleared(attachment_type, post):
  38. uploaded_on = timezone.now() - timedelta(hours=3)
  39. attachment = create_attachment(attachment_type, uploaded_on, post)
  40. command_output = call_command()
  41. assert command_output == "No unused attachments were cleared"
  42. @override_dynamic_settings(unused_attachments_lifetime=2)
  43. def test_old_unused_attachment_is_cleared(attachment_type):
  44. uploaded_on = timezone.now() - timedelta(hours=3)
  45. attachment = create_attachment(attachment_type, uploaded_on)
  46. command_output = call_command()
  47. assert command_output == "Cleared 1 attachments"
  48. with pytest.raises(Attachment.DoesNotExist):
  49. attachment.refresh_from_db()