From 4c7194a88fc970cb0d910f444a2de29911d4a630 Mon Sep 17 00:00:00 2001 From: jeromelebleu Date: Tue, 14 Apr 2020 08:28:58 +0200 Subject: [PATCH] Set file stream curstor to zero position after running validators (#218) The `BaseSizeValidator` read the file stream to create an in memory Pillow Image object. In reading the file, the file streams cursor was set to the end. Therefore, the validator left the file in a different state than receiving it. This patch sets the cursor back to zero after reading the file. --- stdimage/validators.py | 5 +++-- tests/test_models.py | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/stdimage/validators.py b/stdimage/validators.py index f0abd7d..b609c55 100644 --- a/stdimage/validators.py +++ b/stdimage/validators.py @@ -28,8 +28,9 @@ def __call__(self, value): def clean(value): value.seek(0) stream = BytesIO(value.read()) - img = Image.open(stream) - return img.size + size = Image.open(stream).size + value.seek(0) + return size class MaxSizeValidator(BaseSizeValidator): diff --git a/tests/test_models.py b/tests/test_models.py index 021c912..f681e7a 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -227,15 +227,17 @@ def test_render_variations_overwrite(self, db, image_upload_file): class TestValidators(TestStdImage): def test_max_size_validator(self, admin_client): - admin_client.post('/admin/tests/maxsizemodel/add/', { + response = admin_client.post('/admin/tests/maxsizemodel/add/', { 'image': self.fixtures['600x400.jpg'], }) + assert 'too large' in response.context['adminform'].form.errors['image'][0] assert not os.path.exists(os.path.join(IMG_DIR, '800x600.jpg')) def test_min_size_validator(self, admin_client): - admin_client.post('/admin/tests/minsizemodel/add/', { + response = admin_client.post('/admin/tests/minsizemodel/add/', { 'image': self.fixtures['100.gif'], }) + assert 'too small' in response.context['adminform'].form.errors['image'][0] assert not os.path.exists(os.path.join(IMG_DIR, '100.gif'))