pillow not available create dummy classes tests will be skipped anyway mixin class to provide common functionality to imagefield test classes person model to use for tests file class to use for file instances creates a pristine temp directory or deletes and recreates if it already exists that the model uses as its storage directory sets up two imagefile instances for use in tests removes temp directory and all its contents asserts that the given width and height values match both the field s height and width attributes and the height and width fields if defined the image field is caching to note this method will check for dimension fields named by adding width or height to the name of the imagefield so the models used in these tests must have their fields named accordingly by default we check the field named mugshot but this can be specified by passing the fieldname parameter check heightwidth attributes of field check heightwidth fields of model if defined tests for imagefield that don t need to be run with each of the different test model classes bug 9786 ensure and work correctly bug 9508 make sure hash works as expected equal items must hash to the same value create two persons with different mugshots test again with an instance fetched from the db instance from db should match the local instance if the underlying file is unavailable still create instantiate the object without error bug 8175 correctly delete an object where the file no longer exists on the file system bug 8534 filefield size should not leave the file open get a clean model instance it won t have an opened file after asking for the size the file should still be closed imagefield can be pickled unpickled and that the image of the unpickled version is the same as the original tests behavior of an imagefield and its dimensions fields tests assigning an image field through the model s constructor tests behavior when image is not passed in constructor testimagefield value will default to being an instance of its attrclass a testimagefieldfile with name none which will cause it to evaluate as false test setting a fresh created model instance tests assigning an image in manager create the default value for an imagefield is an instance of the field s attrclass testimagefieldfile in this case with no name name set to none assigning imagefield to none clears dimensions if image assigned to none dimension fields should be cleared tests assignment using the field s save method and deletion using the field s delete method a new file should update dimensions field and dimensions should be cleared after a delete dimensions are updated correctly in various situations dimensions should get set if file is saved test dimensions after fetching from database bug 11084 dimensions should not get recalculated if file is coming from the database we test this by checking if the file was opened after checking dimensions on the image field the file will have opened dimensions should now be cached and if we reset wasopened and check dimensions again the file should not have opened if we assign a new image to the instance the dimensions should update dimensions were recalculated and hence file should have opened tests behavior of an imagefield with no dimension fields underlying file object wasnt closed tests behavior of an imagefield with one dimensions field tests behavior of an imagefield where the dimensions fields are defined before the imagefield tests behavior of an imagefield when assigning it a file instance rather than an imagefile instance tests a model with two imagefields clear the imagefields one at a time we can use savetrue when deleting the image field with nulltrue dimension fields and the other field has an image dimensions are updated correctly in various situations dimensions should get set for the saved file test dimensions after fetching from database bug 11084 dimensions should not get recalculated if file is coming from the database we test this by checking if the file was opened after checking dimensions on the image fields the files will have been opened dimensions should now be cached and if we reset wasopened and check dimensions again the file should not have opened if we assign a new image to the instance the dimensions should update dimensions were recalculated and hence file should have opened pillow not available create dummy classes tests will be skipped anyway mixin class to provide common functionality to imagefield test classes person model to use for tests file class to use for file instances creates a pristine temp directory or deletes and recreates if it already exists that the model uses as its storage directory sets up two imagefile instances for use in tests removes temp directory and all its contents asserts that the given width and height values match both the field s height and width attributes and the height and width fields if defined the image field is caching to note this method will check for dimension fields named by adding _width or _height to the name of the imagefield so the models used in these tests must have their fields named accordingly by default we check the field named mugshot but this can be specified by passing the field_name parameter check height width attributes of field check height width fields of model if defined tests for imagefield that don t need to be run with each of the different test model classes bug 9786 ensure and work correctly bug 9508 make sure hash works as expected equal items must hash to the same value create two persons with different mugshots test again with an instance fetched from the db instance from db should match the local instance if the underlying file is unavailable still create instantiate the object without error bug 8175 correctly delete an object where the file no longer exists on the file system bug 8534 filefield size should not leave the file open get a clean model instance it won t have an opened file after asking for the size the file should still be closed imagefield can be pickled unpickled and that the image of the unpickled version is the same as the original tests behavior of an imagefield and its dimensions fields tests assigning an image field through the model s constructor tests behavior when image is not passed in constructor testimagefield value will default to being an instance of its attr_class a testimagefieldfile with name none which will cause it to evaluate as false test setting a fresh created model instance tests assigning an image in manager create the default value for an imagefield is an instance of the field s attr_class testimagefieldfile in this case with no name name set to none assigning imagefield to none clears dimensions if image assigned to none dimension fields should be cleared tests assignment using the field s save method and deletion using the field s delete method a new file should update dimensions field and dimensions should be cleared after a delete dimensions are updated correctly in various situations dimensions should get set if file is saved test dimensions after fetching from database bug 11084 dimensions should not get recalculated if file is coming from the database we test this by checking if the file was opened after checking dimensions on the image field the file will have opened dimensions should now be cached and if we reset was_opened and check dimensions again the file should not have opened if we assign a new image to the instance the dimensions should update dimensions were recalculated and hence file should have opened tests behavior of an imagefield with no dimension fields underlying file object wasn t closed tests behavior of an imagefield with one dimensions field tests behavior of an imagefield where the dimensions fields are defined before the imagefield tests behavior of an imagefield when assigning it a file instance rather than an imagefile instance tests a model with two imagefields clear the imagefields one at a time we can use save true when deleting the image field with null true dimension fields and the other field has an image dimensions are updated correctly in various situations dimensions should get set for the saved file test dimensions after fetching from database bug 11084 dimensions should not get recalculated if file is coming from the database we test this by checking if the file was opened after checking dimensions on the image fields the files will have been opened dimensions should now be cached and if we reset was_opened and check dimensions again the file should not have opened if we assign a new image to the instance the dimensions should update dimensions were recalculated and hence file should have opened
import os
import shutil
from unittest import skipIf

