test_tracing.py 4.74 KB
Newer Older
dugupeiwen's avatar
dugupeiwen committed
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
from io import StringIO
import logging

import unittest
from numba.core import tracing

logger = logging.getLogger('trace')
logger.setLevel(logging.INFO)

# Make sure tracing is enabled
orig_trace = tracing.trace
tracing.trace = tracing.dotrace

class CapturedTrace:
    """Capture the trace temporarily for validation."""

    def __init__(self):
        self.buffer = StringIO()
        self.handler = logging.StreamHandler(self.buffer)
    def __enter__(self):
        self._handlers = logger.handlers
        self.buffer = StringIO()
        logger.handlers = [logging.StreamHandler(self.buffer)]
    def __exit__(self, type, value, traceback):
        logger.handlers = self._handlers
    def getvalue(self):

        # Depending on how the tests are run, object names may be
        # qualified by their containing module.
        # Remove that to make the trace output independent from the testing mode.
        log = self.buffer.getvalue()
        log = log.replace(__name__ + '.','')
        return log

class Class(object):

    @tracing.trace
    @classmethod
    def class_method(cls):
        pass

    @tracing.trace
    @staticmethod
    def static_method():
        pass

    __test = None

    def _test_get(self):
        return self.__test

    def _test_set(self, value):
        self.__test = value

    test = tracing.trace(property(_test_get, _test_set))
        
    @tracing.trace
    def method(self, some, other='value', *args, **kwds):
        pass

    def __repr__(self):
        """Generate a deterministic string for testing."""
        return '<Class instance>'

class Class2(object):
    @classmethod
    def class_method(cls):
        pass

    @staticmethod
    def static_method():
        pass

    __test = None
    @property
    def test(self):
        return self.__test
    @test.setter
    def test(self, value):
        self.__test = value

    def method(self):
        pass

    def __str__(self):
        return 'Test(' + str(self.test) + ')'

    def __repr__(self):
        """Generate a deterministic string for testing."""
        return '<Class2 instance>'


@tracing.trace
def test(x, y, z = True):
    a = x + y
    b = x * y
    if z: return a
    else: return b

class TestTracing(unittest.TestCase):

    def __init__(self, *args):
        super(TestTracing, self).__init__(*args)

    def setUp(self):
        self.capture = CapturedTrace()

    def tearDown(self):
        del self.capture
        
    def test_method(self):

        with self.capture:
            Class().method('foo', bar='baz')
        self.assertEqual(self.capture.getvalue(),
                         ">> Class.method(self=<Class instance>, some='foo', other='value', bar='baz')\n" +
                         "<< Class.method\n")

    def test_class_method(self):

        with self.capture:
            Class.class_method()
        self.assertEqual(self.capture.getvalue(),
                         ">> Class.class_method(cls=<class 'Class'>)\n" +
                         "<< Class.class_method\n")

    def test_static_method(self):

        with self.capture:
            Class.static_method()
        self.assertEqual(self.capture.getvalue(),
                         ">> static_method()\n" +
                         "<< static_method\n")


    def test_property(self):

        with self.capture:
            test = Class()
            test.test = 1
            assert 1 == test.test
        self.assertEqual(self.capture.getvalue(),
                         ">> Class._test_set(self=<Class instance>, value=1)\n" +
                         "<< Class._test_set\n" +
                         ">> Class._test_get(self=<Class instance>)\n" +
                         "<< Class._test_get -> 1\n")

    def test_function(self):

        with self.capture:
            test(5, 5)
            test(5, 5, False)
        self.assertEqual(self.capture.getvalue(),
                         ">> test(x=5, y=5, z=True)\n" +
                         "<< test -> 10\n" +
                         ">> test(x=5, y=5, z=False)\n" +
                         "<< test -> 25\n")

    @unittest.skip("recursive decoration not yet implemented")
    def test_injected(self):

        with self.capture:
            tracing.trace(Class2, recursive=True)
            Class2.class_method()
            Class2.static_method()
            test = Class2()
            test.test = 1
            assert 1 == test.test
            test.method()

            self.assertEqual(self.capture.getvalue(),
                         ">> Class2.class_method(cls=<type 'Class2'>)\n" +
                         "<< Class2.class_method\n"
                         ">> static_method()\n"
                         "<< static_method\n")

            
# Reset tracing to its original value
tracing.trace = orig_trace

if __name__ == '__main__':
    unittest.main()