Skip to content

Commit 3e09234

Browse files
committed
bmk: add Bookmarks.__len__()
1 parent e17e50d commit 3e09234

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

docx/bookmark.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,40 @@
66
absolute_import, division, print_function, unicode_literals
77
)
88

9+
from docx.shared import lazyproperty
10+
911

1012
class Bookmarks(object):
1113
"""Sequence of |Bookmark| objects."""
1214

1315
def __init__(self, document_part):
1416
self._document_part = document_part
17+
18+
def __len__(self):
19+
return len(self._finder.bookmark_pairs)
20+
21+
@lazyproperty
22+
def _finder(self):
23+
"""_DocumentBookmarkFinder instance for this document."""
24+
raise NotImplementedError
25+
26+
27+
class _DocumentBookmarkFinder(object):
28+
"""Provides access to bookmark oxml elements in an overall document."""
29+
30+
@property
31+
def bookmark_pairs(self):
32+
"""List of (bookmarkStart, bookmarkEnd) element pairs for document.
33+
34+
The return value is a list of two-tuples (pairs) each containing
35+
a start and its matching end element.
36+
37+
All story parts of the document are searched, including the main
38+
document story, headers, footers, footnotes, and endnotes. The order
39+
of part searching is not guaranteed, but bookmarks appear in document
40+
order within a particular part. Only well-formed bookmarks appear.
41+
Any open bookmarks (start but no end), reversed bookmarks (end before
42+
start), or duplicate (name same as prior bookmark) bookmarks are
43+
ignored.
44+
"""
45+
raise NotImplementedError

tests/test_bookmark.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# encoding: utf-8
2+
3+
"""Test suite for the docx.bookmark module."""
4+
5+
from __future__ import (
6+
absolute_import, division, print_function, unicode_literals
7+
)
8+
9+
import pytest
10+
11+
from docx.bookmark import Bookmarks, _DocumentBookmarkFinder
12+
13+
from .unitutil.mock import instance_mock, property_mock
14+
15+
16+
class DescribeBookmarks(object):
17+
18+
def it_knows_how_many_bookmarks_the_document_contains(
19+
self, _finder_prop_, finder_):
20+
_finder_prop_.return_value = finder_
21+
finder_.bookmark_pairs = tuple((1, 2) for _ in range(42))
22+
bookmarks = Bookmarks(None)
23+
24+
count = len(bookmarks)
25+
26+
assert count == 42
27+
28+
# fixture components ---------------------------------------------
29+
30+
@pytest.fixture
31+
def finder_(self, request):
32+
return instance_mock(request, _DocumentBookmarkFinder)
33+
34+
@pytest.fixture
35+
def _finder_prop_(self, request):
36+
return property_mock(request, Bookmarks, '_finder')

0 commit comments

Comments
 (0)