Completed
Pull Request — master (#81)
by
unknown
01:17
created

TestModel.test_thumbnail_save_without_directory()   A

Complexity

Conditions 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
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)  # NoQA
28
29
IMG_DIR = os.path.join(settings.MEDIA_ROOT, 'img')
30
31
FIXTURE_DIR = os.path.join(
32
    os.path.dirname(os.path.abspath(__file__)),
33
    'fixtures'
34
)
35
36
37
class TestStdImage(TestCase):
38
    def setUp(self):
39
        User.objects.create_superuser('admin', '[email protected]', 'admin')
40
        self.client.login(username='admin', password='admin')
41
42
        self.fixtures = {}
43
        fixture_paths = os.listdir(FIXTURE_DIR)
44
        for fixture_filename in fixture_paths:
45
            fixture_path = os.path.join(FIXTURE_DIR, fixture_filename)
46
            if os.path.isfile(fixture_path):
47
                f = open(fixture_path, 'rb')
48
                self.fixtures[fixture_filename] = File(f)
49
50
    def tearDown(self):
51
        """Close all open fixtures and delete everything from media"""
52
        for fixture in list(self.fixtures.values()):
53
            fixture.close()
54
55
        for root, dirs, files in os.walk(settings.MEDIA_ROOT, topdown=False):
56
            for name in files:
57
                os.remove(os.path.join(root, name))
58
            for name in dirs:
59
                os.rmdir(os.path.join(root, name))
60
61
62
class TestModel(TestStdImage):
63
    """Tests StdImage ModelField"""
64
65
    def test_simple(self):
66
        """Tests if Field behaves just like Django's ImageField."""
67
        instance = SimpleModel.objects.create(image=self.fixtures['100.gif'])
68
        target_file = os.path.join(IMG_DIR, '100.gif')
69
        source_file = os.path.join(FIXTURE_DIR, '100.gif')
70
71
        self.assertEqual(SimpleModel.objects.count(), 1)
72
        self.assertEqual(SimpleModel.objects.get(pk=1), instance)
73
74
        self.assertTrue(os.path.exists(target_file))
75
76
        self.assertTrue(filecmp.cmp(source_file, target_file))
77
78
    def test_variations(self):
79
        """Adds image and checks filesystem as well as width and height."""
80
        instance = ResizeModel.objects.create(
81
            image=self.fixtures['600x400.jpg']
82
        )
83
84
        source_file = os.path.join(FIXTURE_DIR, '600x400.jpg')
85
86
        self.assertTrue(os.path.exists(os.path.join(IMG_DIR, 'image.jpg')))
87
        self.assertEqual(instance.image.width, 600)
88
        self.assertEqual(instance.image.height, 400)
89
        path = os.path.join(IMG_DIR, 'image.jpg')
90
        assert filecmp.cmp(source_file, path)
91
92
        path = os.path.join(IMG_DIR, 'image.medium.jpg')
93
        assert os.path.exists(path)
94
        self.assertEqual(instance.image.medium.width, 400)
95
        self.assertLessEqual(instance.image.medium.height, 400)
96
        self.assertFalse(filecmp.cmp(
97
            source_file,
98
            os.path.join(IMG_DIR, 'image.medium.jpg')))
99
100
        self.assertTrue(os.path.exists(
101
            os.path.join(IMG_DIR, 'image.thumbnail.jpg'))
102
        )
103
        self.assertEqual(instance.image.thumbnail.width, 100)
104
        self.assertLessEqual(instance.image.thumbnail.height, 75)
105
        self.assertFalse(filecmp.cmp(
106
            source_file,
107
            os.path.join(IMG_DIR, 'image.thumbnail.jpg'))
108
        )
109
110
    def test_cropping(self):
111
        instance = ResizeCropModel.objects.create(
112
            image=self.fixtures['600x400.jpg']
113
        )
114
        self.assertEqual(instance.image.thumbnail.width, 150)
115
        self.assertEqual(instance.image.thumbnail.height, 150)
116
117
    def test_variations_override(self):
118
        source_file = os.path.join(FIXTURE_DIR, '600x400.jpg')
119
        target_file = os.path.join(IMG_DIR, 'image.thumbnail.jpg')
120
        os.mkdir(IMG_DIR)
121
        shutil.copyfile(source_file, target_file)
122
        ResizeModel.objects.create(
123
            image=self.fixtures['600x400.jpg']
124
        )
125
        thumbnail_path = os.path.join(IMG_DIR, 'image.thumbnail.jpg')
126
        assert os.path.exists(thumbnail_path)
127
        thumbnail_path = os.path.join(IMG_DIR, 'image.thumbnail_1.jpg')
