PageRenderTime 77ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/model_fields/imagefield.py

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