forked from c0fec0de/anytree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_search.py
99 lines (80 loc) · 2.78 KB
/
test_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from enum import IntEnum
from nose.tools import eq_
from anytree import AsciiStyle
from anytree import CountError
from anytree import Node
from anytree import PreOrderIter
from anytree import RenderTree
from anytree import find
from anytree import find_by_attr
from anytree import findall
from anytree import findall_by_attr
from helper import assert_raises
def test_findall():
f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
eq_(findall(f, filter_=lambda node: node.name in ("a", "b")), (b, a))
eq_(findall(f, filter_=lambda node: d in node.path), (d, c, e))
with assert_raises(CountError, (
"Expecting at least 4 elements, but found 3. "
"(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))")):
findall(f, filter_=lambda node: d in node.path, mincount=4)
with assert_raises(CountError, (
"Expecting 2 elements at maximum, but found 3. "
"(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))")):
findall(f, filter_=lambda node: d in node.path, maxcount=2)
def test_findall_by_attr():
f = Node("f")
b = Node("b", parent=f)
Node("a", parent=b)
d = Node("d", parent=b)
Node("c", parent=d)
Node("e", parent=d)
eq_(findall_by_attr(f, "d"), (d,))
with assert_raises(CountError, (
"Expecting at least 1 elements, but found 0.")):
findall_by_attr(f, "z", mincount=1)
def test_find():
f = Node("f")
b = Node("b", parent=f)
Node("a", parent=b)
d = Node("d", parent=b)
Node("c", parent=d)
Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
Node("h", parent=i)
eq_(find(f, lambda n: n.name == "d"), d)
eq_(find(f, lambda n: n.name == "z"), None)
with assert_raises(CountError, (
"Expecting 1 elements at maximum, but found 5. "
"(Node('/f/b'), Node('/f/b/a'), Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))")):
find(f, lambda n: b in n.path)
def test_find_by_attr():
f = Node("f")
b = Node("b", parent=f)
Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d, foo=4)
Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
Node("h", parent=i)
eq_(find_by_attr(f, "d"), d)
eq_(find_by_attr(f, name="foo", value=4), c)
eq_(find_by_attr(f, name="foo", value=8), None)
def test_enum():
class Animals(IntEnum):
Mammal = 1
Cat = 2
Dog = 3
root = Node("ANIMAL")
mammal = Node(Animals.Mammal, parent=root)
cat = Node(Animals.Cat, parent=mammal)
dog = Node(Animals.Dog, parent=mammal)
eq_(findall(root), (root, mammal, cat, dog))
eq_(findall_by_attr(root, Animals.Cat), (cat, ))