Debian Codegraph @

tests/brain/test_gi.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 import unittest
6
7 try:
8 import gi # pylint: disable=unused-import
9
10 HAS_GI = True
11 except ImportError:
12 HAS_GI = False
13
14 from astroid import builder, nodes
15
16
17 @unittest.skipUnless(HAS_GI, "This test requires the gobject introspection library.")
18 class GiBrainClassificationTest(unittest.TestCase):
19 """Test that gi functions are correctly classified."""
20
21 def _inferred_gi_symbol(self, namespace, version, symbol):
22 node = builder.extract_node(f"""
23 import gi
24
25 gi.require_version("{namespace}", "{version}")
26 from gi.repository import {namespace}
27 {namespace}.{symbol}
28 """)
29 return node.inferred()
30
31 def test_gi_function_classification(self):
32 """Test that global functions are correctly classified without the 'self' argument."""
33 inferred = self._inferred_gi_symbol("GLib", "2.0", "get_tmp_dir")
34 self.assertEqual(len(inferred), 1)
35 self.assertEqual(inferred[0].pytype(), "builtins.function")
36
37 funcdef = inferred[0].frame()
38 self.assertIsInstance(funcdef, nodes.FunctionDef)
39
40 args = funcdef.argnames()
41 if len(args) > 0:
42 self.assertNotEqual(args[0], "self")
43
44 def test_gi_method_classification(self):
45 """Test that methods are correctly classified and accept the 'self' argument."""
46 inferred = self._inferred_gi_symbol("GLib", "2.0", "String.append")
47 self.assertEqual(len(inferred), 1)
48 self.assertEqual(inferred[0].pytype(), "builtins.instancemethod")
49
50 funcdef = inferred[0].frame()
51 self.assertIsInstance(funcdef, nodes.FunctionDef)
52
53 self.assertIn(
54 funcdef.argnames()[0],
55 {"self", funcdef.args.vararg},
56 "Method does not accept 'self' as first argument",
57 )