| 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 |
from __future__ import annotations |
| 6 |
|
| 7 |
import io |
| 8 |
import re |
| 9 |
import sys |
| 10 |
import unittest |
| 11 |
from unittest.mock import patch |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
import astroid |
| 16 |
from astroid import MANAGER, builder, nodes, objects, test_utils, util |
| 17 |
from astroid.bases import Instance |
| 18 |
from astroid.brain.brain_namedtuple_enum import _get_namedtuple_fields |
| 19 |
from astroid.const import PY312_PLUS, PY313_PLUS, PY315_PLUS |
| 20 |
from astroid.exceptions import ( |
| 21 |
AttributeInferenceError, |
| 22 |
InferenceError, |
| 23 |
UseInferenceDefault, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
def assertEqualMro(klass: nodes.ClassDef, expected_mro: list[str]) -> None: |
| 28 |
"""Check mro names.""" |
| 29 |
assert [member.qname() for member in klass.mro()] == expected_mro |
| 30 |
|
| 31 |
|
| 32 |
class CollectionsDequeTests(unittest.TestCase): |
| 33 |
def _inferred_queue_instance(self) -> Instance: |
| 34 |
node = builder.extract_node(""" |
| 35 |
import collections |
| 36 |
q = collections.deque([]) |
| 37 |
q |
| 38 |
""") |
| 39 |
return next(node.infer()) |
| 40 |
|
| 41 |
def test_deque(self) -> None: |
| 42 |
inferred = self._inferred_queue_instance() |
| 43 |
self.assertTrue(inferred.getattr("__len__")) |
| 44 |
|
| 45 |
def test_deque_py35methods(self) -> None: |
| 46 |
inferred = self._inferred_queue_instance() |
| 47 |
self.assertIn("copy", inferred.locals) |
| 48 |
self.assertIn("insert", inferred.locals) |
| 49 |
self.assertIn("index", inferred.locals) |
| 50 |
|
| 51 |
def test_deque_py39methods(self): |
| 52 |
inferred = self._inferred_queue_instance() |
| 53 |
self.assertTrue(inferred.getattr("__class_getitem__")) |
| 54 |
|
| 55 |
|
| 56 |
class OrderedDictTest(unittest.TestCase): |
| 57 |
def _inferred_ordered_dict_instance(self) -> Instance: |
| 58 |
node = builder.extract_node(""" |
| 59 |
import collections |
| 60 |
d = collections.OrderedDict() |
| 61 |
d |
| 62 |
""") |
| 63 |
return next(node.infer()) |
| 64 |
|
| 65 |
def test_ordered_dict_py34method(self) -> None: |
| 66 |
inferred = self._inferred_ordered_dict_instance() |
| 67 |
self.assertIn("move_to_end", inferred.locals) |
| 68 |
|
| 69 |
|
| 70 |
class DefaultDictTest(unittest.TestCase): |
| 71 |
def test_1(self) -> None: |
| 72 |
node = builder.extract_node(""" |
| 73 |
from collections import defaultdict |
| 74 |
|
| 75 |
X = defaultdict(int) |
| 76 |
X[0] |
| 77 |
""") |
| 78 |
inferred = next(node.infer()) |
| 79 |
self.assertIs(util.Uninferable, inferred) |
| 80 |
|
| 81 |
|
| 82 |
class ModuleExtenderTest(unittest.TestCase): |
| 83 |
def test_extension_modules(self) -> None: |
| 84 |
transformer = MANAGER._transform |
| 85 |
for extender, _ in transformer.transforms[nodes.Module]: |
| 86 |
n = nodes.Module("__main__") |
| 87 |
extender(n) |
| 88 |
|
| 89 |
|
| 90 |
def streams_are_fine(): |
| 91 |
"""Check if streams are being overwritten, |
| 92 |
for example, by pytest |
| 93 |
|
| 94 |
stream inference will not work if they are overwritten |
| 95 |
|
| 96 |
PY3 only |
| 97 |
""" |
| 98 |
return all(isinstance(s, io.IOBase) for s in (sys.stdout, sys.stderr, sys.stdin)) |
| 99 |
|
| 100 |
|
| 101 |
class IOBrainTest(unittest.TestCase): |
| 102 |
@unittest.skipUnless( |
| 103 |
streams_are_fine(), |
| 104 |
"Needs Python 3 io model / doesn't work with plain pytest." |
| 105 |
"use pytest -s for this test to work", |
| 106 |
) |
| 107 |
def test_sys_streams(self): |
| 108 |
for name in ("stdout", "stderr", "stdin"): |
| 109 |
node = astroid.extract_node(f""" |
| 110 |
import sys |
| 111 |
sys.{name} |
| 112 |
""") |
| 113 |
inferred = next(node.infer()) |
| 114 |
buffer_attr = next(inferred.igetattr("buffer")) |
| 115 |
self.assertIsInstance(buffer_attr, astroid.Instance) |
| 116 |
self.assertEqual(buffer_attr.name, "BufferedWriter") |
| 117 |
raw = next(buffer_attr.igetattr("raw")) |
| 118 |
self.assertIsInstance(raw, astroid.Instance) |
| 119 |
self.assertEqual(raw.name, "FileIO") |
| 120 |
|
| 121 |
|
| 122 |
class TypeBrain(unittest.TestCase): |
| 123 |
def test_type_subscript(self): |
| 124 |
""" |
| 125 |
Check that type object has the __class_getitem__ method |
| 126 |
when it is used as a subscript |
| 127 |
""" |
| 128 |
src = builder.extract_node(""" |
| 129 |
a: type[int] = int |
| 130 |
""") |
| 131 |
val_inf = src.annotation.value.inferred()[0] |
| 132 |
self.assertIsInstance(val_inf, nodes.ClassDef) |
| 133 |
self.assertEqual(val_inf.name, "type") |
| 134 |
meth_inf = val_inf.getattr("__class_getitem__")[0] |
| 135 |
self.assertIsInstance(meth_inf, nodes.FunctionDef) |
| 136 |
|
| 137 |
def test_invalid_type_subscript(self): |
| 138 |
""" |
| 139 |
Check that a type (str for example) that inherits |
| 140 |
from type does not have __class_getitem__ method even |
| 141 |
when it is used as a subscript |
| 142 |
""" |
| 143 |
src = builder.extract_node(""" |
| 144 |
a: str[int] = "abc" |
| 145 |
""") |
| 146 |
val_inf = src.annotation.value.inferred()[0] |
| 147 |
self.assertIsInstance(val_inf, nodes.ClassDef) |
| 148 |
self.assertEqual(val_inf.name, "str") |
| 149 |
with self.assertRaises(AttributeInferenceError): |
| 150 |
# pylint: disable=expression-not-assigned |
| 151 |
# noinspection PyStatementEffect |
| 152 |
val_inf.getattr("__class_getitem__")[0] |
| 153 |
|
| 154 |
def test_builtin_subscriptable(self): |
| 155 |
"""Starting with python3.9 builtin types such as list are subscriptable. |
| 156 |
Any builtin class such as "enumerate" or "staticmethod" also works.""" |
| 157 |
for typename in ("tuple", "list", "dict", "set", "frozenset", "enumerate"): |
| 158 |
src = f""" |
| 159 |
{typename:s}[int] |
| 160 |
""" |
| 161 |
right_node = builder.extract_node(src) |
| 162 |
inferred = next(right_node.infer()) |
| 163 |
self.assertIsInstance(inferred, nodes.ClassDef) |
| 164 |
self.assertIsInstance(inferred.getattr("__iter__")[0], nodes.FunctionDef) |
| 165 |
|
| 166 |
|
| 167 |
def check_metaclass_is_abc(node: nodes.ClassDef): |
| 168 |
if PY312_PLUS and node.name == "ByteString": |
| 169 |
# .metaclass() finds the first metaclass in the mro(), |
| 170 |
# which, from 3.12, is _DeprecateByteStringMeta (unhelpful) |
| 171 |
# until ByteString is removed in 3.17. |
| 172 |
# Jump over the first two ByteString classes in the mro(). |
| 173 |
check_metaclass_is_abc(node.mro()[2]) |
| 174 |
else: |
| 175 |
meta = node.metaclass() |
| 176 |
assert isinstance(meta, nodes.ClassDef) |
| 177 |
assert meta.name == "ABCMeta" |
| 178 |
|
| 179 |
|
| 180 |
class CollectionsBrain(unittest.TestCase): |
| 181 |
def test_collections_abc_is_importable(self) -> None: |
| 182 |
""" |
| 183 |
Test that we can import `collections.abc`. |
| 184 |
|
| 185 |
The collections.abc has gone through various formats of being frozen. Therefore, we ensure |
| 186 |
that we can still import it (correctly). |
| 187 |
""" |
| 188 |
import_node = builder.extract_node("import collections.abc") |
| 189 |
assert isinstance(import_node, nodes.Import) |
| 190 |
imported_module = import_node.do_import_module(import_node.names[0][0]) |
| 191 |
# Make sure that the file we have imported is actually the submodule of collections and |
| 192 |
# not the `abc` module. (Which would happen if you call `importlib.util.find_spec("abc")` |
| 193 |
# instead of `importlib.util.find_spec("collections.abc")`) |
| 194 |
assert isinstance(imported_module.file, str) |
| 195 |
assert "collections" in imported_module.file |
| 196 |
|
| 197 |
def test_collections_object_not_subscriptable(self) -> None: |
| 198 |
""" |
| 199 |
Test that unsubscriptable types are detected |
| 200 |
Hashable is not subscriptable even with python39 |
| 201 |
""" |
| 202 |
wrong_node = builder.extract_node(""" |
| 203 |
import collections.abc |
| 204 |
collections.abc.Hashable[int] |
| 205 |
""") |
| 206 |
with self.assertRaises(InferenceError): |
| 207 |
next(wrong_node.infer()) |
| 208 |
right_node = builder.extract_node(""" |
| 209 |
import collections.abc |
| 210 |
collections.abc.Hashable |
| 211 |
""") |
| 212 |
inferred = next(right_node.infer()) |
| 213 |
check_metaclass_is_abc(inferred) |
| 214 |
assertEqualMro( |
| 215 |
inferred, |
| 216 |
[ |
| 217 |
"_collections_abc.Hashable", |
| 218 |
"builtins.object", |
| 219 |
], |
| 220 |
) |
| 221 |
with self.assertRaises(AttributeInferenceError): |
| 222 |
inferred.getattr("__class_getitem__") |
| 223 |
|
| 224 |
def test_collections_object_subscriptable(self): |
| 225 |
"""Starting with python39 some object of collections module are subscriptable. Test one of them""" |
| 226 |
right_node = builder.extract_node(""" |
| 227 |
import collections.abc |
| 228 |
collections.abc.MutableSet[int] |
| 229 |
""") |
| 230 |
inferred = next(right_node.infer()) |
| 231 |
check_metaclass_is_abc(inferred) |
| 232 |
assertEqualMro( |
| 233 |
inferred, |
| 234 |
[ |
| 235 |
"_collections_abc.MutableSet", |
| 236 |
"_collections_abc.Set", |
| 237 |
"_collections_abc.Collection", |
| 238 |
"_collections_abc.Sized", |
| 239 |
"_collections_abc.Iterable", |
| 240 |
"_collections_abc.Container", |
| 241 |
"builtins.object", |
| 242 |
], |
| 243 |
) |
| 244 |
self.assertIsInstance( |
| 245 |
inferred.getattr("__class_getitem__")[0], nodes.FunctionDef |
| 246 |
) |
| 247 |
|
| 248 |
def test_collections_object_subscriptable_2(self): |
| 249 |
"""Starting with python39 Iterator in the collection.abc module is subscriptable""" |
| 250 |
node = builder.extract_node(""" |
| 251 |
import collections.abc |
| 252 |
class Derived(collections.abc.Iterator[int]): |
| 253 |
pass |
| 254 |
""") |
| 255 |
inferred = next(node.infer()) |
| 256 |
check_metaclass_is_abc(inferred) |
| 257 |
assertEqualMro( |
| 258 |
inferred, |
| 259 |
[ |
| 260 |
".Derived", |
| 261 |
"_collections_abc.Iterator", |
| 262 |
"_collections_abc.Iterable", |
| 263 |
"builtins.object", |
| 264 |
], |
| 265 |
) |
| 266 |
|
| 267 |
def test_collections_object_subscriptable_3(self): |
| 268 |
"""With Python 3.9 the ByteString class of the collections module is subscriptable |
| 269 |
(but not the same class from typing module)""" |
| 270 |
right_node = builder.extract_node(""" |
| 271 |
import collections.abc |
| 272 |
collections.abc.ByteString[int] |
| 273 |
""") |
| 274 |
inferred = next(right_node.infer()) |
| 275 |
check_metaclass_is_abc(inferred) |
| 276 |
self.assertIsInstance( |
| 277 |
inferred.getattr("__class_getitem__")[0], nodes.FunctionDef |
| 278 |
) |
| 279 |
|
| 280 |
def test_collections_object_subscriptable_4(self): |
| 281 |
"""Multiple inheritance with subscriptable collection class""" |
| 282 |
node = builder.extract_node(""" |
| 283 |
import collections.abc |
| 284 |
class Derived(collections.abc.Hashable, collections.abc.Iterator[int]): |
| 285 |
pass |
| 286 |
""") |
| 287 |
inferred = next(node.infer()) |
| 288 |
assertEqualMro( |
| 289 |
inferred, |
| 290 |
[ |
| 291 |
".Derived", |
| 292 |
"_collections_abc.Hashable", |
| 293 |
"_collections_abc.Iterator", |
| 294 |
"_collections_abc.Iterable", |
| 295 |
"builtins.object", |
| 296 |
], |
| 297 |
) |
| 298 |
|
| 299 |
def test_statistics_quantiles_from_import(self): |
| 300 |
node = builder.extract_node(""" |
| 301 |
from statistics import quantiles |
| 302 |
quantiles([1, 2, 3, 4, 5, 6, 7, 8, 9], n=4) |
| 303 |
""") |
| 304 |
inferred = next(node.infer()) |
| 305 |
self.assertIs(inferred, util.Uninferable) |
| 306 |
|
| 307 |
|
| 308 |
class TypingBrain(unittest.TestCase): |
| 309 |
def test_namedtuple_base(self) -> None: |
| 310 |
klass = builder.extract_node(""" |
| 311 |
from typing import NamedTuple |
| 312 |
|
| 313 |
class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])): |
| 314 |
pass |
| 315 |
""") |
| 316 |
self.assertEqual( |
| 317 |
[anc.name for anc in klass.ancestors()], ["X", "tuple", "object"] |
| 318 |
) |
| 319 |
for anc in klass.ancestors(): |
| 320 |
self.assertFalse(anc.parent is None) |
| 321 |
|
| 322 |
def test_namedtuple_can_correctly_access_methods(self) -> None: |
| 323 |
klass, called = builder.extract_node(""" |
| 324 |
from typing import NamedTuple |
| 325 |
|
| 326 |
class X(NamedTuple): #@ |
| 327 |
a: int |
| 328 |
b: int |
| 329 |
def as_string(self): |
| 330 |
return '%s' % self.a |
| 331 |
def as_integer(self): |
| 332 |
return 2 + 3 |
| 333 |
X().as_integer() #@ |
| 334 |
""") |
| 335 |
self.assertEqual(len(klass.getattr("as_string")), 1) |
| 336 |
inferred = next(called.infer()) |
| 337 |
self.assertIsInstance(inferred, nodes.Const) |
| 338 |
self.assertEqual(inferred.value, 5) |
| 339 |
|
| 340 |
def test_namedtuple_inference(self) -> None: |
| 341 |
klass = builder.extract_node(""" |
| 342 |
from typing import NamedTuple |
| 343 |
|
| 344 |
class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])): |
| 345 |
pass |
| 346 |
""") |
| 347 |
base = next(base for base in klass.ancestors() if base.name == "X") |
| 348 |
self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs)) |
| 349 |
|
| 350 |
def test_namedtuple_inference_nonliteral(self) -> None: |
| 351 |
# Note: NamedTuples in mypy only work with literals. |
| 352 |
klass = builder.extract_node(""" |
| 353 |
from typing import NamedTuple |
| 354 |
|
| 355 |
name = "X" |
| 356 |
fields = [("a", int), ("b", str), ("c", bytes)] |
| 357 |
NamedTuple(name, fields) |
| 358 |
""") |
| 359 |
inferred = next(klass.infer()) |
| 360 |
self.assertIsInstance(inferred, astroid.Instance) |
| 361 |
self.assertEqual(inferred.qname(), "typing.NamedTuple") |
| 362 |
|
| 363 |
def test_namedtuple_instance_attrs(self) -> None: |
| 364 |
result = builder.extract_node(""" |
| 365 |
from typing import NamedTuple |
| 366 |
NamedTuple("A", [("a", int), ("b", str), ("c", bytes)])(1, 2, 3) #@ |
| 367 |
""") |
| 368 |
inferred = next(result.infer()) |
| 369 |
for name, attr in inferred.instance_attrs.items(): |
| 370 |
self.assertEqual(attr[0].attrname, name) |
| 371 |
|
| 372 |
def test_namedtuple_simple(self) -> None: |
| 373 |
result = builder.extract_node(""" |
| 374 |
from typing import NamedTuple |
| 375 |
NamedTuple("A", [("a", int), ("b", str), ("c", bytes)]) |
| 376 |
""") |
| 377 |
inferred = next(result.infer()) |
| 378 |
self.assertIsInstance(inferred, nodes.ClassDef) |
| 379 |
self.assertSetEqual({"a", "b", "c"}, set(inferred.instance_attrs)) |
| 380 |
|
| 381 |
def test_namedtuple_few_args(self) -> None: |
| 382 |
result = builder.extract_node(""" |
| 383 |
from typing import NamedTuple |
| 384 |
NamedTuple("A") |
| 385 |
""") |
| 386 |
inferred = next(result.infer()) |
| 387 |
self.assertIsInstance(inferred, astroid.Instance) |
| 388 |
self.assertEqual(inferred.qname(), "typing.NamedTuple") |
| 389 |
|
| 390 |
def test_namedtuple_few_fields(self) -> None: |
| 391 |
result = builder.extract_node(""" |
| 392 |
from typing import NamedTuple |
| 393 |
NamedTuple("A", [("a",), ("b", str), ("c", bytes)]) |
| 394 |
""") |
| 395 |
inferred = next(result.infer()) |
| 396 |
self.assertIsInstance(inferred, astroid.Instance) |
| 397 |
self.assertEqual(inferred.qname(), "typing.NamedTuple") |
| 398 |
|
| 399 |
def test_namedtuple_class_form(self) -> None: |
| 400 |
result = builder.extract_node(""" |
| 401 |
from typing import NamedTuple |
| 402 |
|
| 403 |
class Example(NamedTuple): |
| 404 |
CLASS_ATTR = "class_attr" |
| 405 |
mything: int |
| 406 |
|
| 407 |
Example(mything=1) |
| 408 |
""") |
| 409 |
inferred = next(result.infer()) |
| 410 |
self.assertIsInstance(inferred, astroid.Instance) |
| 411 |
|
| 412 |
class_attr = inferred.getattr("CLASS_ATTR")[0] |
| 413 |
self.assertIsInstance(class_attr, nodes.AssignName) |
| 414 |
const = next(class_attr.infer()) |
| 415 |
self.assertEqual(const.value, "class_attr") |
| 416 |
|
| 417 |
def test_namedtuple_inferred_as_class(self) -> None: |
| 418 |
node = builder.extract_node(""" |
| 419 |
from typing import NamedTuple |
| 420 |
NamedTuple |
| 421 |
""") |
| 422 |
inferred = next(node.infer()) |
| 423 |
assert isinstance(inferred, nodes.ClassDef) |
| 424 |
assert inferred.name == "NamedTuple" |
| 425 |
|
| 426 |
def test_namedtuple_bug_pylint_4383(self) -> None: |
| 427 |
"""Inference of 'NamedTuple' function shouldn't cause InferenceError. |
| 428 |
|
| 429 |
https://github.com/pylint-dev/pylint/issues/4383 |
| 430 |
""" |
| 431 |
node = builder.extract_node(""" |
| 432 |
if True: |
| 433 |
def NamedTuple(): |
| 434 |
pass |
| 435 |
NamedTuple |
| 436 |
""") |
| 437 |
next(node.infer()) |
| 438 |
|
| 439 |
def test_namedtuple_uninferable_member(self) -> None: |
| 440 |
call = builder.extract_node(""" |
| 441 |
from typing import namedtuple |
| 442 |
namedtuple('uninf', {x: x for x in range(0)}) #@""") |
| 443 |
with pytest.raises(UseInferenceDefault): |
| 444 |
_get_namedtuple_fields(call) |
| 445 |
|
| 446 |
call = builder.extract_node(""" |
| 447 |
from typing import namedtuple |
| 448 |
uninferable = {x: x for x in range(0)} |
| 449 |
namedtuple('uninferable', uninferable) #@ |
| 450 |
""") |
| 451 |
with pytest.raises(UseInferenceDefault): |
| 452 |
_get_namedtuple_fields(call) |
| 453 |
|
| 454 |
def test_typing_types(self) -> None: |
| 455 |
ast_nodes = builder.extract_node(""" |
| 456 |
from typing import TypeVar, Iterable, Tuple, NewType, Dict, Union |
| 457 |
TypeVar('MyTypeVar', int, float, complex) #@ |
| 458 |
Iterable[Tuple[MyTypeVar, MyTypeVar]] #@ |
| 459 |
TypeVar('AnyStr', str, bytes) #@ |
| 460 |
NewType('UserId', str) #@ |
| 461 |
Dict[str, str] #@ |
| 462 |
Union[int, str] #@ |
| 463 |
""") |
| 464 |
for node in ast_nodes: |
| 465 |
inferred = next(node.infer()) |
| 466 |
self.assertIsInstance(inferred, nodes.ClassDef, node.as_string()) |
| 467 |
|
| 468 |
def test_typing_type_without_tip(self): |
| 469 |
"""Regression test for https://github.com/pylint-dev/pylint/issues/5770""" |
| 470 |
node = builder.extract_node(""" |
| 471 |
from typing import NewType |
| 472 |
|
| 473 |
def make_new_type(t): |
| 474 |
new_type = NewType(f'IntRange_{t}', t) #@ |
| 475 |
""") |
| 476 |
with self.assertRaises(UseInferenceDefault): |
| 477 |
astroid.brain.brain_typing.infer_typing_typevar_or_newtype(node.value) |
| 478 |
|
| 479 |
def test_namedtuple_nested_class(self): |
| 480 |
result = builder.extract_node(""" |
| 481 |
from typing import NamedTuple |
| 482 |
|
| 483 |
class Example(NamedTuple): |
| 484 |
class Foo: |
| 485 |
bar = "bar" |
| 486 |
|
| 487 |
Example |
| 488 |
""") |
| 489 |
inferred = next(result.infer()) |
| 490 |
self.assertIsInstance(inferred, nodes.ClassDef) |
| 491 |
|
| 492 |
class_def_attr = inferred.getattr("Foo")[0] |
| 493 |
self.assertIsInstance(class_def_attr, nodes.ClassDef) |
| 494 |
attr_def = class_def_attr.getattr("bar")[0] |
| 495 |
attr = next(attr_def.infer()) |
| 496 |
self.assertEqual(attr.value, "bar") |
| 497 |
|
| 498 |
def test_namedtuple_class_form_assignment_targets(self): |
| 499 |
"""An assignment in the body may not bind a single plain name. |
| 500 |
|
| 501 |
Regression test for https://github.com/pylint-dev/astroid/issues/3190 |
| 502 |
""" |
| 503 |
attribute, subscript, unpacking = builder.extract_node(""" |
| 504 |
from typing import NamedTuple |
| 505 |
|
| 506 |
class Attribute(NamedTuple): |
| 507 |
cat.color = "black" |
| 508 |
|
| 509 |
class Subscript(NamedTuple): |
| 510 |
basket[0] = "apple" |
| 511 |
|
| 512 |
class Unpacking(NamedTuple): |
| 513 |
apple, banana = "red", "yellow" |
| 514 |
|
| 515 |
Attribute() #@ |
| 516 |
Subscript() #@ |
| 517 |
Unpacking() #@ |
| 518 |
""") |
| 519 |
# Inference must not raise ``AttributeError`` or ``KeyError``. |
| 520 |
for node in (attribute, subscript, unpacking): |
| 521 |
self.assertIsInstance(next(node.infer()), astroid.Instance) |
| 522 |
|
| 523 |
# The names bound by unpacking are still class attributes. |
| 524 |
inferred = next(unpacking.infer()) |
| 525 |
for name, value in (("apple", "red"), ("banana", "yellow")): |
| 526 |
self.assertEqual(next(inferred.getattr(name)[0].infer()).value, value) |
| 527 |
|
| 528 |
def test_tuple_type(self): |
| 529 |
node = builder.extract_node(""" |
| 530 |
from typing import Tuple |
| 531 |
Tuple[int, int] |
| 532 |
""") |
| 533 |
inferred = next(node.infer()) |
| 534 |
assert isinstance(inferred, nodes.ClassDef) |
| 535 |
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 536 |
assert inferred.qname() == "typing.Tuple" |
| 537 |
|
| 538 |
def test_callable_type(self): |
| 539 |
node = builder.extract_node(""" |
| 540 |
from typing import Callable, Any |
| 541 |
Callable[..., Any] |
| 542 |
""") |
| 543 |
inferred = next(node.infer()) |
| 544 |
assert isinstance(inferred, nodes.ClassDef) |
| 545 |
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 546 |
assert inferred.qname() == "typing.Callable" |
| 547 |
|
| 548 |
def test_typing_generic_subscriptable(self): |
| 549 |
"""Test typing.Generic is subscriptable with __class_getitem__ (added in PY37)""" |
| 550 |
node = builder.extract_node(""" |
| 551 |
from typing import Generic, TypeVar |
| 552 |
T = TypeVar('T') |
| 553 |
Generic[T] |
| 554 |
""") |
| 555 |
inferred = next(node.infer()) |
| 556 |
assert isinstance(inferred, nodes.ClassDef) |
| 557 |
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 558 |
|
| 559 |
@test_utils.require_version(minver="3.12") |
| 560 |
def test_typing_generic_subscriptable_pep695(self): |
| 561 |
"""Test class using type parameters is subscriptable with __class_getitem__ (added in PY312)""" |
| 562 |
node = builder.extract_node(""" |
| 563 |
class Foo[T]: ... |
| 564 |
class Bar[T](Foo[T]): ... |
| 565 |
""") |
| 566 |
inferred = next(node.infer()) |
| 567 |
assert isinstance(inferred, nodes.ClassDef) |
| 568 |
assert inferred.name == "Bar" |
| 569 |
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 570 |
ancestors = list(inferred.ancestors()) |
| 571 |
assert len(ancestors) == 2 |
| 572 |
assert ancestors[0].name == "Foo" |
| 573 |
assert ancestors[1].name == "object" |
| 574 |
|
| 575 |
def test_typing_annotated_subscriptable(self): |
| 576 |
"""typing.Annotated is subscriptable with __class_getitem__ below 3.13.""" |
| 577 |
node = builder.extract_node(""" |
| 578 |
import typing |
| 579 |
typing.Annotated[str, "data"] |
| 580 |
""") |
| 581 |
inferred = next(node.infer()) |
| 582 |
if PY313_PLUS: |
| 583 |
assert isinstance(inferred, nodes.FunctionDef) |
| 584 |
else: |
| 585 |
assert isinstance(inferred, nodes.ClassDef) |
| 586 |
assert isinstance( |
| 587 |
inferred.getattr("__class_getitem__")[0], nodes.FunctionDef |
| 588 |
) |
| 589 |
|
| 590 |
def test_typing_generic_slots(self): |
| 591 |
"""Test slots for Generic subclass.""" |
| 592 |
node = builder.extract_node(""" |
| 593 |
from typing import Generic, TypeVar |
| 594 |
T = TypeVar('T') |
| 595 |
class A(Generic[T]): |
| 596 |
__slots__ = ['value'] |
| 597 |
def __init__(self, value): |
| 598 |
self.value = value |
| 599 |
""") |
| 600 |
inferred = next(node.infer()) |
| 601 |
slots = inferred.slots() |
| 602 |
assert len(slots) == 1 |
| 603 |
assert isinstance(slots[0], nodes.Const) |
| 604 |
assert slots[0].value == "value" |
| 605 |
|
| 606 |
def test_typing_no_duplicates(self): |
| 607 |
node = builder.extract_node(""" |
| 608 |
from typing import List |
| 609 |
List[int] |
| 610 |
""") |
| 611 |
assert len(node.inferred()) == 1 |
| 612 |
|
| 613 |
def test_typing_no_duplicates_2(self): |
| 614 |
node = builder.extract_node(""" |
| 615 |
from typing import Optional, Tuple |
| 616 |
Tuple[Optional[int], ...] |
| 617 |
""") |
| 618 |
assert len(node.inferred()) == 1 |
| 619 |
|
| 620 |
def test_typing_param_spec(self): |
| 621 |
node = builder.extract_node(""" |
| 622 |
from typing import ParamSpec |
| 623 |
|
| 624 |
P = ParamSpec("P") |
| 625 |
""") |
| 626 |
inferred = next(node.targets[0].infer()) |
| 627 |
assert next(inferred.igetattr("args")) is not None |
| 628 |
assert next(inferred.igetattr("kwargs")) is not None |
| 629 |
|
| 630 |
def test_collections_generic_alias_slots(self): |
| 631 |
"""Test slots for a class which is a subclass of a generic alias type.""" |
| 632 |
node = builder.extract_node(""" |
| 633 |
import collections |
| 634 |
import typing |
| 635 |
Type = typing.TypeVar('Type') |
| 636 |
class A(collections.abc.AsyncIterator[Type]): |
| 637 |
__slots__ = ('_value',) |
| 638 |
def __init__(self, value: collections.abc.AsyncIterator[Type]): |
| 639 |
self._value = value |
| 640 |
""") |
| 641 |
inferred = next(node.infer()) |
| 642 |
assert isinstance(inferred, nodes.ClassDef) |
| 643 |
slots = inferred.slots() |
| 644 |
assert len(slots) == 1 |
| 645 |
assert isinstance(slots[0], nodes.Const) |
| 646 |
assert slots[0].value == "_value" |
| 647 |
|
| 648 |
def test_has_dunder_args(self) -> None: |
| 649 |
ast_node = builder.extract_node(""" |
| 650 |
from typing import Union |
| 651 |
NumericTypes = Union[int, float] |
| 652 |
NumericTypes.__args__ #@ |
| 653 |
""") |
| 654 |
inferred = next(ast_node.infer()) |
| 655 |
assert isinstance(inferred, nodes.Tuple) |
| 656 |
|
| 657 |
def test_typing_namedtuple_dont_crash_on_no_fields(self) -> None: |
| 658 |
node = builder.extract_node(""" |
| 659 |
from typing import NamedTuple |
| 660 |
|
| 661 |
Bar = NamedTuple("bar", []) |
| 662 |
|
| 663 |
Bar() |
| 664 |
""") |
| 665 |
inferred = next(node.infer()) |
| 666 |
self.assertIsInstance(inferred, astroid.Instance) |
| 667 |
|
| 668 |
def test_typed_dict(self): |
| 669 |
code = builder.extract_node(""" |
| 670 |
from typing import TypedDict |
| 671 |
class CustomTD(TypedDict): #@ |
| 672 |
var: int |
| 673 |
CustomTD(var=1) #@ |
| 674 |
""") |
| 675 |
inferred_base = next(code[0].bases[0].infer()) |
| 676 |
assert isinstance(inferred_base, nodes.ClassDef) |
| 677 |
assert inferred_base.qname() == "typing.TypedDict" |
| 678 |
typedDict_base = next(inferred_base.bases[0].infer()) |
| 679 |
assert typedDict_base.qname() == "builtins.dict" |
| 680 |
|
| 681 |
# Test TypedDict has `__call__` method |
| 682 |
local_call = inferred_base.locals.get("__call__", None) |
| 683 |
assert local_call and len(local_call) == 1 |
| 684 |
assert isinstance(local_call[0], nodes.Name) and local_call[0].name == "dict" |
| 685 |
|
| 686 |
# Test TypedDict instance is callable |
| 687 |
assert next(code[1].infer()).callable() is True |
| 688 |
|
| 689 |
def test_typed_dict_required_and_optional_keys(self): |
| 690 |
"""TypedDict subclasses expose ``__required_keys__`` and ``__optional_keys__``.""" |
| 691 |
code = builder.extract_node(""" |
| 692 |
from typing import TypedDict |
| 693 |
from typing_extensions import TypedDict as ETD |
| 694 |
|
| 695 |
class CustomTD(TypedDict): #@ |
| 696 |
var: int |
| 697 |
|
| 698 |
class CustomTD2(ETD): #@ |
| 699 |
var: int |
| 700 |
""") |
| 701 |
for cls in code: |
| 702 |
for attr in ("__required_keys__", "__optional_keys__"): |
| 703 |
assert cls.getattr(attr), f"{cls.name}.{attr} not found" |
| 704 |
|
| 705 |
def test_typing_alias_type(self): |
| 706 |
""" |
| 707 |
Test that the type aliased thanks to typing._alias function are |
| 708 |
correctly inferred. |
| 709 |
typing_alias function is introduced with python37 |
| 710 |
""" |
| 711 |
node = builder.extract_node(""" |
| 712 |
from typing import TypeVar, MutableSet |
| 713 |
|
| 714 |
T = TypeVar("T") |
| 715 |
MutableSet[T] |
| 716 |
|
| 717 |
class Derived1(MutableSet[T]): |
| 718 |
pass |
| 719 |
""") |
| 720 |
inferred = next(node.infer()) |
| 721 |
assertEqualMro( |
| 722 |
inferred, |
| 723 |
[ |
| 724 |
".Derived1", |
| 725 |
"typing.MutableSet", |
| 726 |
"_collections_abc.MutableSet", |
| 727 |
"_collections_abc.Set", |
| 728 |
"_collections_abc.Collection", |
| 729 |
"_collections_abc.Sized", |
| 730 |
"_collections_abc.Iterable", |
| 731 |
"_collections_abc.Container", |
| 732 |
"builtins.object", |
| 733 |
], |
| 734 |
) |
| 735 |
|
| 736 |
def test_typing_alias_type_2(self): |
| 737 |
""" |
| 738 |
Test that the type aliased thanks to typing._alias function are |
| 739 |
correctly inferred. |
| 740 |
typing_alias function is introduced with python37. |
| 741 |
OrderedDict in the typing module appears only with python 3.7.2 |
| 742 |
""" |
| 743 |
node = builder.extract_node(""" |
| 744 |
import typing |
| 745 |
class Derived2(typing.OrderedDict[int, str]): |
| 746 |
pass |
| 747 |
""") |
| 748 |
inferred = next(node.infer()) |
| 749 |
assertEqualMro( |
| 750 |
inferred, |
| 751 |
[ |
| 752 |
".Derived2", |
| 753 |
"typing.OrderedDict", |
| 754 |
"collections.OrderedDict", |
| 755 |
"builtins.dict", |
| 756 |
"builtins.object", |
| 757 |
], |
| 758 |
) |
| 759 |
|
| 760 |
def test_typing_object_not_subscriptable(self): |
| 761 |
"""Hashable is not subscriptable""" |
| 762 |
wrong_node = builder.extract_node(""" |
| 763 |
import typing |
| 764 |
typing.Hashable[int] |
| 765 |
""") |
| 766 |
with self.assertRaises(InferenceError): |
| 767 |
next(wrong_node.infer()) |
| 768 |
right_node = builder.extract_node(""" |
| 769 |
import typing |
| 770 |
typing.Hashable |
| 771 |
""") |
| 772 |
inferred = next(right_node.infer()) |
| 773 |
assertEqualMro( |
| 774 |
inferred, |
| 775 |
[ |
| 776 |
"typing.Hashable", |
| 777 |
"_collections_abc.Hashable", |
| 778 |
"builtins.object", |
| 779 |
], |
| 780 |
) |
| 781 |
with self.assertRaises(AttributeInferenceError): |
| 782 |
inferred.getattr("__class_getitem__") |
| 783 |
|
| 784 |
def test_typing_object_subscriptable(self): |
| 785 |
"""Test that MutableSet is subscriptable""" |
| 786 |
right_node = builder.extract_node(""" |
| 787 |
import typing |
| 788 |
typing.MutableSet[int] |
| 789 |
""") |
| 790 |
inferred = next(right_node.infer()) |
| 791 |
assertEqualMro( |
| 792 |
inferred, |
| 793 |
[ |
| 794 |
"typing.MutableSet", |
| 795 |
"_collections_abc.MutableSet", |
| 796 |
"_collections_abc.Set", |
| 797 |
"_collections_abc.Collection", |
| 798 |
"_collections_abc.Sized", |
| 799 |
"_collections_abc.Iterable", |
| 800 |
"_collections_abc.Container", |
| 801 |
"builtins.object", |
| 802 |
], |
| 803 |
) |
| 804 |
self.assertIsInstance( |
| 805 |
inferred.getattr("__class_getitem__")[0], nodes.FunctionDef |
| 806 |
) |
| 807 |
|
| 808 |
def test_typing_object_subscriptable_2(self): |
| 809 |
"""Multiple inheritance with subscriptable typing alias""" |
| 810 |
node = builder.extract_node(""" |
| 811 |
import typing |
| 812 |
class Derived(typing.Hashable, typing.Iterator[int]): |
| 813 |
pass |
| 814 |
""") |
| 815 |
inferred = next(node.infer()) |
| 816 |
assertEqualMro( |
| 817 |
inferred, |
| 818 |
[ |
| 819 |
".Derived", |
| 820 |
"typing.Hashable", |
| 821 |
"_collections_abc.Hashable", |
| 822 |
"typing.Iterator", |
| 823 |
"_collections_abc.Iterator", |
| 824 |
"_collections_abc.Iterable", |
| 825 |
"builtins.object", |
| 826 |
], |
| 827 |
) |
| 828 |
|
| 829 |
def test_typing_object_notsubscriptable_3(self): |
| 830 |
"""The ByteString class of the typing module is not |
| 831 |
subscriptable (whereas it is in the collections' module)""" |
| 832 |
right_node = builder.extract_node(""" |
| 833 |
import typing |
| 834 |
typing.ByteString |
| 835 |
""") |
| 836 |
inferred = next(right_node.infer()) |
| 837 |
# From Python 3.15 we add a stub definition of `ByteString`. It doesn't need all properties |
| 838 |
# of the original implementation. |
| 839 |
if not PY315_PLUS: |
| 840 |
check_metaclass_is_abc(inferred) |
| 841 |
with self.assertRaises(AttributeInferenceError): |
| 842 |
self.assertIsInstance( |
| 843 |
inferred.getattr("__class_getitem__")[0], nodes.FunctionDef |
| 844 |
) |
| 845 |
|
| 846 |
def test_typing_object_builtin_subscriptable(self): |
| 847 |
""" |
| 848 |
Test that builtins alias, such as typing.List, are subscriptable |
| 849 |
""" |
| 850 |
for typename in ("List", "Dict", "Set", "FrozenSet", "Tuple"): |
| 851 |
src = f""" |
| 852 |
import typing |
| 853 |
typing.{typename:s}[int] |
| 854 |
""" |
| 855 |
right_node = builder.extract_node(src) |
| 856 |
inferred = next(right_node.infer()) |
| 857 |
self.assertIsInstance(inferred, nodes.ClassDef) |
| 858 |
self.assertIsInstance(inferred.getattr("__iter__")[0], nodes.FunctionDef) |
| 859 |
|
| 860 |
@staticmethod |
| 861 |
def test_typing_type_subscriptable(): |
| 862 |
node = builder.extract_node(""" |
| 863 |
from typing import Type |
| 864 |
Type[int] |
| 865 |
""") |
| 866 |
inferred = next(node.infer()) |
| 867 |
assert isinstance(inferred, nodes.ClassDef) |
| 868 |
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 869 |
assert inferred.qname() == "typing.Type" |
| 870 |
|
| 871 |
def test_typing_cast(self) -> None: |
| 872 |
node = builder.extract_node(""" |
| 873 |
from typing import cast |
| 874 |
class A: |
| 875 |
pass |
| 876 |
|
| 877 |
b = 42 |
| 878 |
cast(A, b) |
| 879 |
""") |
| 880 |
inferred = next(node.infer()) |
| 881 |
assert isinstance(inferred, nodes.Const) |
| 882 |
assert inferred.value == 42 |
| 883 |
|
| 884 |
def test_typing_cast_attribute(self) -> None: |
| 885 |
node = builder.extract_node(""" |
| 886 |
import typing |
| 887 |
class A: |
| 888 |
pass |
| 889 |
|
| 890 |
b = 42 |
| 891 |
typing.cast(A, b) |
| 892 |
""") |
| 893 |
inferred = next(node.infer()) |
| 894 |
assert isinstance(inferred, nodes.Const) |
| 895 |
assert inferred.value == 42 |
| 896 |
|
| 897 |
def test_typing_cast_multiple_inference_calls(self) -> None: |
| 898 |
"""Inference of an outer function should not store the result for cast.""" |
| 899 |
ast_nodes = builder.extract_node(""" |
| 900 |
from typing import TypeVar, cast |
| 901 |
T = TypeVar("T") |
| 902 |
def ident(var: T) -> T: |
| 903 |
return cast(T, var) |
| 904 |
|
| 905 |
ident(2) #@ |
| 906 |
ident("Hello") #@ |
| 907 |
""") |
| 908 |
i0 = next(ast_nodes[0].infer()) |
| 909 |
assert isinstance(i0, nodes.Const) |
| 910 |
assert i0.value == 2 |
| 911 |
|
| 912 |
i1 = next(ast_nodes[1].infer()) |
| 913 |
assert isinstance(i1, nodes.Const) |
| 914 |
assert i1.value == "Hello" |
| 915 |
|
| 916 |
|
| 917 |
class ReBrainTest(unittest.TestCase): |
| 918 |
def test_regex_flags(self) -> None: |
| 919 |
names = [name for name in dir(re) if name.isupper()] |
| 920 |
re_ast = MANAGER.ast_from_module_name("re") |
| 921 |
for name in names: |
| 922 |
self.assertIn(name, re_ast) |
| 923 |
self.assertEqual(next(re_ast[name].infer()).value, getattr(re, name)) |
| 924 |
|
| 925 |
def test_re_pattern_subscriptable(self): |
| 926 |
"""Test re.Pattern and re.Match are subscriptable in PY39+""" |
| 927 |
node1 = builder.extract_node(""" |
| 928 |
import re |
| 929 |
re.Pattern[str] |
| 930 |
""") |
| 931 |
inferred1 = next(node1.infer()) |
| 932 |
assert isinstance(inferred1, nodes.ClassDef) |
| 933 |
assert isinstance(inferred1.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 934 |
|
| 935 |
node2 = builder.extract_node(""" |
| 936 |
import re |
| 937 |
re.Match[str] |
| 938 |
""") |
| 939 |
inferred2 = next(node2.infer()) |
| 940 |
assert isinstance(inferred2, nodes.ClassDef) |
| 941 |
assert isinstance(inferred2.getattr("__class_getitem__")[0], nodes.FunctionDef) |
| 942 |
|
| 943 |
|
| 944 |
class BrainNamedtupleAnnAssignTest(unittest.TestCase): |
| 945 |
def test_no_crash_on_ann_assign_in_namedtuple(self) -> None: |
| 946 |
node = builder.extract_node(""" |
| 947 |
from enum import Enum |
| 948 |
from typing import Optional |
| 949 |
|
| 950 |
class A(Enum): |
| 951 |
B: str = 'B' |
| 952 |
""") |
| 953 |
inferred = next(node.infer()) |
| 954 |
self.assertIsInstance(inferred, nodes.ClassDef) |
| 955 |
|
| 956 |
|
| 957 |
class BrainUUIDTest(unittest.TestCase): |
| 958 |
def test_uuid_has_int_member(self) -> None: |
| 959 |
node = builder.extract_node(""" |
| 960 |
import uuid |
| 961 |
u = uuid.UUID('{12345678-1234-5678-1234-567812345678}') |
| 962 |
u.int |
| 963 |
""") |
| 964 |
inferred = next(node.infer()) |
| 965 |
self.assertIsInstance(inferred, nodes.Const) |
| 966 |
|
| 967 |
|
| 968 |
class RandomSampleTest(unittest.TestCase): |
| 969 |
def test_inferred_successfully(self) -> None: |
| 970 |
node = astroid.extract_node(""" |
| 971 |
import random |
| 972 |
random.sample([1, 2], 2) #@ |
| 973 |
""") |
| 974 |
inferred = next(node.infer()) |
| 975 |
self.assertIsInstance(inferred, nodes.List) |
| 976 |
elems = sorted(elem.value for elem in inferred.elts) |
| 977 |
self.assertEqual(elems, [1, 2]) |
| 978 |
|
| 979 |
def test_arguments_inferred_successfully(self) -> None: |
| 980 |
"""Test inference of `random.sample` when both arguments are of type `nodes.Call`.""" |
| 981 |
node = astroid.extract_node(""" |
| 982 |
import random |
| 983 |
|
| 984 |
def sequence(): |
| 985 |
return [1, 2] |
| 986 |
|
| 987 |
random.sample(sequence(), len([1,2])) #@ |
| 988 |
""") |
| 989 |
# Check that arguments are of type `nodes.Call`. |
| 990 |
sequence, length = node.args |
| 991 |
self.assertIsInstance(sequence, nodes.Call) |
| 992 |
self.assertIsInstance(length, nodes.Call) |
| 993 |
|
| 994 |
# Check the inference of `random.sample` call. |
| 995 |
inferred = next(node.infer()) |
| 996 |
self.assertIsInstance(inferred, nodes.List) |
| 997 |
elems = sorted(elem.value for elem in inferred.elts) |
| 998 |
self.assertEqual(elems, [1, 2]) |
| 999 |
|
| 1000 |
def test_no_crash_on_evaluatedobject(self) -> None: |
| 1001 |
node = astroid.extract_node(""" |
| 1002 |
from random import sample |
| 1003 |
class A: pass |
| 1004 |
sample(list({1: A()}.values()), 1)""") |
| 1005 |
inferred = next(node.infer()) |
| 1006 |
assert isinstance(inferred, nodes.List) |
| 1007 |
assert len(inferred.elts) == 1 |
| 1008 |
assert isinstance(inferred.elts[0], nodes.Call) |
| 1009 |
|
| 1010 |
def test_no_crash_on_uninferable_element(self) -> None: |
| 1011 |
"""Test that random.sample does not crash when elements are Uninferable. |
| 1012 |
|
| 1013 |
Regression test for https://github.com/pylint-dev/astroid/issues/2518 |
| 1014 |
""" |
| 1015 |
node = astroid.extract_node(""" |
| 1016 |
import random |
| 1017 |
random.sample(1*[b], 1) #@ |
| 1018 |
""") |
| 1019 |
inferred = next(node.infer()) |
| 1020 |
assert inferred is astroid.Uninferable |
| 1021 |
|
| 1022 |
def test_no_crash_on_classdef_clone(self) -> None: |
| 1023 |
"""Test that random.sample does not crash when cloning ClassDef nodes. |
| 1024 |
|
| 1025 |
Regression test for https://github.com/pylint-dev/astroid/issues/2923 |
| 1026 |
""" |
| 1027 |
node = astroid.extract_node(""" |
| 1028 |
import random |
| 1029 |
random.sample([dict] * 2, 1) #@ |
| 1030 |
""") |
| 1031 |
inferred = next(node.infer()) |
| 1032 |
assert isinstance(inferred, nodes.List) |
| 1033 |
assert len(inferred.elts) == 1 |
| 1034 |
assert isinstance(inferred.elts[0], nodes.ClassDef) |
| 1035 |
assert inferred.elts[0].name == "dict" |
| 1036 |
|
| 1037 |
def test_no_crash_on_functiondef_clone(self) -> None: |
| 1038 |
"""Test that random.sample does not crash when cloning FunctionDef nodes. |
| 1039 |
|
| 1040 |
Regression test for https://github.com/pylint-dev/astroid/issues/2923 |
| 1041 |
""" |
| 1042 |
node = astroid.extract_node(""" |
| 1043 |
import random |
| 1044 |
random.sample([len] * 2, 1) #@ |
| 1045 |
""") |
| 1046 |
inferred = next(node.infer()) |
| 1047 |
assert isinstance(inferred, nodes.List) |
| 1048 |
assert len(inferred.elts) == 1 |
| 1049 |
assert isinstance(inferred.elts[0], nodes.FunctionDef) |
| 1050 |
assert inferred.elts[0].name == "len" |
| 1051 |
|
| 1052 |
def test_no_crash_on_module_clone(self) -> None: |
| 1053 |
"""Test that random.sample does not crash when cloning Module nodes. |
| 1054 |
|
| 1055 |
Module.__init__ does not accept ``lineno``/``col_offset`` kwargs, so |
| 1056 |
cloning must filter init params to those the class actually accepts. |
| 1057 |
|
| 1058 |
Regression test for https://github.com/pylint-dev/astroid/issues/3043 |
| 1059 |
""" |
| 1060 |
node = astroid.extract_node(""" |
| 1061 |
from random import sample |
| 1062 |
import gc |
| 1063 |
sample(list({gc}) * 2, 1) #@ |
| 1064 |
""") |
| 1065 |
inferred = next(node.infer()) |
| 1066 |
assert isinstance(inferred, nodes.List) |
| 1067 |
assert len(inferred.elts) == 1 |
| 1068 |
assert isinstance(inferred.elts[0], nodes.Module) |
| 1069 |
assert inferred.elts[0].name == "gc" |
| 1070 |
|
| 1071 |
|
| 1072 |
class SubprocessTest(unittest.TestCase): |
| 1073 |
"""Test subprocess brain""" |
| 1074 |
|
| 1075 |
def test_subprocess_args(self) -> None: |
| 1076 |
"""Make sure the args attribute exists for Popen |
| 1077 |
|
| 1078 |
Test for https://github.com/pylint-dev/pylint/issues/1860""" |
| 1079 |
name = astroid.extract_node(""" |
| 1080 |
import subprocess |
| 1081 |
p = subprocess.Popen(['ls']) |
| 1082 |
p #@ |
| 1083 |
""") |
| 1084 |
[inst] = name.inferred() |
| 1085 |
self.assertIsInstance(next(inst.igetattr("args")), nodes.List) |
| 1086 |
|
| 1087 |
def test_subprcess_check_output(self) -> None: |
| 1088 |
code = """ |
| 1089 |
import subprocess |
| 1090 |
|
| 1091 |
subprocess.check_output(['echo', 'hello']); |
| 1092 |
""" |
| 1093 |
node = astroid.extract_node(code) |
| 1094 |
inferred = next(node.infer()) |
| 1095 |
# Can be either str or bytes |
| 1096 |
assert isinstance(inferred, nodes.Const) |
| 1097 |
assert isinstance(inferred.value, (str, bytes)) |
| 1098 |
|
| 1099 |
def test_popen_does_not_have_class_getitem(self): |
| 1100 |
code = """import subprocess; subprocess.Popen""" |
| 1101 |
node = astroid.extract_node(code) |
| 1102 |
inferred = next(node.infer()) |
| 1103 |
assert "__class_getitem__" in inferred |
| 1104 |
|
| 1105 |
|
| 1106 |
class TestIsinstanceInference: |
| 1107 |
"""Test isinstance builtin inference""" |
| 1108 |
|
| 1109 |
def test_type_type(self) -> None: |
| 1110 |
assert _get_result("isinstance(type, type)") == "True" |
| 1111 |
|
| 1112 |
def test_object_type(self) -> None: |
| 1113 |
assert _get_result("isinstance(object, type)") == "True" |
| 1114 |
|
| 1115 |
def test_type_object(self) -> None: |
| 1116 |
assert _get_result("isinstance(type, object)") == "True" |
| 1117 |
|
| 1118 |
def test_isinstance_int_true(self) -> None: |
| 1119 |
"""Make sure isinstance can check builtin int types""" |
| 1120 |
assert _get_result("isinstance(1, int)") == "True" |
| 1121 |
|
| 1122 |
def test_isinstance_int_false(self) -> None: |
| 1123 |
assert _get_result("isinstance('a', int)") == "False" |
| 1124 |
|
| 1125 |
def test_isinstance_object_true(self) -> None: |
| 1126 |
assert _get_result(""" |
| 1127 |
class Bar(object): |
| 1128 |
pass |
| 1129 |
isinstance(Bar(), object) |
| 1130 |
""") == "True" |
| 1131 |
|
| 1132 |
def test_isinstance_object_true3(self) -> None: |
| 1133 |
assert _get_result(""" |
| 1134 |
class Bar(object): |
| 1135 |
pass |
| 1136 |
isinstance(Bar(), Bar) |
| 1137 |
""") == "True" |
| 1138 |
|
| 1139 |
def test_isinstance_class_false(self) -> None: |
| 1140 |
assert _get_result(""" |
| 1141 |
class Foo(object): |
| 1142 |
pass |
| 1143 |
class Bar(object): |
| 1144 |
pass |
| 1145 |
isinstance(Bar(), Foo) |
| 1146 |
""") == "False" |
| 1147 |
|
| 1148 |
def test_isinstance_type_false(self) -> None: |
| 1149 |
assert _get_result(""" |
| 1150 |
class Bar(object): |
| 1151 |
pass |
| 1152 |
isinstance(Bar(), type) |
| 1153 |
""") == "False" |
| 1154 |
|
| 1155 |
def test_isinstance_str_true(self) -> None: |
| 1156 |
"""Make sure isinstance can check builtin str types""" |
| 1157 |
assert _get_result("isinstance('a', str)") == "True" |
| 1158 |
|
| 1159 |
def test_isinstance_str_false(self) -> None: |
| 1160 |
assert _get_result("isinstance(1, str)") == "False" |
| 1161 |
|
| 1162 |
def test_isinstance_tuple_argument(self) -> None: |
| 1163 |
"""obj just has to be an instance of ANY class/type on the right""" |
| 1164 |
assert _get_result("isinstance(1, (str, int))") == "True" |
| 1165 |
|
| 1166 |
def test_isinstance_type_false2(self) -> None: |
| 1167 |
assert _get_result(""" |
| 1168 |
isinstance(1, type) |
| 1169 |
""") == "False" |
| 1170 |
|
| 1171 |
def test_isinstance_object_true2(self) -> None: |
| 1172 |
assert _get_result(""" |
| 1173 |
class Bar(type): |
| 1174 |
pass |
| 1175 |
mainbar = Bar("Bar", tuple(), {}) |
| 1176 |
isinstance(mainbar, object) |
| 1177 |
""") == "True" |
| 1178 |
|
| 1179 |
def test_isinstance_type_true(self) -> None: |
| 1180 |
assert _get_result(""" |
| 1181 |
class Bar(type): |
| 1182 |
pass |
| 1183 |
mainbar = Bar("Bar", tuple(), {}) |
| 1184 |
isinstance(mainbar, type) |
| 1185 |
""") == "True" |
| 1186 |
|
| 1187 |
def test_isinstance_edge_case(self) -> None: |
| 1188 |
"""isinstance allows bad type short-circuting""" |
| 1189 |
assert _get_result("isinstance(1, (int, 1))") == "True" |
| 1190 |
|
| 1191 |
def test_uninferable_bad_type(self) -> None: |
| 1192 |
"""The second argument must be a class or a tuple of classes""" |
| 1193 |
with pytest.raises(InferenceError): |
| 1194 |
_get_result_node("isinstance(int, 1)") |
| 1195 |
|
| 1196 |
def test_uninferable_keywords(self) -> None: |
| 1197 |
"""isinstance does not allow keywords""" |
| 1198 |
with pytest.raises(InferenceError): |
| 1199 |
_get_result_node("isinstance(1, class_or_tuple=int)") |
| 1200 |
|
| 1201 |
def test_too_many_args(self) -> None: |
| 1202 |
"""isinstance must have two arguments""" |
| 1203 |
with pytest.raises(InferenceError): |
| 1204 |
_get_result_node("isinstance(1, int, str)") |
| 1205 |
|
| 1206 |
def test_first_param_is_uninferable(self) -> None: |
| 1207 |
with pytest.raises(InferenceError): |
| 1208 |
_get_result_node("isinstance(something, int)") |
| 1209 |
|
| 1210 |
|
| 1211 |
class TestIssubclassBrain: |
| 1212 |
"""Test issubclass() builtin inference""" |
| 1213 |
|
| 1214 |
def test_type_type(self) -> None: |
| 1215 |
assert _get_result("issubclass(type, type)") == "True" |
| 1216 |
|
| 1217 |
def test_object_type(self) -> None: |
| 1218 |
assert _get_result("issubclass(object, type)") == "False" |
| 1219 |
|
| 1220 |
def test_type_object(self) -> None: |
| 1221 |
assert _get_result("issubclass(type, object)") == "True" |
| 1222 |
|
| 1223 |
def test_issubclass_same_class(self) -> None: |
| 1224 |
assert _get_result("issubclass(int, int)") == "True" |
| 1225 |
|
| 1226 |
def test_issubclass_not_the_same_class(self) -> None: |
| 1227 |
assert _get_result("issubclass(str, int)") == "False" |
| 1228 |
|
| 1229 |
def test_issubclass_object_true(self) -> None: |
| 1230 |
assert _get_result(""" |
| 1231 |
class Bar(object): |
| 1232 |
pass |
| 1233 |
issubclass(Bar, object) |
| 1234 |
""") == "True" |
| 1235 |
|
| 1236 |
def test_issubclass_same_user_defined_class(self) -> None: |
| 1237 |
assert _get_result(""" |
| 1238 |
class Bar(object): |
| 1239 |
pass |
| 1240 |
issubclass(Bar, Bar) |
| 1241 |
""") == "True" |
| 1242 |
|
| 1243 |
def test_issubclass_different_user_defined_classes(self) -> None: |
| 1244 |
assert _get_result(""" |
| 1245 |
class Foo(object): |
| 1246 |
pass |
| 1247 |
class Bar(object): |
| 1248 |
pass |
| 1249 |
issubclass(Bar, Foo) |
| 1250 |
""") == "False" |
| 1251 |
|
| 1252 |
def test_issubclass_type_false(self) -> None: |
| 1253 |
assert _get_result(""" |
| 1254 |
class Bar(object): |
| 1255 |
pass |
| 1256 |
issubclass(Bar, type) |
| 1257 |
""") == "False" |
| 1258 |
|
| 1259 |
def test_isinstance_tuple_argument(self) -> None: |
| 1260 |
"""obj just has to be a subclass of ANY class/type on the right""" |
| 1261 |
assert _get_result("issubclass(int, (str, int))") == "True" |
| 1262 |
|
| 1263 |
def test_isinstance_object_true2(self) -> None: |
| 1264 |
assert _get_result(""" |
| 1265 |
class Bar(type): |
| 1266 |
pass |
| 1267 |
issubclass(Bar, object) |
| 1268 |
""") == "True" |
| 1269 |
|
| 1270 |
def test_issubclass_short_circuit(self) -> None: |
| 1271 |
"""issubclasss allows bad type short-circuting""" |
| 1272 |
assert _get_result("issubclass(int, (int, 1))") == "True" |
| 1273 |
|
| 1274 |
def test_uninferable_bad_type(self) -> None: |
| 1275 |
"""The second argument must be a class or a tuple of classes""" |
| 1276 |
# Should I subclass |
| 1277 |
with pytest.raises(InferenceError): |
| 1278 |
_get_result_node("issubclass(int, 1)") |
| 1279 |
|
| 1280 |
def test_uninferable_keywords(self) -> None: |
| 1281 |
"""issubclass does not allow keywords""" |
| 1282 |
with pytest.raises(InferenceError): |
| 1283 |
_get_result_node("issubclass(int, class_or_tuple=int)") |
| 1284 |
|
| 1285 |
def test_too_many_args(self) -> None: |
| 1286 |
"""issubclass must have two arguments""" |
| 1287 |
with pytest.raises(InferenceError): |
| 1288 |
_get_result_node("issubclass(int, int, str)") |
| 1289 |
|
| 1290 |
|
| 1291 |
def _get_result_node(code: str) -> nodes.Const: |
| 1292 |
node = next(astroid.extract_node(code).infer()) |
| 1293 |
return node |
| 1294 |
|
| 1295 |
|
| 1296 |
def _get_result(code: str) -> str: |
| 1297 |
return _get_result_node(code).as_string() |
| 1298 |
|
| 1299 |
|
| 1300 |
class TestLenBuiltinInference: |
| 1301 |
def test_len_list(self) -> None: |
| 1302 |
# Uses .elts |
| 1303 |
node = astroid.extract_node(""" |
| 1304 |
len(['a','b','c']) |
| 1305 |
""") |
| 1306 |
node = next(node.infer()) |
| 1307 |
assert node.as_string() == "3" |
| 1308 |
assert isinstance(node, nodes.Const) |
| 1309 |
|
| 1310 |
def test_len_tuple(self) -> None: |
| 1311 |
node = astroid.extract_node(""" |
| 1312 |
len(('a','b','c')) |
| 1313 |
""") |
| 1314 |
node = next(node.infer()) |
| 1315 |
assert node.as_string() == "3" |
| 1316 |
|
| 1317 |
def test_len_var(self) -> None: |
| 1318 |
# Make sure argument is inferred |
| 1319 |
node = astroid.extract_node(""" |
| 1320 |
a = [1,2,'a','b','c'] |
| 1321 |
len(a) |
| 1322 |
""") |
| 1323 |
node = next(node.infer()) |
| 1324 |
assert node.as_string() == "5" |
| 1325 |
|
| 1326 |
def test_len_dict(self) -> None: |
| 1327 |
# Uses .items |
| 1328 |
node = astroid.extract_node(""" |
| 1329 |
a = {'a': 1, 'b': 2} |
| 1330 |
len(a) |
| 1331 |
""") |
| 1332 |
node = next(node.infer()) |
| 1333 |
assert node.as_string() == "2" |
| 1334 |
|
| 1335 |
def test_len_set(self) -> None: |
| 1336 |
node = astroid.extract_node(""" |
| 1337 |
len({'a'}) |
| 1338 |
""") |
| 1339 |
inferred_node = next(node.infer()) |
| 1340 |
assert inferred_node.as_string() == "1" |
| 1341 |
|
| 1342 |
def test_len_object(self) -> None: |
| 1343 |
"""Test len with objects that implement the len protocol""" |
| 1344 |
node = astroid.extract_node(""" |
| 1345 |
class A: |
| 1346 |
def __len__(self): |
| 1347 |
return 57 |
| 1348 |
len(A()) |
| 1349 |
""") |
| 1350 |
inferred_node = next(node.infer()) |
| 1351 |
assert inferred_node.as_string() == "57" |
| 1352 |
|
| 1353 |
def test_len_class_with_metaclass(self) -> None: |
| 1354 |
"""Make sure proper len method is located""" |
| 1355 |
cls_node, inst_node = astroid.extract_node(""" |
| 1356 |
class F2(type): |
| 1357 |
def __new__(cls, name, bases, attrs): |
| 1358 |
return super().__new__(cls, name, bases, {}) |
| 1359 |
def __len__(self): |
| 1360 |
return 57 |
| 1361 |
class F(metaclass=F2): |
| 1362 |
def __len__(self): |
| 1363 |
return 4 |
| 1364 |
len(F) #@ |
| 1365 |
len(F()) #@ |
| 1366 |
""") |
| 1367 |
assert next(cls_node.infer()).as_string() == "57" |
| 1368 |
assert next(inst_node.infer()).as_string() == "4" |
| 1369 |
|
| 1370 |
def test_len_object_failure(self) -> None: |
| 1371 |
"""If taking the length of a class, do not use an instance method""" |
| 1372 |
node = astroid.extract_node(""" |
| 1373 |
class F: |
| 1374 |
def __len__(self): |
| 1375 |
return 57 |
| 1376 |
len(F) |
| 1377 |
""") |
| 1378 |
with pytest.raises(InferenceError): |
| 1379 |
next(node.infer()) |
| 1380 |
|
| 1381 |
def test_len_string(self) -> None: |
| 1382 |
node = astroid.extract_node(""" |
| 1383 |
len("uwu") |
| 1384 |
""") |
| 1385 |
assert next(node.infer()).as_string() == "3" |
| 1386 |
|
| 1387 |
def test_len_generator_failure(self) -> None: |
| 1388 |
node = astroid.extract_node(""" |
| 1389 |
def gen(): |
| 1390 |
yield 'a' |
| 1391 |
yield 'b' |
| 1392 |
len(gen()) |
| 1393 |
""") |
| 1394 |
with pytest.raises(InferenceError): |
| 1395 |
next(node.infer()) |
| 1396 |
|
| 1397 |
def test_len_failure_missing_variable(self) -> None: |
| 1398 |
node = astroid.extract_node(""" |
| 1399 |
len(a) |
| 1400 |
""") |
| 1401 |
with pytest.raises(InferenceError): |
| 1402 |
next(node.infer()) |
| 1403 |
|
| 1404 |
def test_len_bytes(self) -> None: |
| 1405 |
node = astroid.extract_node(""" |
| 1406 |
len(b'uwu') |
| 1407 |
""") |
| 1408 |
assert next(node.infer()).as_string() == "3" |
| 1409 |
|
| 1410 |
def test_int_subclass_result(self) -> None: |
| 1411 |
"""Check that a subclass of an int can still be inferred |
| 1412 |
|
| 1413 |
This test does not properly infer the value passed to the |
| 1414 |
int subclass (5) but still returns a proper integer as we |
| 1415 |
fake the result of the `len()` call. |
| 1416 |
""" |
| 1417 |
node = astroid.extract_node(""" |
| 1418 |
class IntSubclass(int): |
| 1419 |
pass |
| 1420 |
|
| 1421 |
class F: |
| 1422 |
def __len__(self): |
| 1423 |
return IntSubclass(5) |
| 1424 |
len(F()) |
| 1425 |
""") |
| 1426 |
assert next(node.infer()).as_string() == "0" |
| 1427 |
|
| 1428 |
@pytest.mark.xfail(reason="Can't use list special astroid fields") |
| 1429 |
def test_int_subclass_argument(self): |
| 1430 |
"""I am unable to access the length of an object which |
| 1431 |
subclasses list""" |
| 1432 |
node = astroid.extract_node(""" |
| 1433 |
class ListSubclass(list): |
| 1434 |
pass |
| 1435 |
len(ListSubclass([1,2,3,4,4])) |
| 1436 |
""") |
| 1437 |
assert next(node.infer()).as_string() == "5" |
| 1438 |
|
| 1439 |
def test_len_builtin_inference_attribute_error_str(self) -> None: |
| 1440 |
"""Make sure len builtin doesn't raise an AttributeError |
| 1441 |
on instances of str or bytes |
| 1442 |
|
| 1443 |
See https://github.com/pylint-dev/pylint/issues/1942 |
| 1444 |
""" |
| 1445 |
code = 'len(str("F"))' |
| 1446 |
try: |
| 1447 |
next(astroid.extract_node(code).infer()) |
| 1448 |
except InferenceError: |
| 1449 |
pass |
| 1450 |
|
| 1451 |
def test_len_builtin_inference_recursion_error_self_referential_attribute( |
| 1452 |
self, |
| 1453 |
) -> None: |
| 1454 |
"""Make sure len calls do not trigger |
| 1455 |
recursion errors for self referential assignment |
| 1456 |
|
| 1457 |
See https://github.com/pylint-dev/pylint/issues/2734 |
| 1458 |
""" |
| 1459 |
code = """ |
| 1460 |
class Data: |
| 1461 |
def __init__(self): |
| 1462 |
self.shape = [] |
| 1463 |
|
| 1464 |
data = Data() |
| 1465 |
data.shape = len(data.shape) |
| 1466 |
data.shape #@ |
| 1467 |
""" |
| 1468 |
try: |
| 1469 |
astroid.extract_node(code).inferred() |
| 1470 |
except RecursionError: |
| 1471 |
pytest.fail("Inference call should not trigger a recursion error") |
| 1472 |
|
| 1473 |
|
| 1474 |
def test_infer_str() -> None: |
| 1475 |
ast_nodes = astroid.extract_node(""" |
| 1476 |
str(s) #@ |
| 1477 |
str('a') #@ |
| 1478 |
str(some_object()) #@ |
| 1479 |
str(7**10000) #@ |
| 1480 |
""") |
| 1481 |
for node in ast_nodes: |
| 1482 |
inferred = next(node.infer()) |
| 1483 |
assert isinstance(inferred, nodes.Const) |
| 1484 |
|
| 1485 |
node = astroid.extract_node(""" |
| 1486 |
str(s='') #@ |
| 1487 |
""") |
| 1488 |
inferred = next(node.infer()) |
| 1489 |
assert isinstance(inferred, astroid.Instance) |
| 1490 |
assert inferred.qname() == "builtins.str" |
| 1491 |
|
| 1492 |
|
| 1493 |
def test_infer_str_const() -> None: |
| 1494 |
ast_nodes = astroid.extract_node(""" |
| 1495 |
str('') #@ |
| 1496 |
str('a') #@ |
| 1497 |
str(1) #@ |
| 1498 |
str(True) #@ |
| 1499 |
str(False) #@ |
| 1500 |
str(None) #@ |
| 1501 |
str(4.33) #@ |
| 1502 |
str(...) #@ |
| 1503 |
str(2 + 2) #@ |
| 1504 |
str() #@ |
| 1505 |
str(int) #@ |
| 1506 |
str(2 if unknown() else 3) #@ |
| 1507 |
""") |
| 1508 |
|
| 1509 |
inferred = list(node.inferred()[0].value for node in ast_nodes) |
| 1510 |
assert inferred[0] == "" |
| 1511 |
assert inferred[1] == "a" |
| 1512 |
assert inferred[2] == "1" |
| 1513 |
assert inferred[3] == "True" |
| 1514 |
assert inferred[4] == "False" |
| 1515 |
assert inferred[5] == "None" |
| 1516 |
assert inferred[6] == "4.33" |
| 1517 |
assert inferred[7] == "Ellipsis" |
| 1518 |
assert inferred[8] == "4" |
| 1519 |
assert inferred[9] == "" |
| 1520 |
assert inferred[10] == "" |
| 1521 |
assert inferred[11] == "" |
| 1522 |
|
| 1523 |
|
| 1524 |
def test_infer_str_does_not_run_user_str() -> None: |
| 1525 |
"""A user-defined __str__ must never be executed during inference.""" |
| 1526 |
node = astroid.extract_node(""" |
| 1527 |
class StrWillFail: |
| 1528 |
def __str__(self): |
| 1529 |
raise RuntimeError |
| 1530 |
|
| 1531 |
str(StrWillFail()) #@ |
| 1532 |
""") |
| 1533 |
# The argument infers to an Instance, not a nodes.Const, so infer_str |
| 1534 |
# returns the empty-string fallback without ever calling __str__. |
| 1535 |
inferred = node.inferred() |
| 1536 |
assert len(inferred) == 1 |
| 1537 |
assert isinstance(inferred[0], nodes.Const) |
| 1538 |
assert inferred[0].value == "" |
| 1539 |
|
| 1540 |
|
| 1541 |
def test_infer_int() -> None: |
| 1542 |
ast_nodes = astroid.extract_node(""" |
| 1543 |
int(0) #@ |
| 1544 |
int('1') #@ |
| 1545 |
""") |
| 1546 |
for node in ast_nodes: |
| 1547 |
inferred = next(node.infer()) |
| 1548 |
assert isinstance(inferred, nodes.Const) |
| 1549 |
|
| 1550 |
ast_nodes = astroid.extract_node(""" |
| 1551 |
int(s='') #@ |
| 1552 |
int('2.5') #@ |
| 1553 |
int('something else') #@ |
| 1554 |
int(unknown) #@ |
| 1555 |
int(b'a') #@ |
| 1556 |
""") |
| 1557 |
for node in ast_nodes: |
| 1558 |
inferred = next(node.infer()) |
| 1559 |
assert isinstance(inferred, astroid.Instance) |
| 1560 |
assert inferred.qname() == "builtins.int" |
| 1561 |
|
| 1562 |
|
| 1563 |
def test_infer_dict_from_keys() -> None: |
| 1564 |
bad_nodes = astroid.extract_node(""" |
| 1565 |
dict.fromkeys() #@ |
| 1566 |
dict.fromkeys(1, 2, 3) #@ |
| 1567 |
dict.fromkeys(a=1) #@ |
| 1568 |
""") |
| 1569 |
for node in bad_nodes: |
| 1570 |
with pytest.raises(InferenceError): |
| 1571 |
if isinstance(next(node.infer()), util.UninferableBase): |
| 1572 |
raise InferenceError |
| 1573 |
|
| 1574 |
# Test uninferable values |
| 1575 |
good_nodes = astroid.extract_node(""" |
| 1576 |
from unknown import Unknown |
| 1577 |
dict.fromkeys(some_value) #@ |
| 1578 |
dict.fromkeys(some_other_value) #@ |
| 1579 |
dict.fromkeys([Unknown(), Unknown()]) #@ |
| 1580 |
dict.fromkeys([Unknown(), Unknown()]) #@ |
| 1581 |
""") |
| 1582 |
for node in good_nodes: |
| 1583 |
inferred = next(node.infer()) |
| 1584 |
assert isinstance(inferred, nodes.Dict) |
| 1585 |
assert inferred.items == [] |
| 1586 |
|
| 1587 |
# Test inferable values |
| 1588 |
|
| 1589 |
# from a dictionary's keys |
| 1590 |
from_dict = astroid.extract_node(""" |
| 1591 |
dict.fromkeys({'a':2, 'b': 3, 'c': 3}) #@ |
| 1592 |
""") |
| 1593 |
inferred = next(from_dict.infer()) |
| 1594 |
assert isinstance(inferred, nodes.Dict) |
| 1595 |
itered = inferred.itered() |
| 1596 |
assert all(isinstance(elem, nodes.Const) for elem in itered) |
| 1597 |
actual_values = [elem.value for elem in itered] |
| 1598 |
assert sorted(actual_values) == ["a", "b", "c"] |
| 1599 |
|
| 1600 |
# from a string |
| 1601 |
from_string = astroid.extract_node(""" |
| 1602 |
dict.fromkeys('abc') |
| 1603 |
""") |
| 1604 |
inferred = next(from_string.infer()) |
| 1605 |
assert isinstance(inferred, nodes.Dict) |
| 1606 |
itered = inferred.itered() |
| 1607 |
assert all(isinstance(elem, nodes.Const) for elem in itered) |
| 1608 |
actual_values = [elem.value for elem in itered] |
| 1609 |
assert sorted(actual_values) == ["a", "b", "c"] |
| 1610 |
|
| 1611 |
# from bytes |
| 1612 |
from_bytes = astroid.extract_node(""" |
| 1613 |
dict.fromkeys(b'abc') |
| 1614 |
""") |
| 1615 |
inferred = next(from_bytes.infer()) |
| 1616 |
assert isinstance(inferred, nodes.Dict) |
| 1617 |
itered = inferred.itered() |
| 1618 |
assert all(isinstance(elem, nodes.Const) for elem in itered) |
| 1619 |
actual_values = [elem.value for elem in itered] |
| 1620 |
assert sorted(actual_values) == [97, 98, 99] |
| 1621 |
|
| 1622 |
# From list/set/tuple |
| 1623 |
from_others = astroid.extract_node(""" |
| 1624 |
dict.fromkeys(('a', 'b', 'c')) #@ |
| 1625 |
dict.fromkeys(['a', 'b', 'c']) #@ |
| 1626 |
dict.fromkeys({'a', 'b', 'c'}) #@ |
| 1627 |
""") |
| 1628 |
for node in from_others: |
| 1629 |
inferred = next(node.infer()) |
| 1630 |
assert isinstance(inferred, nodes.Dict) |
| 1631 |
itered = inferred.itered() |
| 1632 |
assert all(isinstance(elem, nodes.Const) for elem in itered) |
| 1633 |
actual_values = [elem.value for elem in itered] |
| 1634 |
assert sorted(actual_values) == ["a", "b", "c"] |
| 1635 |
|
| 1636 |
|
| 1637 |
def test_container_transform_oversized_str_declines() -> None: |
| 1638 |
"""list/set/tuple/frozenset must not build one Const per character for a |
| 1639 |
str/bytes constant longer than the cap.""" |
| 1640 |
with patch("astroid.brain.brain_builtin_inference._MAX_INFERABLE_STR_LEN", 4): |
| 1641 |
for builtin in ("list", "set", "tuple", "frozenset"): |
| 1642 |
node = astroid.extract_node(f'{builtin}("abcdef")') |
| 1643 |
inferred = next(node.infer()) |
| 1644 |
assert isinstance(inferred, Instance) |
| 1645 |
|
| 1646 |
# Small strings still infer their exact contents. |
| 1647 |
node = astroid.extract_node('list("abc")') |
| 1648 |
inferred = next(node.infer()) |
| 1649 |
assert isinstance(inferred, nodes.List) |
| 1650 |
assert [elem.value for elem in inferred.elts] == ["a", "b", "c"] |
| 1651 |
|
| 1652 |
|
| 1653 |
def test_infer_dict_fromkeys_oversized_str_declines() -> None: |
| 1654 |
"""dict.fromkeys must not build one key per character for a str/bytes |
| 1655 |
constant longer than the cap.""" |
| 1656 |
with patch("astroid.brain.brain_builtin_inference._MAX_INFERABLE_STR_LEN", 4): |
| 1657 |
node = astroid.extract_node('dict.fromkeys("abcdef")') |
| 1658 |
inferred = next(node.infer()) |
| 1659 |
assert isinstance(inferred, nodes.Dict) |
| 1660 |
assert inferred.items == [] |
| 1661 |
|
| 1662 |
|
| 1663 |
def test_infer_dict_from_keys_deduplicates() -> None: |
| 1664 |
# dict.fromkeys drops duplicate keys, so the inferred dict must too. As a |
| 1665 |
# side effect a repeated string no longer materializes one key per |
| 1666 |
# character (dict.fromkeys("x" * 10**8) is a single-key dict). |
| 1667 |
nodes_with_dupes = astroid.extract_node(""" |
| 1668 |
dict.fromkeys("aab") #@ |
| 1669 |
dict.fromkeys(b"aab") #@ |
| 1670 |
dict.fromkeys([1, 1, 2]) #@ |
| 1671 |
dict.fromkeys((1, 2, 1)) #@ |
| 1672 |
""") |
| 1673 |
expected = [["a", "b"], [97, 98], [1, 2], [1, 2]] |
| 1674 |
for node, keys in zip(nodes_with_dupes, expected): |
| 1675 |
inferred = next(node.infer()) |
| 1676 |
assert isinstance(inferred, nodes.Dict) |
| 1677 |
assert [elem.value for elem in inferred.itered()] == keys |
| 1678 |
|
| 1679 |
repeated = astroid.extract_node('dict.fromkeys("x" * 1000)') |
| 1680 |
inferred = next(repeated.infer()) |
| 1681 |
assert isinstance(inferred, nodes.Dict) |
| 1682 |
assert [elem.value for elem in inferred.itered()] == ["x"] |
| 1683 |
|
| 1684 |
|
| 1685 |
class TestFunctoolsPartial: |
| 1686 |
@staticmethod |
| 1687 |
def test_infer_partial() -> None: |
| 1688 |
ast_node = astroid.extract_node(""" |
| 1689 |
from functools import partial |
| 1690 |
def test(a, b): |
| 1691 |
'''Docstring''' |
| 1692 |
return a + b |
| 1693 |
partial(test, 1)(3) #@ |
| 1694 |
""") |
| 1695 |
assert isinstance(ast_node.func, nodes.Call) |
| 1696 |
inferred = ast_node.func.inferred() |
| 1697 |
assert len(inferred) == 1 |
| 1698 |
partial = inferred[0] |
| 1699 |
assert isinstance(partial, objects.PartialFunction) |
| 1700 |
assert isinstance(partial.as_string(), str) |
| 1701 |
assert isinstance(partial.doc_node, nodes.Const) |
| 1702 |
assert partial.doc_node.value == "Docstring" |
| 1703 |
assert partial.lineno == 3 |
| 1704 |
assert partial.col_offset == 0 |
| 1705 |
assert partial.end_lineno == 5 |
| 1706 |
assert partial.end_col_offset == 16 |
| 1707 |
|
| 1708 |
@staticmethod |
| 1709 |
def test_partial_descriptor_binding() -> None: |
| 1710 |
ast_nodes = astroid.extract_node(""" |
| 1711 |
from functools import partial |
| 1712 |
|
| 1713 |
def test(x): |
| 1714 |
return x |
| 1715 |
|
| 1716 |
p = partial(test, x=1) |
| 1717 |
a = p.__get__({}) |
| 1718 |
a #@ |
| 1719 |
a() #@ |
| 1720 |
""") |
| 1721 |
bound, result = ast_nodes |
| 1722 |
inferred_bound = next(bound.infer()) |
| 1723 |
assert isinstance(inferred_bound, astroid.BoundMethod) |
| 1724 |
assert isinstance(inferred_bound._proxied._proxied, objects.PartialFunction) |
| 1725 |
|
| 1726 |
inferred_result = next(result.infer()) |
| 1727 |
assert isinstance(inferred_result, nodes.Const) |
| 1728 |
assert inferred_result.value == 1 |
| 1729 |
|
| 1730 |
def test_invalid_functools_partial_calls(self) -> None: |
| 1731 |
ast_nodes = astroid.extract_node(""" |
| 1732 |
from functools import partial |
| 1733 |
from unknown import Unknown |
| 1734 |
|
| 1735 |
def test(a, b, c): |
| 1736 |
return a + b + c |
| 1737 |
|
| 1738 |
partial() #@ |
| 1739 |
partial(test) #@ |
| 1740 |
partial(func=test) #@ |
| 1741 |
partial(some_func, a=1) #@ |
| 1742 |
partial(Unknown, a=1) #@ |
| 1743 |
partial(2, a=1) #@ |
| 1744 |
partial(test, unknown=1) #@ |
| 1745 |
""") |
| 1746 |
for node in ast_nodes: |
| 1747 |
inferred = next(node.infer()) |
| 1748 |
assert isinstance(inferred, (nodes.FunctionDef, astroid.Instance)) |
| 1749 |
assert inferred.qname() in { |
| 1750 |
"functools.partial", |
| 1751 |
"functools.partial.newfunc", |
| 1752 |
} |
| 1753 |
|
| 1754 |
def test_inferred_partial_function_calls(self) -> None: |
| 1755 |
ast_nodes = astroid.extract_node(""" |
| 1756 |
from functools import partial |
| 1757 |
def test(a, b): |
| 1758 |
return a + b |
| 1759 |
partial(test, 1)(3) #@ |
| 1760 |
partial(test, b=4)(3) #@ |
| 1761 |
partial(test, b=4)(a=3) #@ |
| 1762 |
def other_test(a, b, *, c=1): |
| 1763 |
return (a + b) * c |
| 1764 |
|
| 1765 |
partial(other_test, 1, 2)() #@ |
| 1766 |
partial(other_test, 1, 2)(c=4) #@ |
| 1767 |
partial(other_test, c=4)(1, 3) #@ |
| 1768 |
partial(other_test, 4, c=4)(4) #@ |
| 1769 |
partial(other_test, 4, c=4)(b=5) #@ |
| 1770 |
test(1, 2) #@ |
| 1771 |
partial(other_test, 1, 2)(c=3) #@ |
| 1772 |
partial(test, b=4)(a=3) #@ |
| 1773 |
""") |
| 1774 |
expected_values = [4, 7, 7, 3, 12, 16, 32, 36, 3, 9, 7] |
| 1775 |
for node, expected_value in zip(ast_nodes, expected_values): |
| 1776 |
inferred = next(node.infer()) |
| 1777 |
assert isinstance(inferred, nodes.Const) |
| 1778 |
assert inferred.value == expected_value |
| 1779 |
|
| 1780 |
def test_partial_assignment(self) -> None: |
| 1781 |
"""Make sure partials are not assigned to original scope.""" |
| 1782 |
ast_nodes = astroid.extract_node(""" |
| 1783 |
from functools import partial |
| 1784 |
def test(a, b): #@ |
| 1785 |
return a + b |
| 1786 |
test2 = partial(test, 1) |
| 1787 |
test2 #@ |
| 1788 |
def test3_scope(a): |
| 1789 |
test3 = partial(test, a) |
| 1790 |
test3 #@ |
| 1791 |
""") |
| 1792 |
func1, func2, func3 = ast_nodes |
| 1793 |
assert func1.parent.scope() == func2.parent.scope() |
| 1794 |
assert func1.parent.scope() != func3.parent.scope() |
| 1795 |
partial_func3 = next(func3.infer()) |
| 1796 |
# use scope of parent, so that it doesn't just refer to self |
| 1797 |
scope = partial_func3.parent.scope() |
| 1798 |
assert scope.name == "test3_scope", "parented by closure" |
| 1799 |
|
| 1800 |
def test_partial_does_not_affect_scope(self) -> None: |
| 1801 |
"""Make sure partials are not automatically assigned.""" |
| 1802 |
ast_nodes = astroid.extract_node(""" |
| 1803 |
from functools import partial |
| 1804 |
def test(a, b): |
| 1805 |
return a + b |
| 1806 |
def scope(): |
| 1807 |
test2 = partial(test, 1) |
| 1808 |
test2 #@ |
| 1809 |
""") |
| 1810 |
test2 = next(ast_nodes.infer()) |
| 1811 |
mod_scope = test2.root() |
| 1812 |
scope = test2.parent.scope() |
| 1813 |
assert set(mod_scope) == {"test", "scope", "partial"} |
| 1814 |
assert set(scope) == {"test2"} |
| 1815 |
|
| 1816 |
def test_multiple_partial_args(self) -> None: |
| 1817 |
"Make sure partials remember locked-in args." |
| 1818 |
ast_node = astroid.extract_node(""" |
| 1819 |
from functools import partial |
| 1820 |
def test(a, b, c, d, e=5): |
| 1821 |
return a + b + c + d + e |
| 1822 |
test1 = partial(test, 1) |
| 1823 |
test2 = partial(test1, 2) |
| 1824 |
test3 = partial(test2, 3) |
| 1825 |
test3(4, e=6) #@ |
| 1826 |
""") |
| 1827 |
expected_args = [1, 2, 3, 4] |
| 1828 |
expected_keywords = {"e": 6} |
| 1829 |
|
| 1830 |
call_site = astroid.arguments.CallSite.from_call(ast_node) |
| 1831 |
called_func = next(ast_node.func.infer()) |
| 1832 |
called_args = called_func.filled_args + call_site.positional_arguments |
| 1833 |
called_keywords = {**called_func.filled_keywords, **call_site.keyword_arguments} |
| 1834 |
assert len(called_args) == len(expected_args) |
| 1835 |
assert [arg.value for arg in called_args] == expected_args |
| 1836 |
assert len(called_keywords) == len(expected_keywords) |
| 1837 |
|
| 1838 |
for keyword, value in expected_keywords.items(): |
| 1839 |
assert keyword in called_keywords |
| 1840 |
assert called_keywords[keyword].value == value |
| 1841 |
|
| 1842 |
|
| 1843 |
def test_http_client_brain() -> None: |
| 1844 |
node = astroid.extract_node(""" |
| 1845 |
from http.client import OK |
| 1846 |
OK |
| 1847 |
""") |
| 1848 |
inferred = next(node.infer()) |
| 1849 |
assert isinstance(inferred, astroid.Instance) |
| 1850 |
|
| 1851 |
|
| 1852 |
def test_http_status_brain() -> None: |
| 1853 |
node = astroid.extract_node(""" |
| 1854 |
import http |
| 1855 |
http.HTTPStatus.CONTINUE.phrase |
| 1856 |
""") |
| 1857 |
inferred = next(node.infer()) |
| 1858 |
# Cannot infer the exact value but the field is there. |
| 1859 |
assert inferred.value == "" |
| 1860 |
|
| 1861 |
node = astroid.extract_node(""" |
| 1862 |
import http |
| 1863 |
http.HTTPStatus(200).phrase |
| 1864 |
""") |
| 1865 |
inferred = next(node.infer()) |
| 1866 |
assert isinstance(inferred, nodes.Const) |
| 1867 |
|
| 1868 |
|
| 1869 |
def test_http_status_brain_iterable() -> None: |
| 1870 |
"""Astroid inference of `http.HTTPStatus` is an iterable subclass of `enum.IntEnum`""" |
| 1871 |
node = astroid.extract_node(""" |
| 1872 |
import http |
| 1873 |
http.HTTPStatus |
| 1874 |
""") |
| 1875 |
inferred = next(node.infer()) |
| 1876 |
assert "enum.IntEnum" in [ancestor.qname() for ancestor in inferred.ancestors()] |
| 1877 |
assert inferred.getattr("__iter__") |
| 1878 |
|
| 1879 |
|
| 1880 |
def test_oserror_model() -> None: |
| 1881 |
node = astroid.extract_node(""" |
| 1882 |
try: |
| 1883 |
1/0 |
| 1884 |
except OSError as exc: |
| 1885 |
exc #@ |
| 1886 |
""") |
| 1887 |
inferred = next(node.infer()) |
| 1888 |
strerror = next(inferred.igetattr("strerror")) |
| 1889 |
assert isinstance(strerror, nodes.Const) |
| 1890 |
assert strerror.value == "" |
| 1891 |
|
| 1892 |
|
| 1893 |
@pytest.mark.skipif(PY313_PLUS, reason="Python >= 3.13 no longer has a crypt module") |
| 1894 |
def test_crypt_brain() -> None: |
| 1895 |
module = MANAGER.ast_from_module_name("crypt") |
| 1896 |
dynamic_attrs = [ |
| 1897 |
"METHOD_SHA512", |
| 1898 |
"METHOD_SHA256", |
| 1899 |
"METHOD_BLOWFISH", |
| 1900 |
"METHOD_MD5", |
| 1901 |
"METHOD_CRYPT", |
| 1902 |
] |
| 1903 |
for attr in dynamic_attrs: |
| 1904 |
assert attr in module |
| 1905 |
|
| 1906 |
|
| 1907 |
@pytest.mark.parametrize( |
| 1908 |
"code,expected_class,expected_value", |
| 1909 |
[ |
| 1910 |
("'hey'.encode()", nodes.Const, b""), |
| 1911 |
("b'hey'.decode()", nodes.Const, ""), |
| 1912 |
("'hey'.encode().decode()", nodes.Const, ""), |
| 1913 |
], |
| 1914 |
) |
| 1915 |
def test_str_and_bytes(code, expected_class, expected_value): |
| 1916 |
node = astroid.extract_node(code) |
| 1917 |
inferred = next(node.infer()) |
| 1918 |
assert isinstance(inferred, expected_class) |
| 1919 |
assert inferred.value == expected_value |
| 1920 |
|
| 1921 |
|
| 1922 |
def test_no_recursionerror_on_self_referential_length_check() -> None: |
| 1923 |
""" |
| 1924 |
Regression test for https://github.com/pylint-dev/astroid/issues/777 |
| 1925 |
|
| 1926 |
This test should only raise an InferenceError and no RecursionError. |
| 1927 |
""" |
| 1928 |
with pytest.raises(InferenceError): |
| 1929 |
node = astroid.extract_node(""" |
| 1930 |
class Crash: |
| 1931 |
def __len__(self) -> int: |
| 1932 |
return len(self) |
| 1933 |
len(Crash()) #@ |
| 1934 |
""") |
| 1935 |
assert isinstance(node, nodes.NodeNG) |
| 1936 |
node.inferred() |
| 1937 |
|
| 1938 |
|
| 1939 |
def test_inference_on_outer_referential_length_check() -> None: |
| 1940 |
""" |
| 1941 |
Regression test for https://github.com/pylint-dev/pylint/issues/5244 |
| 1942 |
See also https://github.com/pylint-dev/astroid/pull/1234 |
| 1943 |
|
| 1944 |
This test should succeed without any error. |
| 1945 |
""" |
| 1946 |
node = astroid.extract_node(""" |
| 1947 |
class A: |
| 1948 |
def __len__(self) -> int: |
| 1949 |
return 42 |
| 1950 |
|
| 1951 |
class Crash: |
| 1952 |
def __len__(self) -> int: |
| 1953 |
a = A() |
| 1954 |
return len(a) |
| 1955 |
|
| 1956 |
len(Crash()) #@ |
| 1957 |
""") |
| 1958 |
inferred = node.inferred() |
| 1959 |
assert len(inferred) == 1 |
| 1960 |
assert isinstance(inferred[0], nodes.Const) |
| 1961 |
assert inferred[0].value == 42 |
| 1962 |
|
| 1963 |
|
| 1964 |
def test_no_attributeerror_on_self_referential_length_check() -> None: |
| 1965 |
""" |
| 1966 |
Regression test for https://github.com/pylint-dev/pylint/issues/5244 |
| 1967 |
See also https://github.com/pylint-dev/astroid/pull/1234 |
| 1968 |
|
| 1969 |
This test should only raise an InferenceError and no AttributeError. |
| 1970 |
""" |
| 1971 |
with pytest.raises(InferenceError): |
| 1972 |
node = astroid.extract_node(""" |
| 1973 |
class MyClass: |
| 1974 |
def some_func(self): |
| 1975 |
return lambda: 42 |
| 1976 |
|
| 1977 |
def __len__(self): |
| 1978 |
return len(self.some_func()) |
| 1979 |
|
| 1980 |
len(MyClass()) #@ |
| 1981 |
""") |
| 1982 |
assert isinstance(node, nodes.NodeNG) |
| 1983 |
node.inferred() |