summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2022-08-31 21:33:29 +0100
committerMichael Williamson <mike@zwobble.org>2022-08-31 21:33:29 +0100
commit2736ab6dbfa95c4a6d99837b715ecccb23c84215 (patch)
treed32a35f1a940fac2a81a4457373ab936359b0208
parent8b354c6b086259fe023a6ec333ae99f59f01684d (diff)
Only use the alt text of image elements as a fallback
-rw-r--r--NEWS6
-rw-r--r--mammoth/images.py9
-rw-r--r--tests/images_tests.py19
3 files changed, 30 insertions, 4 deletions
diff --git a/NEWS b/NEWS
index a30c011..10d5334 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,9 @@
+# 1.5.0
+
+* Only use the alt text of image elements as a fallback. If an alt attribute is
+ returned from the function passed to mammoth.images.img_element, that value
+ will now be preferred to the alt text of the image element.
+
# 1.4.19
* Ignore w:u elements when w:val is missing.
diff --git a/mammoth/images.py b/mammoth/images.py
index 9dba353..21b9288 100644
--- a/mammoth/images.py
+++ b/mammoth/images.py
@@ -5,12 +5,13 @@ from . import html
def img_element(func):
def convert_image(image):
- attributes = func(image).copy()
+ attributes = {}
if image.alt_text:
attributes["alt"] = image.alt_text
-
+ attributes.update(func(image))
+
return [html.element("img", attributes)]
-
+
return convert_image
# Undocumented, but retained for backwards-compatibility with 0.3.x
@@ -21,7 +22,7 @@ inline = img_element
def data_uri(image):
with image.open() as image_bytes:
encoded_src = base64.b64encode(image_bytes.read()).decode("ascii")
-
+
return {
"src": "data:{0};base64,{1}".format(image.content_type, encoded_src)
}
diff --git a/tests/images_tests.py b/tests/images_tests.py
index 49784d3..0ab29e1 100644
--- a/tests/images_tests.py
+++ b/tests/images_tests.py
@@ -66,3 +66,22 @@ class ImgElementTests:
assert_that(result, is_sequence(
has_attrs(attributes={"alt": "<alt>", "src": "<src>"}),
))
+
+ @istest
+ def test_image_alt_text_can_be_overridden_by_alt_attribute_returned_from_function(self):
+ image_bytes = b"abc"
+ image = mammoth.documents.Image(
+ alt_text="<alt>",
+ content_type="image/jpeg",
+ open=lambda: io.BytesIO(image_bytes),
+ )
+
+ @mammoth.images.img_element
+ def convert_image(image):
+ return {"alt": "<alt override>", "src": "<src>"}
+
+ result = convert_image(image)
+
+ assert_that(result, is_sequence(
+ has_attrs(attributes={"alt": "<alt override>", "src": "<src>"}),
+ ))