From e8b496cfdc47b0a84c44824a3a04c9222fca764f Mon Sep 17 00:00:00 2001 From: thomas girod Date: Sun, 15 Sep 2024 14:58:37 +0200 Subject: [PATCH] test: Product and ProductType icon resizing --- accounting/models.py | 12 ++++++++ core/fields.py | 2 +- counter/tests/__init__.py | 0 counter/{tests.py => tests/test_counter.py} | 0 counter/tests/test_product.py | 33 +++++++++++++++++++++ 5 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 counter/tests/__init__.py rename counter/{tests.py => tests/test_counter.py} (100%) create mode 100644 counter/tests/test_product.py diff --git a/accounting/models.py b/accounting/models.py index 9276441e..b0c3fab1 100644 --- a/accounting/models.py +++ b/accounting/models.py @@ -43,6 +43,18 @@ class CurrencyField(models.DecimalField): return None +if settings.TESTING: + from model_bakery import baker + + baker.generators.add( + CurrencyField, + lambda: baker.random_gen.gen_decimal(max_digits=8, decimal_places=2), + ) +else: # pragma: no cover + # baker is only used in tests, so we don't need coverage for this part + pass + + # Accounting classes diff --git a/core/fields.py b/core/fields.py index feca650b..de400925 100644 --- a/core/fields.py +++ b/core/fields.py @@ -46,7 +46,7 @@ class ResizedImageFieldFile(ImageFieldFile): extension = formats[new_format] else: raise ValueError(f"Unknown format {new_format}") - return str(Path(self.file.name).with_suffix(f".{extension}")) + return str(Path(self.file.name).with_suffix(extension)) def save(self, name, content, save=True): # noqa FBT002 content.file.seek(0) diff --git a/counter/tests/__init__.py b/counter/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/counter/tests.py b/counter/tests/test_counter.py similarity index 100% rename from counter/tests.py rename to counter/tests/test_counter.py diff --git a/counter/tests/test_product.py b/counter/tests/test_product.py new file mode 100644 index 00000000..d18c6f11 --- /dev/null +++ b/counter/tests/test_product.py @@ -0,0 +1,33 @@ +from io import BytesIO +from uuid import uuid4 + +import pytest +from django.core.files.uploadedfile import SimpleUploadedFile +from model_bakery import baker +from PIL import Image + +from counter.models import Product, ProductType + + +@pytest.mark.django_db +@pytest.mark.parametrize("model", [Product, ProductType]) +def test_resize_product_icon(model): + """Test that the product icon is resized when saved.""" + # Product and ProductType icons have a height of 70px + # so this image should be resized to 50x70 + img = Image.new("RGB", (100, 140)) + content = BytesIO() + img.save(content, format="JPEG") + name = str(uuid4()) + + product = baker.make( + model, + icon=SimpleUploadedFile( + f"{name}.jpg", content.getvalue(), content_type="image/jpeg" + ), + ) + + assert product.icon.width == 50 + assert product.icon.height == 70 + assert product.icon.name == f"products/{name}.webp" + assert Image.open(product.icon).format == "WEBP"