forked from python-openxml/python-docx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_table.py
More file actions
3781 lines (3243 loc) · 133 KB
/
test_table.py
File metadata and controls
3781 lines (3243 loc) · 133 KB
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pyright: reportPrivateUsage=false
"""Test suite for the docx.table module."""
from __future__ import annotations
from typing import cast
import pytest
from docx.document import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import (
WD_ALIGN_VERTICAL,
WD_BORDER_STYLE,
WD_ROW_HEIGHT,
WD_SHADING_PATTERN,
WD_TABLE_ALIGNMENT,
WD_TABLE_AUTOFIT,
WD_TABLE_DIRECTION,
WD_TEXT_DIRECTION,
)
from docx.oxml.parser import parse_xml
from docx.oxml.table import CT_Row, CT_Tbl, CT_TblGridCol, CT_Tc
from docx.parts.document import DocumentPart
from docx.shared import Emu, Inches, Length, Pt, RGBColor, Twips
from docx.table import (
BorderElement,
CellBorders,
CellMargins,
CellShading,
Table,
TableBorders,
TableCellMargins,
TableStyleFlags,
_Cell,
_Column,
_Columns,
_Row,
_Rows,
)
from docx.text.paragraph import Paragraph
from .unitutil.cxml import element, xml
from .unitutil.file import snippet_seq
from .unitutil.mock import FixtureRequest, Mock, instance_mock, property_mock
class DescribeTable:
"""Unit-test suite for `docx.table._Rows` objects."""
def it_can_add_a_row(self, document_: Mock):
snippets = snippet_seq("add-row-col")
tbl = cast(CT_Tbl, parse_xml(snippets[0]))
table = Table(tbl, document_)
row = table.add_row()
assert table._tbl.xml == snippets[1]
assert isinstance(row, _Row)
assert row._tr is table._tbl.tr_lst[-1]
assert row._parent is table
def it_copies_cnfStyle_from_the_preceding_row_when_adding_a_row(
self, document_: Mock
):
"""``add_row`` propagates the prior row's ``w:trPr/w:cnfStyle`` so
conditional banding / firstRow / lastRow formatting flows to the new
row, matching Word's own behaviour. (upstream#306)
"""
# -- 1-col table, existing row has a cnfStyle flagging firstRow+oddHBand --
tbl_cxml = (
"w:tbl/(w:tblPr,w:tblGrid/w:gridCol{w:w=1000},"
"w:tr/(w:trPr/w:cnfStyle{w:val=100000000000},"
"w:tc/(w:tcPr/w:tcW{w:type=dxa,w:w=1000},w:p)))"
)
tbl = cast(CT_Tbl, element(tbl_cxml))
table = Table(tbl, document_)
table.add_row()
new_tr = tbl.tr_lst[-1]
trPr = new_tr.trPr
assert trPr is not None
from docx.oxml.ns import qn
cnfStyle = trPr.find(qn("w:cnfStyle"))
assert cnfStyle is not None
assert cnfStyle.get(qn("w:val")) == "100000000000"
def it_leaves_new_row_trPr_clean_when_predecessor_has_no_cnfStyle(
self, document_: Mock
):
"""Rows whose predecessor lacks ``cnfStyle`` must not get a spurious
``w:trPr`` element. (upstream#306 safety)
"""
snippets = snippet_seq("add-row-col")
tbl = cast(CT_Tbl, parse_xml(snippets[0]))
table = Table(tbl, document_)
table.add_row()
new_tr = table._tbl.tr_lst[-1]
# -- no cnfStyle on predecessor => no trPr on new row --
assert new_tr.trPr is None
@pytest.mark.parametrize(
("body_cxml", "tbl_idx", "expected_cxml"),
[
# --- table removed from body with paragraph sibling ---
("w:body/(w:tbl/w:tblPr,w:p)", 0, "w:body/w:p"),
# --- table removed leaving another table ---
("w:body/(w:tbl/w:tblPr,w:tbl/w:tblPr)", 0, "w:body/w:tbl/w:tblPr"),
# --- second table removed ---
("w:body/(w:p,w:tbl/w:tblPr,w:p)", 0, "w:body/(w:p,w:p)"),
],
)
def it_can_delete_itself(
self,
body_cxml: str,
tbl_idx: int,
expected_cxml: str,
document_: Mock,
):
body = element(body_cxml)
tbl = body.tbl_lst[tbl_idx]
table = Table(tbl, document_)
table.delete()
assert body.xml == xml(expected_cxml)
def it_can_add_a_column(self, document_: Mock):
snippets = snippet_seq("add-row-col")
tbl = cast(CT_Tbl, parse_xml(snippets[0]))
table = Table(tbl, document_)
column = table.add_column(Inches(1.5))
assert table._tbl.xml == snippets[2]
assert isinstance(column, _Column)
assert column._gridCol is table._tbl.tblGrid.gridCol_lst[-1]
assert column._parent is table
def it_add_column_inserts_a_tc_in_every_row(self, document_: Mock):
# -- regression for upstream#1102: `add_column` must append a `w:tc`
# -- in every row in addition to the new `w:gridCol`; otherwise the
# -- rendered document ends up with a grid-column count that doesn't
# -- match row cell counts and Word refuses to open the file. --
tbl = cast(
CT_Tbl,
element(
"w:tbl/(w:tblPr,w:tblGrid/(w:gridCol,w:gridCol),"
"w:tr/(w:tc/w:p,w:tc/w:p),"
"w:tr/(w:tc/w:p,w:tc/w:p))"
),
)
table = Table(tbl, document_)
original_row_tc_counts = [len(tr.tc_lst) for tr in tbl.tr_lst]
table.add_column(Inches(1.0))
new_row_tc_counts = [len(tr.tc_lst) for tr in tbl.tr_lst]
# -- every row gained exactly one new tc --
assert new_row_tc_counts == [n + 1 for n in original_row_tc_counts]
# -- tblGrid gained exactly one new gridCol --
assert len(tbl.tblGrid.gridCol_lst) == 3
# -- every row's total tc count now matches the grid column count --
for tr in tbl.tr_lst:
assert len(tr.tc_lst) == len(tbl.tblGrid.gridCol_lst)
def it_provides_access_to_a_cell_by_row_and_col_indices(self, table: Table):
for row_idx in range(2):
for col_idx in range(2):
cell = table.cell(row_idx, col_idx)
assert isinstance(cell, _Cell)
tr = table._tbl.tr_lst[row_idx]
tc = tr.tc_lst[col_idx]
assert tc is cell._tc
def it_provides_access_to_the_table_rows(self, table: Table):
rows = table.rows
assert isinstance(rows, _Rows)
def it_provides_access_to_the_table_columns(self, table: Table):
columns = table.columns
assert isinstance(columns, _Columns)
def it_provides_access_to_the_cells_in_a_column(
self, _cells_: Mock, _column_count_: Mock, document_: Mock
):
table = Table(cast(CT_Tbl, element("w:tbl")), document_)
_cells_.return_value = [0, 1, 2, 3, 4, 5, 6, 7, 8]
_column_count_.return_value = 3
column_idx = 1
column_cells = table.column_cells(column_idx)
assert column_cells == [1, 4, 7]
def it_provides_access_to_the_cells_in_a_row(
self, _cells_: Mock, _column_count_: Mock, document_: Mock
):
table = Table(cast(CT_Tbl, element("w:tbl")), document_)
_cells_.return_value = [0, 1, 2, 3, 4, 5, 6, 7, 8]
_column_count_.return_value = 3
with pytest.warns(DeprecationWarning, match="row_cells"):
row_cells = table.row_cells(1)
assert row_cells == [3, 4, 5]
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:jc{w:val=center}", WD_TABLE_ALIGNMENT.CENTER),
("w:tbl/w:tblPr/w:jc{w:val=right}", WD_TABLE_ALIGNMENT.RIGHT),
("w:tbl/w:tblPr/w:jc{w:val=left}", WD_TABLE_ALIGNMENT.LEFT),
],
)
def it_knows_its_alignment_setting(
self, tbl_cxml: str, expected_value: WD_TABLE_ALIGNMENT | None, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.alignment == expected_value
@pytest.mark.parametrize(
("tbl_cxml", "new_value", "expected_cxml"),
[
("w:tbl/w:tblPr", WD_TABLE_ALIGNMENT.LEFT, "w:tbl/w:tblPr/w:jc{w:val=left}"),
(
"w:tbl/w:tblPr/w:jc{w:val=left}",
WD_TABLE_ALIGNMENT.RIGHT,
"w:tbl/w:tblPr/w:jc{w:val=right}",
),
("w:tbl/w:tblPr/w:jc{w:val=right}", None, "w:tbl/w:tblPr"),
],
)
def it_can_change_its_alignment_setting(
self,
tbl_cxml: str,
new_value: WD_TABLE_ALIGNMENT | None,
expected_cxml: str,
document_: Mock,
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
table.alignment = new_value
assert table._tbl.xml == xml(expected_cxml)
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
("w:tbl/w:tblPr", True),
("w:tbl/w:tblPr/w:tblLayout", True),
("w:tbl/w:tblPr/w:tblLayout{w:type=autofit}", True),
("w:tbl/w:tblPr/w:tblLayout{w:type=fixed}", False),
],
)
def it_knows_whether_it_should_autofit(
self, tbl_cxml: str, expected_value: bool, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.autofit is expected_value
@pytest.mark.parametrize(
("tbl_cxml", "new_value", "expected_cxml"),
[
("w:tbl/w:tblPr", True, "w:tbl/w:tblPr/w:tblLayout{w:type=autofit}"),
("w:tbl/w:tblPr", False, "w:tbl/w:tblPr/w:tblLayout{w:type=fixed}"),
(
"w:tbl/w:tblPr/w:tblLayout{w:type=fixed}",
True,
"w:tbl/w:tblPr/w:tblLayout{w:type=autofit}",
),
(
"w:tbl/w:tblPr/w:tblLayout{w:type=autofit}",
False,
"w:tbl/w:tblPr/w:tblLayout{w:type=fixed}",
),
],
)
def it_can_change_its_autofit_setting(
self, tbl_cxml: str, new_value: bool, expected_cxml: str, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
table.autofit = new_value
assert table._tbl.xml == xml(expected_cxml)
def it_can_autofit_column_widths_to_cell_content(self, document_: Mock):
# -- build a 3x5 table with distinctly varying content lengths --
import docx
doc = docx.Document()
table = doc.add_table(rows=3, cols=5)
# -- column 2 has the widest content; column 0 and 4 are narrowest --
contents = [
["x", "medium text", "a lot longer content here", "mid", "ab"],
["yy", "short", "longer", "m", "c"],
["z", "m2", "l1", "mmid", "x"],
]
for r_idx, row in enumerate(table.rows):
for c_idx, cell in enumerate(row.cells):
cell.text = contents[r_idx][c_idx]
widths = table.autofit_to_content()
# -- 5 columns returned, all Length-typed --
assert len(widths) == 5
assert all(isinstance(w, Length) for w in widths)
# -- widest is col 2 (len 25), then col 1 (len 11), col 3 (len 4) --
assert widths[2].twips > widths[1].twips > widths[3].twips > widths[0].twips
# -- strict proportionality for the widest column at default 100 twips/char --
assert widths[2].twips == 25 * 100
assert widths[1].twips == 11 * 100
assert widths[0].twips == 2 * 100
# -- layout switched to fixed (autofit now reports False) --
assert table.autofit is False
# -- gridCol widths written, and tcW propagated to every cell --
for c_idx, col in enumerate(table.columns):
assert col.width == widths[c_idx]
for cell in col.cells:
assert cell.width == widths[c_idx]
def it_honours_autofit_char_width_twips_override(self, document_: Mock):
import docx
doc = docx.Document()
table = doc.add_table(rows=1, cols=2)
table.cell(0, 0).text = "abc"
table.cell(0, 1).text = "longer"
table.autofit_char_width_twips = 50
widths = table.autofit_to_content()
assert widths[0].twips == 3 * 50
assert widths[1].twips == 6 * 50
def it_uses_widest_line_for_multi_line_cells(self, document_: Mock):
import docx
doc = docx.Document()
table = doc.add_table(rows=1, cols=2)
table.cell(0, 0).text = "short" # 5
# -- multi-paragraph cell: widest line is 20 chars --
cell = table.cell(0, 1)
cell.text = "tiny" # first p
cell.add_paragraph("twenty-chars-exactly") # 20
widths = table.autofit_to_content()
assert widths[0].twips == 5 * 100
assert widths[1].twips == 20 * 100
def it_returns_empty_list_for_tables_with_no_columns(self, document_: Mock):
tbl_cxml = "w:tbl/(w:tblPr,w:tblGrid)"
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.autofit_to_content() == []
def it_can_autofit_columns_evenly_to_window(self, document_: Mock):
tbl_cxml = (
"w:tbl/(w:tblPr,w:tblGrid/(w:gridCol,w:gridCol,w:gridCol,w:gridCol),"
"w:tr/(w:tc/w:p,w:tc/w:p,w:tc/w:p,w:tc/w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
table.autofit_to_window()
tblPr = table._tblPr
# -- 100% total width via tblW pct=5000 --
assert tblPr.tblW.type == "pct"
assert tblPr.tblW.w == 5000
# -- tblLayout type is autofit --
assert tblPr.tblLayout is not None
assert tblPr.tblLayout.type == "autofit"
# -- every cell has tcW pct=1250 (5000 // 4) --
for tc in table._tbl.tr_lst[0].tc_lst:
tcW = tc.tcPr.tcW
assert tcW is not None
assert tcW.type == "pct"
assert tcW.w == 1250
def it_can_set_fixed_width_columns(self, document_: Mock):
import docx
doc = docx.Document()
table = doc.add_table(rows=2, cols=3)
table.fixed_width_columns([Inches(1), Inches(2), Inches(3)])
# -- layout is fixed --
assert table.autofit is False
# -- each column has its explicit width on both gridCol and every tc --
expected = [Inches(1), Inches(2), Inches(3)]
for c_idx, col in enumerate(table.columns):
assert col.width == expected[c_idx]
for cell in col.cells:
assert cell.width == expected[c_idx]
def it_raises_when_fixed_widths_mismatch_column_count(self, document_: Mock):
import docx
doc = docx.Document()
table = doc.add_table(rows=1, cols=3)
with pytest.raises(ValueError, match="does not match column count"):
table.fixed_width_columns([Inches(1), Inches(2)])
def it_knows_it_is_the_table_its_children_belong_to(self, table: Table):
assert table.table is table
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:bidiVisual", WD_TABLE_DIRECTION.RTL),
("w:tbl/w:tblPr/w:bidiVisual{w:val=0}", WD_TABLE_DIRECTION.LTR),
("w:tbl/w:tblPr/w:bidiVisual{w:val=on}", WD_TABLE_DIRECTION.RTL),
],
)
def it_knows_its_direction(
self, tbl_cxml: str, expected_value: WD_TABLE_DIRECTION | None, document_: Mock
):
tbl = cast(CT_Tbl, element(tbl_cxml))
assert Table(tbl, document_).table_direction == expected_value
@pytest.mark.parametrize(
("tbl_cxml", "new_value", "expected_cxml"),
[
("w:tbl/w:tblPr", WD_TABLE_DIRECTION.RTL, "w:tbl/w:tblPr/w:bidiVisual"),
(
"w:tbl/w:tblPr/w:bidiVisual",
WD_TABLE_DIRECTION.LTR,
"w:tbl/w:tblPr/w:bidiVisual{w:val=0}",
),
(
"w:tbl/w:tblPr/w:bidiVisual{w:val=0}",
WD_TABLE_DIRECTION.RTL,
"w:tbl/w:tblPr/w:bidiVisual",
),
("w:tbl/w:tblPr/w:bidiVisual{w:val=1}", None, "w:tbl/w:tblPr"),
],
)
def it_can_change_its_direction(
self, tbl_cxml: str, new_value: WD_TABLE_DIRECTION, expected_cxml: str, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
table.table_direction = new_value
assert table._element.xml == xml(expected_cxml)
def it_exposes_direction_as_an_upstream_compatible_alias(self, document_: Mock):
"""`Table.direction` is an alias of `table_direction` (upstream#1227).
loadfix renamed the property to ``table_direction``; the alias
preserves upstream-name compatibility.
"""
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
# -- read delegates to table_direction --
assert table.direction is None
# -- write delegates to table_direction --
table.direction = WD_TABLE_DIRECTION.RTL
assert table.table_direction == WD_TABLE_DIRECTION.RTL
assert table.direction == WD_TABLE_DIRECTION.RTL
assert table._element.xml == xml("w:tbl/w:tblPr/w:bidiVisual")
table.direction = None
assert table.table_direction is None
assert table._element.xml == xml("w:tbl/w:tblPr")
def it_knows_its_table_style(self, part_prop_: Mock, document_part_: Mock, document_: Mock):
part_prop_.return_value = document_part_
style_ = document_part_.get_style.return_value
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblStyle{w:val=BarBaz}")), document_)
style = table.style
document_part_.get_style.assert_called_once_with("BarBaz", WD_STYLE_TYPE.TABLE)
assert style is style_
@pytest.mark.parametrize(
("tbl_cxml", "new_value", "style_id", "expected_cxml"),
[
("w:tbl/w:tblPr", "Tbl A", "TblA", "w:tbl/w:tblPr/w:tblStyle{w:val=TblA}"),
(
"w:tbl/w:tblPr/w:tblStyle{w:val=TblA}",
"Tbl B",
"TblB",
"w:tbl/w:tblPr/w:tblStyle{w:val=TblB}",
),
("w:tbl/w:tblPr/w:tblStyle{w:val=TblB}", None, None, "w:tbl/w:tblPr"),
],
)
def it_can_change_its_table_style(
self,
tbl_cxml: str,
new_value: str | None,
style_id: str | None,
expected_cxml: str,
document_: Mock,
part_prop_: Mock,
document_part_: Mock,
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
part_prop_.return_value = document_part_
document_part_.get_style_id.return_value = style_id
table.style = new_value
document_part_.get_style_id.assert_called_once_with(new_value, WD_STYLE_TYPE.TABLE)
assert table._tbl.xml == xml(expected_cxml)
@pytest.mark.parametrize(
("snippet_idx", "cell_count", "unique_count", "matches"),
[
(0, 9, 9, ()),
(1, 9, 8, ((0, 1),)),
(2, 9, 8, ((1, 4),)),
(3, 9, 6, ((0, 1, 3, 4),)),
(4, 9, 4, ((0, 1), (3, 6), (4, 5, 7, 8))),
],
)
def it_provides_access_to_its_cells_to_help(
self,
snippet_idx: int,
cell_count: int,
unique_count: int,
matches: tuple[tuple[int, ...]],
document_: Mock,
):
tbl_xml = snippet_seq("tbl-cells")[snippet_idx]
table = Table(cast(CT_Tbl, parse_xml(tbl_xml)), document_)
cells = table._cells
assert len(cells) == cell_count
assert len(set(cells)) == unique_count
for matching_idxs in matches:
comparator_idx = matching_idxs[0]
for idx in matching_idxs[1:]:
assert cells[idx] is cells[comparator_idx]
def it_knows_its_column_count_to_help(self, document_: Mock):
tbl_cxml = "w:tbl/w:tblGrid/(w:gridCol,w:gridCol,w:gridCol)"
expected_value = 3
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
column_count = table._column_count
assert column_count == expected_value
def it_synthesises_column_count_when_tblGrid_is_missing(self, document_: Mock):
"""A ``w:tbl`` without ``w:tblGrid`` is invalid per ISO-29500 but is
commonly emitted by LibreOffice and PDF-to-docx converters.
Prior to the fix, :attr:`Table._column_count` raised
``InvalidXmlError``. After the fix, the column count is derived from
the widest row (honouring ``gridBefore``/``gridAfter``). Closes
upstream#548.
"""
# -- 3-column widest row, no tblGrid --
tbl_cxml = (
"w:tbl/(w:tblPr,"
"w:tr/(w:tc/w:p,w:tc/w:p,w:tc/w:p),"
"w:tr/(w:tc/w:p,w:tc/w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
# -- should not raise --
assert table._column_count == 3
def it_tolerates_orphan_vMerge_continuation_in_top_row(self, document_: Mock):
"""A vMerge="continue" in the first row has no row above to delegate to.
Without the hardening, ``Table._cells`` would index ``cells[-col_count]``
on an empty-or-short list and raise. After the fix it emits a fresh
cell for the orphan tc.
"""
tbl_cxml = (
"w:tbl/(w:tblGrid/(w:gridCol,w:gridCol),"
"w:tr/(w:tc/w:p,w:tc/(w:tcPr/w:vMerge,w:p)))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
cells = table._cells
assert len(cells) == 2
# -- both cells should resolve to real _Cell objects --
assert all(isinstance(c, _Cell) for c in cells)
def it_resolves_every_continuation_in_a_multi_row_vMerge_span(
self, document_: Mock
):
"""vMerge="restart" + several vMerge (continue) cells all alias to origin."""
tbl_cxml = (
"w:tbl/(w:tblGrid/w:gridCol,"
"w:tr/w:tc/(w:tcPr/w:vMerge{w:val=restart},w:p),"
"w:tr/w:tc/(w:tcPr/w:vMerge,w:p),"
"w:tr/w:tc/(w:tcPr/w:vMerge,w:p),"
"w:tr/w:tc/(w:tcPr/w:vMerge,w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
cells = table._cells
# -- 4 rows * 1 column = 4 grid positions, all the same cell object --
assert len(cells) == 4
assert len(set(cells)) == 1
def it_preserves_nested_table_access_inside_a_merged_origin_cell(
self, document_: Mock
):
"""Nested ``w:tbl`` inside a vMerge origin cell should remain discoverable."""
tbl_cxml = (
"w:tbl/(w:tblGrid/w:gridCol,"
"w:tr/w:tc/(w:tcPr/w:vMerge{w:val=restart},w:p,"
"w:tbl/(w:tblGrid/w:gridCol,w:tr/w:tc/w:p),"
"w:p),"
"w:tr/w:tc/(w:tcPr/w:vMerge,w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
# -- _cells should aggregate correctly (both rows point to origin) --
cells = table._cells
assert len(cells) == 2
assert cells[0] is cells[1]
# -- origin cell should expose its nested table --
origin = cells[0]
assert len(origin.tables) == 1
def it_honours_grid_before_when_flattening_cells(self, document_: Mock):
"""``w:gridBefore`` shifts the row's real cells to later columns.
Prior to the fix, ``Table._cells`` ignored ``w:gridBefore`` so a row
that skipped leading columns would leak its cells into preceding
columns, breaking ``Table.cell(r, c)`` and ``Table.column_cells(c)``
arithmetic. (upstream#939, #1367)
"""
# -- 3x3 grid; row 1 has gridBefore=1 so its two cells live at cols 1-2 --
tbl_cxml = (
"w:tbl/(w:tblGrid/(w:gridCol,w:gridCol,w:gridCol),"
"w:tr/(w:tc/w:p,w:tc/w:p,w:tc/w:p),"
"w:tr/(w:trPr/w:gridBefore{w:val=1},w:tc/w:p,w:tc/w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
cells = table._cells
# -- grid is 3 rows? no: 2 rows * 3 cols = 6 slots --
assert len(cells) == 6
# -- real tc elements for row 1 live at grid columns 1 and 2 --
row1_real_tc_0 = table._tbl.tr_lst[1].tc_lst[0]
row1_real_tc_1 = table._tbl.tr_lst[1].tc_lst[1]
assert table.cell(1, 1)._tc is row1_real_tc_0
assert table.cell(1, 2)._tc is row1_real_tc_1
# -- column 0 should NOT leak the row-1 real tc into row-1, col-0 --
assert table.cell(1, 0)._tc is not row1_real_tc_0
# -- column_cells(2) must pick up the second real tc of row 1 --
col2 = table.column_cells(2)
assert col2[1]._tc is row1_real_tc_1
def it_honours_grid_after_when_flattening_cells(self, document_: Mock):
"""``w:gridAfter`` lets a row end early; omitted slots must not pull
later-column cells into those positions. (upstream#1334, #1193)
"""
tbl_cxml = (
"w:tbl/(w:tblGrid/(w:gridCol,w:gridCol,w:gridCol),"
"w:tr/(w:tc/w:p,w:tc/w:p,w:tc/w:p),"
"w:tr/(w:trPr/w:gridAfter{w:val=1},w:tc/w:p,w:tc/w:p))"
)
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
cells = table._cells
assert len(cells) == 6 # -- 2 rows * 3 cols --
# -- row 1 real cells live at columns 0 and 1 --
row1_real_tc_0 = table._tbl.tr_lst[1].tc_lst[0]
row1_real_tc_1 = table._tbl.tr_lst[1].tc_lst[1]
assert table.cell(1, 0)._tc is row1_real_tc_0
assert table.cell(1, 1)._tc is row1_real_tc_1
# -- column 2 in row 1 is omitted; placeholder comes from row above --
row0_real_tc_2 = table._tbl.tr_lst[0].tc_lst[2]
assert table.cell(1, 2)._tc is row0_real_tc_2
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
# -- no tblLayout, no tblW → autofit-to-contents is the OOXML default --
("w:tbl/w:tblPr", WD_TABLE_AUTOFIT.AUTOFIT_TO_CONTENTS),
# -- explicit w:tblLayout=autofit with auto tblW --
(
"w:tbl/w:tblPr/(w:tblW{w:type=auto,w:w=0},w:tblLayout{w:type=autofit})",
WD_TABLE_AUTOFIT.AUTOFIT_TO_CONTENTS,
),
# -- tblLayout=autofit with tblW type=pct means autofit-to-window --
(
"w:tbl/w:tblPr/w:tblW{w:type=pct,w:w=5000}",
WD_TABLE_AUTOFIT.AUTOFIT_TO_WINDOW,
),
# -- tblLayout=fixed always wins --
(
"w:tbl/w:tblPr/(w:tblW{w:type=pct,w:w=5000},w:tblLayout{w:type=fixed})",
WD_TABLE_AUTOFIT.FIXED_WIDTH,
),
(
"w:tbl/w:tblPr/w:tblLayout{w:type=fixed}",
WD_TABLE_AUTOFIT.FIXED_WIDTH,
),
],
)
def it_knows_its_autofit_behavior(
self, tbl_cxml: str, expected_value: WD_TABLE_AUTOFIT, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.autofit_behavior == expected_value
def it_can_change_its_autofit_behavior_to_fixed(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.autofit_behavior = WD_TABLE_AUTOFIT.FIXED_WIDTH
assert table.autofit_behavior == WD_TABLE_AUTOFIT.FIXED_WIDTH
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblLayout{w:type=fixed}")
def it_can_change_its_autofit_behavior_to_autofit_to_contents(self, document_: Mock):
table = Table(
cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblLayout{w:type=fixed}")),
document_,
)
table.autofit_behavior = WD_TABLE_AUTOFIT.AUTOFIT_TO_CONTENTS
assert table.autofit_behavior == WD_TABLE_AUTOFIT.AUTOFIT_TO_CONTENTS
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblW{w:type=auto,w:w=0}")
def it_can_change_its_autofit_behavior_to_autofit_to_window(self, document_: Mock):
table = Table(
cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblLayout{w:type=fixed}")),
document_,
)
table.autofit_behavior = WD_TABLE_AUTOFIT.AUTOFIT_TO_WINDOW
assert table.autofit_behavior == WD_TABLE_AUTOFIT.AUTOFIT_TO_WINDOW
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblW{w:type=pct,w:w=5000}")
def it_roundtrips_each_autofit_behavior_value(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
for value in (
WD_TABLE_AUTOFIT.FIXED_WIDTH,
WD_TABLE_AUTOFIT.AUTOFIT_TO_CONTENTS,
WD_TABLE_AUTOFIT.AUTOFIT_TO_WINDOW,
WD_TABLE_AUTOFIT.FIXED_WIDTH,
):
table.autofit_behavior = value
assert table.autofit_behavior == value
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
("w:tbl/w:tblPr", True),
("w:tbl/w:tblPr/w:tblLayout", True),
("w:tbl/w:tblPr/w:tblLayout{w:type=autofit}", True),
("w:tbl/w:tblPr/w:tblLayout{w:type=fixed}", False),
],
)
def it_knows_whether_it_allows_autofit(
self, tbl_cxml: str, expected_value: bool, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.allow_autofit is expected_value
@pytest.mark.parametrize(
("tbl_cxml", "new_value", "expected_cxml"),
[
# -- turning autofit off writes an explicit tblLayout=fixed --
("w:tbl/w:tblPr", False, "w:tbl/w:tblPr/w:tblLayout{w:type=fixed}"),
(
"w:tbl/w:tblPr/w:tblLayout{w:type=fixed}",
True,
"w:tbl/w:tblPr",
),
# -- turning autofit on removes the tblLayout child entirely --
(
"w:tbl/w:tblPr/w:tblLayout{w:type=autofit}",
True,
"w:tbl/w:tblPr",
),
(
"w:tbl/w:tblPr/w:tblLayout{w:type=autofit}",
False,
"w:tbl/w:tblPr/w:tblLayout{w:type=fixed}",
),
],
)
def it_can_change_whether_it_allows_autofit(
self, tbl_cxml: str, new_value: bool, expected_cxml: str, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
table.allow_autofit = new_value
assert table._tbl.xml == xml(expected_cxml)
@pytest.mark.parametrize(
("tbl_cxml", "expected_value"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:tblW{w:type=auto,w:w=0}", None),
("w:tbl/w:tblPr/w:tblW{w:type=pct,w:w=5000}", None),
("w:tbl/w:tblPr/w:tblW{w:type=dxa,w:w=1440}", 914400),
("w:tbl/w:tblPr/w:tblW{w:type=dxa,w:w=4680}", 2971800),
],
)
def it_knows_its_preferred_width(
self, tbl_cxml: str, expected_value: int | None, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.preferred_width == expected_value
def it_can_change_its_preferred_width(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.preferred_width = Inches(1)
assert table.preferred_width == Inches(1)
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblW{w:type=dxa,w:w=1440}")
def it_can_clear_its_preferred_width(self, document_: Mock):
table = Table(
cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblW{w:type=dxa,w:w=1440}")),
document_,
)
table.preferred_width = None
assert table.preferred_width is None
assert table._tbl.xml == xml("w:tbl/w:tblPr")
def it_can_overwrite_an_existing_preferred_width(self, document_: Mock):
table = Table(
cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblW{w:type=auto,w:w=0}")),
document_,
)
table.preferred_width = Inches(2)
assert table.preferred_width == Inches(2)
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblW{w:type=dxa,w:w=2880}")
# -- alt_text / alt_description (upstream#1048, #921) ------------
@pytest.mark.parametrize(
("tbl_cxml", "expected"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:tblCaption{w:val=Sales}", "Sales"),
],
)
def it_knows_its_alt_text(
self, tbl_cxml: str, expected: str | None, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.alt_text == expected
def it_can_set_its_alt_text(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.alt_text = "Quarterly sales"
assert table.alt_text == "Quarterly sales"
assert table._tbl.xml == xml(
"w:tbl/w:tblPr/w:tblCaption{w:val=Quarterly sales}"
)
def it_can_clear_its_alt_text(self, document_: Mock):
table = Table(
cast(
CT_Tbl,
element("w:tbl/w:tblPr/w:tblCaption{w:val=x}"),
),
document_,
)
table.alt_text = None
assert table.alt_text is None
assert table._tbl.xml == xml("w:tbl/w:tblPr")
@pytest.mark.parametrize(
("tbl_cxml", "expected"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:tblDescription{w:val=Monthly totals}", "Monthly totals"),
],
)
def it_knows_its_alt_description(
self, tbl_cxml: str, expected: str | None, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.alt_description == expected
def it_can_set_and_clear_its_alt_description(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.alt_description = "A long description"
assert table.alt_description == "A long description"
assert table._tbl.xml == xml(
"w:tbl/w:tblPr/w:tblDescription{w:val=A long description}"
)
table.alt_description = None
assert table.alt_description is None
# -- indent / left_indent (upstream#1144, #586) ------------------
@pytest.mark.parametrize(
("tbl_cxml", "expected"),
[
("w:tbl/w:tblPr", None),
("w:tbl/w:tblPr/w:tblInd{w:w=720,w:type=dxa}", Twips(720)),
],
)
def it_knows_its_indent(
self, tbl_cxml: str, expected: Length | None, document_: Mock
):
table = Table(cast(CT_Tbl, element(tbl_cxml)), document_)
assert table.indent == expected
assert table.left_indent == expected
def it_can_change_its_indent(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.indent = Inches(0.5)
assert table.indent == Inches(0.5)
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblInd{w:w=720,w:type=dxa}")
def it_left_indent_is_an_alias_of_indent(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.left_indent = Inches(1)
assert table.indent == Inches(1)
assert table._tbl.xml == xml("w:tbl/w:tblPr/w:tblInd{w:w=1440,w:type=dxa}")
def it_can_clear_its_indent(self, document_: Mock):
table = Table(
cast(CT_Tbl, element("w:tbl/w:tblPr/w:tblInd{w:w=720,w:type=dxa}")),
document_,
)
table.indent = None
assert table.indent is None
assert table._tbl.xml == xml("w:tbl/w:tblPr")
# -- cell_margins (upstream#1401) --------------------------------
def it_exposes_cell_margins_as_a_TableCellMargins(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
assert isinstance(table.cell_margins, TableCellMargins)
def it_reads_None_for_every_cell_margin_edge_when_absent(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
m = table.cell_margins
assert m.top is None
assert m.bottom is None
assert m.start is None
assert m.end is None
def it_creates_tblCellMar_on_first_write(self, document_: Mock):
table = Table(cast(CT_Tbl, element("w:tbl/w:tblPr")), document_)
table.cell_margins.top = Twips(100)
assert table.cell_margins.top == Twips(100)
assert table._tbl.xml == xml(
"w:tbl/w:tblPr/w:tblCellMar/w:top{w:w=100,w:type=dxa}"
)
def it_removes_empty_tblCellMar_when_last_edge_cleared(self, document_: Mock):
table = Table(
cast(
CT_Tbl,
element("w:tbl/w:tblPr/w:tblCellMar/w:top{w:w=100,w:type=dxa}"),
),
document_,
)
table.cell_margins.top = None
assert table._tbl.xml == xml("w:tbl/w:tblPr")
# -- merged_cell_ranges (PR#1036) --------------------------------
def it_returns_empty_list_when_no_merged_cells(self, document_: Mock):
tbl = cast(
CT_Tbl,
element("w:tbl/(w:tblPr,w:tblGrid/(w:gridCol,w:gridCol),w:tr/(w:tc,w:tc))"),
)
table = Table(tbl, document_)
assert table.merged_cell_ranges() == []
def it_reports_horizontal_merge_range(self, document_: Mock):
tbl = cast(
CT_Tbl,
element(
"w:tbl/("
"w:tblPr,"
"w:tblGrid/(w:gridCol,w:gridCol,w:gridCol),"
"w:tr/("
"w:tc/w:tcPr/w:gridSpan{w:val=2},"
"w:tc)"
")"
),