aboutsummaryrefslogtreecommitdiff
path: root/Tests/misc/visitor_test.py
blob: 268cc716d7741285e574901c8c55cb2abf4b6b2a (plain)
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
from fontTools.misc.visitor import Visitor
import enum
import pytest


class E(enum.Enum):
    E1 = 1
    E2 = 2
    E3 = 3


class A:
    def __init__(self):
        self.a = 1
        self.b = [2, 3]
        self.c = {4: 5, 6: 7}
        self._d = 8
        self.e = E.E2
        self.f = 10


class B:
    def __init__(self):
        self.a = A()


class TestVisitor(Visitor):
    def __init__(self):
        self.value = []

    def _add(self, s):
        self.value.append(s)

    def visitLeaf(self, obj):
        self._add(obj)
        super().visitLeaf(obj)


@TestVisitor.register(A)
def visit(self, obj):
    self._add("A")


@TestVisitor.register_attrs([(A, "e")])
def visit(self, obj, attr, value):
    self._add(attr)
    self._add(value)
    return False


@TestVisitor.register(B)
def visit(self, obj):
    self._add("B")
    self.visitObject(obj)
    return False


@TestVisitor.register_attr(B, "a")
def visit(self, obj, attr, value):
    self._add("B a")


class VisitorTest(object):
    def test_visitor(self):
        b = B()
        visitor = TestVisitor()
        visitor.visit(b)
        assert visitor.value == ["B", "B a", "A", 1, 2, 3, 5, 7, "e", E.E2, 10]

        visitor.value = []
        visitor.defaultStop = True
        visitor.visit(b)
        assert visitor.value == ["B", "B a"]