Skip to content

Commit

Permalink
Fix UnboundLocalError: cannot access local variable 'url'
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe committed Jul 2, 2024
1 parent 4c2636d commit 0930403
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pictures/templatetags/pictures.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import warnings

from django import template
from django.template import loader

Expand Down Expand Up @@ -68,6 +70,12 @@ def img_url(field_file, file_type, width, ratio=None) -> str:
raise ValueError(
f"Invalid file type: {file_type}. Choices are: {', '.join(file_types.keys())}"
) from e
url = field_file.url
if not sizes.items():
warnings.warn(
"Image is smaller than requested size, using source file URL.",
stacklevel=2,
)
for w, img in sorted(sizes.items()):
url = img.url
if w >= int(width):
Expand Down
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ def image_upload_file():
return SimpleUploadedFile("image.png", output.getvalue())


@pytest.fixture
def tiny_image_upload_file():
img = Image.new("RGBA", (1, 1), (255, 55, 255, 1))

with io.BytesIO() as output:
img.save(output, format="PNG")
return SimpleUploadedFile("image.png", output.getvalue())


@pytest.fixture(autouse=True, scope="function")
def media_root(settings, tmpdir_factory):
settings.MEDIA_ROOT = tmpdir_factory.mktemp("media", numbered=True)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_templatetags.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,18 @@ def test_img_url__raise_wrong_file_type(image_upload_file):
with pytest.raises(ValueError) as e:
img_url(profile.picture, ratio="3/2", file_type="gif", width=800)
assert "Invalid file type: gif. Choices are: WEBP" in str(e.value)


@pytest.mark.django_db
def test_img_url__too_small(tiny_image_upload_file, caplog):
profile = Profile.objects.create(name="Spiderman", picture=tiny_image_upload_file)
with pytest.warns() as record:
assert (
img_url(profile.picture, ratio="3/2", file_type="webp", width="800")
== "/media/testapp/profile/image.png"
)
assert len(record) == 1
assert (
"Image is smaller than requested size, using source file URL."
in record[0].message.args[0]
)

0 comments on commit 0930403

Please sign in to comment.