128
        assert not os.path.exists(thumbnail_path)
129
130
    def test_delete_thumbnail(self):
131
        """Delete an image with thumbnail"""
132
        obj = ThumbnailModel.objects.create(
133
            image=self.fixtures['100.gif']
134
        )
135
        obj.image.delete()
136
        path = os.path.join(IMG_DIR, 'image.gif')
137
        assert not os.path.exists(path)
138
139
        path = os.path.join(IMG_DIR, 'image.thumbnail.gif')
140
        assert not os.path.exists(path)
141
142
    def test_fore_min_size(self):
143
        self.client.post('/admin/tests/forceminsizemodel/add/', {
144
            'image': self.fixtures['100.gif'],
145
        })
146
        path = os.path.join(IMG_DIR, 'image.gif')
147
        assert not os.path.exists(path)
148
149
    def test_thumbnail_save_without_directory(self):
150
        obj = ThumbnailWithoutDirectoryModel.objects.create(
151
            image=self.fixtures['100.gif']
152
        )
153
        obj.save()
154
        # Our model saves the images directly into the MEDIA_ROOT directory
155
        # not IMG_DIR, under a custom name
156
        original = os.path.join(settings.MEDIA_ROOT, 'custom.gif')
157
        thumbnail = os.path.join(settings.MEDIA_ROOT, 'custom.thumbnail.gif')
158
        assert os.path.exists(original)
159
        assert os.path.exists(thumbnail)
160
161
162
class TestUtils(TestStdImage):
163
    """Tests Utils"""
164
165
    def test_deletion_singnal_receiver(self):
166
        obj = SimpleModel.objects.create(
167
            image=self.fixtures['100.gif']
168
        )
169
        obj.delete()
170
        self.assertFalse(
171
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
172
        )
173
174
    def test_pre_save_delete_callback_clear(self):
175
        AdminDeleteModel.objects.create(
176
            image=self.fixtures['100.gif']
177
        )
178
        if django.VERSION >= (1, 9):
179
            self.client.post('/admin/tests/admindeletemodel/1/change/', {
180
                'image-clear': 'checked',
181
            })
182
        else:
183
            self.client.post('/admin/tests/admindeletemodel/1/', {
184
                'image-clear': 'checked',
185
            })
186
        self.assertFalse(
187
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
188
        )
189
190
    def test_pre_save_delete_callback_new(self):
191
        AdminDeleteModel.objects.create(
192
            image=self.fixtures['100.gif']
193
        )
194
        if django.VERSION >= (1, 9):
195
            self.client.post('/admin/tests/admindeletemodel/1/change/', {
196
                'image': self.fixtures['600x400.jpg'],
197
            })
198
        else:
199
            self.client.post('/admin/tests/admindeletemodel/1/', {
200
                'image': self.fixtures['600x400.jpg'],
201
            })
202
        self.assertFalse(
203
            os.path.exists(os.path.join(IMG_DIR, 'image.gif'))
204
        )
205
206
    def test_upload_to_auto_slug_class_name_dir(self):
207
        AutoSlugClassNameDirModel.objects.create(
208
            name='foo bar',
209
            image=self.fixtures['100.gif']
210
        )
211
        file_path = os.path.join(
212
            settings.MEDIA_ROOT,
213
            'autoslugclassnamedirmodel',
214
            'foo-bar.gif'
215
        )
216
        self.assertTrue(os.path.exists(file_path))
217
218
    def test_upload_to_uuid(self):
219
        UUIDModel.objects.create(image=self.fixtures['100.gif'])
220
        file_path = os.path.join(
221
            IMG_DIR,
222
            '653d1c6863404b9689b75fa930c9d0a0.gif'
223
        )
224
        self.assertTrue(os.path.exists(file_path))
225
226
    def test_render_variations_callback(self):
227
        UtilVariationsModel.objects.create(image=self.fixtures['100.gif'])
228
        file_path = os.path.join(
229
            IMG_DIR,
230
            'image.thumbnail.gif'
231
        )
232
        self.assertTrue(os.path.exists(file_path))
233
234
235
class TestValidators(TestStdImage):
236
    def test_max_size_validator(self):
237
        self.client.post('/admin/tests/maxsizemodel/add/', {
238
            'image': self.fixtures['600x400.jpg'],
239
        })
240
        self.assertFalse(os.path.exists(os.path.join(IMG_DIR, 'image.jpg')))
241
242
    def test_min_size_validator(self):
243
        self.client.post('/admin/tests/minsizemodel/add/', {
244
            'image': self.fixtures['100.gif'],
245
        })
246
        self.assertFalse(os.path.exists(os.path.join(IMG_DIR, 'image.gif')))
247