test_imagefield.py 16 KB

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