summaryrefslogtreecommitdiff
path: root/tests/checkers/unittest_typecheck.py
blob: 90714ece92f32afcace48ff020fff406b7ef8725 (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# Copyright (c) 2014 Google, Inc.
# Copyright (c) 2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2014 Holger Peters <email@holger-peters.de>
# Copyright (c) 2015-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
# Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2016 Filipe Brandenburger <filbranden@google.com>
# Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com>
# Copyright (c) 2019 Ashley Whetter <ashley@awhetter.co.uk>
# Copyright (c) 2019 Martin Vielsmaier <martin.vielsmaier@gmail.com>
# Copyright (c) 2019 Federico Bond <federicobond@gmail.com>
# Copyright (c) 2020 Julien Palard <julien@palard.fr>
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2020 Damien Baty <damien.baty@polyconseil.fr>
# Copyright (c) 2020 Anthony Sottile <asottile@umich.edu>
# Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
# Copyright (c) 2021 David Liu <david@cs.toronto.edu>
# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
# Copyright (c) 2021 David Gilman <davidgilman1@gmail.com>

# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

import astroid
import pytest

from pylint.checkers import typecheck
from pylint.interfaces import UNDEFINED
from pylint.testutils import CheckerTestCase, Message, set_config

try:
    from coverage import tracer as _  # pylint: disable=unused-import

    C_EXTENTIONS_AVAILABLE = True
except ImportError:
    _ = None
    C_EXTENTIONS_AVAILABLE = False

needs_c_extension = pytest.mark.skipif(
    not C_EXTENTIONS_AVAILABLE, reason="Requires coverage (source of C-extension)"
)


class TestTypeChecker(CheckerTestCase):
    "Tests for pylint.checkers.typecheck"
    CHECKER_CLASS = typecheck.TypeChecker

    def test_no_member_in_getattr(self) -> None:
        """Make sure that a module attribute access is checked by pylint."""

        node = astroid.extract_node(
            """
        import optparse
        optparse.THIS_does_not_EXIST
        """
        )
        with self.assertAddsMessages(
            Message(
                "no-member",
                node=node,
                args=("Module", "optparse", "THIS_does_not_EXIST", ""),
            )
        ):
            self.checker.visit_attribute(node)

    @set_config(ignored_modules=("argparse",))
    def test_no_member_in_getattr_ignored(self) -> None:
        """Make sure that a module attribute access check is omitted with a
        module that is configured to be ignored.
        """

        node = astroid.extract_node(
            """
        import argparse
        argparse.THIS_does_not_EXIST
        """
        )
        with self.assertNoMessages():
            self.checker.visit_attribute(node)

    @set_config(ignored_modules=("xml.etree.",))
    def test_ignored_modules_invalid_pattern(self) -> None:
        node = astroid.extract_node(
            """
        import xml
        xml.etree.Lala
        """
        )
        message = Message(
            "no-member", node=node, args=("Module", "xml.etree", "Lala", "")
        )
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node)

    @set_config(ignored_modules=("xml",))
    def test_ignored_modules_root_one_applies_as_well(self) -> None:
        # Check that when a root module is completely ignored, submodules are skipped.
        node = astroid.extract_node(
            """
        import xml
        xml.etree.Lala
        """
        )
        with self.assertNoMessages():
            self.checker.visit_attribute(node)

    @set_config(ignored_modules=("xml.etree*",))
    def test_ignored_modules_patterns(self) -> None:
        node = astroid.extract_node(
            """
        import xml
        xml.etree.portocola #@
        """
        )
        with self.assertNoMessages():
            self.checker.visit_attribute(node)

    @set_config(ignored_classes=("xml.*",))
    def test_ignored_classes_no_recursive_pattern(self) -> None:
        node = astroid.extract_node(
            """
        import xml
        xml.etree.ElementTree.Test
        """
        )
        message = Message(
            "no-member", node=node, args=("Module", "xml.etree.ElementTree", "Test", "")
        )
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node)

    @set_config(ignored_classes=("optparse.Values",))
    def test_ignored_classes_qualified_name(self) -> None:
        """Test that ignored-classes supports qualified name for ignoring."""
        node = astroid.extract_node(
            """
        import optparse
        optparse.Values.lala
        """
        )
        with self.assertNoMessages():
            self.checker.visit_attribute(node)

    @set_config(ignored_classes=("Values",))
    def test_ignored_classes_only_name(self) -> None:
        """Test that ignored_classes works with the name only."""
        node = astroid.extract_node(
            """
        import optparse
        optparse.Values.lala
        """
        )
        with self.assertNoMessages():
            self.checker.visit_attribute(node)

    @set_config(suggestion_mode=False)
    @needs_c_extension
    def test_nomember_on_c_extension_error_msg(self) -> None:
        node = astroid.extract_node(
            """
        from coverage import tracer
        tracer.CTracer  #@
        """
        )
        message = Message(
            "no-member", node=node, args=("Module", "coverage.tracer", "CTracer", "")
        )
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node)

    @set_config(suggestion_mode=True)
    @needs_c_extension
    def test_nomember_on_c_extension_info_msg(self) -> None:
        node = astroid.extract_node(
            """
        from coverage import tracer
        tracer.CTracer  #@
        """
        )
        message = Message(
            "c-extension-no-member",
            node=node,
            args=("Module", "coverage.tracer", "CTracer", ""),
        )
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node)

    @set_config(
        contextmanager_decorators=(
            "contextlib.contextmanager",
            ".custom_contextmanager",
        )
    )
    def test_custom_context_manager(self):
        """Test that @custom_contextmanager is recognized as configured."""
        node = astroid.extract_node(
            """
        from contextlib import contextmanager
        def custom_contextmanager(f):
            return contextmanager(f)
        @custom_contextmanager
        def dec():
            yield
        with dec():
            pass
        """
        )
        with self.assertNoMessages():
            self.checker.visit_with(node)

    def test_invalid_metaclass(self) -> None:
        module = astroid.parse(
            """
        class InvalidAsMetaclass(object):
            pass

        class FirstInvalid(object, metaclass=int):
            pass

        class SecondInvalid(object, metaclass=InvalidAsMetaclass):
            pass

        class ThirdInvalid(object, metaclass=2):
            pass

        class FourthInvalid(object, metaclass=InvalidAsMetaclass()):
            pass
        """
        )
        for class_obj, metaclass_name in (
            ("FourthInvalid", "Instance of .InvalidAsMetaclass"),
            ("ThirdInvalid", "2"),
            ("SecondInvalid", "InvalidAsMetaclass"),
            ("FirstInvalid", "int"),
        ):
            classdef = module[class_obj]
            message = Message(
                "invalid-metaclass", node=classdef, args=(metaclass_name,)
            )
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef)

    def test_invalid_metaclass_function_metaclasses(self) -> None:
        module = astroid.parse(
            """
        def invalid_metaclass_1(name, bases, attrs):
            return int
        def invalid_metaclass_2(name, bases, attrs):
            return 1
        class Invalid(metaclass=invalid_metaclass_1):
            pass
        class InvalidSecond(metaclass=invalid_metaclass_2):
            pass
        """
        )
        for class_obj, metaclass_name in (("Invalid", "int"), ("InvalidSecond", "1")):
            classdef = module[class_obj]
            message = Message(
                "invalid-metaclass", node=classdef, args=(metaclass_name,)
            )
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef)

    def test_typing_namedtuple_not_callable_issue1295(self) -> None:
        module = astroid.parse(
            """
        import typing
        Named = typing.NamedTuple('Named', [('foo', int), ('bar', int)])
        named = Named(1, 2)
        """
        )
        call = module.body[-1].value
        callables = call.func.inferred()
        assert len(callables) == 1
        assert callables[0].callable()
        with self.assertNoMessages():
            self.checker.visit_call(call)

    def test_typing_namedtuple_unsubscriptable_object_issue1295(self) -> None:
        module = astroid.parse(
            """
        import typing
        MyType = typing.Tuple[str, str]
        """
        )
        subscript = module.body[-1].value
        with self.assertNoMessages():
            self.checker.visit_subscript(subscript)

    def test_staticmethod_multiprocessing_call(self) -> None:
        """Make sure not-callable isn't raised for descriptors

        astroid can't process descriptors correctly so
        pylint needs to ignore not-callable for them
        right now

        Test for https://github.com/PyCQA/pylint/issues/1699
        """
        call = astroid.extract_node(
            """
        import multiprocessing
        multiprocessing.current_process() #@
        """
        )
        with self.assertNoMessages():
            self.checker.visit_call(call)

    def test_not_callable_uninferable_property(self) -> None:
        """Make sure not-callable isn't raised for uninferable
        properties
        """
        call = astroid.extract_node(
            """
        class A:
            @property
            def call(self):
                return undefined

        a = A()
        a.call() #@
        """
        )
        with self.assertNoMessages():
            self.checker.visit_call(call)

    def test_descriptor_call(self) -> None:
        call = astroid.extract_node(
            """
        def func():
            pass

        class ADescriptor:
            def __get__(self, instance, owner):
                return func

        class AggregateCls:
            a = ADescriptor()

        AggregateCls().a() #@
        """
        )
        with self.assertNoMessages():
            self.checker.visit_call(call)

    def test_unknown_parent(self) -> None:
        """Make sure the callable check does not crash when a node's parent
        cannot be determined.
        """
        call = astroid.extract_node(
            """
        def get_num(n):
            return 2 * n
        get_num(10)()
        """
        )
        with self.assertAddsMessages(
            Message("not-callable", node=call, args="get_num(10)")
        ):
            self.checker.visit_call(call)


