test_attachments_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. def test_upload_too_big_for_type(self):
  103. """too big uploads are rejected"""
  104. AttachmentType.objects.create(
  105. name="Test extension",
  106. extensions="png",
  107. mimetypes="image/png",
  108. size_limit=100,
  109. )
  110. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  111. response = self.client.post(self.api_link, data={"upload": upload})
  112. self.assertEqual(response.status_code, 400)
  113. self.assertEqual(
  114. response.json(),
  115. {
  116. "detail": (
  117. "You can't upload files of this type larger "
  118. "than 100.0\xa0KB (your file has 253.9\xa0KB)."
  119. )
  120. },
  121. )
  122. @patch_user_acl({"max_attachment_size": 100})
  123. def test_upload_too_big_for_user(self):
  124. """too big uploads are rejected"""
  125. AttachmentType.objects.create(
  126. name="Test extension", extensions="png", mimetypes="image/png"
  127. )
  128. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  129. response = self.client.post(self.api_link, data={"upload": upload})
  130. self.assertEqual(response.status_code, 400)
  131. self.assertEqual(
  132. response.json(),
  133. {
  134. "detail": (
  135. "You can't upload files larger than 100.0\xa0KB "
  136. "(your file has 253.9\xa0KB)."
  137. )
  138. },
  139. )
  140. def test_corrupted_image_upload(self):
  141. """corrupted image upload is handled"""
  142. AttachmentType.objects.create(name="Test extension", extensions="gif")
  143. with open(TEST_CORRUPTEDIMG_PATH, "rb") as upload:
  144. response = self.client.post(self.api_link, data={"upload": upload})
  145. self.assertEqual(response.status_code, 400)
  146. self.assertEqual(
  147. response.json(), {"detail": "Uploaded image was corrupted or invalid."}
  148. )
  149. def test_document_upload(self):
  150. """successful upload creates orphan attachment"""
  151. AttachmentType.objects.create(
  152. name="Test extension", extensions="pdf", mimetypes="application/pdf"
  153. )
  154. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  155. response = self.client.post(self.api_link, data={"upload": upload})
  156. self.assertEqual(response.status_code, 200)
  157. response_json = response.json()
  158. attachment = Attachment.objects.get(id=response_json["id"])
  159. self.assertEqual(attachment.filename, "document.pdf")
  160. self.assertTrue(attachment.is_file)
  161. self.assertFalse(attachment.is_image)
  162. self.assertIsNotNone(attachment.file)
  163. self.assertTrue(not attachment.image)
  164. self.assertTrue(not attachment.thumbnail)
  165. self.assertTrue(str(attachment.file).endswith("document.pdf"))
  166. self.assertIsNone(response_json["post"])
  167. self.assertEqual(response_json["uploader_name"], self.user.username)
  168. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  169. self.assertIsNone(response_json["url"]["thumb"])
  170. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  171. self.assertEqual(self.user.audittrail_set.count(), 1)
  172. # files associated with attachment are deleted on its deletion
  173. file_path = attachment.file.path
  174. self.assertTrue(os.path.exists(file_path))
  175. attachment.delete()
  176. self.assertFalse(os.path.exists(file_path))
  177. def test_small_image_upload(self):
  178. """successful small image upload creates orphan attachment without thumbnail"""
  179. AttachmentType.objects.create(
  180. name="Test extension", extensions="jpeg,jpg", mimetypes="image/jpeg"
  181. )
  182. with open(TEST_SMALLJPG_PATH, "rb") as upload:
  183. response = self.client.post(self.api_link, data={"upload": upload})
  184. self.assertEqual(response.status_code, 200)
  185. response_json = response.json()
  186. attachment = Attachment.objects.get(id=response_json["id"])
  187. self.assertEqual(attachment.filename, "small.jpg")
  188. self.assertFalse(attachment.is_file)
  189. self.assertTrue(attachment.is_image)
  190. self.assertTrue(not attachment.file)
  191. self.assertIsNotNone(attachment.image)
  192. self.assertTrue(not attachment.thumbnail)
  193. self.assertTrue(str(attachment.image).endswith("small.jpg"))
  194. self.assertIsNone(response_json["post"])
  195. self.assertEqual(response_json["uploader_name"], self.user.username)
  196. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  197. self.assertIsNone(response_json["url"]["thumb"])
  198. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  199. self.assertEqual(self.user.audittrail_set.count(), 1)
  200. @patch_user_acl({"max_attachment_size": 10 * 1024})
  201. def test_large_image_upload(self):
  202. """successful large image upload creates orphan attachment with thumbnail"""
  203. AttachmentType.objects.create(
  204. name="Test extension", extensions="png", mimetypes="image/png"
  205. )
  206. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  207. response = self.client.post(self.api_link, data={"upload": upload})
  208. self.assertEqual(response.status_code, 200)
  209. response_json = response.json()
  210. attachment = Attachment.objects.get(id=response_json["id"])
  211. self.assertEqual(attachment.filename, "large.png")
  212. self.assertFalse(attachment.is_file)
  213. self.assertTrue(attachment.is_image)
  214. self.assertTrue(not attachment.file)
  215. self.assertIsNotNone(attachment.image)
  216. self.assertIsNotNone(attachment.thumbnail)
  217. self.assertTrue(str(attachment.image).endswith("large.png"))
  218. self.assertTrue(str(attachment.thumbnail).endswith("large.png"))
  219. self.assertIsNone(response_json["post"])
  220. self.assertEqual(response_json["uploader_name"], self.user.username)
  221. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  222. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  223. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  224. self.assertEqual(self.user.audittrail_set.count(), 1)
  225. # thumbnail was scaled down
  226. thumbnail = Image.open(attachment.thumbnail.path)
  227. self.assertEqual(
  228. thumbnail.size[0], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[0]
  229. )
  230. self.assertLess(
  231. thumbnail.size[1], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[1]
  232. )
  233. # files associated with attachment are deleted on its deletion
  234. image_path = attachment.image.path
  235. thumbnail_path = attachment.thumbnail.path
  236. self.assertTrue(os.path.exists(image_path))
  237. self.assertTrue(os.path.exists(thumbnail_path))
  238. attachment.delete()
  239. self.assertFalse(os.path.exists(image_path))
  240. self.assertFalse(os.path.exists(thumbnail_path))
  241. def test_animated_image_upload(self):
  242. """successful gif upload creates orphan attachment with thumbnail"""
  243. AttachmentType.objects.create(
  244. name="Test extension", extensions="gif", mimetypes="image/gif"
  245. )
  246. with open(TEST_ANIMATEDGIF_PATH, "rb") as upload:
  247. response = self.client.post(self.api_link, data={"upload": upload})
  248. self.assertEqual(response.status_code, 200)
  249. response_json = response.json()
  250. attachment = Attachment.objects.get(id=response_json["id"])
  251. self.assertEqual(attachment.filename, "animated.gif")
  252. self.assertFalse(attachment.is_file)
  253. self.assertTrue(attachment.is_image)
  254. self.assertTrue(not attachment.file)
  255. self.assertIsNotNone(attachment.image)
  256. self.assertIsNotNone(attachment.thumbnail)
  257. self.assertTrue(str(attachment.image).endswith("animated.gif"))
  258. self.assertTrue(str(attachment.thumbnail).endswith("animated.gif"))
  259. self.assertIsNone(response_json["post"])
  260. self.assertEqual(response_json["uploader_name"], self.user.username)
  261. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  262. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  263. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  264. self.assertEqual(self.user.audittrail_set.count(), 1)