Debian Codegraph @

tests/test_raw_building.py

raw
1 """
2 'tests.testdata.python3.data.fake_module_with_warnings' and
3 'tests.testdata.python3.data.fake_module_with_warnings' are fake modules
4 to simulate issues in unittest below
5 """
6
7 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
8 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
9 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
10
11 from __future__ import annotations
12
13 import _io
14 import logging
15 import os
16 import sys
17 import types
18 import unittest
19 from typing import Any
20 from unittest import mock
21
22 import pytest
23
24 import tests.testdata.python3.data.fake_module_with_broken_getattr as fm_getattr
25 import tests.testdata.python3.data.fake_module_with_collection_getattribute as fm_collection
26 import tests.testdata.python3.data.fake_module_with_warnings as fm
27 from astroid import nodes, util
28 from astroid.builder import AstroidBuilder
29 from astroid.const import IS_PYPY, PY312_PLUS
30 from astroid.manager import AstroidManager
31 from astroid.raw_building import (
32 attach_dummy_node,
33 build_class,
34 build_from_import,
35 build_function,
36 build_module,
37 object_build_class,
38 object_build_datadescriptor,
39 )
40
41 try:
42 import mypy.build
43
44 HAS_MYPY = True
45 except ImportError:
46 HAS_MYPY = False
47
48 DUMMY_MOD = build_module("DUMMY")
49
50
51 class RawBuildingTC(unittest.TestCase):
52 def test_attach_dummy_node(self) -> None:
53 node = build_module("MyModule")
54 attach_dummy_node(node, "DummyNode")
55 self.assertEqual(1, len(list(node.get_children())))
56
57 def test_build_module(self) -> None:
58 node = build_module("MyModule")
59 self.assertEqual(node.name, "MyModule")
60 self.assertEqual(node.pure_python, False)
61 self.assertEqual(node.package, False)
62 self.assertEqual(node.parent, None)
63
64 def test_build_class(self) -> None:
65 node = build_class("MyClass", DUMMY_MOD)
66 self.assertEqual(node.name, "MyClass")
67 self.assertEqual(node.doc_node, None)
68
69 def test_build_function(self) -> None:
70 node = build_function("MyFunction", DUMMY_MOD)
71 self.assertEqual(node.name, "MyFunction")
72 self.assertEqual(node.doc_node, None)
73
74 def test_build_function_args(self) -> None:
75 args = ["myArgs1", "myArgs2"]
76 node = build_function("MyFunction", DUMMY_MOD, args)
77 self.assertEqual("myArgs1", node.args.args[0].name)
78 self.assertEqual("myArgs2", node.args.args[1].name)
79 self.assertEqual(2, len(node.args.args))
80
81 def test_build_function_defaults(self) -> None:
82 defaults = ["defaults1", "defaults2"]
83 node = build_function("MyFunction", DUMMY_MOD, args=None, defaults=defaults)
84 self.assertEqual(2, len(node.args.defaults))
85
86 def test_build_function_posonlyargs(self) -> None:
87 node = build_function("MyFunction", DUMMY_MOD, posonlyargs=["a", "b"])
88 self.assertEqual(2, len(node.args.posonlyargs))
89
90 def test_build_function_kwonlyargs(self) -> None:
91 node = build_function("MyFunction", DUMMY_MOD, kwonlyargs=["a", "b"])
92 assert len(node.args.kwonlyargs) == 2
93 assert node.args.kwonlyargs[0].name == "a"
94 assert node.args.kwonlyargs[1].name == "b"
95
96 def test_object_build_datadescriptor(self) -> None:
97 # Tests https://github.com/pylint-dev/pylint/issues/11218
98 # A data descriptor used to be modelled as a class named after the
99 # attribute, so the value it returns was inferred as that class and the
100 # attributes of the real value were reported as missing.
101 node = object_build_datadescriptor(DUMMY_MOD, types.TracebackType.tb_frame)
102 self.assertIsInstance(node, nodes.EmptyNode)
103 self.assertEqual(node.inferred(), [util.Uninferable])
104
105 def test_build_from_import(self) -> None:
106 names = ["exceptions, inference, inspector"]
107 node = build_from_import("astroid", names)
108 self.assertEqual(len(names), len(node.names))
109
110 @unittest.skipIf(IS_PYPY, "Only affects CPython")
111 def test_io_is__io(self):
112 # _io module calls itself io before Python 3.12. This leads
113 # to cyclic dependencies when astroid tries to resolve
114 # what io.BufferedReader is. The code that handles this
115 # is in astroid.raw_building.imported_member, which verifies
116 # the true name of the module.
117 builder = AstroidBuilder(AstroidManager())
118 module = builder.inspect_build(_io)
119 buffered_reader = module.getattr("BufferedReader")[0]
120 expected = "_io" if PY312_PLUS else "io"
121 self.assertEqual(buffered_reader.root().name, expected)
122
123 def test_build_function_deepinspect_deprecation(self) -> None:
124 # Tests https://github.com/pylint-dev/astroid/issues/1717
125 # When astroid deep inspection of modules raises
126 # attribute errors when getting all attributes
127 # Create a mock module to simulate a Cython module
128 m = types.ModuleType("test")
129
130 # Attach a mock of pandas with the same behavior
131 m.pd = fm
132
133 # This should not raise an exception
134 AstroidBuilder(AstroidManager()).module_build(m, "test")
135
136 def test_module_object_with_broken_getattr(self) -> None:
137 # Tests https://github.com/pylint-dev/astroid/issues/1958
138 # When astroid deep inspection of modules raises
139 # errors when using hasattr().
140
141 # This should not raise an exception
142 AstroidBuilder(AstroidManager()).inspect_build(fm_getattr, "test")
143
144 def test_module_collection_with_object_getattribute(self) -> None:
145 # Tests https://github.com/pylint-dev/astroid/issues/2686
146 # When astroid live inspection of module's collection raises
147 # error when element __getattribute__ causes collection to change size.
148
149 # This should not raise an exception
150 AstroidBuilder(AstroidManager()).inspect_build(fm_collection, "test")
151
152 def test_module_object_with_getattr_typeerror(self) -> None:
153 # Regression test for the PyPy 7.3.22 bootstrap crash: PyPy 7.3.22
154 # raises ``TypeError("expected str, got getset_descriptor object")``
155 # instead of ``AttributeError`` for unset getset descriptors like
156 # ``types.FunctionType.__text_signature__`` when accessed on the
157 # type. ``InspectBuilder.object_build`` must treat that the same as a
158 # missing attribute, otherwise ``_astroid_bootstrapping()`` blows up
159 # on import. Refs pylint-dev/pylint#10999.
160 class _TypeErrorOnGetattr(types.ModuleType):
161 def __getattr__(self, name: str) -> Any:
162 if name == "pypy_text_signature_like":
163 raise TypeError("expected str, got getset_descriptor object")
164 raise AttributeError(name)
165
166 def __dir__(self) -> list[str]:
167 return [*super().__dir__(), "pypy_text_signature_like"]
168
169 m = _TypeErrorOnGetattr("test_typeerror_on_getattr")
170
171 # This should not raise: the alias is skipped via attach_dummy_node,
172 # the same path used for AttributeError.
173 node = AstroidBuilder(AstroidManager()).inspect_build(m, "test")
174 self.assertIn("pypy_text_signature_like", node.locals)
175
176
177 @pytest.mark.skipif(
178 "posix" not in sys.builtin_module_names, reason="Platform doesn't support posix"
179 )
180 def test_build_module_getattr_catch_output(
181 capsys: pytest.CaptureFixture[str],
182 caplog: pytest.LogCaptureFixture,
183 ) -> None:
184 """Catch stdout and stderr in module __getattr__ calls when building a module.
185
186 Usually raised by DeprecationWarning or FutureWarning.
187 """
188 caplog.set_level(logging.INFO)
189 original_sys = sys.modules
190 original_module = sys.modules["posix"]
191 expected_out = "INFO (TEST): Welcome to posix!"
192 expected_err = "WARNING (TEST): Monkey-patched version of posix - module getattr"
193
194 class CustomGetattr:
195 def __getattr__(self, name: str) -> Any:
196 print(f"{expected_out}")
197 print(expected_err, file=sys.stderr)
198 return getattr(original_module, name)
199
200 def mocked_sys_modules_getitem(name: str) -> types.ModuleType | CustomGetattr:
201 if name != "posix":
202 return original_sys[name]
203 return CustomGetattr()
204
205 with mock.patch("astroid.raw_building.sys.modules") as sys_mock:
206 sys_mock.__getitem__.side_effect = mocked_sys_modules_getitem
207 builder = AstroidBuilder(AstroidManager())
208 builder.inspect_build(os)
209
210 out, err = capsys.readouterr()
211 assert expected_out in caplog.text
212 assert expected_err in caplog.text
213 assert not out
214 assert not err
215
216
217 @pytest.mark.skipif(not HAS_MYPY, reason="This test requires mypy")
218 def test_missing__dict__():
219 # This shouldn't raise an exception.
220 object_build_class(DUMMY_MOD, mypy.build.ModuleNotFound)