Debian Codegraph @

tests/test_special_methods_access.py

raw
1 """
2 The methods of the `NodeMixin` class should not access the user class special methods.
3
4 For instance, the user define a `MyNode` class as below:
5
6 ```python
7 from anytree import NodeMixin
8
9
10 class MyNode(NodeMixin):
11 def __init__(self, name, parent=None, children=None):
12 super(MyNode, self).__init__()
13 self.name = name
14 self.parent = parent
15 if children:
16 self.children = children
17 ```
18
19 In this class, the used can implement some special methods, like ``__eq__`` or ``__len__``,
20 which can have a specific meaning not related to the Tree structure.
21 A good example could be a `NodeMixin` subclass which also implements `collections.abc.Mapping`:
22
23
24 ```python
25 import collections
26
27 from anytree import NodeMixin
28
29
30 class MyMapping(NodeMixin, collections.abc.Mapping):
31 def __init__(self, name, parent=None, children=None):
32 super(MyMapping, self).__init__()
33 self.name = name
34 self.parent = parent
35 if children:
36 self.children = children
37
38 def __iter__(self):
39 for child in self.children:
40 yield child
41 for item in child:
42 yield item
43
44 def __len__(self):
45 return len(list(iter(self)))
46
47 def __getitem__(self, name):
48 for child in self:
49 if child.name == name:
50 return child
51 raise KeyError(name)
52 ```
53
54 In this example, the `NodeMixin` class shouldn't make any call to `__iter__`, `__len__` or `__getitem__`.
55
56 To avoid that, the `NodeMixin` class should respect the following rules:
57
58 - Do not compare nodes by value but by reference.
59 In other words, the `NodeMixin` class should not use `==` or `!=` but compare nodes with the `id()` function.
60 Comparison could be done with the `is` or `is not` operator. Avoid using `in` or `not in`.
61
62 - Do not use truth value testing to check if a node is "empty".
63 The `NodeMixin` class should not `if node`, `if not node`, `while node` nor `while not node`.
64 Instead, it must compare the node with `None` like this: `if node is not None`, `if node is None`,
65 `while node is not None` or `while node is None`.
66
67 - Do not presume that nodes are hashable.
68 The `NodeMixin` class should not store nodes in `set` or `dict`.
69 Instead, it can store node IDs using the `id()` function.
70 """
71
72 import functools
73 import unittest
74 from collections.abc import Mapping
75
76 from anytree import NodeMixin
77
78 # List of method names to which we want to control access:
79 #
80 # - This list does not contain the access control methods (`__getattribute__`, `__getattr__`,
81 # `__setattr__`, and `__delattr__`) which are used by the NodeMixin class anyway.
82 # - This list does not contain `__new__`, `__init__`, and `__del__` which are required for testing.
83 # - Some methods are not available in all Python version: `__bytes__`, `__unicode__` and `__dir__`.
84
85 SPECIAL_METHODS = [
86 # rich comparison methods
87 "__lt__",
88 "__le__",
89 "__eq__",
90 "__ne__",
91 "__gt__",
92 "__ge__",
93 # repr/str/bytes
94 "__repr__",
95 "__str__",
96 # "__bytes__",
97 # "__unicode__",
98 "__format__",
99 # hashing
100 "__hash__",
101 # attribute listing
102 # "__dir__",
103 # pickle protocol
104 "__getnewargs_ex__",
105 "__getnewargs__",
106 "__getstate__",
107 "__setstate__",
108 "__reduce_ex__",
109 # object size
110 "__sizeof__",
111 # truth value testing
112 "__bool__",
113 # callable objects
114 "__call__",
115 # container types
116 "__len__",
117 "__length_hint__",
118 "__getitem__",
119 "__setitem__",
120 "__delitem__",
121 "__missing__",
122 "__iter__",
123 "__reversed__",
124 "__contains__",
125 # numeric types
126 "__add__",
127 "__sub__",
128 "__mul__",
129 "__matmul__",
130 "__truediv__",
131 "__floordiv__",
132 "__mod__",
133 "__divmod__",
134 "__pow__",
135 "__lshift__",
136 "__rshift__",
137 "__and__",
138 "__xor__",
139 "__or__",
140 "__radd__",
141 "__rsub__",
142 "__rmul__",
143 "__rmatmul__",
144 "__rtruediv__",
145 "__rfloordiv__",
146 "__rmod__",
147 "__rdivmod__",
148 "__rpow__",
149 "__rlshift__",
150 "__rrshift__",
151 "__rand__",
152 "__rxor__",
153 "__ror__",
154 "__iadd__",
155 "__isub__",
156 "__imul__",
157 "__imatmul__",
158 "__itruediv__",
159 "__ifloordiv__",
160 "__imod__",
161 "__ipow__",
162 "__ilshift__",
163 "__irshift__",
164 "__iand__",
165 "__ixor__",
166 "__ior__",
167 "__neg__",
168 "__pos__",
169 "__abs__",
170 "__invert__",
171 "__complex__",
172 "__int__",
173 "__float__",
174 "__index__",
175 "__round__",
176 "__trunc__",
177 "__floor__",
178 "__ceil__",
179 # With Statement Context Managers
180 "__enter__",
181 "__exit__",
182 ]
183 SPECIAL_METHODS += [attr for attr in ["__bytes__", "__unicode__", "__dir"] if hasattr(object, attr)]
184
185
186 def prevent_access(attr, *args, **kwargs):
187 raise AssertionError("invalid call to " + attr)
188
189
190 class MyNode(NodeMixin):
191 @staticmethod
192 def __new__(cls, *args, **kwargs):
193 for attr in SPECIAL_METHODS:
194 setattr(cls, attr, functools.partial(prevent_access, attr))
195 return super(NodeMixin, cls).__new__(cls)
196
197 def __init__(self, name, parent=None, children=None):
198 super().__init__()
199 self.name = name
200 self.parent = parent
201 if children:
202 self.children = children
203
204
205 class TestConsistency(unittest.TestCase):
206 """Control the access to special methods."""
207
208 def setUp(self):
209 super().setUp()
210 self.root1 = MyNode("root1")
211 self.child1 = MyNode("child1", parent=self.root1)
212 self.child2a = MyNode("child2a", parent=self.child1)
213 self.child2b = MyNode("child2b", parent=self.child1)
214 self.other = MyNode("other")
215
216 def test_parent__root1(self):
217 _ = self.root1.parent
218
219 def test_parent__setter__root1(self):
220 self.root1.parent = self.other
221
222 def test_children__root1(self):
223 _ = self.root1.children
224
225 def test_children__setter__root1(self):
226 self.root1.children = [self.other]
227
228 def test_path__root1(self):
229 _ = self.root1.path
230
231 def test_iter_path_reverse__root1(self):
232 for _ in self.root1.iter_path_reverse():
233 pass
234
235 def test_ancestors__root1(self):
236 _ = self.root1.ancestors
237
238 def test_descendants__root1(self):
239 _ = self.root1.descendants
240
241 def test_root__root1(self):
242 _ = self.root1.root
243
244 def test_siblings__root1(self):
245 _ = self.root1.siblings
246
247 def test_leaves__root1(self):
248 _ = self.root1.leaves
249
250 def test_is_leaf__root1(self):
251 _ = self.root1.is_leaf
252
253 def test_is_root__root1(self):
254 _ = self.root1.is_root
255
256 def test_height__root1(self):
257 _ = self.root1.height
258
259 def test_depth__root1(self):
260 _ = self.root1.depth
261
262 def test_parent__child2b(self):
263 _ = self.child2b.parent
264
265 def test_parent__setter__child2b(self):
266 self.child2b.parent = self.other
267
268 def test_children__child2b(self):
269 _ = self.child2b.children
270
271 def test_children__setter__child2b(self):
272 self.child2b.children = [self.other]
273
274 def test_path__child2b(self):
275 _ = self.child2b.path
276
277 def test_iter_path_reverse__child2b(self):
278 for _ in self.child2b.iter_path_reverse():
279 pass
280
281 def test_ancestors__child2b(self):
282 _ = self.child2b.ancestors
283
284 def test_descendants__child2b(self):
285 _ = self.child2b.descendants
286
287 def test_root__child2b(self):
288 _ = self.child2b.root
289
290 def test_siblings__child2b(self):
291 _ = self.child2b.siblings
292
293 def test_leaves__child2b(self):
294 _ = self.child2b.leaves
295
296 def test_is_leaf__child2b(self):
297 _ = self.child2b.is_leaf
298
299 def test_is_root__child2b(self):
300 _ = self.child2b.is_root
301
302 def test_height__child2b(self):
303 _ = self.child2b.height
304
305 def test_depth__child2b(self):
306 _ = self.child2b.depth
307
308
309 class MyMapping(NodeMixin, Mapping):
310 """
311 This class is used to demonstrate a possible implementation which defines some special methods.
312 """
313
314 def __init__(self, name, parent=None, children=None):
315 super().__init__()
316 self.name = name
317 self.parent = parent
318 if children:
319 self.children = children
320
321 def __iter__(self):
322 """Iterate over all children recursively."""
323 for child in self.children:
324 yield child
325 yield from child
326
327 def __len__(self):
328 """Total number of children."""
329 return len(list(iter(self)))
330
331 def __getitem__(self, name):
332 for child in self:
333 if child.name == name:
334 return child
335 raise KeyError(name)
336
337
338 class TestMyMapping(unittest.TestCase):
339 def setUp(self):
340 super().setUp()
341 self.root1 = MyMapping("root1")
342 self.child1 = MyMapping("child1", parent=self.root1)
343 self.child2a = MyMapping("child2a", parent=self.child1)
344 self.child2b = MyMapping("child2b", parent=self.child1)
345
346 def test_iter(self):
347 expected_list = [self.child1, self.child2a, self.child2b]
348 for actual, expected in zip(iter(self.root1), expected_list):
349 self.assertIs(actual, expected)
350
351 def test_len(self):
352 self.assertEqual(len(self.root1), 3)
353
354 def test_getitem(self):
355 self.assertIs(self.root1["child1"], self.child1)
356 self.assertIs(self.root1["child2a"], self.child2a)
357 self.assertIs(self.root1["child2b"], self.child2b)
358 with self.assertRaises(KeyError):
359 _ = self.root1["missing"]