diff --git a/docx/oxml/shape.py b/docx/oxml/shape.py index 77ca7db8a..b93c7507e 100644 --- a/docx/oxml/shape.py +++ b/docx/oxml/shape.py @@ -91,7 +91,7 @@ def _inline_xml(cls): return ( '\n' ' \n' - ' \n' + ' \n' ' \n' ' \n' ' \n' diff --git a/docx/shape.py b/docx/shape.py index e4f885d73..82ca2a1db 100644 --- a/docx/shape.py +++ b/docx/shape.py @@ -101,3 +101,14 @@ def width(self): def width(self, cx): self._inline.extent.cx = cx self._inline.graphic.graphicData.pic.spPr.cx = cx + + @property + def alt_text(self): + """ + Read/write. The alt-text associated with this shape. + """ + return self._inline.docPr.attrib["descr"] + + @alt_text.setter + def alt_text(self, text): + self._inline.docPr.attrib["descr"] = text diff --git a/tests/test_files/snippets/inline.txt b/tests/test_files/snippets/inline.txt index 3b0d58148..8553d3be5 100644 --- a/tests/test_files/snippets/inline.txt +++ b/tests/test_files/snippets/inline.txt @@ -1,6 +1,6 @@ - + diff --git a/tests/test_shape.py b/tests/test_shape.py index 105d2fa40..796f3a0d8 100644 --- a/tests/test_shape.py +++ b/tests/test_shape.py @@ -11,6 +11,7 @@ from docx.enum.shape import WD_INLINE_SHAPE from docx.oxml.ns import nsmap from docx.shape import InlineShape, InlineShapes +from docx.oxml.shape import CT_Inline from docx.shared import Length from .oxml.unitdata.dml import ( @@ -99,6 +100,17 @@ def it_can_change_its_display_dimensions(self, dimensions_set_fixture): inline_shape.height = cy assert inline_shape._inline.xml == expected_xml + def it_has_blank_alt_text(self, alt_text_blank_get_fixture): + inline_shape, expected_alt_text = alt_text_blank_get_fixture + alt_text = inline_shape.alt_text + assert alt_text == expected_alt_text + + def it_can_change_its_alt_text(self, alt_text_set_fixture): + inline_shape, expected_alt_text = alt_text_set_fixture + inline_shape.alt_text = "new alt text" + alt_text = inline_shape._inline.docPr.attrib["descr"] + assert alt_text == expected_alt_text + # fixtures ------------------------------------------------------- @pytest.fixture @@ -122,6 +134,22 @@ def dimensions_set_fixture(self): expected_xml = xml(expected_cxml) return inline_shape, new_cx, new_cy, expected_xml + @pytest.fixture + def alt_text_blank_get_fixture(self): + expected_alt_text = "" + image = "tests/test_files/monty-truth.png" + inline_shape = CT_Inline.new_pic_inline(0, "", image, 333, 666) + inline_shape = InlineShape(inline_shape) + return inline_shape, expected_alt_text + + @pytest.fixture + def alt_text_set_fixture(self): + expected_alt_text = "new alt text" + image = "tests/test_files/monty-truth.png" + inline_shape = CT_Inline.new_pic_inline(0, "", image, 333, 666) + inline_shape = InlineShape(inline_shape) + return inline_shape, expected_alt_text + @pytest.fixture(params=[ 'embed pic', 'link pic', 'link+embed pic', 'chart', 'smart art', 'not implemented'