2
0

test_imagefield.py 16 KB

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