test_attachments_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import os
  2. from django.urls import reverse
  3. from PIL import Image
  4. from misago.acl.models import Role
  5. from misago.acl.test import patch_user_acl
  6. from misago.conf import settings
  7. from misago.threads.models import Attachment, AttachmentType
  8. from misago.users.test import AuthenticatedUserTestCase
  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 (your file has 253.9\xa0KB)."
  136. )
  137. },
  138. )
  139. def test_corrupted_image_upload(self):
  140. """corrupted image upload is handled"""
  141. AttachmentType.objects.create(name="Test extension", extensions="gif")
  142. with open(TEST_CORRUPTEDIMG_PATH, "rb") as upload:
  143. response = self.client.post(self.api_link, data={"upload": upload})
  144. self.assertEqual(response.status_code, 400)
  145. self.assertEqual(
  146. response.json(), {"detail": "Uploaded image was corrupted or invalid."}
  147. )
  148. def test_document_upload(self):
  149. """successful upload creates orphan attachment"""
  150. AttachmentType.objects.create(
  151. name="Test extension", extensions="pdf", mimetypes="application/pdf"
  152. )
  153. with open(TEST_DOCUMENT_PATH, "rb") as upload:
  154. response = self.client.post(self.api_link, data={"upload": upload})
  155. self.assertEqual(response.status_code, 200)
  156. response_json = response.json()
  157. attachment = Attachment.objects.get(id=response_json["id"])
  158. self.assertEqual(attachment.filename, "document.pdf")
  159. self.assertTrue(attachment.is_file)
  160. self.assertFalse(attachment.is_image)
  161. self.assertIsNotNone(attachment.file)
  162. self.assertTrue(not attachment.image)
  163. self.assertTrue(not attachment.thumbnail)
  164. self.assertTrue(str(attachment.file).endswith("document.pdf"))
  165. self.assertIsNone(response_json["post"])
  166. self.assertEqual(response_json["uploader_name"], self.user.username)
  167. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  168. self.assertIsNone(response_json["url"]["thumb"])
  169. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  170. self.assertEqual(self.user.audittrail_set.count(), 1)
  171. # files associated with attachment are deleted on its deletion
  172. file_path = attachment.file.path
  173. self.assertTrue(os.path.exists(file_path))
  174. attachment.delete()
  175. self.assertFalse(os.path.exists(file_path))
  176. def test_small_image_upload(self):
  177. """successful small image upload creates orphan attachment without thumbnail"""
  178. AttachmentType.objects.create(
  179. name="Test extension", extensions="jpeg,jpg", mimetypes="image/jpeg"
  180. )
  181. with open(TEST_SMALLJPG_PATH, "rb") as upload:
  182. response = self.client.post(self.api_link, data={"upload": upload})
  183. self.assertEqual(response.status_code, 200)
  184. response_json = response.json()
  185. attachment = Attachment.objects.get(id=response_json["id"])
  186. self.assertEqual(attachment.filename, "small.jpg")
  187. self.assertFalse(attachment.is_file)
  188. self.assertTrue(attachment.is_image)
  189. self.assertTrue(not attachment.file)
  190. self.assertIsNotNone(attachment.image)
  191. self.assertTrue(not attachment.thumbnail)
  192. self.assertTrue(str(attachment.image).endswith("small.jpg"))
  193. self.assertIsNone(response_json["post"])
  194. self.assertEqual(response_json["uploader_name"], self.user.username)
  195. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  196. self.assertIsNone(response_json["url"]["thumb"])
  197. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  198. self.assertEqual(self.user.audittrail_set.count(), 1)
  199. @patch_user_acl({"max_attachment_size": 10 * 1024})
  200. def test_large_image_upload(self):
  201. """successful large image upload creates orphan attachment with thumbnail"""
  202. AttachmentType.objects.create(
  203. name="Test extension", extensions="png", mimetypes="image/png"
  204. )
  205. with open(TEST_LARGEPNG_PATH, "rb") as upload:
  206. response = self.client.post(self.api_link, data={"upload": upload})
  207. self.assertEqual(response.status_code, 200)
  208. response_json = response.json()
  209. attachment = Attachment.objects.get(id=response_json["id"])
  210. self.assertEqual(attachment.filename, "large.png")
  211. self.assertFalse(attachment.is_file)
  212. self.assertTrue(attachment.is_image)
  213. self.assertTrue(not attachment.file)
  214. self.assertIsNotNone(attachment.image)
  215. self.assertIsNotNone(attachment.thumbnail)
  216. self.assertTrue(str(attachment.image).endswith("large.png"))
  217. self.assertTrue(str(attachment.thumbnail).endswith("large.png"))
  218. self.assertIsNone(response_json["post"])
  219. self.assertEqual(response_json["uploader_name"], self.user.username)
  220. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  221. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  222. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  223. self.assertEqual(self.user.audittrail_set.count(), 1)
  224. # thumbnail was scaled down
  225. thumbnail = Image.open(attachment.thumbnail.path)
  226. self.assertEqual(
  227. thumbnail.size[0], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[0]
  228. )
  229. self.assertLess(
  230. thumbnail.size[1], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[1]
  231. )
  232. # files associated with attachment are deleted on its deletion
  233. image_path = attachment.image.path
  234. thumbnail_path = attachment.thumbnail.path
  235. self.assertTrue(os.path.exists(image_path))
  236. self.assertTrue(os.path.exists(thumbnail_path))
  237. attachment.delete()
  238. self.assertFalse(os.path.exists(image_path))
  239. self.assertFalse(os.path.exists(thumbnail_path))
  240. def test_animated_image_upload(self):
  241. """successful gif upload creates orphan attachment with thumbnail"""
  242. AttachmentType.objects.create(
  243. name="Test extension", extensions="gif", mimetypes="image/gif"
  244. )
  245. with open(TEST_ANIMATEDGIF_PATH, "rb") as upload:
  246. response = self.client.post(self.api_link, data={"upload": upload})
  247. self.assertEqual(response.status_code, 200)
  248. response_json = response.json()
  249. attachment = Attachment.objects.get(id=response_json["id"])
  250. self.assertEqual(attachment.filename, "animated.gif")
  251. self.assertFalse(attachment.is_file)
  252. self.assertTrue(attachment.is_image)
  253. self.assertTrue(not attachment.file)
  254. self.assertIsNotNone(attachment.image)
  255. self.assertIsNotNone(attachment.thumbnail)
  256. self.assertTrue(str(attachment.image).endswith("animated.gif"))
  257. self.assertTrue(str(attachment.thumbnail).endswith("animated.gif"))
  258. self.assertIsNone(response_json["post"])
  259. self.assertEqual(response_json["uploader_name"], self.user.username)
  260. self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url())
  261. self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url())
  262. self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url())
  263. self.assertEqual(self.user.audittrail_set.count(), 1)