test_attachments_api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import os
  2. from django.urls import reverse
  3. from PIL import Image
  4. from ...acl.models import Role
  5. from ...acl.test import patch_user_acl
  6. from ...conf import settings
  7. from ...users.test import AuthenticatedUserTestCase
  8. from ..models import Attachment, AttachmentType
  9. TESTFILES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "testfiles")
  10. TEST_DOCUMENT_PATH = os.path.join(TESTFILES_DIR, "document.pdf")
  11. TEST_LARGEPNG_PATH = os.path.join(TESTFILES_DIR, "large.png")
  12. TEST_SMALLJPG_PATH = os.path.join(TESTFILES_DIR, "small.jpg")
  13. TEST_ANIMATEDGIF_PATH = os.path.join(TESTFILES_DIR, "animated.gif")
  14. TEST_CORRUPTEDIMG_PATH = os.path.join(TESTFILES_DIR, "corrupted.gif")
  15. class AttachmentsApiTestCase(AuthenticatedUserTestCase):
  16. def setUp(self):
  17. super().setUp()
  18. AttachmentType.objects.all().delete()
  19. self.api_link = reverse("misago:api:attachment-list")
  20. def test_anonymous(self):
  21. """user has to be authenticated to be able to upload files"""
  22. self.logout_user()
  23. response = self.client.post(self.api_link)
  24. self.assertEqual(response.status_code, 403)
  25. @patch_user_acl({"max_attachment_size": 0})
  26. def test_no_permission(self):
  27. """user needs permission to upload files"""
  28. response = self.client.post(self.api_link)
  29. self.assertEqual(response.status_code, 403)
  30. self.assertEqual(
  31. response.json(),
  32. {"detail": "You don't have permission to upload new files."},
  33. )
  34. def test_no_file_uploaded(self):
  35. """no file uploaded scenario is handled"""
  36. response = self.client.post(self.api_link)
  37. self.assertEqual(response.status_code, 400)
  38. self.assertEqual(response.json(), {"detail": "No file has been uploaded."})
  39. def test_invalid_extension(self):
  40. """uploaded file's extension is rejected as invalid"""
  41. AttachmentType.objects.create(
  42. name="Test extension", extensions="jpg,jpeg", mimetypes=None
  43. )
  44. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  45. response = self.client.post(self.api_link, data={"upload": upload})
  46. self.assertEqual(response.status_code, 400)
  47. self.assertEqual(
  48. response.json(), {"detail": "You can't upload files of this type."}
  49. )
  50. def test_invalid_mime(self):
  51. """uploaded file's mimetype is rejected as invalid"""
  52. AttachmentType.objects.create(
  53. name="Test extension", extensions="png", mimetypes="loremipsum"
  54. )
  55. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  56. response = self.client.post(self.api_link, data={"upload": upload})
  57. self.assertEqual(response.status_code, 400)
  58. self.assertEqual(
  59. response.json(), {"detail": "You can't upload files of this type."}
  60. )
  61. def test_no_perm_to_type(self):
  62. """user needs permission to upload files of this type"""
  63. attachment_type = AttachmentType.objects.create(
  64. name="Test extension", extensions="png", mimetypes="application/pdf"
  65. )
  66. user_roles = (r.pk for r in self.user.get_roles())
  67. attachment_type.limit_uploads_to.set(Role.objects.exclude(id__in=user_roles))
  68. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  69. response = self.client.post(self.api_link, data={"upload": upload})
  70. self.assertEqual(response.status_code, 400)
  71. self.assertEqual(
  72. response.json(), {"detail": "You can't upload files of this type."}
  73. )
  74. def test_type_is_locked(self):
  75. """new uploads for this filetype are locked"""
  76. AttachmentType.objects.create(
  77. name="Test extension",
  78. extensions="png",
  79. mimetypes="application/pdf",
  80. status=AttachmentType.LOCKED,
  81. )
  82. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  83. response = self.client.post(self.api_link, data={"upload": upload})
  84. self.assertEqual(response.status_code, 400)
  85. self.assertEqual(
  86. response.json(), {"detail": "You can't upload files of this type."}
  87. )
  88. def test_type_is_disabled(self):
  89. """new uploads for this filetype are disabled"""
  90. AttachmentType.objects.create(
  91. name="Test extension",
  92. extensions="png",
  93. mimetypes="application/pdf",
  94. status=AttachmentType.DISABLED,
  95. )
  96. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  97. response = self.client.post(self.api_link, data={"upload": upload})
  98. self.assertEqual(response.status_code, 400)
  99. self.assertEqual(
  100. response.json(), {"detail": "You can't upload files of this type."}
  101. )
  102. @patch_user_acl({"max_attachment_size": 100})
  103. def test_upload_too_big_for_user(self):
  104. """too big uploads are rejected"""
  105. AttachmentType.objects.create(
  106. name="Test extension", extensions="png", mimetypes="image/png"
  107. )
  108. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  109. response = self.client.post(self.api_link, data={"upload": upload})
  110. self.assertEqual(response.status_code, 400)
  111. self.assertEqual(
  112. response.json(),
  113. {
  114. "detail": (
  115. "You can't upload files larger than 100.0\xa0KB "
  116. "(your file has 253.9\xa0KB)."
  117. )
  118. },
  119. )
  120. def test_corrupted_image_upload(self):
  121. """corrupted image upload is handled"""
  122. AttachmentType.objects.create(name="Test extension", extensions="gif")
  123. with open(TEST_CORRUPTEDIMG_PATH, "rb") as upload:
  124. response = self.client.post(self.api_link, data={"upload": upload})
  125. self.assertEqual(response.status_code, 400)
  126. self.assertEqual(
  127. response.json(), {"detail": "Uploaded image was corrupted or invalid."}
  128. )
  129. def test_document_upload(self):
  130. """successful upload creates orphan attachment"""
  131. AttachmentType.objects.create(
  132. name="Test extension", extensions="pdf", mimetypes="application/pdf"
  133. )
  134. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  135. response = self.client.post(self.api_link, data={"upload": upload})
  136. self.assertEqual(response.status_code, 200)
  137. response_json = response.json()
  138. attachment = Attachment.objects.get(id=response_json["id"])
  139. self.assertEqual(attachment.filename, "document.pdf")
  140. self.assertTrue(attachment.is_file)
  141. self.assertFalse(attachment.is_image)
  142. self.assertIsNotNone(attachment.file)
  143. self.assertTrue(not attachment.image)
  144. self.assertTrue(not attachment.thumbnail)
  145. self.assertTrue(str(attachment.file).endswith("document.pdf"))
  146. self.assertIsNone(response_json["post"])
  147. self.assertEqual(response_json["uploader_name"], self.user.username)
  148. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  149. self.assertIsNone(response_json["url"]["thumb"])
  150. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  151. self.assertEqual(self.user.audittrail_set.count(), 1)
  152. # files associated with attachment are deleted on its deletion
  153. file_path = attachment.file.path
  154. self.assertTrue(os.path.exists(file_path))
  155. attachment.delete()
  156. self.assertFalse(os.path.exists(file_path))
  157. def test_small_image_upload(self):
  158. """successful small image upload creates orphan attachment without thumbnail"""
  159. AttachmentType.objects.create(
  160. name="Test extension", extensions="jpeg,jpg", mimetypes="image/jpeg"
  161. )
  162. with open(TEST_SMALLJPG_PATH, "rb") as upload:
  163. response = self.client.post(self.api_link, data={"upload": upload})
  164. self.assertEqual(response.status_code, 200)
  165. response_json = response.json()
  166. attachment = Attachment.objects.get(id=response_json["id"])
  167. self.assertEqual(attachment.filename, "small.jpg")
  168. self.assertFalse(attachment.is_file)
  169. self.assertTrue(attachment.is_image)
  170. self.assertTrue(not attachment.file)
  171. self.assertIsNotNone(attachment.image)
  172. self.assertTrue(not attachment.thumbnail)
  173. self.assertTrue(str(attachment.image).endswith("small.jpg"))
  174. self.assertIsNone(response_json["post"])
  175. self.assertEqual(response_json["uploader_name"], self.user.username)
  176. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  177. self.assertIsNone(response_json["url"]["thumb"])
  178. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  179. self.assertEqual(self.user.audittrail_set.count(), 1)
  180. @patch_user_acl({"max_attachment_size": 10 * 1024})
  181. def test_large_image_upload(self):
  182. """successful large image upload creates orphan attachment with thumbnail"""
  183. AttachmentType.objects.create(
  184. name="Test extension", extensions="png", mimetypes="image/png"
  185. )
  186. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  187. response = self.client.post(self.api_link, data={"upload": upload})
  188. self.assertEqual(response.status_code, 200)
  189. response_json = response.json()
  190. attachment = Attachment.objects.get(id=response_json["id"])
  191. self.assertEqual(attachment.filename, "large.png")
  192. self.assertFalse(attachment.is_file)
  193. self.assertTrue(attachment.is_image)
  194. self.assertTrue(not attachment.file)
  195. self.assertIsNotNone(attachment.image)
  196. self.assertIsNotNone(attachment.thumbnail)
  197. self.assertTrue(str(attachment.image).endswith("large.png"))
  198. self.assertTrue(str(attachment.thumbnail).endswith("large.png"))
  199. self.assertIsNone(response_json["post"])
  200. self.assertEqual(response_json["uploader_name"], self.user.username)
  201. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  202. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  203. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  204. self.assertEqual(self.user.audittrail_set.count(), 1)
  205. # thumbnail was scaled down
  206. thumbnail = Image.open(attachment.thumbnail.path)
  207. self.assertEqual(
  208. thumbnail.size[0], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[0]
  209. )
  210. self.assertLess(
  211. thumbnail.size[1], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[1]
  212. )
  213. # files associated with attachment are deleted on its deletion
  214. image_path = attachment.image.path
  215. thumbnail_path = attachment.thumbnail.path
  216. self.assertTrue(os.path.exists(image_path))
  217. self.assertTrue(os.path.exists(thumbnail_path))
  218. attachment.delete()
  219. self.assertFalse(os.path.exists(image_path))
  220. self.assertFalse(os.path.exists(thumbnail_path))
  221. def test_animated_image_upload(self):
  222. """successful gif upload creates orphan attachment with thumbnail"""
  223. AttachmentType.objects.create(
  224. name="Test extension", extensions="gif", mimetypes="image/gif"
  225. )
  226. with open(TEST_ANIMATEDGIF_PATH, "rb") as upload:
  227. response = self.client.post(self.api_link, data={"upload": upload})
  228. self.assertEqual(response.status_code, 200)
  229. response_json = response.json()
  230. attachment = Attachment.objects.get(id=response_json["id"])
  231. self.assertEqual(attachment.filename, "animated.gif")
  232. self.assertFalse(attachment.is_file)
  233. self.assertTrue(attachment.is_image)
  234. self.assertTrue(not attachment.file)
  235. self.assertIsNotNone(attachment.image)
  236. self.assertIsNotNone(attachment.thumbnail)
  237. self.assertTrue(str(attachment.image).endswith("animated.gif"))
  238. self.assertTrue(str(attachment.thumbnail).endswith("animated.gif"))
  239. self.assertIsNone(response_json["post"])
  240. self.assertEqual(response_json["uploader_name"], self.user.username)
  241. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  242. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  243. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  244. self.assertEqual(self.user.audittrail_set.count(), 1)