Skip to content

Commit 71f4d03

Browse files
author
Steve Canny
committed
shr: add ElementProxy.__eq__()
1 parent 013f32f commit 71f4d03

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

docx/shared.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,37 @@ def write_only_property(f):
164164
return property(fset=f, doc=docstring)
165165

166166

167+
class ElementProxy(object):
168+
"""
169+
Base class for lxml element proxy classes. An element proxy class is one
170+
whose primary responsibilities are fulfilled by manipulating the
171+
attributes and child elements of an XML element. They are the most common
172+
type of class in python-docx other than custom element (oxml) classes.
173+
"""
174+
175+
__slots__ = ('_element',)
176+
177+
def __init__(self, element):
178+
self._element = element
179+
180+
def __eq__(self, other):
181+
"""
182+
Return |True| if this proxy object refers to the same oxml element as
183+
does *other*. ElementProxy objects are value objects and should
184+
maintain no mutable local state. Equality for proxy objects is
185+
defined as referring to the same XML element, whether or not they are
186+
the same proxy object instance.
187+
"""
188+
if not isinstance(other, ElementProxy):
189+
return False
190+
return self._element is other._element
191+
192+
def __ne__(self, other):
193+
if not isinstance(other, ElementProxy):
194+
return True
195+
return self._element is not other._element
196+
197+
167198
class Parented(object):
168199
"""
169200
Provides common services for document elements that occur below a part

tests/test_shared.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# encoding: utf-8
2+
3+
"""
4+
Test suite for the docx.shared module
5+
"""
6+
7+
from __future__ import (
8+
absolute_import, division, print_function, unicode_literals
9+
)
10+
11+
import pytest
12+
13+
from docx.shared import ElementProxy
14+
15+
from .unitutil.cxml import element
16+
17+
18+
class DescribeElementProxy(object):
19+
20+
def it_knows_when_its_equal_to_another_proxy_object(self, eq_fixture):
21+
proxy, proxy_2, proxy_3, not_a_proxy = eq_fixture
22+
23+
assert (proxy == proxy_2) is True
24+
assert (proxy == proxy_3) is False
25+
assert (proxy == not_a_proxy) is False
26+
27+
assert (proxy != proxy_2) is False
28+
assert (proxy != proxy_3) is True
29+
assert (proxy != not_a_proxy) is True
30+
31+
# fixture --------------------------------------------------------
32+
33+
@pytest.fixture
34+
def eq_fixture(self):
35+
p, q = element('w:p'), element('w:p')
36+
proxy = ElementProxy(p)
37+
proxy_2 = ElementProxy(p)
38+
proxy_3 = ElementProxy(q)
39+
not_a_proxy = 'Foobar'
40+
return proxy, proxy_2, proxy_3, not_a_proxy

0 commit comments

Comments
 (0)