Debian Codegraph @

tests/model_fields/test_imagefield.py

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