1. import os
    
  2. import shutil
    
  3. from unittest import skipIf
    
  4. 
    
  5. from django.core.exceptions import ImproperlyConfigured
    
  6. from django.core.files import File
    
  7. from django.core.files.images import ImageFile
    
  8. from django.test import TestCase
    
  9. from django.test.testcases import SerializeMixin
    
  10. 
    
  11. try:
    
  12.     from .models import Image
    
  13. except ImproperlyConfigured:
    
  14.     Image = None
    
  15. 
    
  16. if Image:
    
  17.     from .models import (
    
  18.         Person,
    
  19.         PersonDimensionsFirst,
    
  20.         PersonTwoImages,
    
  21.         PersonWithHeight,
    
  22.         PersonWithHeightAndWidth,
    
  23.         TestImageFieldFile,
    
  24.         temp_storage_dir,
    
  25.     )
    
  26. else:
    
  27.     # Pillow not available, create dummy classes (tests will be skipped anyway)
    
  28.     class Person:
    
  29.         pass
    
  30. 
    
  31.     PersonWithHeight = PersonWithHeightAndWidth = PersonDimensionsFirst = Person
    
  32.     PersonTwoImages = Person
    
  33. 
    
  34. 
    
  35. class ImageFieldTestMixin(SerializeMixin):
    
  36.     """
    
  37.     Mixin class to provide common functionality to ImageField test classes.
    
  38.     """
    
  39. 
    
  40.     lockfile = __file__
    
  41. 
    
  42.     # Person model to use for tests.
    
  43.     PersonModel = PersonWithHeightAndWidth
    
  44.     # File class to use for file instances.
    
  45.     File = ImageFile
    
  46. 
    
  47.     def setUp(self):
    
  48.         """
    
  49.         Creates a pristine temp directory (or deletes and recreates if it
    
  50.         already exists) that the model uses as its storage directory.
    
  51. 
    
  52.         Sets up two ImageFile instances for use in tests.
    
  53.         """
    
  54.         if os.path.exists(temp_storage_dir):
    
  55.             shutil.rmtree(temp_storage_dir)
    
  56.         os.mkdir(temp_storage_dir)
    
  57. 
    
  58.         file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png")
    
  59.         self.file1 = self.File(open(file_path1, "rb"), name="4x8.png")
    
  60. 
    
  61.         file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png")
    
  62.         self.file2 = self.File(open(file_path2, "rb"), name="8x4.png")
    
  63. 
    
  64.     def tearDown(self):
    
  65.         """
    
  66.         Removes temp directory and all its contents.
    
  67.         """
    
  68.         self.file1.close()
    
  69.         self.file2.close()
    
  70.         shutil.rmtree(temp_storage_dir)
    
  71. 
    
  72.     def check_dimensions(self, instance, width, height, field_name="mugshot"):
    
  73.         """
    
  74.         Asserts that the given width and height values match both the
    
  75.         field's height and width attributes and the height and width fields
    
  76.         (if defined) the image field is caching to.
    
  77. 
    
  78.         Note, this method will check for dimension fields named by adding
    
  79.         "_width" or "_height" to the name of the ImageField.  So, the
    
  80.         models used in these tests must have their fields named
    
  81.         accordingly.
    
  82. 
    
  83.         By default, we check the field named "mugshot", but this can be
    
  84.         specified by passing the field_name parameter.
    
  85.         """
    
  86.         field = getattr(instance, field_name)
    
  87.         # Check height/width attributes of field.
    
  88.         if width is None and height is None:
    
  89.             with self.assertRaises(ValueError):
    
  90.                 getattr(field, "width")
    
  91.             with self.assertRaises(ValueError):
    
  92.                 getattr(field, "height")
    
  93.         else:
    
  94.             self.assertEqual(field.width, width)
    
  95.             self.assertEqual(field.height, height)
    
  96. 
    
  97.         # Check height/width fields of model, if defined.
    
  98.         width_field_name = field_name + "_width"
    
  99.         if hasattr(instance, width_field_name):
    
  100.             self.assertEqual(getattr(instance, width_field_name), width)
    
  101.         height_field_name = field_name + "_height"
    
  102.         if hasattr(instance, height_field_name):
    
  103.             self.assertEqual(getattr(instance, height_field_name), height)
    
  104. 
    
  105. 
    
  106. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  107. class ImageFieldTests(ImageFieldTestMixin, TestCase):
    
  108.     """
    
  109.     Tests for ImageField that don't need to be run with each of the
    
  110.     different test model classes.
    
  111.     """
    
  112. 
    
  113.     def test_equal_notequal_hash(self):
    
  114.         """
    
  115.         Bug #9786: Ensure '==' and '!=' work correctly.
    
  116.         Bug #9508: make sure hash() works as expected (equal items must
    
  117.         hash to the same value).
    
  118.         """
    
  119.         # Create two Persons with different mugshots.
    
  120.         p1 = self.PersonModel(name="Joe")
    
  121.         p1.mugshot.save("mug", self.file1)
    
  122.         p2 = self.PersonModel(name="Bob")
    
  123.         p2.mugshot.save("mug", self.file2)
    
  124.         self.assertIs(p1.mugshot == p2.mugshot, False)
    
  125.         self.assertIs(p1.mugshot != p2.mugshot, True)
    
  126. 
    
  127.         # Test again with an instance fetched from the db.
    
  128.         p1_db = self.PersonModel.objects.get(name="Joe")
    
  129.         self.assertIs(p1_db.mugshot == p2.mugshot, False)
    
  130.         self.assertIs(p1_db.mugshot != p2.mugshot, True)
    
  131. 
    
  132.         # Instance from db should match the local instance.
    
  133.         self.assertIs(p1_db.mugshot == p1.mugshot, True)
    
  134.         self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot))
    
  135.         self.assertIs(p1_db.mugshot != p1.mugshot, False)
    
  136. 
    
  137.     def test_instantiate_missing(self):
    
  138.         """
    
  139.         If the underlying file is unavailable, still create instantiate the
    
  140.         object without error.
    
  141.         """
    
  142.         p = self.PersonModel(name="Joan")
    
  143.         p.mugshot.save("shot", self.file1)
    
  144.         p = self.PersonModel.objects.get(name="Joan")
    
  145.         path = p.mugshot.path
    
  146.         shutil.move(path, path + ".moved")
    
  147.         self.PersonModel.objects.get(name="Joan")
    
  148. 
    
  149.     def test_delete_when_missing(self):
    
  150.         """
    
  151.         Bug #8175: correctly delete an object where the file no longer
    
  152.         exists on the file system.
    
  153.         """
    
  154.         p = self.PersonModel(name="Fred")
    
  155.         p.mugshot.save("shot", self.file1)
    
  156.         os.remove(p.mugshot.path)
    
  157.         p.delete()
    
  158. 
    
  159.     def test_size_method(self):
    
  160.         """
    
  161.         Bug #8534: FileField.size should not leave the file open.
    
  162.         """
    
  163.         p = self.PersonModel(name="Joan")
    
  164.         p.mugshot.save("shot", self.file1)
    
  165. 
    
  166.         # Get a "clean" model instance
    
  167.         p = self.PersonModel.objects.get(name="Joan")
    
  168.         # It won't have an opened file.
    
  169.         self.assertIs(p.mugshot.closed, True)
    
  170. 
    
  171.         # After asking for the size, the file should still be closed.
    
  172.         p.mugshot.size
    
  173.         self.assertIs(p.mugshot.closed, True)
    
  174. 
    
  175.     def test_pickle(self):
    
  176.         """
    
  177.         ImageField can be pickled, unpickled, and that the image of
    
  178.         the unpickled version is the same as the original.
    
  179.         """
    
  180.         import pickle
    
  181. 
    
  182.         p = Person(name="Joe")
    
  183.         p.mugshot.save("mug", self.file1)
    
  184.         dump = pickle.dumps(p)
    
  185. 
    
  186.         loaded_p = pickle.loads(dump)
    
  187.         self.assertEqual(p.mugshot, loaded_p.mugshot)
    
  188.         self.assertEqual(p.mugshot.url, loaded_p.mugshot.url)
    
  189.         self.assertEqual(p.mugshot.storage, loaded_p.mugshot.storage)
    
  190.         self.assertEqual(p.mugshot.instance, loaded_p.mugshot.instance)
    
  191.         self.assertEqual(p.mugshot.field, loaded_p.mugshot.field)
    
  192. 
    
  193.         mugshot_dump = pickle.dumps(p.mugshot)
    
  194.         loaded_mugshot = pickle.loads(mugshot_dump)
    
  195.         self.assertEqual(p.mugshot, loaded_mugshot)
    
  196.         self.assertEqual(p.mugshot.url, loaded_mugshot.url)
    
  197.         self.assertEqual(p.mugshot.storage, loaded_mugshot.storage)
    
  198.         self.assertEqual(p.mugshot.instance, loaded_mugshot.instance)
    
  199.         self.assertEqual(p.mugshot.field, loaded_mugshot.field)
    
  200. 
    
  201.     def test_defer(self):
    
  202.         self.PersonModel.objects.create(name="Joe", mugshot=self.file1)
    
  203.         with self.assertNumQueries(1):
    
  204.             qs = list(self.PersonModel.objects.defer("mugshot"))
    
  205.         with self.assertNumQueries(0):
    
  206.             self.assertEqual(qs[0].name, "Joe")
    
  207. 
    
  208. 
    
  209. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  210. class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
    
  211.     """
    
  212.     Tests behavior of an ImageField and its dimensions fields.
    
  213.     """
    
  214. 
    
  215.     def test_constructor(self):
    
  216.         """
    
  217.         Tests assigning an image field through the model's constructor.
    
  218.         """
    
  219.         p = self.PersonModel(name="Joe", mugshot=self.file1)
    
  220.         self.check_dimensions(p, 4, 8)
    
  221.         p.save()
    
  222.         self.check_dimensions(p, 4, 8)
    
  223. 
    
  224.     def test_image_after_constructor(self):
    
  225.         """
    
  226.         Tests behavior when image is not passed in constructor.
    
  227.         """
    
  228.         p = self.PersonModel(name="Joe")
    
  229.         # TestImageField value will default to being an instance of its
    
  230.         # attr_class, a  TestImageFieldFile, with name == None, which will
    
  231.         # cause it to evaluate as False.
    
  232.         self.assertIsInstance(p.mugshot, TestImageFieldFile)
    
  233.         self.assertFalse(p.mugshot)
    
  234. 
    
  235.         # Test setting a fresh created model instance.
    
  236.         p = self.PersonModel(name="Joe")
    
  237.         p.mugshot = self.file1
    
  238.         self.check_dimensions(p, 4, 8)
    
  239. 
    
  240.     def test_create(self):
    
  241.         """
    
  242.         Tests assigning an image in Manager.create().
    
  243.         """
    
  244.         p = self.PersonModel.objects.create(name="Joe", mugshot=self.file1)
    
  245.         self.check_dimensions(p, 4, 8)
    
  246. 
    
  247.     def test_default_value(self):
    
  248.         """
    
  249.         The default value for an ImageField is an instance of
    
  250.         the field's attr_class (TestImageFieldFile in this case) with no
    
  251.         name (name set to None).
    
  252.         """
    
  253.         p = self.PersonModel()
    
  254.         self.assertIsInstance(p.mugshot, TestImageFieldFile)
    
  255.         self.assertFalse(p.mugshot)
    
  256. 
    
  257.     def test_assignment_to_None(self):
    
  258.         """
    
  259.         Assigning ImageField to None clears dimensions.
    
  260.         """
    
  261.         p = self.PersonModel(name="Joe", mugshot=self.file1)
    
  262.         self.check_dimensions(p, 4, 8)
    
  263. 
    
  264.         # If image assigned to None, dimension fields should be cleared.
    
  265.         p.mugshot = None
    
  266.         self.check_dimensions(p, None, None)
    
  267. 
    
  268.         p.mugshot = self.file2
    
  269.         self.check_dimensions(p, 8, 4)
    
  270. 
    
  271.     def test_field_save_and_delete_methods(self):
    
  272.         """
    
  273.         Tests assignment using the field's save method and deletion using
    
  274.         the field's delete method.
    
  275.         """
    
  276.         p = self.PersonModel(name="Joe")
    
  277.         p.mugshot.save("mug", self.file1)
    
  278.         self.check_dimensions(p, 4, 8)
    
  279. 
    
  280.         # A new file should update dimensions.
    
  281.         p.mugshot.save("mug", self.file2)
    
  282.         self.check_dimensions(p, 8, 4)
    
  283. 
    
  284.         # Field and dimensions should be cleared after a delete.
    
  285.         p.mugshot.delete(save=False)
    
  286.         self.assertIsNone(p.mugshot.name)
    
  287.         self.check_dimensions(p, None, None)
    
  288. 
    
  289.     def test_dimensions(self):
    
  290.         """
    
  291.         Dimensions are updated correctly in various situations.
    
  292.         """
    
  293.         p = self.PersonModel(name="Joe")
    
  294. 
    
  295.         # Dimensions should get set if file is saved.
    
  296.         p.mugshot.save("mug", self.file1)
    
  297.         self.check_dimensions(p, 4, 8)
    
  298. 
    
  299.         # Test dimensions after fetching from database.
    
  300.         p = self.PersonModel.objects.get(name="Joe")
    
  301.         # Bug 11084: Dimensions should not get recalculated if file is
    
  302.         # coming from the database.  We test this by checking if the file
    
  303.         # was opened.
    
  304.         self.assertIs(p.mugshot.was_opened, False)
    
  305.         self.check_dimensions(p, 4, 8)
    
  306.         # After checking dimensions on the image field, the file will have
    
  307.         # opened.
    
  308.         self.assertIs(p.mugshot.was_opened, True)
    
  309.         # Dimensions should now be cached, and if we reset was_opened and
    
  310.         # check dimensions again, the file should not have opened.
    
  311.         p.mugshot.was_opened = False
    
  312.         self.check_dimensions(p, 4, 8)
    
  313.         self.assertIs(p.mugshot.was_opened, False)
    
  314. 
    
  315.         # If we assign a new image to the instance, the dimensions should
    
  316.         # update.
    
  317.         p.mugshot = self.file2
    
  318.         self.check_dimensions(p, 8, 4)
    
  319.         # Dimensions were recalculated, and hence file should have opened.
    
  320.         self.assertIs(p.mugshot.was_opened, True)
    
  321. 
    
  322. 
    
  323. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  324. class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests):
    
  325.     """
    
  326.     Tests behavior of an ImageField with no dimension fields.
    
  327.     """
    
  328. 
    
  329.     PersonModel = Person
    
  330. 
    
  331. 
    
  332. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  333. class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests):
    
  334.     """
    
  335.     Tests behavior of an ImageField with one dimensions field.
    
  336.     """
    
  337. 
    
  338.     PersonModel = PersonWithHeight
    
  339. 
    
  340. 
    
  341. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  342. class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests):
    
  343.     """
    
  344.     Tests behavior of an ImageField where the dimensions fields are
    
  345.     defined before the ImageField.
    
  346.     """
    
  347. 
    
  348.     PersonModel = PersonDimensionsFirst
    
  349. 
    
  350. 
    
  351. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  352. class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests):
    
  353.     """
    
  354.     Tests behavior of an ImageField when assigning it a File instance
    
  355.     rather than an ImageFile instance.
    
  356.     """
    
  357. 
    
  358.     PersonModel = PersonDimensionsFirst
    
  359.     File = File
    
  360. 
    
  361. 
    
  362. @skipIf(Image is None, "Pillow is required to test ImageField")
    
  363. class TwoImageFieldTests(ImageFieldTestMixin, TestCase):
    
  364.     """
    
  365.     Tests a model with two ImageFields.
    
  366.     """
    
  367. 
    
  368.     PersonModel = PersonTwoImages
    
  369. 
    
  370.     def test_constructor(self):
    
  371.         p = self.PersonModel(mugshot=self.file1, headshot=self.file2)
    
  372.         self.check_dimensions(p, 4, 8, "mugshot")
    
  373.         self.check_dimensions(p, 8, 4, "headshot")
    
  374.         p.save()
    
  375.         self.check_dimensions(p, 4, 8, "mugshot")
    
  376.         self.check_dimensions(p, 8, 4, "headshot")
    
  377. 
    
  378.     def test_create(self):
    
  379.         p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2)
    
  380.         self.check_dimensions(p, 4, 8)
    
  381.         self.check_dimensions(p, 8, 4, "headshot")
    
  382. 
    
  383.     def test_assignment(self):
    
  384.         p = self.PersonModel()
    
  385.         self.check_dimensions(p, None, None, "mugshot")
    
  386.         self.check_dimensions(p, None, None, "headshot")
    
  387. 
    
  388.         p.mugshot = self.file1
    
  389.         self.check_dimensions(p, 4, 8, "mugshot")
    
  390.         self.check_dimensions(p, None, None, "headshot")
    
  391.         p.headshot = self.file2
    
  392.         self.check_dimensions(p, 4, 8, "mugshot")
    
  393.         self.check_dimensions(p, 8, 4, "headshot")
    
  394. 
    
  395.         # Clear the ImageFields one at a time.
    
  396.         p.mugshot = None
    
  397.         self.check_dimensions(p, None, None, "mugshot")
    
  398.         self.check_dimensions(p, 8, 4, "headshot")
    
  399.         p.headshot = None
    
  400.         self.check_dimensions(p, None, None, "mugshot")
    
  401.         self.check_dimensions(p, None, None, "headshot")
    
  402. 
    
  403.     def test_field_save_and_delete_methods(self):
    
  404.         p = self.PersonModel(name="Joe")
    
  405.         p.mugshot.save("mug", self.file1)
    
  406.         self.check_dimensions(p, 4, 8, "mugshot")
    
  407.         self.check_dimensions(p, None, None, "headshot")
    
  408.         p.headshot.save("head", self.file2)
    
  409.         self.check_dimensions(p, 4, 8, "mugshot")
    
  410.         self.check_dimensions(p, 8, 4, "headshot")
    
  411. 
    
  412.         # We can use save=True when deleting the image field with null=True
    
  413.         # dimension fields and the other field has an image.
    
  414.         p.headshot.delete(save=True)
    
  415.         self.check_dimensions(p, 4, 8, "mugshot")
    
  416.         self.check_dimensions(p, None, None, "headshot")
    
  417.         p.mugshot.delete(save=False)
    
  418.         self.check_dimensions(p, None, None, "mugshot")
    
  419.         self.check_dimensions(p, None, None, "headshot")
    
  420. 
    
  421.     def test_dimensions(self):
    
  422.         """
    
  423.         Dimensions are updated correctly in various situations.
    
  424.         """
    
  425.         p = self.PersonModel(name="Joe")
    
  426. 
    
  427.         # Dimensions should get set for the saved file.
    
  428.         p.mugshot.save("mug", self.file1)
    
  429.         p.headshot.save("head", self.file2)
    
  430.         self.check_dimensions(p, 4, 8, "mugshot")
    
  431.         self.check_dimensions(p, 8, 4, "headshot")
    
  432. 
    
  433.         # Test dimensions after fetching from database.
    
  434.         p = self.PersonModel.objects.get(name="Joe")
    
  435.         # Bug 11084: Dimensions should not get recalculated if file is
    
  436.         # coming from the database.  We test this by checking if the file
    
  437.         # was opened.
    
  438.         self.assertIs(p.mugshot.was_opened, False)
    
  439.         self.assertIs(p.headshot.was_opened, False)
    
  440.         self.check_dimensions(p, 4, 8, "mugshot")
    
  441.         self.check_dimensions(p, 8, 4, "headshot")
    
  442.         # After checking dimensions on the image fields, the files will
    
  443.         # have been opened.
    
  444.         self.assertIs(p.mugshot.was_opened, True)
    
  445.         self.assertIs(p.headshot.was_opened, True)
    
  446.         # Dimensions should now be cached, and if we reset was_opened and
    
  447.         # check dimensions again, the file should not have opened.
    
  448.         p.mugshot.was_opened = False
    
  449.         p.headshot.was_opened = False
    
  450.         self.check_dimensions(p, 4, 8, "mugshot")
    
  451.         self.check_dimensions(p, 8, 4, "headshot")
    
  452.         self.assertIs(p.mugshot.was_opened, False)
    
  453.         self.assertIs(p.headshot.was_opened, False)
    
  454. 
    
  455.         # If we assign a new image to the instance, the dimensions should
    
  456.         # update.
    
  457.         p.mugshot = self.file2
    
  458.         p.headshot = self.file1
    
  459.         self.check_dimensions(p, 8, 4, "mugshot")
    
  460.         self.check_dimensions(p, 4, 8, "headshot")
    
  461.         # Dimensions were recalculated, and hence file should have opened.
    
  462.         self.assertIs(p.mugshot.was_opened, True)
    
  463.         self.assertIs(p.headshot.was_opened, True)