Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Fix text wrapping in watermarked images (#2467)

Zack Kridae1318152b9f3
diff --git a/api/api/utils/watermark.py b/api/api/utils/watermark.py
index 6352ca5e5..b111ab0d9 100644
--- a/api/api/utils/watermark.py
+++ b/api/api/utils/watermark.py
@@ -79,7 +79,9 @@ def _fit_in_width(text, font, max_width):
"""
char_length = font.getlength("x") # x has the closest to average width
- max_chars = max_width // char_length
+ max_chars = int(
+ max_width // char_length
+ ) # Must be an integer to be used with `wrap` below
text = "\n".join(["\n".join(wrap(line, max_chars)) for line in text.split("\n")])
diff --git a/api/test/unit/utils/test_watermark.py b/api/test/unit/utils/test_watermark.py
index f9a8c994d..0cb5b7f87 100644
--- a/api/test/unit/utils/test_watermark.py
+++ b/api/test/unit/utils/test_watermark.py
@@ -51,3 +51,18 @@ def test_sends_UA_header(requests):
assert len(requests.requests) > 0
for r in requests.requests:
assert r.headers == HEADERS
+
+
+# Previously, wrapped titles would throw a TypeError:
+# slice indices must be integers or None or have an __index__ method.
+# See: https://github.com/WordPress/openverse/issues/2466
+def test_long_title_wraps_correctly(requests):
+ # Make the title 400 chars long
+ _MOCK_IMAGE_INFO_LONG_TITLE = dict(_MOCK_IMAGE_INFO)
+ _MOCK_IMAGE_INFO_LONG_TITLE["title"] = "a" * 400
+
+ watermark("http://example.com/", _MOCK_IMAGE_INFO_LONG_TITLE)
+
+ assert len(requests.requests) > 0
+ for r in requests.requests:
+ assert r.headers == HEADERS