Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e65ec0d

Browse files
committed
bmk: add _Bookmark.close()
1 parent 9be433b commit e65ec0d

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

docx/bookmark.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ def close(self, bookmarkEnd):
8282
Raises ValueError if this bookmark is already closed or if `id` attribute of
8383
`bookmarkEnd` does not match that of the `bookmarkStart` element.
8484
"""
85-
raise NotImplementedError
85+
if self._bookmarkEnd is not None:
86+
raise ValueError("bookmark already closed")
87+
if bookmarkEnd.id != self._bookmarkStart.id:
88+
raise ValueError("end id does not match start id")
89+
self._bookmarkEnd = bookmarkEnd
90+
return self
8691

8792
@property
8893
def id(self):

tests/test_bookmark.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,33 @@ def _iter_(self, request):
206206
class Describe_Bookmark(object):
207207
"""Unit-test suite for `docx.bookmark._Bookmark` object."""
208208

209+
def it_can_close_itself_when_open(self):
210+
bookmarkStart = element("w:bookmarkStart{w:id=42}")
211+
bookmarkEnd = element("w:bookmarkEnd{w:id=42}")
212+
bookmark = _Bookmark((bookmarkStart, None))
213+
214+
return_value = bookmark.close(bookmarkEnd)
215+
216+
assert bookmark._bookmarkEnd == bookmarkEnd
217+
assert return_value is bookmark
218+
219+
def but_it_raises_if_it_is_already_closed(self):
220+
bookmarkEnd = element("w:bookmarkEnd")
221+
bookmark = _Bookmark((None, bookmarkEnd))
222+
223+
with pytest.raises(ValueError) as e:
224+
bookmark.close(bookmarkEnd)
225+
assert "bookmark already closed" in str(e.value)
226+
227+
def and_it_raises_if_the_ids_dont_match(self):
228+
bookmarkStart = element("w:bookmarkStart{w:id=42}")
229+
bookmarkEnd = element("w:bookmarkEnd{w:id=24}")
230+
bookmark = _Bookmark((bookmarkStart, None))
231+
232+
with pytest.raises(ValueError) as e:
233+
bookmark.close(bookmarkEnd)
234+
assert "end id does not match start id" in str(e.value)
235+
209236
def it_knows_its_id(self):
210237
bookmarkStart = element("w:bookmarkStart{w:id=42}")
211238
bookmarkEnd = element("w:bookmarkEnd")

0 commit comments

Comments
 (0)