tests.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. Tests for file field behavior, and specifically #639, in which Model.save()
  3. gets called *again* for each FileField. This test will fail if calling a
  4. ModelForm's save() method causes Model.save() to be called more than once.
  5. """
  6. from __future__ import absolute_import
  7. import os
  8. import shutil
  9. from django.core.files.uploadedfile import SimpleUploadedFile
  10. from django.utils import unittest
  11. from .models import Photo, PhotoForm, temp_storage_dir
  12. class Bug639Test(unittest.TestCase):
  13. def testBug639(self):
  14. """
  15. Simulate a file upload and check how many times Model.save() gets
  16. called.
  17. """
  18. # Grab an image for testing.
  19. filename = os.path.join(os.path.dirname(__file__), "test.jpg")
  20. with open(filename, "rb") as fp:
  21. img = fp.read()
  22. # Fake a POST QueryDict and FILES MultiValueDict.
  23. data = {'title': 'Testing'}
  24. files = {"image": SimpleUploadedFile('test.jpg', img, 'image/jpeg')}
  25. form = PhotoForm(data=data, files=files)
  26. p = form.save()
  27. # Check the savecount stored on the object (see the model).
  28. self.assertEqual(p._savecount, 1)
  29. def tearDown(self):
  30. """
  31. Make sure to delete the "uploaded" file to avoid clogging /tmp.
  32. """
  33. p = Photo.objects.get()
  34. p.image.delete(save=False)
  35. shutil.rmtree(temp_storage_dir)