Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/docx/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ def _gather_image_parts(self):
continue
if rel.target_part in self.image_parts:
continue
# an image that could not be parsed when the package was loaded
# (e.g. one having broken EXIF data) is represented by a plain
# |Part| and has no `.sha1` member; skip it here rather than fail
# with AttributeError on the next `add_picture()` call
if not isinstance(rel.target_part, ImagePart):
continue
self.image_parts.append(cast("ImagePart", rel.target_part))


Expand Down
27 changes: 27 additions & 0 deletions tests/test_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,33 @@ def it_gathers_package_image_parts_after_unmarshalling(self):
assert len(image_parts) == 3
assert all(isinstance(p, ImagePart) for p in image_parts)

def but_it_skips_image_rels_whose_target_part_is_not_an_ImagePart(self):
"""Broken or otherwise unparsed images load as plain Part objects.

Such parts must not be added to the image-part collection, or a later
`add_picture()` call fails with "'Part' object has no attribute 'sha1'".
"""
from docx.opc.constants import RELATIONSHIP_TYPE as RT
from docx.opc.part import Part
from docx.opc.packuri import PackURI

package = Package()
plain_part = Part(PackURI("/word/media/image1.wmf"), "image/x-wmf", b"\x01", package)

class _Rel:
is_external = False
reltype = RT.IMAGE
target_part = plain_part

original_iter_rels = package.iter_rels
package.iter_rels = lambda: iter([_Rel()]) # type: ignore[method-assign]
try:
package._gather_image_parts()
finally:
package.iter_rels = original_iter_rels # type: ignore[method-assign]

assert len(package.image_parts) == 0

# fixture components ---------------------------------------------

@pytest.fixture
Expand Down