summaryrefslogtreecommitdiff
path: root/tests/docx/body_xml_tests.py
blob: 02d8b85f1d1a81106e4c1c3953be21b8f95d3692 (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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
import io

from nose.tools import istest, assert_equal
from nose_parameterized import parameterized, param
import funk

from mammoth import documents, results
from mammoth.docx.xmlparser import element as xml_element, text as xml_text
from mammoth.docx import body_xml
from mammoth.docx.numbering_xml import Numbering
from mammoth.docx.relationships_xml import Relationships, Relationship
from mammoth.docx.styles_xml import Styles, Style


@istest
class ReadXmlElementTests(object):
    @istest
    def text_from_text_element_is_read(self):
        element = _text_element("Hello!")
        assert_equal(documents.Text("Hello!"), _read_and_get_document_xml_element(element))
    
    @istest
    def can_read_text_within_run(self):
        element = _run_element_with_text("Hello!")
        assert_equal(
            documents.run([documents.Text("Hello!")]),
            _read_and_get_document_xml_element(element)
        )
    
    @istest
    def can_read_text_within_paragraph(self):
        element = _paragraph_element_with_text("Hello!")
        assert_equal(
            documents.paragraph([documents.run([documents.Text("Hello!")])]),
            _read_and_get_document_xml_element(element)
        )
        
    @istest
    def paragraph_has_no_style_if_it_has_no_properties(self):
        element = xml_element("w:p")
        assert_equal(None, _read_and_get_document_xml_element(element).style_id)
        
    @istest
    def paragraph_has_style_id_and_name_read_from_paragraph_properties_if_present(self):
        style_xml = xml_element("w:pStyle", {"w:val": "Heading1"})
        properties_xml = xml_element("w:pPr", {}, [style_xml])
        paragraph_xml = xml_element("w:p", {}, [properties_xml])
        
        styles = Styles({"Heading1": Style(style_id="Heading1", name="Heading 1")}, {})
        
        paragraph = _read_and_get_document_xml_element(paragraph_xml, styles=styles)
        assert_equal("Heading1", paragraph.style_id)
        assert_equal("Heading 1", paragraph.style_name)
        
    @istest
    def warning_is_emitted_when_paragraph_style_cannot_be_found(self):
        style_xml = xml_element("w:pStyle", {"w:val": "Heading1"})
        properties_xml = xml_element("w:pPr", {}, [style_xml])
        paragraph_xml = xml_element("w:p", {}, [properties_xml])
        
        styles = Styles({}, {})
        
        result = _read_document_xml_element(paragraph_xml, styles=styles)
        paragraph = result.value
        assert_equal("Heading1", paragraph.style_id)
        assert_equal(None, paragraph.style_name)
        assert_equal([results.warning("Paragraph style with ID Heading1 was referenced but not defined in the document")], result.messages)
        
    @istest
    def paragraph_has_no_numbering_if_it_has_no_numbering_properties(self):
        element = xml_element("w:p")
        assert_equal(None, _read_and_get_document_xml_element(element).numbering)
        
    @istest
    def paragraph_has_numbering_properties_from_paragraph_properties_if_present(self):
        paragraph_xml = self._paragraph_with_numbering_properties([
            xml_element("w:ilvl", {"w:val": "1"}),
            xml_element("w:numId", {"w:val": "42"}),
        ])
        
        numbering = Numbering({"42": {"1": documents.numbering_level("1", True)}})
        paragraph = _read_and_get_document_xml_element(paragraph_xml, numbering=numbering)
        
        assert_equal("1", paragraph.numbering.level_index)
        assert_equal(True, paragraph.numbering.is_ordered)
        
    @istest
    def numbering_properties_are_ignored_if_lvl_is_missing(self):
        paragraph_xml = self._paragraph_with_numbering_properties([
            xml_element("w:numId", {"w:val": "42"}),
        ])
        
        numbering = Numbering({"42": {"1": documents.numbering_level("1", True)}})
        paragraph = _read_and_get_document_xml_element(paragraph_xml, numbering=numbering)
        
        assert_equal(None, paragraph.numbering)
        
    @istest
    def numbering_properties_are_ignored_if_num_id_is_missing(self):
        paragraph_xml = self._paragraph_with_numbering_properties([
            xml_element("w:ilvl", {"w:val": "1"}),
        ])
        
        numbering = Numbering({"42": {"1": documents.numbering_level("1", True)}})
        paragraph = _read_and_get_document_xml_element(paragraph_xml, numbering=numbering)
        
        assert_equal(None, paragraph.numbering)
    
    def _paragraph_with_numbering_properties(self, children):
        numbering_properties_xml = xml_element("w:numPr", {}, children)
        properties_xml = xml_element("w:pPr", {}, [numbering_properties_xml])
        return xml_element("w:p", {}, [properties_xml])
    
    @istest
    def run_has_no_style_if_it_has_no_properties(self):
        element = xml_element("w:r")
        assert_equal(None, _read_and_get_document_xml_element(element).style_id)
        
    @istest
    def run_has_style_id_and_name_read_from_run_properties_if_present(self):
        style_xml = xml_element("w:rStyle", {"w:val": "Heading1Char"})
        
        styles = Styles({}, {"Heading1Char": Style(style_id="Heading1Char", name="Heading 1 Char")})
        
        run = self._read_run_with_properties([style_xml], styles=styles)
        assert_equal("Heading1Char", run.style_id)
        assert_equal("Heading 1 Char", run.style_name)
        
    @istest
    def warning_is_emitted_when_run_style_cannot_be_found(self):
        style_xml = xml_element("w:rStyle", {"w:val": "Heading1Char"})
        properties_xml = xml_element("w:rPr", {}, [style_xml])
        run_xml = xml_element("w:r", {}, [properties_xml])
        
        styles = Styles({}, {})
        
        result = _read_document_xml_element(run_xml, styles=styles)
        run = result.value
        assert_equal("Heading1Char", run.style_id)
        assert_equal(None, run.style_name)
        assert_equal([results.warning("Run style with ID Heading1Char was referenced but not defined in the document")], result.messages)
        
        
    @istest
    def run_is_not_bold_if_bold_element_is_not_present(self):
        run = self._read_run_with_properties([])
        assert_equal(False, run.is_bold)
    
    @istest
    def run_is_bold_if_bold_element_is_present(self):
        run = self._read_run_with_properties([xml_element("w:b")])
        assert_equal(True, run.is_bold)
        
    @istest
    def run_is_not_italic_if_italic_element_is_not_present(self):
        run = self._read_run_with_properties([])
        assert_equal(False, run.is_italic)
    
    @istest
    def run_is_italic_if_italic_element_is_present(self):
        run = self._read_run_with_properties([xml_element("w:i")])
        assert_equal(True, run.is_italic)
        
    @istest
    def run_is_not_underlined_if_underline_element_is_not_present(self):
        run = self._read_run_with_properties([])
        assert_equal(False, run.is_underline)
    
    @istest
    def run_is_underlined_if_underline_element_is_present(self):
        run = self._read_run_with_properties([xml_element("w:u")])
        assert_equal(True, run.is_underline)
        
    @istest
    def run_is_not_struckthrough_if_strikethrough_element_is_not_present(self):
        run = self._read_run_with_properties([])
        assert_equal(False, run.is_strikethrough)
    
    @istest
    def run_is_struckthrough_if_strikethrough_element_is_present(self):
        run = self._read_run_with_properties([xml_element("w:strike")])
        assert_equal(True, run.is_strikethrough)

    run_boolean_property_test = lambda func: parameterized([
        param(attr_name="is_bold", tag_name="w:b"),
        param(attr_name="is_underline", tag_name="w:u"),
        param(attr_name="is_italic", tag_name="w:i"),
        param(attr_name="is_strikethrough", tag_name="w:strike"),
    ])(istest(func))

    @run_boolean_property_test
    def run_boolean_property_is_false_if_element_is_present_and_val_is_false(self, attr_name, tag_name):
        run = self._read_run_with_properties([xml_element(tag_name, {"w:val": "false"})])
        assert_equal(False, getattr(run, attr_name))

    @run_boolean_property_test
    def run_boolean_property_is_false_if_element_is_present_and_val_is_0(self, attr_name, tag_name):
        run = self._read_run_with_properties([xml_element(tag_name, {"w:val": "0"})])
        assert_equal(False, getattr(run, attr_name))

    @run_boolean_property_test
    def run_boolean_property_is_true_if_element_is_present_and_val_is_true(self, attr_name, tag_name):
        run = self._read_run_with_properties([xml_element(tag_name, {"w:val": "true"})])
        assert_equal(True, getattr(run, attr_name))

    @run_boolean_property_test
    def run_boolean_property_is_true_if_element_is_present_and_val_is_1(self, attr_name, tag_name):
        run = self._read_run_with_properties([xml_element(tag_name, {"w:val": "1"})])
        assert_equal(True, getattr(run, attr_name))
    
    @istest
    def run_has_baseline_vertical_alignment_if_vertical_alignment_element_is_not_present(self):
        run = self._read_run_with_properties([])
        assert_equal(documents.VerticalAlignment.baseline, run.vertical_alignment)
        
    @istest
    def run_has_vertical_alignment_read_from_vertical_alignment_element(self):
        run = self._read_run_with_properties([xml_element("w:vertAlign", {"w:val": "superscript"})])
        assert_equal(documents.VerticalAlignment.superscript, run.vertical_alignment)
    
    def _read_run_with_properties(self, properties, styles=None):
        properties_xml = xml_element("w:rPr", {}, properties)
        run_xml = xml_element("w:r", {}, [properties_xml])
        return _read_and_get_document_xml_element(run_xml, styles=styles)


    @istest
    def can_read_tab_element(self):
        element = xml_element("w:tab")
        tab = _read_and_get_document_xml_element(element)
        assert_equal(documents.tab(), tab)
    
    
    @istest
    def word_table_is_read_as_document_table_element(self):
        element = xml_element("w:tbl", {}, [
            xml_element("w:tr", {}, [
                xml_element("w:tc", {}, [
                    xml_element("w:p", {}, [])
                ]),
            ]),
        ])
        table = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([
                documents.table_cell([
                    documents.paragraph([])
                ])
            ])
        ])
        assert_equal(expected_result, table)
    
    
    @istest
    def gridspan_is_read_as_colspan_for_table_cell(self):
        element = xml_element("w:tbl", {}, [
            xml_element("w:tr", {}, [
                xml_element("w:tc", {}, [
                    xml_element("w:tcPr", {}, [
                        xml_element("w:gridSpan", {"w:val": "2"})
                    ]),
                    xml_element("w:p", {}, [])
                ]),
            ]),
        ])
        table = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([
                documents.table_cell([
                    documents.paragraph([])
                ], colspan=2)
            ])
        ])
        assert_equal(expected_result, table)


    @istest
    def vmerge_is_read_as_rowspan_for_table_cell(self):
        element = xml_element("w:tbl", {}, [
            w_tr(w_tc()),
            w_tr(w_tc(properties=[w_vmerge("restart")])),
            w_tr(w_tc(properties=[w_vmerge("continue")])),
            w_tr(w_tc(properties=[w_vmerge("continue")])),
            w_tr(w_tc())
        ])
        result = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([documents.table_cell([])]),
            documents.table_row([documents.table_cell([], rowspan=3)]),
            documents.table_row([]),
            documents.table_row([]),
            documents.table_row([documents.table_cell([])]),
        ])
        assert_equal(expected_result, result)


    @istest
    def vmerge_without_val_is_treated_as_continue(self):
        element = xml_element("w:tbl", {}, [
            w_tr(w_tc(properties=[w_vmerge("restart")])),
            w_tr(w_tc(properties=[w_vmerge(None)])),
        ])
        result = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([documents.table_cell([], rowspan=2)]),
            documents.table_row([]),
        ])
        assert_equal(expected_result, result)


    @istest
    def vmerge_accounts_for_cells_spanning_columns(self):
        element = xml_element("w:tbl", {}, [
            w_tr(w_tc(), w_tc(), w_tc(properties=[w_vmerge("restart")])),
            w_tr(w_tc(properties=[w_gridspan("2")]), w_tc(properties=[w_vmerge("continue")])),
            w_tr(w_tc(), w_tc(), w_tc(properties=[w_vmerge("continue")])),
            w_tr(w_tc(), w_tc(), w_tc()),
        ])
        result = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([documents.table_cell([]), documents.table_cell([]), documents.table_cell([], rowspan=3)]),
            documents.table_row([documents.table_cell([], colspan=2)]),
            documents.table_row([documents.table_cell([]), documents.table_cell([])]),
            documents.table_row([documents.table_cell([]), documents.table_cell([]), documents.table_cell([])]),
        ])
        assert_equal(expected_result, result)


    @istest
    def no_vertical_cell_merging_if_merged_cells_do_not_line_up(self):
        element = xml_element("w:tbl", {}, [
            w_tr(w_tc(properties=[w_gridspan("2")]), w_tc(properties=[w_vmerge("restart")])),
            w_tr(w_tc(), w_tc(properties=[w_vmerge("continue")])),
        ])
        result = _read_and_get_document_xml_element(element)
        expected_result = documents.table([
            documents.table_row([documents.table_cell([], colspan=2), documents.table_cell([])]),
            documents.table_row([documents.table_cell([]), documents.table_cell([])]),
        ])
        assert_equal(expected_result, result)


    @istest
    def warning_if_non_row_in_table(self):
        element = xml_element("w:tbl", {}, [xml_element("w:p")])
        result = _read_document_xml_element(element)
        expected_warning = results.warning("unexpected non-row element in table, cell merging may be incorrect")
        assert_equal([expected_warning], result.messages)


    @istest
    def warning_if_non_cell_in_table_row(self):
        element = xml_element("w:tbl", {}, [w_tr(xml_element("w:p"))])
        result = _read_document_xml_element(element)
        expected_warning = results.warning("unexpected non-cell element in table row, cell merging may be incorrect")
        assert_equal([expected_warning], result.messages)


    @istest
    def children_of_w_ins_are_converted_normally(self):
        element = xml_element("w:p", {}, [
            xml_element("w:ins", {}, [
                xml_element("w:r")
            ])
        ])
        assert_equal(
            documents.paragraph([documents.run([])]),
            _read_and_get_document_xml_element(element)
        )
        
    @istest
    def children_of_w_smart_tag_are_converted_normally(self):
        element = xml_element("w:p", {}, [
            xml_element("w:smartTag", {}, [
                xml_element("w:r")
            ])
        ])
        assert_equal(
            documents.paragraph([documents.run([])]),
            _read_and_get_document_xml_element(element)
        )
        
    @istest
    def hyperlink_is_read_if_it_has_a_relationship_id(self):
        relationships = Relationships({
            "r42": Relationship(target="http://example.com")
        })
        run_element = xml_element("w:r")
        element = xml_element("w:hyperlink", {"r:id": "r42"}, [run_element])
        assert_equal(
            documents.hyperlink(href="http://example.com", children=[documents.run([])]),
            _read_and_get_document_xml_element(element, relationships=relationships)
        )
        
    @istest
    def hyperlink_is_read_if_it_has_an_anchor_attribute(self):
        run_element = xml_element("w:r")
        element = xml_element("w:hyperlink", {"w:anchor": "start"}, [run_element])
        assert_equal(
            documents.hyperlink(anchor="start", children=[documents.run([])]),
            _read_and_get_document_xml_element(element)
        )
        
    @istest
    def hyperlink_is_ignored_if_it_does_not_have_a_relationship_id_nor_anchor(self):
        run_element = xml_element("w:r")
        element = xml_element("w:hyperlink", {}, [run_element])
        assert_equal(
            documents.run([]),
            _read_and_get_document_xml_element(element)
        )
        
    @istest
    def go_back_bookmark_is_ignored(self):
        element = xml_element("w:bookmarkStart", {"w:name": "_GoBack"})
        assert_equal(None, _read_and_get_document_xml_element(element))
        
    @istest
    def bookmark_start_is_read_if_name_is_not_go_back(self):
        element = xml_element("w:bookmarkStart", {"w:name": "start"})
        assert_equal(
            documents.bookmark("start"),
            _read_and_get_document_xml_element(element)
        )

    @istest
    def br_without_explicit_type_is_read_as_line_break(self):
        break_element = xml_element("w:br", {}, [])
        result = _read_document_xml_element(break_element)
        assert_equal(documents.line_break, result.value)

    @istest
    def br_with_text_wrapping_type_is_read_as_line_break(self):
        break_element = xml_element("w:br", {"w:type": "textWrapping"}, [])
        result = _read_document_xml_element(break_element)
        assert_equal(documents.line_break, result.value)

    @istest
    def br_with_page_type_is_read_as_page_break(self):
        break_element = xml_element("w:br", {"w:type": "page"}, [])
        result = _read_document_xml_element(break_element)
        assert_equal(documents.page_break, result.value)

    @istest
    def br_with_column_type_is_read_as_column_break(self):
        break_element = xml_element("w:br", {"w:type": "column"}, [])
        result = _read_document_xml_element(break_element)
        assert_equal(documents.column_break, result.value)

    @istest
    def warning_on_break_types_that_arent_recognised(self):
        break_element = xml_element("w:br", {"w:type": "unknownBreakType"}, [])
        result = _read_document_xml_element(break_element)
        expected_warning = results.warning("Unsupported break type: unknownBreakType")
        assert_equal([expected_warning], result.messages)
        assert_equal(None, result.value)

    
    IMAGE_BYTES = b"Not an image at all!"
    IMAGE_RELATIONSHIP_ID = "rId5"
    
    def _read_embedded_image(self, element):
        relationships = Relationships({
            self.IMAGE_RELATIONSHIP_ID: Relationship(target="media/hat.png")
        })
        
        mocks = funk.Mocks()
        docx_file = mocks.mock()
        funk.allows(docx_file).open("word/media/hat.png").returns(io.BytesIO(self.IMAGE_BYTES))
        
        content_types = mocks.mock()
        funk.allows(content_types).find_content_type("word/media/hat.png").returns("image/png")
        
        return _read_and_get_document_xml_element(
            element,
            content_types=content_types,
            relationships=relationships,
            docx_file=docx_file,
        )
    
    @istest
    def can_read_imagedata_elements_with_rid_attribute(self):
        imagedata_element = xml_element("v:imagedata", {
            "r:id": self.IMAGE_RELATIONSHIP_ID,
            "o:title": "It's a hat"
        })
        
        image = self._read_embedded_image(imagedata_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
    
    @istest
    def when_imagedata_element_has_no_relationship_id_then_it_is_ignored_with_warning(self):
        imagedata_element = xml_element("v:imagedata")
        
        result = _read_document_xml_element(imagedata_element)
        expected_warning = results.warning("A v:imagedata element without a relationship ID was ignored")
        assert_equal([expected_warning], result.messages)
        assert_equal(None, result.value)
        
        
    @istest
    def can_read_inline_pictures(self):
        drawing_element = _create_inline_image(
            blip=_embedded_blip(self.IMAGE_RELATIONSHIP_ID),
            description="It's a hat",
        )
        
        image = self._read_embedded_image(drawing_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
        
        
    @istest
    def alt_text_title_is_used_if_alt_text_description_is_blank(self):
        drawing_element = _create_inline_image(
            blip=_embedded_blip(self.IMAGE_RELATIONSHIP_ID),
            description=" ",
            title="It's a hat",
        )
        
        image = self._read_embedded_image(drawing_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
        
        
    @istest
    def alt_text_title_is_used_if_alt_text_description_is_missing(self):
        drawing_element = _create_inline_image(
            blip=_embedded_blip(self.IMAGE_RELATIONSHIP_ID),
            title="It's a hat",
        )
        
        image = self._read_embedded_image(drawing_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
        
        
    @istest
    def alt_text_description_is_preferred_to_alt_text_title(self):
        drawing_element = _create_inline_image(
            blip=_embedded_blip(self.IMAGE_RELATIONSHIP_ID),
            description="It's a hat",
            title="hat",
        )
        
        image = self._read_embedded_image(drawing_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
        
    @istest
    def can_read_anchored_pictures(self):
        drawing_element = _create_anchored_image(
            blip=_embedded_blip(self.IMAGE_RELATIONSHIP_ID),
            description="It's a hat",
        )
        
        image = self._read_embedded_image(drawing_element)
        
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
        
        
    @istest
    @funk.with_mocks
    def warning_if_unsupported_image_type(self, mocks):
        drawing_element = _create_inline_image(
            blip=_embedded_blip("rId5"),
            description="It's a hat",
        )
        
        relationships = Relationships({
            "rId5": Relationship(target="media/hat.emf")
        })
        
        docx_file = mocks.mock()
        funk.allows(docx_file).open("word/media/hat.emf").returns(io.BytesIO(self.IMAGE_BYTES))
        
        content_types = mocks.mock()
        funk.allows(content_types).find_content_type("word/media/hat.emf").returns("image/x-emf")
        
        result = _read_document_xml_element(
            drawing_element,
            content_types=content_types,
            relationships=relationships,
            docx_file=docx_file,
        )
        assert_equal("image/x-emf", result.value.content_type)
        expected_warning = results.warning("Image of type image/x-emf is unlikely to display in web browsers")
        assert_equal([expected_warning], result.messages)
        
        
    @istest
    @funk.with_mocks
    def can_read_linked_pictures(self, mocks):
        drawing_element = _create_inline_image(
            blip=_linked_blip("rId5"),
            description="It's a hat",
        )
        
        relationships = Relationships({
            "rId5": Relationship(target="file:///media/hat.png")
        })
        
        files = mocks.mock()
        funk.allows(files).verify("file:///media/hat.png")
        funk.allows(files).open("file:///media/hat.png").returns(io.BytesIO(self.IMAGE_BYTES))
        
        content_types = mocks.mock()
        funk.allows(content_types).find_content_type("file:///media/hat.png").returns("image/png")
        
        image = _read_and_get_document_xml_element(
            drawing_element,
            content_types=content_types,
            relationships=relationships,
            files=files,
        )
        assert_equal(documents.Image, type(image))
        assert_equal("It's a hat", image.alt_text)
        assert_equal("image/png", image.content_type)
        with image.open() as image_file:
            assert_equal(self.IMAGE_BYTES, image_file.read())
    
    @istest
    def footnote_reference_has_id_read(self):
        footnote_xml = xml_element("w:footnoteReference", {"w:id": "4"})
        footnote = _read_and_get_document_xml_element(footnote_xml)
        assert_equal("4", footnote.note_id)
    
    @istest
    def comment_reference_has_id_read(self):
        comment_reference_xml = xml_element("w:commentReference", {"w:id": "4"})
        comment_reference = _read_and_get_document_xml_element(comment_reference_xml)
        assert_equal(documents.CommentReference("4"), comment_reference)

    @istest
    def ignored_elements_are_ignored_without_message(self):
        element = xml_element("w:bookmarkEnd")
        result = _read_document_xml_element(element)
        assert_equal(None, result.value)
        assert_equal([], result.messages)
    
    @istest
    def unrecognised_elements_emit_warning(self):
        element = xml_element("w:huh", {}, [])
        result = _read_document_xml_element(element)
        expected_warning = results.warning("An unrecognised element was ignored: w:huh")
        assert_equal([expected_warning], result.messages)
    
    @istest
    def unrecognised_elements_are_ignored(self):
        element = xml_element("w:huh", {}, [])
        assert_equal(None, _read_document_xml_element(element).value)
    
    @istest
    def unrecognised_children_are_ignored(self):
        element = xml_element("w:r", {}, [_text_element("Hello!"), xml_element("w:huh", {}, [])])
        assert_equal(
            documents.run([documents.Text("Hello!")]),
            _read_document_xml_element(element).value
        )
        
    @istest
    def text_boxes_have_content_appended_after_containing_paragraph(self):
        text_box = xml_element("w:pict", {}, [
            xml_element("v:shape", {}, [
                xml_element("v:textbox", {}, [
                    xml_element("w:txbxContent", {}, [
                        _paragraph_with_style_id("textbox-content")
                    ])
                ])
            ])
        ])
        paragraph = xml_element("w:p", {}, [
            xml_element("w:r", {}, [text_box])
        ])
        result = _read_and_get_document_xml_elements(paragraph)
        assert_equal(result[1].style_id, "textbox-content")
    
    @istest
    def alternate_content_is_read_using_fallback(self):
        element = xml_element("mc:AlternateContent", {}, [
            xml_element("mc:Choice", {"Requires": "wps"}, [
                _paragraph_with_style_id("first")
            ]),
            xml_element("mc:Fallback", {}, [
                _paragraph_with_style_id("second")
            ])
        ])
        result = _read_and_get_document_xml_element(element)
        assert_equal("second", result.style_id)
    
    @istest
    def sdt_is_read_using_sdt_content(self):
        element = xml_element("w:sdt", {}, [
            xml_element("w:sdtContent", {}, [
                xml_element("w:t", {}, [xml_text("Blackdown")]),
            ]),
        ])
        result = _read_and_get_document_xml_element(element)
        assert_equal(documents.text("Blackdown"), result)

    @istest
    def text_nodes_are_ignored_when_reading_children(self):
        element = xml_element("w:r", {}, [xml_text("[text]")])
        assert_equal(
            documents.run([]),
            _read_and_get_document_xml_element(element)
        )

def _read_and_get_document_xml_element(*args, **kwargs):
    return _read_and_get_document_xml(
        lambda reader, element: reader.read(element),
        *args,
        **kwargs)


def _read_and_get_document_xml_elements(*args, **kwargs):
    return _read_and_get_document_xml(
        lambda reader, element: reader.read_all([element]),
        *args,
        **kwargs)


def _read_and_get_document_xml(func, *args, **kwargs):
    styles = kwargs.pop("styles", FakeStyles())
    result = _read_document_xml(func, *args, styles=styles, **kwargs)
    assert_equal([], result.messages)
    return result.value


def _read_document_xml_element(*args, **kwargs):
    return _read_document_xml(
        lambda reader, element: reader.read(element),
        *args,
        **kwargs)


def _read_document_xml_elements(*args, **kwargs):
    return _read_document_xml(
        lambda reader, element: reader.read_all([element]),
        *args,
        **kwargs)


def _read_document_xml(func, element, *args, **kwargs):
    reader = body_xml.reader(*args, **kwargs)
    return func(reader, element)


class FakeStyles(object):
    def find_paragraph_style_by_id(self, style_id):
        return Style(style_id, style_id)
    
    def find_character_style_by_id(self, style_id):
        return None

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 _paragraph_with_style_id(style_id):
    style_xml = xml_element("w:pStyle", {"w:val": style_id})
    properties_xml = xml_element("w:pPr", {}, [style_xml])
    return xml_element("w:p", {}, [properties_xml])

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)])
    

def _create_inline_image(blip, description=None, title=None):
    return xml_element("w:drawing", {}, [
        xml_element("wp:inline", {}, _create_image_elements(blip, description=description, title=title))
    ])


def _create_anchored_image(description, blip):
    return xml_element("w:drawing", {}, [
        xml_element("wp:anchor", {}, _create_image_elements(blip, description=description, ))
    ])

    
def _create_image_elements(blip, description=None, title=None):
    properties = {}
    if description is not None:
        properties["descr"] = description
    if title is not None:
        properties["title"] = title
    
    return [
        xml_element("wp:docPr", properties),
        xml_element("a:graphic", {}, [
            xml_element("a:graphicData", {}, [
                xml_element("pic:pic", {}, [
                    xml_element("pic:blipFill", {}, [
                        blip
                    ])
                ])
            ])
        ])
    ]

def _embedded_blip(relationship_id):
    return _blip({"r:embed": relationship_id})

def _linked_blip(relationship_id):
    return _blip({"r:link": relationship_id})

def _blip(attributes):
    return xml_element("a:blip", attributes)


def w_tr(*children):
    return xml_element("w:tr", {}, children)

def w_tc(properties=None, *children):
    return xml_element("w:tc", {}, [xml_element("w:tcPr", {}, properties)] + list(children))

def w_gridspan(val):
    return xml_element("w:gridSpan", {"w:val": val})

def w_vmerge(val):
    return xml_element("w:vMerge", {"w:val": val})