File: test_document.py

package info (click to toggle)
python-docx 1.2.0%2Bdfsg-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 7,216 kB
  • sloc: xml: 25,323; python: 23,414; makefile: 175
file content (423 lines) | stat: -rw-r--r-- 14,353 bytes parent folder | download
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# pyright: reportPrivateUsage=false
# pyright: reportUnknownMemberType=false

"""Unit test suite for the docx.document module."""

from __future__ import annotations

from typing import cast

import pytest

from docx.comments import Comment, Comments
from docx.document import Document, _Body
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_BREAK
from docx.opc.coreprops import CoreProperties
from docx.oxml.document import CT_Body, CT_Document
from docx.parts.document import DocumentPart
from docx.section import Section, Sections
from docx.settings import Settings
from docx.shape import InlineShape, InlineShapes
from docx.shared import Length
from docx.styles.styles import Styles
from docx.table import Table
from docx.text.paragraph import Paragraph
from docx.text.run import Run

from .unitutil.cxml import element, xml
from .unitutil.mock import (
    FixtureRequest,
    Mock,
    class_mock,
    instance_mock,
    method_mock,
    property_mock,
)


class DescribeDocument:
    """Unit-test suite for `docx.document.Document`."""

    def it_can_add_a_comment(
        self,
        document_part_: Mock,
        comments_prop_: Mock,
        comments_: Mock,
        comment_: Mock,
        run_mark_comment_range_: Mock,
    ):
        comment_.comment_id = 42
        comments_.add_comment.return_value = comment_
        comments_prop_.return_value = comments_
        document = Document(cast(CT_Document, element("w:document/w:body/w:p/w:r")), document_part_)
        run = document.paragraphs[0].runs[0]

        comment = document.add_comment(run, "Comment text.")

        comments_.add_comment.assert_called_once_with("Comment text.", "", "")
        run_mark_comment_range_.assert_called_once_with(run, run, 42)
        assert comment is comment_

    @pytest.mark.parametrize(
        ("level", "style"), [(0, "Title"), (1, "Heading 1"), (2, "Heading 2"), (9, "Heading 9")]
    )
    def it_can_add_a_heading(
        self, level: int, style: str, document: Document, add_paragraph_: Mock, paragraph_: Mock
    ):
        add_paragraph_.return_value = paragraph_

        paragraph = document.add_heading("Spam vs. Bacon", level)

        add_paragraph_.assert_called_once_with(document, "Spam vs. Bacon", style)
        assert paragraph is paragraph_

    def it_raises_on_heading_level_out_of_range(self, document: Document):
        with pytest.raises(ValueError, match="level must be in range 0-9, got -1"):
            document.add_heading(level=-1)
        with pytest.raises(ValueError, match="level must be in range 0-9, got 10"):
            document.add_heading(level=10)

    def it_can_add_a_page_break(
        self, document: Document, add_paragraph_: Mock, paragraph_: Mock, run_: Mock
    ):
        add_paragraph_.return_value = paragraph_
        paragraph_.add_run.return_value = run_

        paragraph = document.add_page_break()

        add_paragraph_.assert_called_once_with(document)
        paragraph_.add_run.assert_called_once_with()
        run_.add_break.assert_called_once_with(WD_BREAK.PAGE)
        assert paragraph is paragraph_

    @pytest.mark.parametrize(
        ("text", "style"), [("", None), ("", "Heading 1"), ("foo\rbar", "Body Text")]
    )
    def it_can_add_a_paragraph(
        self,
        text: str,
        style: str | None,
        document: Document,
        body_: Mock,
        body_prop_: Mock,
        paragraph_: Mock,
    ):
        body_prop_.return_value = body_
        body_.add_paragraph.return_value = paragraph_

        paragraph = document.add_paragraph(text, style)

        body_.add_paragraph.assert_called_once_with(text, style)
        assert paragraph is paragraph_

    def it_can_add_a_picture(
        self, document: Document, add_paragraph_: Mock, run_: Mock, picture_: Mock
    ):
        path, width, height = "foobar.png", 100, 200
        add_paragraph_.return_value.add_run.return_value = run_
        run_.add_picture.return_value = picture_

        picture = document.add_picture(path, width, height)

        run_.add_picture.assert_called_once_with(path, width, height)
        assert picture is picture_

    @pytest.mark.parametrize(
        ("sentinel_cxml", "start_type", "new_sentinel_cxml"),
        [
            ("w:sectPr", WD_SECTION.EVEN_PAGE, "w:sectPr/w:type{w:val=evenPage}"),
            (
                "w:sectPr/w:type{w:val=evenPage}",
                WD_SECTION.ODD_PAGE,
                "w:sectPr/w:type{w:val=oddPage}",
            ),
            ("w:sectPr/w:type{w:val=oddPage}", WD_SECTION.NEW_PAGE, "w:sectPr"),
        ],
    )
    def it_can_add_a_section(
        self,
        sentinel_cxml: str,
        start_type: WD_SECTION,
        new_sentinel_cxml: str,
        Section_: Mock,
        section_: Mock,
        document_part_: Mock,
    ):
        Section_.return_value = section_
        document = Document(
            cast(CT_Document, element("w:document/w:body/(w:p,%s)" % sentinel_cxml)),
            document_part_,
        )

        section = document.add_section(start_type)

        assert document.element.xml == xml(
            "w:document/w:body/(w:p,w:p/w:pPr/%s,%s)" % (sentinel_cxml, new_sentinel_cxml)
        )
        sectPr = document.element.xpath("w:body/w:sectPr")[0]
        Section_.assert_called_once_with(sectPr, document_part_)
        assert section is section_

    def it_can_add_a_table(
        self,
        document: Document,
        _block_width_prop_: Mock,
        body_prop_: Mock,
        body_: Mock,
        table_: Mock,
    ):
        rows, cols, style = 4, 2, "Light Shading Accent 1"
        body_prop_.return_value = body_
        body_.add_table.return_value = table_
        _block_width_prop_.return_value = width = 42

        table = document.add_table(rows, cols, style)

        body_.add_table.assert_called_once_with(rows, cols, width)
        assert table == table_
        assert table.style == style

    def it_can_save_the_document_to_a_file(self, document_part_: Mock):
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        document.save("foobar.docx")

        document_part_.save.assert_called_once_with("foobar.docx")

    def it_provides_access_to_the_comments(self, document_part_: Mock, comments_: Mock):
        document_part_.comments = comments_
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        assert document.comments is comments_

    def it_provides_access_to_its_core_properties(
        self, document_part_: Mock, core_properties_: Mock
    ):
        document_part_.core_properties = core_properties_
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        core_properties = document.core_properties

        assert core_properties is core_properties_

    def it_provides_access_to_its_inline_shapes(self, document_part_: Mock, inline_shapes_: Mock):
        document_part_.inline_shapes = inline_shapes_
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        assert document.inline_shapes is inline_shapes_

    def it_can_iterate_the_inner_content_of_the_document(
        self, body_prop_: Mock, body_: Mock, document_part_: Mock
    ):
        body_prop_.return_value = body_
        body_.iter_inner_content.return_value = iter((1, 2, 3))
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        assert list(document.iter_inner_content()) == [1, 2, 3]

    def it_provides_access_to_its_paragraphs(
        self, document: Document, body_prop_: Mock, body_: Mock, paragraphs_: Mock
    ):
        body_prop_.return_value = body_
        body_.paragraphs = paragraphs_
        paragraphs = document.paragraphs
        assert paragraphs is paragraphs_

    def it_provides_access_to_its_sections(
        self, document_part_: Mock, Sections_: Mock, sections_: Mock
    ):
        document_elm = cast(CT_Document, element("w:document"))
        Sections_.return_value = sections_
        document = Document(document_elm, document_part_)

        sections = document.sections

        Sections_.assert_called_once_with(document_elm, document_part_)
        assert sections is sections_

    def it_provides_access_to_its_settings(self, document_part_: Mock, settings_: Mock):
        document_part_.settings = settings_
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        assert document.settings is settings_

    def it_provides_access_to_its_styles(self, document_part_: Mock, styles_: Mock):
        document_part_.styles = styles_
        document = Document(cast(CT_Document, element("w:document")), document_part_)

        assert document.styles is styles_

    def it_provides_access_to_its_tables(
        self, document: Document, body_prop_: Mock, body_: Mock, tables_: Mock
    ):
        body_prop_.return_value = body_
        body_.tables = tables_

        assert document.tables is tables_

    def it_provides_access_to_the_document_part(self, document_part_: Mock):
        document = Document(cast(CT_Document, element("w:document")), document_part_)
        assert document.part is document_part_

    def it_provides_access_to_the_document_body(
        self, _Body_: Mock, body_: Mock, document_part_: Mock
    ):
        _Body_.return_value = body_
        document_elm = cast(CT_Document, element("w:document/w:body"))
        body_elm = document_elm[0]
        document = Document(document_elm, document_part_)

        body = document._body

        _Body_.assert_called_once_with(body_elm, document)
        assert body is body_

    def it_determines_block_width_to_help(
        self, document: Document, sections_prop_: Mock, section_: Mock
    ):
        sections_prop_.return_value = [None, section_]
        section_.page_width = 6000
        section_.left_margin = 1500
        section_.right_margin = 1000

        width = document._block_width

        assert isinstance(width, Length)
        assert width == 3500

    # -- fixtures --------------------------------------------------------------------------------

    @pytest.fixture
    def add_paragraph_(self, request: FixtureRequest):
        return method_mock(request, Document, "add_paragraph")

    @pytest.fixture
    def _Body_(self, request: FixtureRequest):
        return class_mock(request, "docx.document._Body")

    @pytest.fixture
    def body_(self, request: FixtureRequest):
        return instance_mock(request, _Body)

    @pytest.fixture
    def _block_width_prop_(self, request: FixtureRequest):
        return property_mock(request, Document, "_block_width")

    @pytest.fixture
    def body_prop_(self, request: FixtureRequest):
        return property_mock(request, Document, "_body")

    @pytest.fixture
    def comment_(self, request: FixtureRequest):
        return instance_mock(request, Comment)

    @pytest.fixture
    def comments_(self, request: FixtureRequest):
        return instance_mock(request, Comments)

    @pytest.fixture
    def comments_prop_(self, request: FixtureRequest):
        return property_mock(request, Document, "comments")

    @pytest.fixture
    def core_properties_(self, request: FixtureRequest):
        return instance_mock(request, CoreProperties)

    @pytest.fixture
    def document(self, document_part_: Mock) -> Document:
        document_elm = cast(CT_Document, element("w:document"))
        return Document(document_elm, document_part_)

    @pytest.fixture
    def document_part_(self, request: FixtureRequest):
        return instance_mock(request, DocumentPart)

    @pytest.fixture
    def inline_shapes_(self, request: FixtureRequest):
        return instance_mock(request, InlineShapes)

    @pytest.fixture
    def paragraph_(self, request: FixtureRequest):
        return instance_mock(request, Paragraph)

    @pytest.fixture
    def paragraphs_(self, request: FixtureRequest):
        return instance_mock(request, list)

    @pytest.fixture
    def picture_(self, request: FixtureRequest):
        return instance_mock(request, InlineShape)

    @pytest.fixture
    def run_(self, request: FixtureRequest):
        return instance_mock(request, Run)

    @pytest.fixture
    def run_mark_comment_range_(self, request: FixtureRequest):
        return method_mock(request, Run, "mark_comment_range")

    @pytest.fixture
    def Section_(self, request: FixtureRequest):
        return class_mock(request, "docx.document.Section")

    @pytest.fixture
    def section_(self, request: FixtureRequest):
        return instance_mock(request, Section)

    @pytest.fixture
    def Sections_(self, request: FixtureRequest):
        return class_mock(request, "docx.document.Sections")

    @pytest.fixture
    def sections_(self, request: FixtureRequest):
        return instance_mock(request, Sections)

    @pytest.fixture
    def sections_prop_(self, request: FixtureRequest):
        return property_mock(request, Document, "sections")

    @pytest.fixture
    def settings_(self, request: FixtureRequest):
        return instance_mock(request, Settings)

    @pytest.fixture
    def styles_(self, request: FixtureRequest):
        return instance_mock(request, Styles)

    @pytest.fixture
    def table_(self, request: FixtureRequest):
        return instance_mock(request, Table)

    @pytest.fixture
    def tables_(self, request: FixtureRequest):
        return instance_mock(request, list)


class Describe_Body:
    """Unit-test suite for `docx.document._Body`."""

    @pytest.mark.parametrize(
        ("cxml", "expected_cxml"),
        [
            ("w:body", "w:body"),
            ("w:body/w:p", "w:body"),
            ("w:body/w:sectPr", "w:body/w:sectPr"),
            ("w:body/(w:p, w:sectPr)", "w:body/w:sectPr"),
        ],
    )
    def it_can_clear_itself_of_all_content_it_holds(
        self, cxml: str, expected_cxml: str, document_: Mock
    ):
        body = _Body(cast(CT_Body, element(cxml)), document_)

        _body = body.clear_content()

        assert body._body.xml == xml(expected_cxml)
        assert _body is body

    # -- fixtures --------------------------------------------------------------------------------

    @pytest.fixture
    def document_(self, request: FixtureRequest):
        return instance_mock(request, Document)