aboutsummaryrefslogtreecommitdiff
path: root/tests/docx/document_xml_tests.py
blob: f86974990cc738e73ccc0792fc0acda076e38de9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
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(
        documents.document([documents.paragraph([documents.run([documents.Text("Hello!")])])]),
        _read_and_get_document_xml_element(element)
    )


def test_footnotes_of_document_are_read():
    notes = [documents.note("footnote", "4", [documents.paragraph([])])]

    body_xml = xml_element("w:body")
    document_xml = xml_element("w:document", {}, [body_xml])

    document = _read_and_get_document_xml_element(document_xml, notes=notes)
    footnote = document.notes.find_note("footnote", "4")
    assert_equal("4", footnote.note_id)
    assert isinstance(footnote.body[0], documents.Paragraph)


def _read_and_get_document_xml_element(*args, **kwargs):
    body_reader = body_xml.reader()
    result = read_document_xml_element(*args, body_reader=body_reader, **kwargs)
    assert_equal([], result.messages)
    return result.value


def _document_element_with_text(text):
    return xml_element("w:document", {}, [
        xml_element("w:body", {}, [_paragraph_element_with_text(text)])
    ])

def _paragraph_element_with_text(text):
    return xml_element("w:p", {}, [_run_element_with_text(text)])

def _run_element_with_text(text):
    return xml_element("w:r", {}, [_text_element(text)])


def _text_element(value):
    return xml_element("w:t", {}, [xml_text(value)])