summaryrefslogtreecommitdiff
path: root/tests/brain/test_threading.py
blob: f7576499f7ac1c1a084fb15afd45dc01c9f4dcad (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
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt

from __future__ import annotations

import unittest

import astroid
from astroid import builder
from astroid.bases import Instance


class ThreadingBrainTest(unittest.TestCase):
    def test_lock(self) -> None:
        lock_instance = builder.extract_node(
            """
        import threading
        threading.Lock()
        """
        )
        inferred = next(lock_instance.infer())
        self.assert_is_valid_lock(inferred)

        acquire_method = inferred.getattr("acquire")[0]
        parameters = [param.name for param in acquire_method.args.args[1:]]
        assert parameters == ["blocking", "timeout"]

        assert inferred.getattr("locked")

    def test_rlock(self) -> None:
        self._test_lock_object("RLock")

    def test_semaphore(self) -> None:
        self._test_lock_object("Semaphore")

    def test_boundedsemaphore(self) -> None:
        self._test_lock_object("BoundedSemaphore")

    def _test_lock_object(self, object_name: str) -> None:
        lock_instance = builder.extract_node(
            f"""
        import threading
        threading.{object_name}()
        """
        )
        inferred = next(lock_instance.infer())
        self.assert_is_valid_lock(inferred)

    def assert_is_valid_lock(self, inferred: Instance) -> None:
        self.assertIsInstance(inferred, astroid.Instance)
        self.assertEqual(inferred.root().name, "threading")
        for method in ("acquire", "release", "__enter__", "__exit__"):
            self.assertIsInstance(next(inferred.igetattr(method)), astroid.BoundMethod)