test_imagefield.py 16 KB

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