Skip to content

Commit 0930403

Browse files
committed
Fix UnboundLocalError: cannot access local variable 'url'
1 parent 4c2636d commit 0930403

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

pictures/templatetags/pictures.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import warnings
2+
13
from django import template
24
from django.template import loader
35

@@ -68,6 +70,12 @@ def img_url(field_file, file_type, width, ratio=None) -> str:
6870
raise ValueError(
6971
f"Invalid file type: {file_type}. Choices are: {', '.join(file_types.keys())}"
7072
) from e
73+
url = field_file.url
74+
if not sizes.items():
75+
warnings.warn(
76+
"Image is smaller than requested size, using source file URL.",
77+
stacklevel=2,
78+
)
7179
for w, img in sorted(sizes.items()):
7280
url = img.url
7381
if w >= int(width):

tests/conftest.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ def image_upload_file():
1717
return SimpleUploadedFile("image.png", output.getvalue())
1818

1919

20+
@pytest.fixture
21+
def tiny_image_upload_file():
22+
img = Image.new("RGBA", (1, 1), (255, 55, 255, 1))
23+
24+
with io.BytesIO() as output:
25+
img.save(output, format="PNG")
26+
return SimpleUploadedFile("image.png", output.getvalue())
27+
28+
2029
@pytest.fixture(autouse=True, scope="function")
2130
def media_root(settings, tmpdir_factory):
2231
settings.MEDIA_ROOT = tmpdir_factory.mktemp("media", numbered=True)

tests/test_templatetags.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,18 @@ def test_img_url__raise_wrong_file_type(image_upload_file):
111111
with pytest.raises(ValueError) as e:
112112
img_url(profile.picture, ratio="3/2", file_type="gif", width=800)
113113
assert "Invalid file type: gif. Choices are: WEBP" in str(e.value)
114+
115+
116+
@pytest.mark.django_db
117+
def test_img_url__too_small(tiny_image_upload_file, caplog):
118+
profile = Profile.objects.create(name="Spiderman", picture=tiny_image_upload_file)
119+
with pytest.warns() as record:
120+
assert (
121+
img_url(profile.picture, ratio="3/2", file_type="webp", width="800")
122+
== "/media/testapp/profile/image.png"
123+
)
124+
assert len(record) == 1
125+
assert (
126+
"Image is smaller than requested size, using source file URL."
127+
in record[0].message.args[0]
128+
)

0 commit comments

Comments
 (0)