from django.core.exceptions import ImproperlyConfigured
from django.core.files import File
from django.core.files.images import ImageFile
from django.db.models import signals
from django.test import TestCase
from django.test.testcases import SerializeMixin

try:
    from .models import Image
except ImproperlyConfigured:
    Image = None

if Image:
    from .models import (
        Person,
        PersonDimensionsFirst,
        PersonTwoImages,
        PersonWithHeight,
        PersonWithHeightAndWidth,
        TestImageFieldFile,
        temp_storage_dir,
    )
else:
    
    class Person:
        pass

    PersonWithHeight = PersonWithHeightAndWidth = PersonDimensionsFirst = Person
    PersonTwoImages = Person


class ImageFieldTestMixin(SerializeMixin):
    

    lockfile = __file__

    
    PersonModel = PersonWithHeightAndWidth
    
    File = ImageFile

    def setUp(self):
        
        if os.path.exists(temp_storage_dir):
            shutil.rmtree(temp_storage_dir)
        os.mkdir(temp_storage_dir)

        file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png")
        self.file1 = self.File(open(file_path1, "rb"), name="4x8.png")

        file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png")
        self.file2 = self.File(open(file_path2, "rb"), name="8x4.png")

    def tearDown(self):
        
        self.file1.close()
        self.file2.close()
        shutil.rmtree(temp_storage_dir)

    def check_dimensions(self, instance, width, height, field_name="mugshot"):
        
        field = getattr(instance, field_name)
        
        if width is None and height is None:
            with self.assertRaises(ValueError):
                getattr(field, "width")
            with self.assertRaises(ValueError):
                getattr(field, "height")
        else:
            self.assertEqual(field.width, width)
            self.assertEqual(field.height, height)

        
        width_field_name = field_name + "_width"
        if hasattr(instance, width_field_name):
            self.assertEqual(getattr(instance, width_field_name), width)
        height_field_name = field_name + "_height"
        if hasattr(instance, height_field_name):
            self.assertEqual(getattr(instance, height_field_name), height)


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldTests(ImageFieldTestMixin, TestCase):
    

    def test_equal_notequal_hash(self):
        
        
        p1 = self.PersonModel(name="Joe")
        p1.mugshot.save("mug", self.file1)
        p2 = self.PersonModel(name="Bob")
        p2.mugshot.save("mug", self.file2)
        self.assertIs(p1.mugshot == p2.mugshot, False)
        self.assertIs(p1.mugshot != p2.mugshot, True)

        
        p1_db = self.PersonModel.objects.get(name="Joe")
        self.assertIs(p1_db.mugshot == p2.mugshot, False)
        self.assertIs(p1_db.mugshot != p2.mugshot, True)

        
        self.assertIs(p1_db.mugshot == p1.mugshot, True)
        self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot))
        self.assertIs(p1_db.mugshot != p1.mugshot, False)

    def test_instantiate_missing(self):
        
        p = self.PersonModel(name="Joan")
        p.mugshot.save("shot", self.file1)
        p = self.PersonModel.objects.get(name="Joan")
        path = p.mugshot.path
        shutil.move(path, path + ".moved")
        self.PersonModel.objects.get(name="Joan")

    def test_delete_when_missing(self):
        
        p = self.PersonModel(name="Fred")
        p.mugshot.save("shot", self.file1)
        os.remove(p.mugshot.path)
        p.delete()

    def test_size_method(self):
        
        p = self.PersonModel(name="Joan")
        p.mugshot.save("shot", self.file1)

        
        p = self.PersonModel.objects.get(name="Joan")
        
        self.assertIs(p.mugshot.closed, True)

        
        p.mugshot.size
        self.assertIs(p.mugshot.closed, True)

    def test_pickle(self):
        
        import pickle

        p = Person(name="Joe")
        p.mugshot.save("mug", self.file1)
        dump = pickle.dumps(p)

        loaded_p = pickle.loads(dump)
        self.assertEqual(p.mugshot, loaded_p.mugshot)
        self.assertEqual(p.mugshot.url, loaded_p.mugshot.url)
        self.assertEqual(p.mugshot.storage, loaded_p.mugshot.storage)
        self.assertEqual(p.mugshot.instance, loaded_p.mugshot.instance)
        self.assertEqual(p.mugshot.field, loaded_p.mugshot.field)

        mugshot_dump = pickle.dumps(p.mugshot)
        loaded_mugshot = pickle.loads(mugshot_dump)
        self.assertEqual(p.mugshot, loaded_mugshot)
        self.assertEqual(p.mugshot.url, loaded_mugshot.url)
        self.assertEqual(p.mugshot.storage, loaded_mugshot.storage)
        self.assertEqual(p.mugshot.instance, loaded_mugshot.instance)
        self.assertEqual(p.mugshot.field, loaded_mugshot.field)

    def test_defer(self):
        self.PersonModel.objects.create(name="Joe", mugshot=self.file1)
        with self.assertNumQueries(1):
            qs = list(self.PersonModel.objects.defer("mugshot"))
        with self.assertNumQueries(0):
            self.assertEqual(qs[0].name, "Joe")


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
    

    def test_constructor(self):
        
        p = self.PersonModel(name="Joe", mugshot=self.file1)
        self.check_dimensions(p, 4, 8)
        p.save()
        self.check_dimensions(p, 4, 8)

    def test_image_after_constructor(self):
        
        p = self.PersonModel(name="Joe")
        
        
        
        self.assertIsInstance(p.mugshot, TestImageFieldFile)
        self.assertFalse(p.mugshot)

        
        p = self.PersonModel(name="Joe")
        p.mugshot = self.file1
        self.check_dimensions(p, 4, 8)

    def test_create(self):
        
        p = self.PersonModel.objects.create(name="Joe", mugshot=self.file1)
        self.check_dimensions(p, 4, 8)

    def test_default_value(self):
        
        p = self.PersonModel()
        self.assertIsInstance(p.mugshot, TestImageFieldFile)
        self.assertFalse(p.mugshot)

    def test_assignment_to_None(self):
        
        p = self.PersonModel(name="Joe", mugshot=self.file1)
        self.check_dimensions(p, 4, 8)

        
        p.mugshot = None
        self.check_dimensions(p, None, None)

        p.mugshot = self.file2
        self.check_dimensions(p, 8, 4)

    def test_field_save_and_delete_methods(self):
        
        p = self.PersonModel(name="Joe")
        p.mugshot.save("mug", self.file1)
        self.check_dimensions(p, 4, 8)

        
        p.mugshot.save("mug", self.file2)
        self.check_dimensions(p, 8, 4)

        
        p.mugshot.delete(save=False)
        self.assertIsNone(p.mugshot.name)
        self.check_dimensions(p, None, None)

    def test_dimensions(self):
        
        p = self.PersonModel(name="Joe")

        
        p.mugshot.save("mug", self.file1)
        self.check_dimensions(p, 4, 8)

        
        p = self.PersonModel.objects.get(name="Joe")
        
        
        
        self.assertIs(p.mugshot.was_opened, False)
        self.check_dimensions(p, 4, 8)
        
        
        self.assertIs(p.mugshot.was_opened, True)
        
        
        p.mugshot.was_opened = False
        self.check_dimensions(p, 4, 8)
        self.assertIs(p.mugshot.was_opened, False)

        
        
        p.mugshot = self.file2
        self.check_dimensions(p, 8, 4)
        
        self.assertIs(p.mugshot.was_opened, True)


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests):
    

    PersonModel = Person

    def test_post_init_not_connected(self):
        person_model_id = id(self.PersonModel)
        self.assertNotIn(
            person_model_id,
            [sender_id for (_, sender_id), *_ in signals.post_init.receivers],
        )

    def test_save_does_not_close_file(self):
        p = self.PersonModel(name="Joe")
        p.mugshot.save("mug", self.file1)
        with p.mugshot as f:
            
            self.assertEqual(f.tell(), 0)


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests):
    

    PersonModel = PersonWithHeight


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests):
    

    PersonModel = PersonDimensionsFirst


