| 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 builtins |
| 6 |
import unittest |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from astroid import builder, helpers, manager, nodes, raw_building, util |
| 11 |
from astroid.builder import AstroidBuilder |
| 12 |
from astroid.const import IS_PYPY, PY312_PLUS |
| 13 |
from astroid.exceptions import InferenceError, _NonDeducibleTypeHierarchy |
| 14 |
|
| 15 |
|
| 16 |
class TestHelpers(unittest.TestCase): |
| 17 |
def setUp(self) -> None: |
| 18 |
builtins_name = builtins.__name__ |
| 19 |
astroid_manager = manager.AstroidManager() |
| 20 |
AstroidBuilder(astroid_manager) # Only to ensure boostrap |
| 21 |
self.builtins = astroid_manager.astroid_cache[builtins_name] |
| 22 |
self.manager = manager.AstroidManager() |
| 23 |
|
| 24 |
def _extract(self, obj_name: str) -> nodes.ClassDef: |
| 25 |
return self.builtins.getattr(obj_name)[0] |
| 26 |
|
| 27 |
def _build_custom_builtin(self, obj_name: str) -> nodes.ClassDef: |
| 28 |
proxy = raw_building.build_class(obj_name, self.builtins) |
| 29 |
return proxy |
| 30 |
|
| 31 |
def assert_classes_equal(self, cls: nodes.ClassDef, other: nodes.ClassDef) -> None: |
| 32 |
self.assertEqual(cls.name, other.name) |
| 33 |
self.assertEqual(cls.parent, other.parent) |
| 34 |
self.assertEqual(cls.qname(), other.qname()) |
| 35 |
|
| 36 |
def test_object_type(self) -> None: |
| 37 |
pairs = [ |
| 38 |
("1", self._extract("int")), |
| 39 |
("[]", self._extract("list")), |
| 40 |
("{1, 2, 3}", self._extract("set")), |
| 41 |
("{1:2, 4:3}", self._extract("dict")), |
| 42 |
("type", self._extract("type")), |
| 43 |
("object", self._extract("type")), |
| 44 |
("object()", self._extract("object")), |
| 45 |
("super()", self._extract("super")), |
| 46 |
("lambda: None", self._build_custom_builtin("function")), |
| 47 |
("len", self._build_custom_builtin("builtin_function_or_method")), |
| 48 |
("None", self._build_custom_builtin("NoneType")), |
| 49 |
("import sys\nsys#@", self._build_custom_builtin("module")), |
| 50 |
] |
| 51 |
for code, expected in pairs: |
| 52 |
node = builder.extract_node(code) |
| 53 |
objtype = helpers.object_type(node) |
| 54 |
self.assert_classes_equal(objtype, expected) |
| 55 |
|
| 56 |
def test_object_type_classes_and_functions(self) -> None: |
| 57 |
ast_nodes = builder.extract_node(""" |
| 58 |
def generator(): |
| 59 |
yield |
| 60 |
|
| 61 |
class A(object): |
| 62 |
def test(self): |
| 63 |
self #@ |
| 64 |
@classmethod |
| 65 |
def cls_method(cls): pass |
| 66 |
@staticmethod |
| 67 |
def static_method(): pass |
| 68 |
A #@ |
| 69 |
A() #@ |
| 70 |
A.test #@ |
| 71 |
A().test #@ |
| 72 |
A.cls_method #@ |
| 73 |
A().cls_method #@ |
| 74 |
A.static_method #@ |
| 75 |
A().static_method #@ |
| 76 |
generator() #@ |
| 77 |
""") |
| 78 |
assert isinstance(ast_nodes, list) |
| 79 |
from_self = helpers.object_type(ast_nodes[0]) |
| 80 |
cls = next(ast_nodes[1].infer()) |
| 81 |
self.assert_classes_equal(from_self, cls) |
| 82 |
|
| 83 |
cls_type = helpers.object_type(ast_nodes[1]) |
| 84 |
self.assert_classes_equal(cls_type, self._extract("type")) |
| 85 |
|
| 86 |
instance_type = helpers.object_type(ast_nodes[2]) |
| 87 |
cls = next(ast_nodes[2].infer())._proxied |
| 88 |
self.assert_classes_equal(instance_type, cls) |
| 89 |
|
| 90 |
expected_method_types = [ |
| 91 |
(ast_nodes[3], "function"), |
| 92 |
(ast_nodes[4], "method"), |
| 93 |
(ast_nodes[5], "method"), |
| 94 |
(ast_nodes[6], "method"), |
| 95 |
(ast_nodes[7], "function"), |
| 96 |
(ast_nodes[8], "function"), |
| 97 |
(ast_nodes[9], "generator"), |
| 98 |
] |
| 99 |
for node, expected in expected_method_types: |
| 100 |
node_type = helpers.object_type(node) |
| 101 |
expected_type = self._build_custom_builtin(expected) |
| 102 |
self.assert_classes_equal(node_type, expected_type) |
| 103 |
|
| 104 |
def test_object_type_metaclasses(self) -> None: |
| 105 |
module = builder.parse(""" |
| 106 |
import abc |
| 107 |
class Meta(metaclass=abc.ABCMeta): |
| 108 |
pass |
| 109 |
meta_instance = Meta() |
| 110 |
""") |
| 111 |
meta_type = helpers.object_type(module["Meta"]) |
| 112 |
self.assert_classes_equal(meta_type, module["Meta"].metaclass()) |
| 113 |
|
| 114 |
meta_instance = next(module["meta_instance"].infer()) |
| 115 |
instance_type = helpers.object_type(meta_instance) |
| 116 |
self.assert_classes_equal(instance_type, module["Meta"]) |
| 117 |
|
| 118 |
def test_object_type_most_derived(self) -> None: |
| 119 |
node = builder.extract_node(""" |
| 120 |
class A(type): |
| 121 |
def __new__(*args, **kwargs): |
| 122 |
return type.__new__(*args, **kwargs) |
| 123 |
class B(object): pass |
| 124 |
class C(object, metaclass=A): pass |
| 125 |
|
| 126 |
# The most derived metaclass of D is A rather than type. |
| 127 |
class D(B , C): #@ |
| 128 |
pass |
| 129 |
""") |
| 130 |
assert isinstance(node, nodes.NodeNG) |
| 131 |
metaclass = node.metaclass() |
| 132 |
self.assertEqual(metaclass.name, "A") |
| 133 |
obj_type = helpers.object_type(node) |
| 134 |
self.assertEqual(metaclass, obj_type) |
| 135 |
|
| 136 |
def test_inference_errors(self) -> None: |
| 137 |
node = builder.extract_node(""" |
| 138 |
from unknown import Unknown |
| 139 |
u = Unknown #@ |
| 140 |
""") |
| 141 |
self.assertEqual(helpers.object_type(node), util.Uninferable) |
| 142 |
|
| 143 |
@pytest.mark.skipif(IS_PYPY, reason="__code__ will not be Unknown on PyPy") |
| 144 |
def test_inference_errors_2(self) -> None: |
| 145 |
node = builder.extract_node("type(float.__new__.__code__)") |
| 146 |
self.assertIs(helpers.object_type(node), util.Uninferable) |
| 147 |
|
| 148 |
def test_object_type_too_many_types(self) -> None: |
| 149 |
node = builder.extract_node(""" |
| 150 |
from unknown import Unknown |
| 151 |
def test(x): |
| 152 |
if x: |
| 153 |
return lambda: None |
| 154 |
else: |
| 155 |
return 1 |
| 156 |
test(Unknown) #@ |
| 157 |
""") |
| 158 |
self.assertEqual(helpers.object_type(node), util.Uninferable) |
| 159 |
|
| 160 |
def test_is_subtype(self) -> None: |
| 161 |
ast_nodes = builder.extract_node(""" |
| 162 |
class int_subclass(int): |
| 163 |
pass |
| 164 |
class A(object): pass #@ |
| 165 |
class B(A): pass #@ |
| 166 |
class C(A): pass #@ |
| 167 |
int_subclass() #@ |
| 168 |
""") |
| 169 |
assert isinstance(ast_nodes, list) |
| 170 |
cls_a = ast_nodes[0] |
| 171 |
cls_b = ast_nodes[1] |
| 172 |
cls_c = ast_nodes[2] |
| 173 |
int_subclass = ast_nodes[3] |
| 174 |
int_subclass = helpers.object_type(next(int_subclass.infer())) |
| 175 |
base_int = self._extract("int") |
| 176 |
self.assertTrue(helpers.is_subtype(int_subclass, base_int)) |
| 177 |
self.assertTrue(helpers.is_supertype(base_int, int_subclass)) |
| 178 |
|
| 179 |
self.assertTrue(helpers.is_supertype(cls_a, cls_b)) |
| 180 |
self.assertTrue(helpers.is_supertype(cls_a, cls_c)) |
| 181 |
self.assertTrue(helpers.is_subtype(cls_b, cls_a)) |
| 182 |
self.assertTrue(helpers.is_subtype(cls_c, cls_a)) |
| 183 |
self.assertFalse(helpers.is_subtype(cls_a, cls_b)) |
| 184 |
self.assertFalse(helpers.is_subtype(cls_a, cls_b)) |
| 185 |
|
| 186 |
def test_is_subtype_supertype_mro_error(self) -> None: |
| 187 |
cls_e, cls_f = builder.extract_node(""" |
| 188 |
class A(object): pass |
| 189 |
class B(A): pass |
| 190 |
class C(A): pass |
| 191 |
class D(B, C): pass |
| 192 |
class E(C, B): pass #@ |
| 193 |
class F(D, E): pass #@ |
| 194 |
""") |
| 195 |
self.assertFalse(helpers.is_subtype(cls_e, cls_f)) |
| 196 |
|
| 197 |
self.assertFalse(helpers.is_subtype(cls_e, cls_f)) |
| 198 |
with self.assertRaises(_NonDeducibleTypeHierarchy): |
| 199 |
helpers.is_subtype(cls_f, cls_e) |
| 200 |
self.assertFalse(helpers.is_supertype(cls_f, cls_e)) |
| 201 |
|
| 202 |
def test_is_subtype_supertype_unknown_bases(self) -> None: |
| 203 |
cls_a, cls_b = builder.extract_node(""" |
| 204 |
from unknown import Unknown |
| 205 |
class A(Unknown): pass #@ |
| 206 |
class B(A): pass #@ |
| 207 |
""") |
| 208 |
with self.assertRaises(_NonDeducibleTypeHierarchy): |
| 209 |
helpers.is_subtype(cls_a, cls_b) |
| 210 |
with self.assertRaises(_NonDeducibleTypeHierarchy): |
| 211 |
helpers.is_supertype(cls_a, cls_b) |
| 212 |
|
| 213 |
def test_is_subtype_supertype_unrelated_classes(self) -> None: |
| 214 |
cls_a, cls_b = builder.extract_node(""" |
| 215 |
class A(object): pass #@ |
| 216 |
class B(object): pass #@ |
| 217 |
""") |
| 218 |
self.assertFalse(helpers.is_subtype(cls_a, cls_b)) |
| 219 |
self.assertFalse(helpers.is_subtype(cls_b, cls_a)) |
| 220 |
self.assertFalse(helpers.is_supertype(cls_a, cls_b)) |
| 221 |
self.assertFalse(helpers.is_supertype(cls_b, cls_a)) |
| 222 |
|
| 223 |
def test_is_subtype_supertype_classes_no_type_ancestor(self) -> None: |
| 224 |
cls_a = builder.extract_node(""" |
| 225 |
class A(object): #@ |
| 226 |
pass |
| 227 |
""") |
| 228 |
builtin_type = self._extract("type") |
| 229 |
self.assertFalse(helpers.is_supertype(builtin_type, cls_a)) |
| 230 |
self.assertFalse(helpers.is_subtype(cls_a, builtin_type)) |
| 231 |
|
| 232 |
def test_is_subtype_supertype_classes_metaclasses(self) -> None: |
| 233 |
cls_a = builder.extract_node(""" |
| 234 |
class A(type): #@ |
| 235 |
pass |
| 236 |
""") |
| 237 |
builtin_type = self._extract("type") |
| 238 |
self.assertTrue(helpers.is_supertype(builtin_type, cls_a)) |
| 239 |
self.assertTrue(helpers.is_subtype(cls_a, builtin_type)) |
| 240 |
|
| 241 |
def test_is_subtype_supertype_function_metaclass(self) -> None: |
| 242 |
"""A metaclass that is a function makes the type of the class a function. |
| 243 |
|
| 244 |
Regression test for https://github.com/pylint-dev/astroid/issues/3191 |
| 245 |
""" |
| 246 |
cls_a = builder.extract_node(""" |
| 247 |
class A(metaclass=sum): #@ |
| 248 |
pass |
| 249 |
""") |
| 250 |
cls_a_type = helpers.object_type(cls_a) |
| 251 |
self.assertIsInstance(cls_a_type, nodes.FunctionDef) |
| 252 |
builtin_type = self._extract("type") |
| 253 |
# A function has no bases, so the hierarchy cannot be deduced. |
| 254 |
with self.assertRaises(_NonDeducibleTypeHierarchy): |
| 255 |
helpers.is_subtype(cls_a_type, builtin_type) |
| 256 |
with self.assertRaises(_NonDeducibleTypeHierarchy): |
| 257 |
helpers.is_supertype(cls_a_type, builtin_type) |
| 258 |
|
| 259 |
def test_binop_with_function_metaclass_no_crash(self) -> None: |
| 260 |
"""Regression test for https://github.com/pylint-dev/astroid/issues/3191""" |
| 261 |
node = builder.extract_node(""" |
| 262 |
class A(metaclass=sum): |
| 263 |
pass |
| 264 |
A | None #@ |
| 265 |
""") |
| 266 |
# Inference must not raise ``AttributeError``. |
| 267 |
self.assertIs(next(node.infer()), util.Uninferable) |
| 268 |
|
| 269 |
|
| 270 |
def test_uninferable_for_safe_infer() -> None: |
| 271 |
uninfer = util.Uninferable |
| 272 |
assert util.safe_infer(util.Uninferable) == uninfer |
| 273 |
|
| 274 |
|
| 275 |
def test_class_to_container() -> None: |
| 276 |
node = builder.extract_node("""isinstance(3, int)""") |
| 277 |
|
| 278 |
container = helpers.class_or_tuple_to_container(node.args[1]) |
| 279 |
|
| 280 |
assert len(container) == 1 |
| 281 |
assert isinstance(container[0], nodes.ClassDef) |
| 282 |
assert container[0].name == "int" |
| 283 |
|
| 284 |
|
| 285 |
def test_tuple_to_container() -> None: |
| 286 |
node = builder.extract_node("""isinstance(3, (int, str))""") |
| 287 |
|
| 288 |
container = helpers.class_or_tuple_to_container(node.args[1]) |
| 289 |
|
| 290 |
assert len(container) == 2 |
| 291 |
|
| 292 |
assert isinstance(container[0], nodes.ClassDef) |
| 293 |
assert container[0].name == "int" |
| 294 |
|
| 295 |
assert isinstance(container[1], nodes.ClassDef) |
| 296 |
assert container[1].name == "str" |
| 297 |
|
| 298 |
|
| 299 |
def test_class_to_container_uninferable() -> None: |
| 300 |
node = builder.extract_node(""" |
| 301 |
def f(x): |
| 302 |
isinstance(3, x) #@ |
| 303 |
""") |
| 304 |
|
| 305 |
container = helpers.class_or_tuple_to_container(node.args[1]) |
| 306 |
|
| 307 |
assert len(container) == 1 |
| 308 |
assert container[0] is util.Uninferable |
| 309 |
|
| 310 |
|
| 311 |
def test_tuple_to_container_uninferable() -> None: |
| 312 |
node = builder.extract_node(""" |
| 313 |
def f(x, y): |
| 314 |
isinstance(3, (x, y)) #@ |
| 315 |
""") |
| 316 |
|
| 317 |
container = helpers.class_or_tuple_to_container(node.args[1]) |
| 318 |
|
| 319 |
assert len(container) == 2 |
| 320 |
assert container[0] is util.Uninferable |
| 321 |
assert container[1] is util.Uninferable |
| 322 |
|
| 323 |
|
| 324 |
def test_class_to_container_inference_error() -> None: |
| 325 |
node = builder.extract_node("""isinstance(3, undefined_type)""") |
| 326 |
|
| 327 |
with pytest.raises(InferenceError): |
| 328 |
helpers.class_or_tuple_to_container(node.args[1]) |
| 329 |
|
| 330 |
|
| 331 |
def test_tuple_to_container_inference_error() -> None: |
| 332 |
node = builder.extract_node("""isinstance(3, (int, undefined_type))""") |
| 333 |
|
| 334 |
with pytest.raises(InferenceError): |
| 335 |
helpers.class_or_tuple_to_container(node.args[1]) |
| 336 |
|
| 337 |
|
| 338 |
@pytest.mark.skipif(not PY312_PLUS, reason="PEP 695 syntax requires Python 3.12") |
| 339 |
def test_object_type_pep695_type_params() -> None: |
| 340 |
"""PEP 695 type parameters have no concrete type at static-analysis time. |
| 341 |
|
| 342 |
Regression test for the AssertionError introduced when |
| 343 |
``generic_type_assigned_stmts`` started yielding the TypeVar/TypeVarTuple/ |
| 344 |
ParamSpec node itself: ``object_type`` previously crashed instead of |
| 345 |
returning ``Uninferable``. |
| 346 |
""" |
| 347 |
binop = builder.extract_node(""" |
| 348 |
def func[_T](var: _T) -> _T: |
| 349 |
value: _T | None = None #@ |
| 350 |
return var |
| 351 |
""").annotation |
| 352 |
assert helpers.object_type(binop) is util.Uninferable |
| 353 |
|
| 354 |
for code in ( |
| 355 |
"type Alias[*Ts] = tuple[*Ts]", |
| 356 |
"type Alias[**P] = Callable[P, int]", |
| 357 |
): |
| 358 |
assign = builder.extract_node(code) |
| 359 |
type_param_name = assign.type_params[0].name |
| 360 |
assert helpers.object_type(type_param_name) is util.Uninferable |