Skip to content

Commit 422c504

Browse files
author
Steve Canny
committed
doc: add _Document.next_id
1 parent aa84f3b commit 422c504

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

docx/parts/document.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,11 @@ def next_id(self):
6969
in id sequence are filled. The id attribute value is unique in the
7070
document, without regard to the element type it appears on.
7171
"""
72-
raise NotImplementedError
72+
id_str_lst = self._element.xpath('//@id')
73+
used_ids = [int(id_str) for id_str in id_str_lst]
74+
for n in range(1, len(used_ids)+2):
75+
if n not in used_ids:
76+
return n
7377

7478
@property
7579
def part(self):

tests/parts/test_document.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ def it_provides_access_to_the_inline_shapes_in_the_document(
8989
def it_knows_it_is_the_part_its_child_objects_belong_to(self, document):
9090
assert document.part is document
9191

92+
def it_knows_the_next_available_xml_id(self, next_id_fixture):
93+
document, expected_id = next_id_fixture
94+
assert document.next_id == expected_id
95+
9296
# fixtures -------------------------------------------------------
9397

9498
@pytest.fixture
@@ -157,6 +161,20 @@ def inline_shapes_fixture(self, request, InlineShapes_):
157161
document = _Document(None, None, document_elm, None)
158162
return document, InlineShapes_, body_elm
159163

164+
@pytest.fixture(params=[
165+
((), 1), ((1,), 2), ((2,), 1), ((1, 2, 3), 4), ((1, 2, 4), 3),
166+
((0, 0), 1), ((0, 0, 1, 3), 2),
167+
])
168+
def next_id_fixture(self, request):
169+
existing_ids, expected_id = request.param
170+
document_elm = a_document().with_nsdecls().element
171+
for n in existing_ids:
172+
p = a_p().with_nsdecls().element
173+
p.set('id', str(n))
174+
document_elm.append(p)
175+
document = _Document(None, None, document_elm, None)
176+
return document, expected_id
177+
160178
@pytest.fixture
161179
def oxml_fromstring_(self, request):
162180
return function_mock(request, 'docx.parts.document.oxml_fromstring')

0 commit comments

Comments
 (0)