Completed
Pull Request — master (#102)
by
unknown
01:31
created

TestModel.test_progressive_jpeg_from_gif()   A

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 13
loc 13
rs 9.4285
cc 3
1
# coding: utf-8
2
from __future__ import absolute_import, unicode_literals
3
4
import filecmp
5
import os
6
import shutil
7
import uuid
8
9
10
class UUID4Monkey(object):
11
    hex = '653d1c6863404b9689b75fa930c9d0a0'
12
13
14
uuid.__dict__['uuid4'] = lambda: UUID4Monkey()
15
16
import django  # NoQA
17
from django.conf import settings  # NoQA
18
from django.core.files import File  # NoQA
19
from django.test import TestCase  # NoQA
20
from django.contrib.auth.models import User  # NoQA
21
22
from .models import (
23
    SimpleModel, ResizeModel, AdminDeleteModel,
24
    ThumbnailModel, ResizeCropModel, AutoSlugClassNameDirModel,
25
    UUIDModel,
26
    UtilVariationsModel,
27
    ThumbnailWithoutDirectoryModel,
28
    CustomRenderVariationsModel, ProgressiveJpegModel)  # NoQA
29
30
IMG_DIR = os.path.join(settings.MEDIA_ROOT, 'img')
31
32
FIXTURE_DIR = os.path.join(
33
    os.path.dirname(os.path.abspath(__file__)),
34
    'fixtures'
35
)
36
37
38
class TestStdImage(TestCase):
39
    def setUp(self):
40
        User.objects.create_superuser('admin', '[email protected]', 'admin')
41
        self.client.login(username='admin', password='admin')
42
43
        self.fixtures = {}
44
        fixture_paths = os.listdir(FIXTURE_DIR)
45
        for fixture_filename in fixture_paths:
46
            fixture_path = os.path.join(FIXTURE_DIR, fixture_filename)
47
            if os.path.isfile(fixture_path):
48
                f = open(fixture_path, 'rb')
49
                self.fixtures[fixture_filename] = File(f)
50
51
    def tearDown(self):
52
        """Close all open fixtures and delete everything from media"""
53
        for fixture in list(self.fixtures.values()):
54
            fixture.close()
55
56
        for root, dirs, files in os.walk(settings.MEDIA_ROOT, topdown=False):
57
            for name in files:
58
                os.remove(os.path.join(root, name))
59
            for name in dirs:
60
                os.rmdir(os.path.join(root, name))
61
62
63
class TestModel(TestStdImage):
64
    """Tests StdImage ModelField"""
65
66
    def test_simple(self):
67
        """Tests if Field behaves just like Django's ImageField."""
68
        instance = SimpleModel.objects.create(image=self.fixtures['100.gif'])
69
        target_file = os.path.join(IMG_DIR, '100.gif')
70
        source_file = os.path.join(FIXTURE_DIR, '100.gif')
71
72
        self.assertEqual(SimpleModel.objects.count(), 1)
73
        self.assertEqual(SimpleModel.objects.get(pk=1), instance)
74
75
        self.assertTrue(os.path.exists(target_file))
76
77
        self.assertTrue(filecmp.cmp(source_file, target_file))
78
79
    def test_variations(self):
80
        """Adds image and checks filesystem as well as width and height."""
81
        instance = ResizeModel.objects.create(
82
            image=self.fixtures['600x400.jpg']
83
        )
84
85
        source_file = os.path.join(FIXTURE_DIR, '600x400.jpg')
86
87
        self.assertTrue(os.path.exists(os.path.join(IMG_DIR, 'image.jpg')))
88
        self.assertEqual(instance.image.width, 600)
89
        self.assertEqual(instance.image.height, 400)
90
        path = os.path.join(IMG_DIR, 'image.jpg')
91
        assert filecmp.cmp(source_file, path)
92
93
        path = os.path.join(IMG_DIR, 'image.medium.jpg')
94
        assert os.path.exists(path)
95
        self.assertEqual(instance.image.medium.width, 400)
96
        self.assertLessEqual(instance.image.medium.height, 400)
97
        self.assertFalse(filecmp.cmp(
98
            source_file,
99
            os.path.join(IMG_DIR, 'image.medium.jpg')))
100
101
        self.assertTrue(os.path.exists(
102
            os.path.join(IMG_DIR, 'image.thumbnail.jpg'))
103
        )
104
        self.assertEqual(instance.image.thumbnail.width, 100)
105
        self.assertLessEqual(instance.image.thumbnail.height, 75)
106
        self.assertFalse(filecmp.cmp(
107
            source_file,
108
            os.path.join(IMG_DIR, 'image.thumbnail.jpg'))
109
        )
110
111
    def test_cropping(self):
112
        instance = ResizeCropModel.objects.create(
113
            image=self.fixtures['600x400.jpg']
114
        )
115
        self.assertEqual(instance.image.thumbnail.width, 150)
116
        self.assertEqual(instance.image.thumbnail.height, 150)
117
118 View Code Duplication
    def test_variations_override(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
119
        source_file = os.path.join(FIXTURE_DIR, '600x400.jpg')
120
        target_file = os.path.join(IMG_DIR, 'image.thumbnail.jpg')
121
        os.mkdir(IMG_DIR)
122
        shutil.copyfile(source_file, target_file)
123
        ResizeModel.objects.create(
124
            image=self.fixtures['600x400.jpg']
125
        )
126
        thumbnail_path = os.path.join(IMG_DIR, 'image.thumbnail.jpg')
127
        assert os.path.exists(thumbnail_path)
128
        thumbnail_path = os.path.join(IMG_DIR, 'image.thumbnail_1.jpg')
129
        assert not os.path.exists(thumbnail_path)
130
131
    def test_delete_thumbnail(self):
132
        """Delete an image with thumbnail"""
133
        obj = ThumbnailModel.objects.create(
134
            image=self.fixtures['100.gif']
135
        )
136
        obj.image.delete()
137
        path = os.path.join(IMG_DIR, 'image.gif')
138
        assert not os.path.exists(path)
139
140
        path = os.path.join(IMG_DIR, 'image.thumbnail.gif')
141
        assert not os.path.exists(path)
142
143
    def test_force_min_size(self):
144
        self.client.post('/admin/tests/forceminsizemodel/add/', {
145
            'image': self.fixtures['100.gif'],
146
        })
147
        path = os.path.join(IMG_DIR, 'image.gif')
148
        assert not os.path.exists(path)
149
150
    def test_progressive_jpeg_from_jpeg(self):
151
        source_file = os.path.join(FIXTURE_DIR, '600x400.jpg')
152
        target_file = os.path.join(IMG_DIR, 'image.progressive.jpg')
153
        os.mkdir(IMG_DIR)
154
        shutil.copyfile(source_file, target_file)
155
        ProgressiveJpegModel.objects.create(
156
            image=self.fixtures['600x400.jpg']
157
        )
158
        thumbnail_path = os.path.join(IMG_DIR, 'image.progressive.jpg')
159
        assert os.path.exists(thumbnail_path)
160
161 View Code Duplication
    def test_progressive_jpeg_from_png(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
162
        source_file = os.path.join(FIXTURE_DIR, '600x400.png')
163
        target_file = os.path.join(IMG_DIR, 'image.progressive.jpg')
164
        os.mkdir(IMG_DIR)
165
        shutil.copyfile(source_file, target_file)
166
        ProgressiveJpegModel.objects.create(
167
            image=self.fixtures['600x400.png']
168
        )
169
        thumbnail_path = os.path.join(IMG_DIR, 'image.progressive.jpg')
170
        assert os.path.exists(thumbnail_path)
171
172
        thumbnail_path = os.path.join(IMG_DIR, 'image.progressive.png')
173
        assert not os.path.exists(thumbnail_path)
174
175 View Code Duplication
    def test_progressive_jpeg_from_gif(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
176
        source_file = os.path.join(FIXTURE_DIR, '600x400.gif')
177
        target_file = os.path.join(IMG_DIR, 'image.progressive.jpg')
178
        os.mkdir(IMG_DIR)
179
        shutil.copyfile(source_file, target_file)
180
        ProgressiveJpegModel.objects.create(
181
            image=self.fixtures['600x400.gif']
182
        )
183
        thumbnail_path = os.path.join(IMG_DIR, 'image.progressive.jpg')
184
        assert os.path.exists(thumbnail_path)
185
186
        thumbnail_path = os.path.join(IMG_DIR, 'image.progressive.gif')
187
        assert not os.path.exists(thumbnail_path)
188
189
    def test_thumbnail_save_without_directory(self):
190
        obj = ThumbnailWithoutDirectoryModel.objects.create(
191
            image=self.fixtures['100.gif']
192
        )
193
        obj.save()
194
        # Our model saves the images directly into the MEDIA_ROOT directory
195
        # not IMG_DIR, under a custom name
196
        original = os.path.join(settings.MEDIA_ROOT, 'custom.gif')
197
        thumbnail = os.path.join(settings.MEDIA_ROOT, 'custom.thumbnail.gif')
198
        assert os.path.exists(original)
199
        assert os.path.exists(thumbnail)
200
201
    def test_custom_render_variations(self):
202
        instance = CustomRenderVariationsModel.objects.create(
203
            image=self.fixtures['600x400.jpg']
204
        )
205
        # Image size must be 100x100 despite variations settings
206
        assert instance.image.thumbnail.width == 100
207
        assert instance.image.thumbnail.height == 100
208
209
210
class TestUtils(TestStdImage):
211
    """Tests Utils"""
212
213
    def test_deletion_singnal_receiver(self):
214
        obj = SimpleModel.objects.create(
215
            image=self.fixtures['100.gif']
216
        )
217
        obj.delete()
218
        self.assertFalse(
219
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
220
        )
221
222
    def test_pre_save_delete_callback_clear(self):
223
        AdminDeleteModel.objects.create(
224
            image=self.fixtures['100.gif']
225
        )
226
        if django.VERSION >= (1, 9):
227
            self.client.post('/admin/tests/admindeletemodel/1/change/', {
228
                'image-clear': 'checked',
229
            })
230
        else:
231
            self.client.post('/admin/tests/admindeletemodel/1/', {
232
                'image-clear': 'checked',
233
            })
234
        self.assertFalse(
235
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
236
        )
237
238
    def test_pre_save_delete_callback_new(self):
239
        AdminDeleteModel.objects.create(
240
            image=self.fixtures['100.gif']
241
        )
242
        if django.VERSION >= (1, 9):
243
            self.client.post('/admin/tests/admindeletemodel/1/change/', {
244
                'image': self.fixtures['600x400.jpg'],
245
            })
246
        else:
247
            self.client.post('/admin/tests/admindeletemodel/1/', {
248
                'image': self.fixtures['600x400.jpg'],
249
            })
250
        self.assertFalse(
251
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
252
        )
253
254
    def test_upload_to_auto_slug_class_name_dir(self):
255
        AutoSlugClassNameDirModel.objects.create(
256
            name='foo bar',
257
            image=self.fixtures['100.gif']
258
        )
259
        file_path = os.path.join(
260
            settings.MEDIA_ROOT,
261
            'autoslugclassnamedirmodel',
262
            'foo-bar.gif'
263
        )
264
        self.assertTrue(os.path.exists(file_path))
265
266
    def test_upload_to_uuid(self):
267
        UUIDModel.objects.create(image=self.fixtures['100.gif'])
268
        file_path = os.path.join(
269
            IMG_DIR,
270
            '653d1c6863404b9689b75fa930c9d0a0.gif'
271
        )
272
        self.assertTrue(os.path.exists(file_path))
273
274
    def test_render_variations_callback(self):
275
        UtilVariationsModel.objects.create(image=self.fixtures['100.gif'])
276
        file_path = os.path.join(
277
            IMG_DIR,
278
            'image.thumbnail.gif'
279
        )
280
        self.assertTrue(os.path.exists(file_path))
281
282
283
class TestValidators(TestStdImage):
284
    def test_max_size_validator(self):
285
        self.client.post('/admin/tests/maxsizemodel/add/', {
286
            'image': self.fixtures['600x400.jpg'],
287
        })
288
        self.assertFalse(os.path.exists(os.path.join(IMG_DIR, 'image.jpg')))
289
290
    def test_min_size_validator(self):
291
        self.client.post('/admin/tests/minsizemodel/add/', {
292
            'image': self.fixtures['100.gif'],
293
        })
294
        self.assertFalse(os.path.exists(os.path.join(IMG_DIR, 'image.gif')))
295