class TestTypeCheckerOnDecorators(CheckerTestCase):
    "Tests for pylint.checkers.typecheck on decorated functions."
    CHECKER_CLASS = typecheck.TypeChecker

    def test_issue3882_class_decorators(self) -> None:
        decorators = """
        class Unsubscriptable:
            def __init__(self, f):
                self.f = f

        class Subscriptable:
            def __init__(self, f):
                self.f = f

            def __getitem__(self, item):
                return item
        """
        for generic in "Optional", "List", "ClassVar", "Final", "Literal":
            self.typing_objects_are_subscriptable(generic)

        self.getitem_on_modules()
        self.decorated_by_a_subscriptable_class(decorators)
        self.decorated_by_an_unsubscriptable_class(decorators)

        self.decorated_by_subscriptable_then_unsubscriptable_class(decorators)
        self.decorated_by_unsubscriptable_then_subscriptable_class(decorators)

    def getitem_on_modules(self) -> None:
        """Mainly validate the code won't crash if we're not having a function."""
        module = astroid.parse(
            """
        import collections
        test = collections[int]
        """
        )
        subscript = module.body[-1].value
        with self.assertAddsMessages(
            Message(
                "unsubscriptable-object",
                node=subscript.value,
                args="collections",
                confidence=UNDEFINED,
            )
        ):
            self.checker.visit_subscript(subscript)

    def typing_objects_are_subscriptable(self, generic: str) -> None:
        module = astroid.parse(
            f"""
        import typing
        test = typing.{generic}[int]
        """
        )
        subscript = module.body[-1].value
        with self.assertNoMessages():
            self.checker.visit_subscript(subscript)

    def decorated_by_a_subscriptable_class(self, decorators: str) -> None:
        module = astroid.parse(
            decorators
            + """
        @Subscriptable
        def decorated():
            ...

        test = decorated[None]
        """
        )
        subscript = module.body[-1].value
        with self.assertNoMessages():
            self.checker.visit_subscript(subscript)

    def decorated_by_subscriptable_then_unsubscriptable_class(
        self, decorators: str
    ) -> None:
        module = astroid.parse(
            decorators
            + """
        @Unsubscriptable
        @Subscriptable
        def decorated():
            ...

        test = decorated[None]
        """
        )
        subscript = module.body[-1].value
        with self.assertAddsMessages(
            Message(
                "unsubscriptable-object",
                node=subscript.value,
                args="decorated",
                confidence=UNDEFINED,
            )
        ):
            self.checker.visit_subscript(subscript)

    def decorated_by_unsubscriptable_then_subscriptable_class(
        self, decorators: str
    ) -> None:
        module = astroid.parse(
            decorators
            + """
        @Subscriptable
        @Unsubscriptable
        def decorated():
            ...

        test = decorated[None]
        """
        )
        subscript = module.body[-1].value
        with self.assertNoMessages():
            self.checker.visit_subscript(subscript)

    def decorated_by_an_unsubscriptable_class(self, decorators: str) -> None:
        module = astroid.parse(
            decorators
            + """
        @Unsubscriptable
        def decorated():
            ...

        test = decorated[None]
        """
        )
        subscript = module.body[-1].value
        with self.assertAddsMessages(
            Message(
                "unsubscriptable-object",
                node=subscript.value,
                args="decorated",
                confidence=UNDEFINED,
            )
        ):
            self.checker.visit_subscript(subscript)