summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2024-02-18 10:59:28 +0000
committerMichael Williamson <mike@zwobble.org>2024-02-18 10:59:28 +0000
commitc210c304a329de3184a04448fa11b31bc5933193 (patch)
tree181e8c080a3d19791c8fbc2a26d1cd20542237a7
parent0204b943b1a4daaf102ec53b59cd491d9dc3984f (diff)
Improve error message when failing to find the body element in a document
-rw-r--r--NEWS2
-rw-r--r--mammoth/docx/document_xml.py8
-rw-r--r--tests/docx/document_xml_tests.py25
3 files changed, 33 insertions, 2 deletions
diff --git a/NEWS b/NEWS
index 84d8902..d627a85 100644
--- a/NEWS
+++ b/NEWS
@@ -2,6 +2,8 @@
* Support attributes in HTML paths in style mappings.
+* Improve error message when failing to find the body element in a document.
+
* Drop support for Python 2.7, Python 3.5 and Python 3.6.
# 1.6.0
diff --git a/mammoth/docx/document_xml.py b/mammoth/docx/document_xml.py
index e0d19a4..45905c6 100644
--- a/mammoth/docx/document_xml.py
+++ b/mammoth/docx/document_xml.py
@@ -6,13 +6,17 @@ def read_document_xml_element(
body_reader,
notes=None,
comments=None):
-
+
if notes is None:
notes = []
if comments is None:
comments = []
-
+
body_element = element.find_child("w:body")
+
+ if body_element is None:
+ raise ValueError("Could not find the body element: are you sure this is a docx file?")
+
return body_reader.read_all(body_element.children) \
.map(lambda children: documents.document(
children,
diff --git a/tests/docx/document_xml_tests.py b/tests/docx/document_xml_tests.py
index a044154..f869749 100644
--- a/tests/docx/document_xml_tests.py
+++ b/tests/docx/document_xml_tests.py
@@ -1,3 +1,5 @@
+import pytest
+
from mammoth import documents
from mammoth.docx.xmlparser import element as xml_element, text as xml_text
from mammoth.docx.document_xml import read_document_xml_element
@@ -5,6 +7,29 @@ from mammoth.docx import body_xml
from ..testing import assert_equal
+def test_when_body_element_is_present_then_body_is_read():
+ paragraph_xml = xml_element("w:p", {}, [])
+ body_xml = xml_element("w:body", {}, [paragraph_xml])
+ document_xml = xml_element("w:document", {}, [body_xml])
+
+ document = _read_and_get_document_xml_element(document_xml)
+
+ assert_equal(
+ documents.document([documents.paragraph([])]),
+ document
+ )
+
+
+def test_when_body_element_is_not_present_then_error_is_raised():
+ paragraph_xml = xml_element("w:p", {}, [])
+ body_xml = xml_element("w:body2", {}, [paragraph_xml])
+ document_xml = xml_element("w:document", {}, [body_xml])
+
+ error = pytest.raises(ValueError, lambda: _read_and_get_document_xml_element(document_xml))
+
+ assert_equal(str(error.value), "Could not find the body element: are you sure this is a docx file?")
+
+
def test_can_read_text_within_document():
element = _document_element_with_text("Hello!")
assert_equal(