@skipIf(Image is None, "Pillow is required to test ImageField")
class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests):
    

    PersonModel = PersonDimensionsFirst
    File = File


@skipIf(Image is None, "Pillow is required to test ImageField")
class TwoImageFieldTests(ImageFieldTestMixin, TestCase):
    

    PersonModel = PersonTwoImages

    def test_constructor(self):
        p = self.PersonModel(mugshot=self.file1, headshot=self.file2)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")
        p.save()
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")

    def test_create(self):
        p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2)
        self.check_dimensions(p, 4, 8)
        self.check_dimensions(p, 8, 4, "headshot")

    def test_assignment(self):
        p = self.PersonModel()
        self.check_dimensions(p, None, None, "mugshot")
        self.check_dimensions(p, None, None, "headshot")

        p.mugshot = self.file1
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, None, None, "headshot")
        p.headshot = self.file2
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")

        
        p.mugshot = None
        self.check_dimensions(p, None, None, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")
        p.headshot = None
        self.check_dimensions(p, None, None, "mugshot")
        self.check_dimensions(p, None, None, "headshot")

    def test_field_save_and_delete_methods(self):
        p = self.PersonModel(name="Joe")
        p.mugshot.save("mug", self.file1)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, None, None, "headshot")
        p.headshot.save("head", self.file2)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")

        
        
        p.headshot.delete(save=True)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, None, None, "headshot")
        p.mugshot.delete(save=False)
        self.check_dimensions(p, None, None, "mugshot")
        self.check_dimensions(p, None, None, "headshot")

    def test_dimensions(self):
        
        p = self.PersonModel(name="Joe")

        
        p.mugshot.save("mug", self.file1)
        p.headshot.save("head", self.file2)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")

        
        p = self.PersonModel.objects.get(name="Joe")
        
        
        
        self.assertIs(p.mugshot.was_opened, False)
        self.assertIs(p.headshot.was_opened, False)
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")
        
        
        self.assertIs(p.mugshot.was_opened, True)
        self.assertIs(p.headshot.was_opened, True)
        
        
        p.mugshot.was_opened = False
        p.headshot.was_opened = False
        self.check_dimensions(p, 4, 8, "mugshot")
        self.check_dimensions(p, 8, 4, "headshot")
        self.assertIs(p.mugshot.was_opened, False)
        self.assertIs(p.headshot.was_opened, False)

        
        
        p.mugshot = self.file2
        p.headshot = self.file1
        self.check_dimensions(p, 8, 4, "mugshot")
        self.check_dimensions(p, 4, 8, "headshot")
        
        self.assertIs(p.mugshot.was_opened, True)
        self.assertIs(p.headshot.was_opened, True)