4 from django.conf import settings
5 from sorl.thumbnail.base import Thumbnail
10 from sets import Set as set # For Python 2.3
13 def get_default_settings():
14 from sorl.thumbnail import defaults
16 for key in dir(defaults):
17 if key == key.upper() and key not in ['WVPS', 'CONVERT']:
18 def_settings[key] = getattr(defaults, key)
22 DEFAULT_THUMBNAIL_SETTINGS = get_default_settings()
23 RELATIVE_PIC_NAME = "sorl-thumbnail-test_source.jpg"
24 PIC_NAME = os.path.join(settings.MEDIA_ROOT, RELATIVE_PIC_NAME)
25 THUMB_NAME = os.path.join(settings.MEDIA_ROOT, "sorl-thumbnail-test_%02d.jpg")
31 self.default_settings = DEFAULT_THUMBNAIL_SETTINGS.copy()
33 def change(self, override=None):
34 if override is not None:
35 self.default_settings.update(override)
36 for setting, default in self.default_settings.items():
37 settings_s = 'THUMBNAIL_%s' % setting
38 self_s = 'original_%s' % setting
39 if hasattr(settings, settings_s) and not hasattr(self, self_s):
40 setattr(self, self_s, getattr(settings, settings_s))
41 if hasattr(settings, settings_s) or \
42 default != DEFAULT_THUMBNAIL_SETTINGS[setting]:
43 setattr(settings, settings_s, default)
46 for setting in self.default_settings:
47 settings_s = 'THUMBNAIL_%s' % setting
48 self_s = 'original_%s' % setting
49 if hasattr(self, self_s):
50 setattr(settings, settings_s, getattr(self, self_s))
54 class BaseTest(unittest.TestCase):
56 self.images_to_delete = set()
57 # Create the test image
58 Image.new('RGB', PIC_SIZE).save(PIC_NAME, 'JPEG')
59 self.images_to_delete.add(PIC_NAME)
60 # Change settings so we know they will be constant
61 self.change_settings = ChangeSettings()
62 self.change_settings.change()
64 def verify_thumbnail(self, expected_size, thumbnail=None,
65 expected_filename=None, expected_mode=None):
66 assert thumbnail is not None or expected_filename is not None, \
67 'verify_thumbnail should be passed at least a thumbnail or an' \
70 if thumbnail is not None:
71 # Verify that the templatetag method returned a Thumbnail instance
72 self.assertTrue(isinstance(thumbnail, Thumbnail))
73 thumb_name = thumbnail.dest
75 thumb_name = expected_filename
77 if isinstance(thumb_name, basestring):
78 # Verify that the thumbnail file exists
79 self.assert_(os.path.isfile(thumb_name),
80 'Thumbnail file not found')
82 # Remember to delete the file
83 self.images_to_delete.add(thumb_name)
85 # If we got an expected_filename, check that it is right
86 if expected_filename is not None and thumbnail is not None:
87 self.assertEqual(thumbnail.dest, expected_filename)
89 image = Image.open(thumb_name)
91 # Verify the thumbnail has the expected dimensions
92 self.assertEqual(image.size, expected_size)
94 if expected_mode is not None:
95 self.assertEqual(image.mode, expected_mode)
98 # Remove all the files that have been created
99 for image in self.images_to_delete:
104 # Change settings back to original
105 self.change_settings.revert()