| 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 os |
| 6 |
import re |
| 7 |
import sys |
| 8 |
import time |
| 9 |
import types |
| 10 |
import unittest |
| 11 |
import warnings |
| 12 |
from collections.abc import Iterator |
| 13 |
from contextlib import contextmanager |
| 14 |
from unittest import mock |
| 15 |
|
| 16 |
import pytest |
| 17 |
|
| 18 |
import astroid |
| 19 |
from astroid import manager, nodes, test_utils |
| 20 |
from astroid.const import IS_JYTHON, IS_PYPY, PY312_PLUS |
| 21 |
from astroid.exceptions import ( |
| 22 |
AstroidBuildingError, |
| 23 |
AstroidImportError, |
| 24 |
AttributeInferenceError, |
| 25 |
) |
| 26 |
from astroid.interpreter._import import util |
| 27 |
from astroid.modutils import EXT_LIB_DIRS, module_in_path |
| 28 |
from astroid.nodes import Const |
| 29 |
from astroid.nodes.scoped_nodes import ClassDef, Module |
| 30 |
|
| 31 |
from . import resources |
| 32 |
|
| 33 |
|
| 34 |
def _get_file_from_object(obj) -> str: |
| 35 |
if IS_JYTHON: |
| 36 |
return obj.__file__.split("$py.class")[0] + ".py" |
| 37 |
return obj.__file__ |
| 38 |
|
| 39 |
|
| 40 |
_NSPKG_PTH_PARTS_RE = re.compile(r"\*\(([^)]+)\)") |
| 41 |
|
| 42 |
|
| 43 |
def _parse_pth_package_parts(line: str) -> tuple[str, ...]: |
| 44 |
"""Extract the namespace package tuple from a setuptools nspkg .pth line.""" |
| 45 |
match = _NSPKG_PTH_PARTS_RE.search(line) |
| 46 |
if not match: |
| 47 |
return () |
| 48 |
parts = [] |
| 49 |
for token in match.group(1).split(","): |
| 50 |
token = token.strip().strip("'\"") |
| 51 |
if token: |
| 52 |
parts.append(token) |
| 53 |
return tuple(parts) |
| 54 |
|
| 55 |
|
| 56 |
def _load_namespace_package_pth(pth: str) -> None: |
| 57 |
"""Apply a setuptools-style namespace package .pth fixture without exec(). |
| 58 |
|
| 59 |
Each non-comment line in the fixture wires up one namespace package by |
| 60 |
appending a directory under `resources.RESOURCE_PATH` to that package's |
| 61 |
``__path__``. We parse the package tuple out of the line and replay the |
| 62 |
same effect here. |
| 63 |
""" |
| 64 |
sitedir = str(resources.RESOURCE_PATH) |
| 65 |
with (resources.RESOURCE_PATH / pth).open(encoding="utf-8") as pth_file: |
| 66 |
for raw_line in pth_file: |
| 67 |
line = raw_line.strip() |
| 68 |
if not line or line.startswith("#"): |
| 69 |
continue |
| 70 |
parts = _parse_pth_package_parts(line) |
| 71 |
if not parts: |
| 72 |
continue |
| 73 |
package_name = ".".join(parts) |
| 74 |
package_path = os.path.join(sitedir, *parts) |
| 75 |
if os.path.exists(os.path.join(package_path, "__init__.py")): |
| 76 |
continue |
| 77 |
module = sys.modules.setdefault( |
| 78 |
package_name, types.ModuleType(package_name) |
| 79 |
) |
| 80 |
mod_path = module.__dict__.setdefault("__path__", []) |
| 81 |
if package_path not in mod_path: |
| 82 |
mod_path.append(package_path) |
| 83 |
|
| 84 |
|
| 85 |
class AstroidManagerTest(resources.SysPathSetup, unittest.TestCase): |
| 86 |
def setUp(self) -> None: |
| 87 |
super().setUp() |
| 88 |
self.manager = test_utils.brainless_manager() |
| 89 |
self.manager.clear_cache() |
| 90 |
|
| 91 |
def test_ast_from_file(self) -> None: |
| 92 |
filepath = unittest.__file__ |
| 93 |
ast = self.manager.ast_from_file(filepath) |
| 94 |
self.assertEqual(ast.name, "unittest") |
| 95 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 96 |
|
| 97 |
def test_ast_from_file_cache(self) -> None: |
| 98 |
filepath = unittest.__file__ |
| 99 |
self.manager.ast_from_file(filepath) |
| 100 |
ast = self.manager.ast_from_file("unhandledName", "unittest") |
| 101 |
self.assertEqual(ast.name, "unittest") |
| 102 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 103 |
|
| 104 |
def test_ast_from_file_astro_builder(self) -> None: |
| 105 |
filepath = unittest.__file__ |
| 106 |
ast = self.manager.ast_from_file(filepath, None, True, True) |
| 107 |
self.assertEqual(ast.name, "unittest") |
| 108 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 109 |
|
| 110 |
def test_ast_from_file_name_astro_builder_exception(self) -> None: |
| 111 |
self.assertRaises( |
| 112 |
AstroidBuildingError, self.manager.ast_from_file, "unhandledName" |
| 113 |
) |
| 114 |
|
| 115 |
def test_ast_from_string(self) -> None: |
| 116 |
filepath = unittest.__file__ |
| 117 |
dirname = os.path.dirname(filepath) |
| 118 |
modname = os.path.basename(dirname) |
| 119 |
with open(filepath, encoding="utf-8") as file: |
| 120 |
data = file.read() |
| 121 |
ast = self.manager.ast_from_string(data, modname, filepath) |
| 122 |
self.assertEqual(ast.name, "unittest") |
| 123 |
self.assertEqual(ast.file, filepath) |
| 124 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 125 |
|
| 126 |
def test_do_not_expose_main(self) -> None: |
| 127 |
obj = self.manager.ast_from_module_name("__main__") |
| 128 |
self.assertEqual(obj.name, "__main__") |
| 129 |
self.assertEqual(obj.items(), []) |
| 130 |
|
| 131 |
def test_ast_from_module_name(self) -> None: |
| 132 |
ast = self.manager.ast_from_module_name("unittest") |
| 133 |
self.assertEqual(ast.name, "unittest") |
| 134 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 135 |
|
| 136 |
def test_ast_from_module_name_not_python_source(self) -> None: |
| 137 |
ast = self.manager.ast_from_module_name("time") |
| 138 |
self.assertEqual(ast.name, "time") |
| 139 |
self.assertIn("time", self.manager.astroid_cache) |
| 140 |
self.assertEqual(ast.pure_python, False) |
| 141 |
|
| 142 |
def test_ast_from_module_name_astro_builder_exception(self) -> None: |
| 143 |
self.assertRaises( |
| 144 |
AstroidBuildingError, |
| 145 |
self.manager.ast_from_module_name, |
| 146 |
"unhandledModule", |
| 147 |
) |
| 148 |
|
| 149 |
def _test_ast_from_old_namespace_package_protocol(self, root: str) -> None: |
| 150 |
origpath = sys.path[:] |
| 151 |
paths = [resources.find(f"data/path_{root}_{index}") for index in range(1, 4)] |
| 152 |
sys.path.extend(paths) |
| 153 |
try: |
| 154 |
for name in ("foo", "bar", "baz"): |
| 155 |
module = self.manager.ast_from_module_name("package." + name) |
| 156 |
self.assertIsInstance(module, nodes.Module) |
| 157 |
finally: |
| 158 |
sys.path = origpath |
| 159 |
|
| 160 |
def test_ast_from_namespace_pkgutil(self) -> None: |
| 161 |
self._test_ast_from_old_namespace_package_protocol("pkgutil") |
| 162 |
|
| 163 |
def test_ast_from_namespace_pkg_resources(self) -> None: |
| 164 |
self._test_ast_from_old_namespace_package_protocol("pkg_resources") |
| 165 |
|
| 166 |
def test_identify_old_namespace_package_protocol(self) -> None: |
| 167 |
# Like the above cases, this package follows the old namespace package protocol |
| 168 |
# astroid currently assumes such packages are in sys.modules, so import it |
| 169 |
with warnings.catch_warnings(): |
| 170 |
warnings.filterwarnings( |
| 171 |
"ignore", |
| 172 |
category=UserWarning, |
| 173 |
message=".*pkg_resources is deprecated.*", |
| 174 |
) |
| 175 |
|
| 176 |
# pylint: disable-next=import-outside-toplevel |
| 177 |
import tests.testdata.python3.data.path_pkg_resources_1.package.foo as _ # noqa |
| 178 |
|
| 179 |
self.assertTrue( |
| 180 |
util.is_namespace("tests.testdata.python3.data.path_pkg_resources_1") |
| 181 |
) |
| 182 |
|
| 183 |
def test_submodule_homonym_with_non_module(self) -> None: |
| 184 |
self.assertFalse( |
| 185 |
util.is_namespace("tests.testdata.python3.data.parent_of_homonym.doc") |
| 186 |
) |
| 187 |
|
| 188 |
def test_module_is_not_namespace(self) -> None: |
| 189 |
self.assertFalse(util.is_namespace("tests.testdata.python3.data.all")) |
| 190 |
self.assertFalse(util.is_namespace("__main__")) |
| 191 |
self.assertFalse( |
| 192 |
util.is_namespace(next(iter(EXT_LIB_DIRS)).rsplit("/", maxsplit=1)[-1]), |
| 193 |
) |
| 194 |
self.assertFalse(util.is_namespace("importlib._bootstrap")) |
| 195 |
|
| 196 |
def test_module_unexpectedly_missing_spec(self) -> None: |
| 197 |
astroid_module = sys.modules["astroid"] |
| 198 |
original_spec = astroid_module.__spec__ |
| 199 |
del astroid_module.__spec__ |
| 200 |
try: |
| 201 |
self.assertFalse(util.is_namespace("astroid")) |
| 202 |
finally: |
| 203 |
astroid_module.__spec__ = original_spec |
| 204 |
|
| 205 |
@mock.patch( |
| 206 |
"astroid.interpreter._import.util._find_spec_from_path", |
| 207 |
side_effect=AttributeError, |
| 208 |
) |
| 209 |
def test_module_unexpectedly_missing_path(self, mocked) -> None: |
| 210 |
"""Https://github.com/pylint-dev/pylint/issues/7592.""" |
| 211 |
self.assertFalse(util.is_namespace("astroid")) |
| 212 |
|
| 213 |
def test_module_unexpectedly_spec_is_none(self) -> None: |
| 214 |
astroid_module = sys.modules["astroid"] |
| 215 |
original_spec = astroid_module.__spec__ |
| 216 |
astroid_module.__spec__ = None |
| 217 |
try: |
| 218 |
self.assertFalse(util.is_namespace("astroid")) |
| 219 |
finally: |
| 220 |
astroid_module.__spec__ = original_spec |
| 221 |
|
| 222 |
def test_implicit_namespace_package(self) -> None: |
| 223 |
data_dir = os.path.dirname(resources.find("data/namespace_pep_420")) |
| 224 |
contribute = os.path.join(data_dir, "contribute_to_namespace") |
| 225 |
for value in (data_dir, contribute): |
| 226 |
sys.path.insert(0, value) |
| 227 |
|
| 228 |
try: |
| 229 |
module = self.manager.ast_from_module_name("namespace_pep_420.module") |
| 230 |
self.assertIsInstance(module, nodes.Module) |
| 231 |
self.assertEqual(module.name, "namespace_pep_420.module") |
| 232 |
var = next(module.igetattr("var")) |
| 233 |
self.assertIsInstance(var, nodes.Const) |
| 234 |
self.assertEqual(var.value, 42) |
| 235 |
finally: |
| 236 |
for _ in range(2): |
| 237 |
sys.path.pop(0) |
| 238 |
|
| 239 |
@pytest.mark.skipif( |
| 240 |
IS_PYPY, |
| 241 |
reason="PyPy provides no way to tell apart frozen stdlib from old-style namespace packages", |
| 242 |
) |
| 243 |
def test_namespace_package_pth_support(self) -> None: |
| 244 |
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth" |
| 245 |
_load_namespace_package_pth(pth) |
| 246 |
|
| 247 |
try: |
| 248 |
module = self.manager.ast_from_module_name("foogle.fax") |
| 249 |
submodule = next(module.igetattr("a")) |
| 250 |
value = next(submodule.igetattr("x")) |
| 251 |
self.assertIsInstance(value, nodes.Const) |
| 252 |
with self.assertRaises(AstroidImportError): |
| 253 |
self.manager.ast_from_module_name("foogle.moogle") |
| 254 |
finally: |
| 255 |
sys.modules.pop("foogle", None) |
| 256 |
sys.modules.pop("foogle.crank", None) |
| 257 |
|
| 258 |
@pytest.mark.skipif( |
| 259 |
IS_PYPY, |
| 260 |
reason="PyPy provides no way to tell apart frozen stdlib from old-style namespace packages", |
| 261 |
) |
| 262 |
def test_nested_namespace_import(self) -> None: |
| 263 |
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth" |
| 264 |
_load_namespace_package_pth(pth) |
| 265 |
try: |
| 266 |
self.manager.ast_from_module_name("foogle.crank") |
| 267 |
finally: |
| 268 |
sys.modules.pop("foogle", None) |
| 269 |
sys.modules.pop("foogle.crank", None) |
| 270 |
|
| 271 |
def test_namespace_and_file_mismatch(self) -> None: |
| 272 |
filepath = unittest.__file__ |
| 273 |
ast = self.manager.ast_from_file(filepath) |
| 274 |
self.assertEqual(ast.name, "unittest") |
| 275 |
pth = "foogle_fax-0.12.5-py2.7-nspkg.pth" |
| 276 |
_load_namespace_package_pth(pth) |
| 277 |
try: |
| 278 |
with self.assertRaises(AstroidImportError): |
| 279 |
self.manager.ast_from_module_name("unittest.foogle.fax") |
| 280 |
finally: |
| 281 |
sys.modules.pop("foogle", None) |
| 282 |
sys.modules.pop("foogle.crank", None) |
| 283 |
|
| 284 |
def _test_ast_from_zip(self, archive: str) -> None: |
| 285 |
sys.modules.pop("mypypa", None) |
| 286 |
archive_path = resources.find(archive) |
| 287 |
sys.path.insert(0, archive_path) |
| 288 |
module = self.manager.ast_from_module_name("mypypa") |
| 289 |
self.assertEqual(module.name, "mypypa") |
| 290 |
end = os.path.join(archive, "mypypa") |
| 291 |
self.assertTrue( |
| 292 |
module.file.endswith(end), f"{module.file} doesn't endswith {end}" |
| 293 |
) |
| 294 |
|
| 295 |
@contextmanager |
| 296 |
def _restore_package_cache(self) -> Iterator: |
| 297 |
orig_path = sys.path[:] |
| 298 |
orig_pathcache = sys.path_importer_cache.copy() |
| 299 |
orig_modcache = self.manager.astroid_cache.copy() |
| 300 |
orig_modfilecache = self.manager._mod_file_cache.copy() |
| 301 |
orig_importhooks = self.manager._failed_import_hooks[:] |
| 302 |
yield |
| 303 |
self.manager._failed_import_hooks = orig_importhooks |
| 304 |
self.manager._mod_file_cache = orig_modfilecache |
| 305 |
self.manager.astroid_cache = orig_modcache |
| 306 |
sys.path_importer_cache = orig_pathcache |
| 307 |
sys.path = orig_path |
| 308 |
|
| 309 |
def test_ast_from_module_name_egg(self) -> None: |
| 310 |
with self._restore_package_cache(): |
| 311 |
self._test_ast_from_zip( |
| 312 |
os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.egg")]) |
| 313 |
) |
| 314 |
|
| 315 |
def test_ast_from_module_name_zip(self) -> None: |
| 316 |
with self._restore_package_cache(): |
| 317 |
self._test_ast_from_zip( |
| 318 |
os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.zip")]) |
| 319 |
) |
| 320 |
|
| 321 |
def test_ast_from_module_name_pyz(self) -> None: |
| 322 |
try: |
| 323 |
linked_file_name = os.path.join( |
| 324 |
resources.RESOURCE_PATH, "MyPyPa-0.1.0-py2.5.pyz" |
| 325 |
) |
| 326 |
os.symlink( |
| 327 |
os.path.join(resources.RESOURCE_PATH, "MyPyPa-0.1.0-py2.5.zip"), |
| 328 |
linked_file_name, |
| 329 |
) |
| 330 |
|
| 331 |
with self._restore_package_cache(): |
| 332 |
self._test_ast_from_zip(linked_file_name) |
| 333 |
finally: |
| 334 |
os.remove(linked_file_name) |
| 335 |
|
| 336 |
def test_ast_from_module_name_pyz_with_submodule(self) -> None: |
| 337 |
with self._restore_package_cache(): |
| 338 |
archive_path = os.path.join(resources.RESOURCE_PATH, "x.zip") |
| 339 |
sys.path.insert(0, archive_path) |
| 340 |
module = self.manager.ast_from_module_name("xxx.test") |
| 341 |
self.assertEqual(module.name, "xxx.test") |
| 342 |
end = os.path.join(archive_path, "xxx", "test") |
| 343 |
self.assertTrue( |
| 344 |
module.file.endswith(end), f"{module.file} doesn't endswith {end}" |
| 345 |
) |
| 346 |
|
| 347 |
def test_zip_import_data(self) -> None: |
| 348 |
"""Check if zip_import_data works.""" |
| 349 |
with self._restore_package_cache(): |
| 350 |
filepath = resources.find("data/MyPyPa-0.1.0-py2.5.zip/mypypa") |
| 351 |
ast = self.manager.zip_import_data(filepath) |
| 352 |
self.assertEqual(ast.name, "mypypa") |
| 353 |
|
| 354 |
def test_zip_import_data_without_zipimport(self) -> None: |
| 355 |
"""Check if zip_import_data return None without zipimport.""" |
| 356 |
self.assertEqual(self.manager.zip_import_data("path"), None) |
| 357 |
|
| 358 |
def test_file_from_module(self) -> None: |
| 359 |
"""Check if the unittest filepath is equals to the result of the method.""" |
| 360 |
self.assertEqual( |
| 361 |
_get_file_from_object(unittest), |
| 362 |
self.manager.file_from_module_name("unittest", None).location, |
| 363 |
) |
| 364 |
|
| 365 |
def test_file_from_module_name_astro_building_exception(self) -> None: |
| 366 |
"""Check if the method raises an exception with a wrong module name.""" |
| 367 |
self.assertRaises( |
| 368 |
AstroidBuildingError, |
| 369 |
self.manager.file_from_module_name, |
| 370 |
"unhandledModule", |
| 371 |
None, |
| 372 |
) |
| 373 |
|
| 374 |
def test_ast_from_module(self) -> None: |
| 375 |
ast = self.manager.ast_from_module(unittest) |
| 376 |
self.assertEqual(ast.pure_python, True) |
| 377 |
ast = self.manager.ast_from_module(time) |
| 378 |
self.assertEqual(ast.pure_python, False) |
| 379 |
|
| 380 |
def test_ast_from_module_cache(self) -> None: |
| 381 |
"""Check if the module is in the cache manager.""" |
| 382 |
ast = self.manager.ast_from_module(unittest) |
| 383 |
self.assertEqual(ast.name, "unittest") |
| 384 |
self.assertIn("unittest", self.manager.astroid_cache) |
| 385 |
|
| 386 |
def test_ast_from_class(self) -> None: |
| 387 |
ast = self.manager.ast_from_class(int) |
| 388 |
self.assertEqual(ast.name, "int") |
| 389 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 390 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 391 |
|
| 392 |
ast = self.manager.ast_from_class(object) |
| 393 |
self.assertEqual(ast.name, "object") |
| 394 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 395 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 396 |
self.assertIn("__setattr__", ast) |
| 397 |
|
| 398 |
def test_ast_from_class_with_module(self) -> None: |
| 399 |
"""Check if the method works with the module name.""" |
| 400 |
ast = self.manager.ast_from_class(int, int.__module__) |
| 401 |
self.assertEqual(ast.name, "int") |
| 402 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 403 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 404 |
|
| 405 |
ast = self.manager.ast_from_class(object, object.__module__) |
| 406 |
self.assertEqual(ast.name, "object") |
| 407 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 408 |
self.assertEqual(ast.parent.frame().name, "builtins") |
| 409 |
self.assertIn("__setattr__", ast) |
| 410 |
|
| 411 |
def test_ast_from_class_attr_error(self) -> None: |
| 412 |
"""Give a wrong class at the ast_from_class method.""" |
| 413 |
self.assertRaises(AstroidBuildingError, self.manager.ast_from_class, None) |
| 414 |
|
| 415 |
def test_failed_import_hooks(self) -> None: |
| 416 |
def hook(modname: str): |
| 417 |
if modname == "foo.bar": |
| 418 |
return unittest |
| 419 |
|
| 420 |
raise AstroidBuildingError() |
| 421 |
|
| 422 |
with self.assertRaises(AstroidBuildingError): |
| 423 |
self.manager.ast_from_module_name("foo.bar") |
| 424 |
|
| 425 |
with self._restore_package_cache(): |
| 426 |
self.manager.register_failed_import_hook(hook) |
| 427 |
self.assertEqual(unittest, self.manager.ast_from_module_name("foo.bar")) |
| 428 |
with self.assertRaises(AstroidBuildingError): |
| 429 |
self.manager.ast_from_module_name("foo.bar.baz") |
| 430 |
|
| 431 |
def test_same_name_import_module(self) -> None: |
| 432 |
"""Test inference of an import statement with the same name as the module. |
| 433 |
|
| 434 |
See https://github.com/pylint-dev/pylint/issues/5151. |
| 435 |
""" |
| 436 |
math_file = resources.find("data/import_conflicting_names/math.py") |
| 437 |
module = self.manager.ast_from_file(math_file) |
| 438 |
|
| 439 |
# Change the cache key and module name to mimic importing the test file |
| 440 |
# from the root/top level. This creates a clash between math.py and stdlib math. |
| 441 |
self.manager.astroid_cache["math"] = self.manager.astroid_cache.pop(module.name) |
| 442 |
module.name = "math" |
| 443 |
|
| 444 |
# Infer the 'import math' statement |
| 445 |
stdlib_math = next(module.body[1].value.args[0].infer()) |
| 446 |
assert self.manager.astroid_cache["math"] != stdlib_math |
| 447 |
|
| 448 |
def test_raises_exception_for_empty_modname(self) -> None: |
| 449 |
with pytest.raises(AstroidBuildingError): |
| 450 |
self.manager.ast_from_module_name(None) |
| 451 |
|
| 452 |
def test_denied_modules_raise(self) -> None: |
| 453 |
self.manager.module_denylist.add("random") |
| 454 |
with pytest.raises(AstroidImportError, match="random"): |
| 455 |
self.manager.ast_from_module_name("random") |
| 456 |
# and module not in the deny list shouldn't raise |
| 457 |
self.manager.ast_from_module_name("math") |
| 458 |
|
| 459 |
|
| 460 |
class IsolatedAstroidManagerTest(unittest.TestCase): |
| 461 |
@pytest.mark.skipif(PY312_PLUS, reason="distutils was removed in python 3.12") |
| 462 |
def test_no_user_warning(self): |
| 463 |
"""When Python 3.12 is minimum, this test will no longer provide value.""" |
| 464 |
mgr = manager.AstroidManager() |
| 465 |
self.addCleanup(mgr.clear_cache) |
| 466 |
with warnings.catch_warnings(): |
| 467 |
warnings.filterwarnings("error", category=UserWarning) |
| 468 |
mgr.ast_from_module_name("setuptools") |
| 469 |
try: |
| 470 |
mgr.ast_from_module_name("pip") |
| 471 |
except astroid.AstroidImportError: |
| 472 |
pytest.skip("pip is not installed") |
| 473 |
|
| 474 |
|
| 475 |
class BorgAstroidManagerTC(unittest.TestCase): |
| 476 |
def test_borg(self) -> None: |
| 477 |
"""Test that the AstroidManager is really a borg, i.e. that two different |
| 478 |
instances has same cache. |
| 479 |
""" |
| 480 |
first_manager = manager.AstroidManager() |
| 481 |
built = first_manager.ast_from_module_name("builtins") |
| 482 |
|
| 483 |
second_manager = manager.AstroidManager() |
| 484 |
second_built = second_manager.ast_from_module_name("builtins") |
| 485 |
self.assertIs(built, second_built) |
| 486 |
|
| 487 |
def test_max_inferable_values(self) -> None: |
| 488 |
mgr = manager.AstroidManager() |
| 489 |
original_limit = mgr.max_inferable_values |
| 490 |
|
| 491 |
def reset_limit(): |
| 492 |
nonlocal original_limit |
| 493 |
manager.AstroidManager().max_inferable_values = original_limit |
| 494 |
|
| 495 |
self.addCleanup(reset_limit) |
| 496 |
|
| 497 |
mgr.max_inferable_values = 4 |
| 498 |
self.assertEqual(manager.AstroidManager.brain["max_inferable_values"], 4) |
| 499 |
|
| 500 |
|
| 501 |
class ClearCacheTest(unittest.TestCase): |
| 502 |
def test_clear_cache_clears_other_lru_caches(self) -> None: |
| 503 |
lrus = ( |
| 504 |
astroid.nodes._base_nodes.LookupMixIn.lookup, |
| 505 |
astroid.modutils._cache_normalize_path_, |
| 506 |
util.is_namespace, |
| 507 |
astroid.interpreter.objectmodel.ObjectModel.attributes, |
| 508 |
ClassDef._metaclass_lookup_attribute, |
| 509 |
) |
| 510 |
|
| 511 |
# Get a baseline for the size of the cache after simply calling bootstrap() |
| 512 |
baseline_cache_infos = [lru.cache_info() for lru in lrus] |
| 513 |
|
| 514 |
# Generate some hits and misses |
| 515 |
module = Module("", file="", path=[], package=False) |
| 516 |
ClassDef( |
| 517 |
"", |
| 518 |
lineno=0, |
| 519 |
col_offset=0, |
| 520 |
end_lineno=0, |
| 521 |
end_col_offset=0, |
| 522 |
parent=module, |
| 523 |
).lookup("garbage") |
| 524 |
module_in_path("unittest", "garbage_path") |
| 525 |
util.is_namespace("unittest") |
| 526 |
astroid.interpreter.objectmodel.ObjectModel().attributes() |
| 527 |
with pytest.raises(AttributeInferenceError): |
| 528 |
ClassDef( |
| 529 |
"", |
| 530 |
lineno=0, |
| 531 |
col_offset=0, |
| 532 |
end_lineno=0, |
| 533 |
end_col_offset=0, |
| 534 |
parent=module, |
| 535 |
).getattr("garbage") |
| 536 |
|
| 537 |
# Did the hits or misses actually happen? |
| 538 |
incremented_cache_infos = [lru.cache_info() for lru in lrus] |
| 539 |
for incremented_cache, baseline_cache in zip( |
| 540 |
incremented_cache_infos, baseline_cache_infos |
| 541 |
): |
| 542 |
with self.subTest(incremented_cache=incremented_cache): |
| 543 |
self.assertGreater( |
| 544 |
incremented_cache.hits + incremented_cache.misses, |
| 545 |
baseline_cache.hits + baseline_cache.misses, |
| 546 |
) |
| 547 |
|
| 548 |
astroid.MANAGER.clear_cache() # also calls bootstrap() |
| 549 |
|
| 550 |
self.assertEqual(astroid.context._INFERENCE_CACHE, {}) |
| 551 |
|
| 552 |
# The cache sizes are now as low or lower than the original baseline |
| 553 |
cleared_cache_infos = [lru.cache_info() for lru in lrus] |
| 554 |
for cleared_cache, baseline_cache in zip( |
| 555 |
cleared_cache_infos, baseline_cache_infos |
| 556 |
): |
| 557 |
with self.subTest(cleared_cache=cleared_cache): |
| 558 |
# less equal because the "baseline" might have had multiple calls to bootstrap() |
| 559 |
self.assertLessEqual(cleared_cache.currsize, baseline_cache.currsize) |
| 560 |
|
| 561 |
def test_file_cache_after_clear_cache(self) -> None: |
| 562 |
"""Test to mimic the behavior of how pylint lints file and |
| 563 |
ensure clear cache clears everything stored in the cache. |
| 564 |
See https://github.com/pylint-dev/pylint/pull/9932#issuecomment-2364985551 |
| 565 |
for more information. |
| 566 |
""" |
| 567 |
orig_sys_path = sys.path[:] |
| 568 |
try: |
| 569 |
search_path = resources.RESOURCE_PATH |
| 570 |
sys.path.insert(0, search_path) |
| 571 |
node = astroid.MANAGER.ast_from_file(resources.find("data/cache/a.py")) |
| 572 |
self.assertEqual(node.name, "cache.a") |
| 573 |
|
| 574 |
# This import from statement should succeed and update the astroid cache |
| 575 |
importfrom_node = astroid.extract_node("from cache import a") |
| 576 |
importfrom_node.do_import_module(importfrom_node.modname) |
| 577 |
finally: |
| 578 |
sys.path = orig_sys_path |
| 579 |
|
| 580 |
astroid.MANAGER.clear_cache() |
| 581 |
|
| 582 |
importfrom_node = astroid.extract_node("from cache import a") |
| 583 |
# Try import from again after clear cache, this should raise an error |
| 584 |
with self.assertRaises(AstroidBuildingError): |
| 585 |
importfrom_node.do_import_module(importfrom_node.modname) |
| 586 |
|
| 587 |
def test_brain_plugins_reloaded_after_clearing_cache(self) -> None: |
| 588 |
astroid.MANAGER.clear_cache() |
| 589 |
format_call = astroid.extract_node("''.format()") |
| 590 |
inferred = next(format_call.infer()) |
| 591 |
self.assertIsInstance(inferred, Const) |
| 592 |
|
| 593 |
def test_builtins_inference_after_clearing_cache(self) -> None: |
| 594 |
astroid.MANAGER.clear_cache() |
| 595 |
isinstance_call = astroid.extract_node("isinstance(1, int)") |
| 596 |
inferred = next(isinstance_call.infer()) |
| 597 |
self.assertIs(inferred.value, True) |
| 598 |
|
| 599 |
def test_builtins_inference_after_clearing_cache_manually(self) -> None: |
| 600 |
# Not recommended to manipulate this, so we detect it and call clear_cache() instead |
| 601 |
astroid.MANAGER.brain["astroid_cache"].clear() |
| 602 |
isinstance_call = astroid.extract_node("isinstance(1, int)") |
| 603 |
inferred = next(isinstance_call.infer()) |
| 604 |
self.assertIs(inferred.value, True) |
| 605 |
|
| 606 |
|
| 607 |
class NamespacePthParserTest(unittest.TestCase): |
| 608 |
"""Direct coverage for the .pth parsing helpers used by namespace tests.""" |
| 609 |
|
| 610 |
def test_parse_extracts_quoted_tuple(self) -> None: |
| 611 |
line = "import sys; p = os.path.join(s, *('foogle', 'crank'))" |
| 612 |
self.assertEqual(_parse_pth_package_parts(line), ("foogle", "crank")) |
| 613 |
|
| 614 |
def test_parse_handles_double_quotes_and_whitespace(self) -> None: |
| 615 |
line = '*( "foo" , "bar" )' |
| 616 |
self.assertEqual(_parse_pth_package_parts(line), ("foo", "bar")) |
| 617 |
|
| 618 |
def test_parse_skips_empty_tokens(self) -> None: |
| 619 |
line = "*('foo', '', 'bar',)" |
| 620 |
self.assertEqual(_parse_pth_package_parts(line), ("foo", "bar")) |
| 621 |
|
| 622 |
def test_parse_returns_empty_when_no_match(self) -> None: |
| 623 |
self.assertEqual(_parse_pth_package_parts("# comment only"), ()) |
| 624 |
self.assertEqual(_parse_pth_package_parts(""), ()) |