File: test_run.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 (408 lines) | stat: -rw-r--r-- 14,859 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
# pyright: reportPrivateUsage=false

"""Test suite for the docx.text.run module."""

from __future__ import annotations

from typing import Any, List, cast

import pytest

from docx import types as t
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_BREAK, WD_UNDERLINE
from docx.oxml.text.paragraph import CT_P
from docx.oxml.text.run import CT_R
from docx.parts.document import DocumentPart
from docx.shape import InlineShape
from docx.text.font import Font
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, property_mock


class DescribeRun:
    """Unit-test suite for `docx.text.run.Run`."""

    @pytest.mark.parametrize(
        ("r_cxml", "bool_prop_name", "expected_value"),
        [
            ("w:r/w:rPr", "bold", None),
            ("w:r/w:rPr/w:b", "bold", True),
            ("w:r/w:rPr/w:b{w:val=on}", "bold", True),
            ("w:r/w:rPr/w:b{w:val=off}", "bold", False),
            ("w:r/w:rPr/w:b{w:val=1}", "bold", True),
            ("w:r/w:rPr/w:i{w:val=0}", "italic", False),
        ],
    )
    def it_knows_its_bool_prop_states(
        self, r_cxml: str, bool_prop_name: str, expected_value: bool | None, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)
        assert getattr(run, bool_prop_name) == expected_value

    @pytest.mark.parametrize(
        ("initial_r_cxml", "bool_prop_name", "value", "expected_cxml"),
        [
            # -- nothing to True, False, and None ---------------------------
            ("w:r", "bold", True, "w:r/w:rPr/w:b"),
            ("w:r", "bold", False, "w:r/w:rPr/w:b{w:val=0}"),
            ("w:r", "italic", None, "w:r/w:rPr"),
            # -- default to True, False, and None ---------------------------
            ("w:r/w:rPr/w:b", "bold", True, "w:r/w:rPr/w:b"),
            ("w:r/w:rPr/w:b", "bold", False, "w:r/w:rPr/w:b{w:val=0}"),
            ("w:r/w:rPr/w:i", "italic", None, "w:r/w:rPr"),
            # -- True to True, False, and None ------------------------------
            ("w:r/w:rPr/w:b{w:val=on}", "bold", True, "w:r/w:rPr/w:b"),
            ("w:r/w:rPr/w:b{w:val=1}", "bold", False, "w:r/w:rPr/w:b{w:val=0}"),
            ("w:r/w:rPr/w:b{w:val=1}", "bold", None, "w:r/w:rPr"),
            # -- False to True, False, and None -----------------------------
            ("w:r/w:rPr/w:i{w:val=false}", "italic", True, "w:r/w:rPr/w:i"),
            ("w:r/w:rPr/w:i{w:val=0}", "italic", False, "w:r/w:rPr/w:i{w:val=0}"),
            ("w:r/w:rPr/w:i{w:val=off}", "italic", None, "w:r/w:rPr"),
        ],
    )
    def it_can_change_its_bool_prop_settings(
        self,
        initial_r_cxml: str,
        bool_prop_name: str,
        value: bool | None,
        expected_cxml: str,
        paragraph_: Mock,
    ):
        run = Run(cast(CT_R, element(initial_r_cxml)), paragraph_)

        setattr(run, bool_prop_name, value)

        assert run._r.xml == xml(expected_cxml)

    @pytest.mark.parametrize(
        ("r_cxml", "expected_value"),
        [
            ("w:r", False),
            ('w:r/w:t"foobar"', False),
            ('w:r/(w:t"abc", w:lastRenderedPageBreak, w:t"def")', True),
            ("w:r/(w:lastRenderedPageBreak, w:lastRenderedPageBreak)", True),
        ],
    )
    def it_knows_whether_it_contains_a_page_break(
        self, r_cxml: str, expected_value: bool, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)
        assert run.contains_page_break == expected_value

    @pytest.mark.parametrize(
        ("r_cxml", "expected"),
        [
            # -- no content produces an empty iterator --
            ("w:r", []),
            # -- contiguous text content is condensed into a single str --
            ('w:r/(w:t"foo",w:cr,w:t"bar")', ["str"]),
            # -- page-breaks are a form of inner-content --
            (
                'w:r/(w:t"abc",w:br,w:lastRenderedPageBreak,w:noBreakHyphen,w:t"def")',
                ["str", "RenderedPageBreak", "str"],
            ),
            # -- as are drawings --
            (
                'w:r/(w:t"abc", w:lastRenderedPageBreak, w:drawing)',
                ["str", "RenderedPageBreak", "Drawing"],
            ),
        ],
    )
    def it_can_iterate_its_inner_content_items(
        self, r_cxml: str, expected: List[str], fake_parent: t.ProvidesStoryPart
    ):
        r = cast(CT_R, element(r_cxml))
        run = Run(r, fake_parent)

        inner_content = run.iter_inner_content()

        actual = [type(item).__name__ for item in inner_content]
        assert actual == expected, f"expected: {expected}, got: {actual}"

    def it_can_mark_a_comment_reference_range(self, paragraph_: Mock):
        p = cast(CT_P, element('w:p/w:r/w:t"referenced text"'))
        run = last_run = Run(p.r_lst[0], paragraph_)

        run.mark_comment_range(last_run, comment_id=42)

        assert p.xml == xml(
            'w:p/(w:commentRangeStart{w:id=42},w:r/w:t"referenced text"'
            ",w:commentRangeEnd{w:id=42}"
            ",w:r/(w:rPr/w:rStyle{w:val=CommentReference},w:commentReference{w:id=42}))"
        )

    def it_knows_its_character_style(
        self, part_prop_: Mock, document_part_: Mock, paragraph_: Mock
    ):
        style_ = document_part_.get_style.return_value
        part_prop_.return_value = document_part_
        style_id = "Barfoo"
        run = Run(cast(CT_R, element(f"w:r/w:rPr/w:rStyle{{w:val={style_id}}}")), paragraph_)

        style = run.style

        document_part_.get_style.assert_called_once_with(style_id, WD_STYLE_TYPE.CHARACTER)
        assert style is style_

    @pytest.mark.parametrize(
        ("r_cxml", "value", "style_id", "expected_cxml"),
        [
            ("w:r", "Foo Font", "FooFont", "w:r/w:rPr/w:rStyle{w:val=FooFont}"),
            ("w:r/w:rPr", "Foo Font", "FooFont", "w:r/w:rPr/w:rStyle{w:val=FooFont}"),
            (
                "w:r/w:rPr/w:rStyle{w:val=FooFont}",
                "Bar Font",
                "BarFont",
                "w:r/w:rPr/w:rStyle{w:val=BarFont}",
            ),
            ("w:r/w:rPr/w:rStyle{w:val=FooFont}", None, None, "w:r/w:rPr"),
            ("w:r", None, None, "w:r/w:rPr"),
        ],
    )
    def it_can_change_its_character_style(
        self,
        r_cxml: str,
        value: str | None,
        style_id: str | None,
        expected_cxml: str,
        part_prop_: Mock,
        paragraph_: Mock,
    ):
        part_ = part_prop_.return_value
        part_.get_style_id.return_value = style_id
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)

        run.style = value

        part_.get_style_id.assert_called_once_with(value, WD_STYLE_TYPE.CHARACTER)
        assert run._r.xml == xml(expected_cxml)

    @pytest.mark.parametrize(
        ("r_cxml", "expected_value"),
        [
            ("w:r", None),
            ("w:r/w:rPr/w:u", None),
            ("w:r/w:rPr/w:u{w:val=single}", True),
            ("w:r/w:rPr/w:u{w:val=none}", False),
            ("w:r/w:rPr/w:u{w:val=double}", WD_UNDERLINE.DOUBLE),
            ("w:r/w:rPr/w:u{w:val=wave}", WD_UNDERLINE.WAVY),
        ],
    )
    def it_knows_its_underline_type(
        self, r_cxml: str, expected_value: bool | WD_UNDERLINE | None, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)
        assert run.underline is expected_value

    @pytest.mark.parametrize(
        ("initial_r_cxml", "new_underline", "expected_cxml"),
        [
            ("w:r", True, "w:r/w:rPr/w:u{w:val=single}"),
            ("w:r", False, "w:r/w:rPr/w:u{w:val=none}"),
            ("w:r", None, "w:r/w:rPr"),
            ("w:r", WD_UNDERLINE.SINGLE, "w:r/w:rPr/w:u{w:val=single}"),
            ("w:r", WD_UNDERLINE.THICK, "w:r/w:rPr/w:u{w:val=thick}"),
            ("w:r/w:rPr/w:u{w:val=single}", True, "w:r/w:rPr/w:u{w:val=single}"),
            ("w:r/w:rPr/w:u{w:val=single}", False, "w:r/w:rPr/w:u{w:val=none}"),
            ("w:r/w:rPr/w:u{w:val=single}", None, "w:r/w:rPr"),
            (
                "w:r/w:rPr/w:u{w:val=single}",
                WD_UNDERLINE.SINGLE,
                "w:r/w:rPr/w:u{w:val=single}",
            ),
            (
                "w:r/w:rPr/w:u{w:val=single}",
                WD_UNDERLINE.DOTTED,
                "w:r/w:rPr/w:u{w:val=dotted}",
            ),
        ],
    )
    def it_can_change_its_underline_type(
        self,
        initial_r_cxml: str,
        new_underline: bool | WD_UNDERLINE | None,
        expected_cxml: str,
        paragraph_: Mock,
    ):
        run = Run(cast(CT_R, element(initial_r_cxml)), paragraph_)

        run.underline = new_underline

        assert run._r.xml == xml(expected_cxml)

    @pytest.mark.parametrize("invalid_value", ["foobar", 42, "single"])
    def it_raises_on_assign_invalid_underline_value(self, invalid_value: Any, paragraph_: Mock):
        run = Run(cast(CT_R, element("w:r/w:rPr")), paragraph_)
        with pytest.raises(ValueError, match=" is not a valid WD_UNDERLINE"):
            run.underline = invalid_value

    def it_provides_access_to_its_font(self, Font_: Mock, font_: Mock, paragraph_: Mock):
        Font_.return_value = font_
        run = Run(cast(CT_R, element("w:r")), paragraph_)

        font = run.font

        Font_.assert_called_once_with(run._element)
        assert font is font_

    @pytest.mark.parametrize(
        ("r_cxml", "new_text", "expected_cxml"),
        [
            ("w:r", "foo", 'w:r/w:t"foo"'),
            ('w:r/w:t"foo"', "bar", 'w:r/(w:t"foo", w:t"bar")'),
            ("w:r", "fo ", 'w:r/w:t{xml:space=preserve}"fo "'),
            ("w:r", "f o", 'w:r/w:t"f o"'),
        ],
    )
    def it_can_add_text(
        self, r_cxml: str, new_text: str, expected_cxml: str, Text_: Mock, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)

        text = run.add_text(new_text)

        assert run._r.xml == xml(expected_cxml)
        assert text is Text_.return_value

    @pytest.mark.parametrize(
        ("break_type", "expected_cxml"),
        [
            (WD_BREAK.LINE, "w:r/w:br"),
            (WD_BREAK.PAGE, "w:r/w:br{w:type=page}"),
            (WD_BREAK.COLUMN, "w:r/w:br{w:type=column}"),
            (WD_BREAK.LINE_CLEAR_LEFT, "w:r/w:br{w:clear=left}"),
            (WD_BREAK.LINE_CLEAR_RIGHT, "w:r/w:br{w:clear=right}"),
            (WD_BREAK.LINE_CLEAR_ALL, "w:r/w:br{w:clear=all}"),
        ],
    )
    def it_can_add_a_break(self, break_type: WD_BREAK, expected_cxml: str, paragraph_: Mock):
        run = Run(cast(CT_R, element("w:r")), paragraph_)

        run.add_break(break_type)

        assert run._r.xml == xml(expected_cxml)

    @pytest.mark.parametrize(
        ("r_cxml", "expected_cxml"), [('w:r/w:t"foo"', 'w:r/(w:t"foo", w:tab)')]
    )
    def it_can_add_a_tab(self, r_cxml: str, expected_cxml: str, paragraph_: Mock):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)

        run.add_tab()

        assert run._r.xml == xml(expected_cxml)

    def it_can_add_a_picture(
        self,
        part_prop_: Mock,
        document_part_: Mock,
        InlineShape_: Mock,
        picture_: Mock,
        paragraph_: Mock,
    ):
        part_prop_.return_value = document_part_
        run = Run(cast(CT_R, element("w:r/wp:x")), paragraph_)
        image = "foobar.png"
        width, height, inline = 1111, 2222, element("wp:inline{id=42}")
        document_part_.new_pic_inline.return_value = inline
        InlineShape_.return_value = picture_

        picture = run.add_picture(image, width, height)

        document_part_.new_pic_inline.assert_called_once_with(image, width, height)
        assert run._r.xml == xml("w:r/(wp:x,w:drawing/wp:inline{id=42})")
        InlineShape_.assert_called_once_with(inline)
        assert picture is picture_

    @pytest.mark.parametrize(
        ("initial_r_cxml", "expected_cxml"),
        [
            ("w:r", "w:r"),
            ('w:r/w:t"foo"', "w:r"),
            ("w:r/w:br", "w:r"),
            ("w:r/w:rPr", "w:r/w:rPr"),
            ('w:r/(w:rPr, w:t"foo")', "w:r/w:rPr"),
            (
                'w:r/(w:rPr/(w:b, w:i), w:t"foo", w:cr, w:t"bar")',
                "w:r/w:rPr/(w:b, w:i)",
            ),
        ],
    )
    def it_can_remove_its_content_but_keep_formatting(
        self, initial_r_cxml: str, expected_cxml: str, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element(initial_r_cxml)), paragraph_)

        cleared_run = run.clear()

        assert run._r.xml == xml(expected_cxml)
        assert cleared_run is run

    @pytest.mark.parametrize(
        ("r_cxml", "expected_text"),
        [
            ("w:r", ""),
            ('w:r/w:t"foobar"', "foobar"),
            ('w:r/(w:t"abc", w:tab, w:t"def", w:cr)', "abc\tdef\n"),
            ('w:r/(w:br{w:type=page}, w:t"abc", w:t"def", w:tab)', "abcdef\t"),
        ],
    )
    def it_knows_the_text_it_contains(self, r_cxml: str, expected_text: str, paragraph_: Mock):
        run = Run(cast(CT_R, element(r_cxml)), paragraph_)
        assert run.text == expected_text

    @pytest.mark.parametrize(
        ("new_text", "expected_cxml"),
        [
            ("abc  def", 'w:r/w:t"abc  def"'),
            ("abc\tdef", 'w:r/(w:t"abc", w:tab, w:t"def")'),
            ("abc\ndef", 'w:r/(w:t"abc", w:br,  w:t"def")'),
            ("abc\rdef", 'w:r/(w:t"abc", w:br,  w:t"def")'),
        ],
    )
    def it_can_replace_the_text_it_contains(
        self, new_text: str, expected_cxml: str, paragraph_: Mock
    ):
        run = Run(cast(CT_R, element('w:r/w:t"should get deleted"')), paragraph_)

        run.text = new_text

        assert run._r.xml == xml(expected_cxml)

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

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

    @pytest.fixture
    def Font_(self, request: FixtureRequest):
        return class_mock(request, "docx.text.run.Font")

    @pytest.fixture
    def font_(self, request: FixtureRequest):
        return instance_mock(request, Font)

    @pytest.fixture
    def InlineShape_(self, request: FixtureRequest):
        return class_mock(request, "docx.text.run.InlineShape")

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

    @pytest.fixture
    def part_prop_(self, request: FixtureRequest):
        return property_mock(request, Run, "part")

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

    @pytest.fixture
    def Text_(self, request: FixtureRequest):
        return class_mock(request, "docx.text.run._Text")