summaryrefslogtreecommitdiff
path: root/tests/test_util_inspect.py
blob: f0188cafa790d115dafb7e44b89bb8a59a8c3974 (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
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# -*- coding: utf-8 -*-
"""
    test_util_inspect
    ~~~~~~~~~~~~~~~

    Tests util.inspect functions.

    :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""
import sys
from six import PY3
import functools
from textwrap import dedent
import pytest

from sphinx.util import inspect


def test_getargspec():
    def func(a, b, c=1, d=2, *e, **f):
        pass

    spec = inspect.getargspec(func)
    assert spec.args == ['a', 'b', 'c', 'd']
    assert spec.varargs == 'e'
    if PY3:
        assert spec.varkw == 'f'
        assert spec.defaults == (1, 2)
        assert spec.kwonlyargs == []
        assert spec.kwonlydefaults is None
        assert spec.annotations == {}
    else:
        assert spec.keywords == 'f'
        assert spec.defaults == [1, 2]


def test_getargspec_partial():
    def func1(a, b, c=1, d=2, *e, **f):
        pass

    partial = functools.partial(func1, 10, c=11)
    spec = inspect.getargspec(partial)
    if PY3:
        assert spec.args == ['b']
        assert spec.varargs is None
        assert spec.varkw == 'f'
        assert spec.defaults is None
        assert spec.kwonlyargs == ['c', 'd']
        assert spec.kwonlydefaults == {'c': 11, 'd': 2}
        assert spec.annotations == {}
    else:
        assert spec.args == ['b', 'd']
        assert spec.varargs == 'e'
        assert spec.keywords == 'f'
        assert spec.defaults == [2]


def test_getargspec_partial2():
    def fun(a, b, c=1, d=2):
        pass
    p = functools.partial(fun, 10, c=11)

    if PY3:
        # Python 3's partial is rather cleverer than Python 2's, and we
        # have to jump through some hoops to define an equivalent function
        # in a way that won't confuse Python 2's parser:
        ns = {}
        exec(dedent("""
            def f_expected(b, *, c=11, d=2):
                    pass
        """), ns)
        f_expected = ns["f_expected"]
    else:
        def f_expected(b, d=2):
            pass
    expected = inspect.getargspec(f_expected)

    assert expected == inspect.getargspec(p)


def test_getargspec_builtin_type():
    with pytest.raises(TypeError):
        inspect.getargspec(int)


def test_getargspec_bound_methods():
    def f_expected_unbound(self, arg1, **kwargs):
        pass
    expected_unbound = inspect.getargspec(f_expected_unbound)

    def f_expected_bound(arg1, **kwargs):
        pass
    expected_bound = inspect.getargspec(f_expected_bound)

    class Foo:
        def method(self, arg1, **kwargs):
            pass

    bound_method = Foo().method

    @functools.wraps(bound_method)
    def wrapped_bound_method(*args, **kwargs):
        pass

    assert expected_unbound == inspect.getargspec(Foo.method)
    if PY3 and sys.version_info >= (3, 4, 4):
        # On py2, the inspect functions don't properly handle bound
        # methods (they include a spurious 'self' argument)
        assert expected_bound == inspect.getargspec(bound_method)
        # On py2, the inspect functions can't properly handle wrapped
        # functions (no __wrapped__ support)
        assert expected_bound == inspect.getargspec(wrapped_bound_method)


def test_Signature():
    # literals
    with pytest.raises(TypeError):
        inspect.Signature(1)

    with pytest.raises(TypeError):
        inspect.Signature('')

    # builitin classes
    with pytest.raises(TypeError):
        inspect.Signature(int)

    with pytest.raises(TypeError):
        inspect.Signature(str)

    # normal function
    def func(a, b, c=1, d=2, *e, **f):
        pass

    sig = inspect.Signature(func).format_args()
    assert sig == '(a, b, c=1, d=2, *e, **f)'


def test_Signature_partial():
    def fun(a, b, c=1, d=2):
        pass
    p = functools.partial(fun, 10, c=11)

    sig = inspect.Signature(p).format_args()
    if sys.version_info < (3,):
        assert sig == '(b, d=2)'
    else:
        assert sig == '(b, *, c=11, d=2)'


def test_Signature_methods():
    class Foo:
        def meth1(self, arg1, **kwargs):
            pass

        @classmethod
        def meth2(cls, arg1, *args, **kwargs):
            pass

        @staticmethod
        def meth3(arg1, *args, **kwargs):
            pass

    @functools.wraps(Foo().meth1)
    def wrapped_bound_method(*args, **kwargs):
        pass

    # unbound method
    sig = inspect.Signature(Foo.meth1).format_args()
    assert sig == '(self, arg1, **kwargs)'

    sig = inspect.Signature(Foo.meth1, bound_method=True).format_args()
    assert sig == '(arg1, **kwargs)'

    # bound method
    sig = inspect.Signature(Foo().meth1).format_args()
    assert sig == '(arg1, **kwargs)'

    # class method
    sig = inspect.Signature(Foo.meth2).format_args()
    assert sig == '(arg1, *args, **kwargs)'

    sig = inspect.Signature(Foo().meth2).format_args()
    assert sig == '(arg1, *args, **kwargs)'

    # static method
    sig = inspect.Signature(Foo.meth3).format_args()
    assert sig == '(arg1, *args, **kwargs)'

    sig = inspect.Signature(Foo().meth3).format_args()
    assert sig == '(arg1, *args, **kwargs)'

    # wrapped bound method
    sig = inspect.Signature(wrapped_bound_method).format_args()
    if sys.version_info < (3,):
        assert sig == '(*args, **kwargs)'
    elif sys.version_info < (3, 4, 4):
        assert sig == '(self, arg1, **kwargs)'
    else:
        assert sig == '(arg1, **kwargs)'


@pytest.mark.skipif(sys.version_info < (3, 5),
                    reason='type annotation test is available on py35 or above')
def test_Signature_annotations():
    from typing_test_data import f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11

    # Class annotations
    sig = inspect.Signature(f0).format_args()
    assert sig == '(x: int, y: numbers.Integral) -> None'

    # Generic types with concrete parameters
    sig = inspect.Signature(f1).format_args()
    assert sig == '(x: typing.List[int]) -> typing.List[int]'

    # TypeVars and generic types with TypeVars
    sig = inspect.Signature(f2).format_args()
    assert sig == '(x: typing.List[T], y: typing.List[T_co], z: T) -> typing.List[T_contra]'

    # Union types
    sig = inspect.Signature(f3).format_args()
    assert sig == '(x: typing.Union[str, numbers.Integral]) -> None'

    # Quoted annotations
    sig = inspect.Signature(f4).format_args()
    assert sig == '(x: str, y: str) -> None'

    # Keyword-only arguments
    sig = inspect.Signature(f5).format_args()
    assert sig == '(x: int, *, y: str, z: str) -> None'

    # Keyword-only arguments with varargs
    sig = inspect.Signature(f6).format_args()
    assert sig == '(x: int, *args, y: str, z: str) -> None'

    # Space around '=' for defaults
    sig = inspect.Signature(f7).format_args()
    assert sig == '(x: int = None, y: dict = {}) -> None'

    # Callable types
    sig = inspect.Signature(f8).format_args()
    assert sig == '(x: typing.Callable[[int, str], int]) -> None'

    sig = inspect.Signature(f9).format_args()
    assert sig == '(x: typing.Callable) -> None'

    # Tuple types
    sig = inspect.Signature(f10).format_args()
    assert sig == '(x: typing.Tuple[int, str], y: typing.Tuple[int, ...]) -> None'

    # Instance annotations
    sig = inspect.Signature(f11).format_args()
    assert sig == '(x: CustomAnnotation, y: 123) -> None'


def test_safe_getattr_with_default():
    class Foo(object):
        def __getattr__(self, item):
            raise Exception

    obj = Foo()

    result = inspect.safe_getattr(obj, 'bar', 'baz')

    assert result == 'baz'


def test_safe_getattr_with_exception():
    class Foo(object):
        def __getattr__(self, item):
            raise Exception

    obj = Foo()

    try:
        inspect.safe_getattr(obj, 'bar')
    except AttributeError as exc:
        assert exc.args[0] == 'bar'
    else:
        pytest.fail('AttributeError not raised')


def test_safe_getattr_with_property_exception():
    class Foo(object):
        @property
        def bar(self):
            raise Exception

    obj = Foo()

    try:
        inspect.safe_getattr(obj, 'bar')
    except AttributeError as exc:
        assert exc.args[0] == 'bar'
    else:
        pytest.fail('AttributeError not raised')


def test_safe_getattr_with___dict___override():
    class Foo(object):
        @property
        def __dict__(self):
            raise Exception

    obj = Foo()

    try:
        inspect.safe_getattr(obj, 'bar')
    except AttributeError as exc:
        assert exc.args[0] == 'bar'
    else:
        pytest.fail('AttributeError not raised')


def test_dictionary_sorting():
    dictionary = {"c": 3, "a": 1, "d": 2, "b": 4}
    description = inspect.object_description(dictionary)
    assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}"


def test_dict_customtype():
    class CustomType(object):
        def __init__(self, value):
            self._value = value

        def __repr__(self):
            return "<CustomType(%r)>" % self._value

    dictionary = {CustomType(2): 2, CustomType(1): 1}
    description = inspect.object_description(dictionary)
    # Type is unsortable, just check that it does not crash
    assert "<CustomType(2)>: 2" in description