test_imagefield.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import unittest
  3. from django.core.files.uploadedfile import SimpleUploadedFile
  4. from django.forms import ImageField
  5. from django.test import SimpleTestCase
  6. try:
  7. from PIL import Image
  8. except ImportError:
  9. Image = None
  10. def get_img_path(path):
  11. return os.path.join(os.path.abspath(os.path.join(__file__, '..', '..')), 'tests', path)
  12. @unittest.skipUnless(Image, "Pillow is required to test ImageField")
  13. class ImageFieldTest(SimpleTestCase):
  14. def test_imagefield_annotate_with_image_after_clean(self):
  15. f = ImageField()
  16. img_path = get_img_path('filepath_test_files/1x1.png')
  17. with open(img_path, 'rb') as img_file:
  18. img_data = img_file.read()
  19. img_file = SimpleUploadedFile('1x1.png', img_data)
  20. img_file.content_type = 'text/plain'
  21. uploaded_file = f.clean(img_file)
  22. self.assertEqual('PNG', uploaded_file.image.format)
  23. self.assertEqual('image/png', uploaded_file.content_type)
  24. def test_imagefield_annotate_with_bitmap_image_after_clean(self):
  25. """
  26. This also tests the situation when Pillow doesn't detect the MIME type
  27. of the image (#24948).
  28. """
  29. from PIL.BmpImagePlugin import BmpImageFile
  30. try:
  31. Image.register_mime(BmpImageFile.format, None)
  32. f = ImageField()
  33. img_path = get_img_path('filepath_test_files/1x1.bmp')
  34. with open(img_path, 'rb') as img_file:
  35. img_data = img_file.read()
  36. img_file = SimpleUploadedFile('1x1.bmp', img_data)
  37. img_file.content_type = 'text/plain'
  38. uploaded_file = f.clean(img_file)
  39. self.assertEqual('BMP', uploaded_file.image.format)
  40. self.assertIsNone(uploaded_file.content_type)
  41. finally:
  42. Image.register_mime(BmpImageFile.format, 'image/bmp')