| 1 |
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html |
| 2 |
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE |
| 3 |
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt |
| 4 |
|
| 5 |
import unittest |
| 6 |
from textwrap import dedent |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from astroid import exceptions, nodes |
| 11 |
from astroid.builder import AstroidBuilder, extract_node |
| 12 |
from astroid.const import PY315_PLUS |
| 13 |
from astroid.manager import AstroidManager |
| 14 |
|
| 15 |
|
| 16 |
class Python3TC(unittest.TestCase): |
| 17 |
@classmethod |
| 18 |
def setUpClass(cls): |
| 19 |
cls.builder = AstroidBuilder(AstroidManager()) |
| 20 |
|
| 21 |
def test_starred_notation(self) -> None: |
| 22 |
astroid = self.builder.string_build("*a, b = [1, 2, 3]", "test", "test") |
| 23 |
|
| 24 |
# Get the star node |
| 25 |
node = next(next(next(astroid.get_children()).get_children()).get_children()) |
| 26 |
|
| 27 |
self.assertTrue(isinstance(node.assign_type(), nodes.Assign)) |
| 28 |
|
| 29 |
def test_yield_from(self) -> None: |
| 30 |
body = dedent(""" |
| 31 |
def func(): |
| 32 |
yield from iter([1, 2]) |
| 33 |
""") |
| 34 |
astroid = self.builder.string_build(body) |
| 35 |
func = astroid.body[0] |
| 36 |
self.assertIsInstance(func, nodes.FunctionDef) |
| 37 |
yieldfrom_stmt = func.body[0] |
| 38 |
|
| 39 |
self.assertIsInstance(yieldfrom_stmt, nodes.Expr) |
| 40 |
self.assertIsInstance(yieldfrom_stmt.value, nodes.YieldFrom) |
| 41 |
self.assertEqual(yieldfrom_stmt.as_string(), "yield from iter([1, 2])") |
| 42 |
|
| 43 |
def test_yield_from_is_generator(self) -> None: |
| 44 |
body = dedent(""" |
| 45 |
def func(): |
| 46 |
yield from iter([1, 2]) |
| 47 |
""") |
| 48 |
astroid = self.builder.string_build(body) |
| 49 |
func = astroid.body[0] |
| 50 |
self.assertIsInstance(func, nodes.FunctionDef) |
| 51 |
self.assertTrue(func.is_generator()) |
| 52 |
|
| 53 |
def test_yield_from_as_string(self) -> None: |
| 54 |
body = dedent(""" |
| 55 |
def func(): |
| 56 |
yield from iter([1, 2]) |
| 57 |
value = yield from other() |
| 58 |
""") |
| 59 |
astroid = self.builder.string_build(body) |
| 60 |
func = astroid.body[0] |
| 61 |
self.assertEqual(func.as_string().strip(), body.strip()) |
| 62 |
|
| 63 |
# metaclass tests |
| 64 |
|
| 65 |
def test_simple_metaclass(self) -> None: |
| 66 |
astroid = self.builder.string_build("class Test(metaclass=type): pass") |
| 67 |
klass = astroid.body[0] |
| 68 |
|
| 69 |
metaclass = klass.metaclass() |
| 70 |
self.assertIsInstance(metaclass, nodes.ClassDef) |
| 71 |
self.assertEqual(metaclass.name, "type") |
| 72 |
|
| 73 |
def test_metaclass_error(self) -> None: |
| 74 |
astroid = self.builder.string_build("class Test(metaclass=typ): pass") |
| 75 |
klass = astroid.body[0] |
| 76 |
self.assertFalse(klass.metaclass()) |
| 77 |
|
| 78 |
def test_metaclass_imported(self) -> None: |
| 79 |
astroid = self.builder.string_build(dedent(""" |
| 80 |
from abc import ABCMeta |
| 81 |
class Test(metaclass=ABCMeta): pass""")) |
| 82 |
klass = astroid.body[1] |
| 83 |
|
| 84 |
metaclass = klass.metaclass() |
| 85 |
self.assertIsInstance(metaclass, nodes.ClassDef) |
| 86 |
self.assertEqual(metaclass.name, "ABCMeta") |
| 87 |
|
| 88 |
def test_metaclass_multiple_keywords(self) -> None: |
| 89 |
astroid = self.builder.string_build( |
| 90 |
"class Test(magic=None, metaclass=type): pass" |
| 91 |
) |
| 92 |
klass = astroid.body[0] |
| 93 |
|
| 94 |
metaclass = klass.metaclass() |
| 95 |
self.assertIsInstance(metaclass, nodes.ClassDef) |
| 96 |
self.assertEqual(metaclass.name, "type") |
| 97 |
|
| 98 |
def test_as_string(self) -> None: |
| 99 |
body = dedent(""" |
| 100 |
from abc import ABCMeta |
| 101 |
class Test(metaclass=ABCMeta): pass""") |
| 102 |
astroid = self.builder.string_build(body) |
| 103 |
klass = astroid.body[1] |
| 104 |
|
| 105 |
self.assertEqual( |
| 106 |
klass.as_string(), "\n\nclass Test(metaclass=ABCMeta):\n pass\n" |
| 107 |
) |
| 108 |
|
| 109 |
def test_old_syntax_works(self) -> None: |
| 110 |
astroid = self.builder.string_build(dedent(""" |
| 111 |
class Test: |
| 112 |
__metaclass__ = type |
| 113 |
class SubTest(Test): pass |
| 114 |
""")) |
| 115 |
klass = astroid["SubTest"] |
| 116 |
metaclass = klass.metaclass() |
| 117 |
self.assertIsNone(metaclass) |
| 118 |
|
| 119 |
def test_metaclass_yes_leak(self) -> None: |
| 120 |
astroid = self.builder.string_build(dedent(""" |
| 121 |
# notice `ab` instead of `abc` |
| 122 |
from ab import ABCMeta |
| 123 |
|
| 124 |
class Meta(metaclass=ABCMeta): pass |
| 125 |
""")) |
| 126 |
klass = astroid["Meta"] |
| 127 |
self.assertIsNone(klass.metaclass()) |
| 128 |
|
| 129 |
def test_parent_metaclass(self) -> None: |
| 130 |
astroid = self.builder.string_build(dedent(""" |
| 131 |
from abc import ABCMeta |
| 132 |
class Test(metaclass=ABCMeta): pass |
| 133 |
class SubTest(Test): pass |
| 134 |
""")) |
| 135 |
klass = astroid["SubTest"] |
| 136 |
metaclass = klass.metaclass() |
| 137 |
self.assertIsInstance(metaclass, nodes.ClassDef) |
| 138 |
self.assertEqual(metaclass.name, "ABCMeta") |
| 139 |
|
| 140 |
def test_metaclass_ancestors(self) -> None: |
| 141 |
astroid = self.builder.string_build(dedent(""" |
| 142 |
from abc import ABCMeta |
| 143 |
|
| 144 |
class FirstMeta(metaclass=ABCMeta): pass |
| 145 |
class SecondMeta(metaclass=type): |
| 146 |
pass |
| 147 |
|
| 148 |
class Simple: |
| 149 |
pass |
| 150 |
|
| 151 |
class FirstImpl(FirstMeta): pass |
| 152 |
class SecondImpl(FirstImpl): pass |
| 153 |
class ThirdImpl(Simple, SecondMeta): |
| 154 |
pass |
| 155 |
""")) |
| 156 |
classes = {"ABCMeta": ("FirstImpl", "SecondImpl"), "type": ("ThirdImpl",)} |
| 157 |
for metaclass, names in classes.items(): |
| 158 |
for name in names: |
| 159 |
impl = astroid[name] |
| 160 |
meta = impl.metaclass() |
| 161 |
self.assertIsInstance(meta, nodes.ClassDef) |
| 162 |
self.assertEqual(meta.name, metaclass) |
| 163 |
|
| 164 |
def test_annotation_support(self) -> None: |
| 165 |
astroid = self.builder.string_build(dedent(""" |
| 166 |
def test(a: int, b: str, c: None, d, e, |
| 167 |
*args: float, **kwargs: int)->int: |
| 168 |
pass |
| 169 |
""")) |
| 170 |
func = astroid["test"] |
| 171 |
self.assertIsInstance(func.args.varargannotation, nodes.Name) |
| 172 |
self.assertEqual(func.args.varargannotation.name, "float") |
| 173 |
self.assertIsInstance(func.args.kwargannotation, nodes.Name) |
| 174 |
self.assertEqual(func.args.kwargannotation.name, "int") |
| 175 |
self.assertIsInstance(func.returns, nodes.Name) |
| 176 |
self.assertEqual(func.returns.name, "int") |
| 177 |
arguments = func.args |
| 178 |
self.assertIsInstance(arguments.annotations[0], nodes.Name) |
| 179 |
self.assertEqual(arguments.annotations[0].name, "int") |
| 180 |
self.assertIsInstance(arguments.annotations[1], nodes.Name) |
| 181 |
self.assertEqual(arguments.annotations[1].name, "str") |
| 182 |
self.assertIsInstance(arguments.annotations[2], nodes.Const) |
| 183 |
self.assertIsNone(arguments.annotations[2].value) |
| 184 |
self.assertIsNone(arguments.annotations[3]) |
| 185 |
self.assertIsNone(arguments.annotations[4]) |
| 186 |
|
| 187 |
astroid = self.builder.string_build(dedent(""" |
| 188 |
def test(a: int=1, b: str=2): |
| 189 |
pass |
| 190 |
""")) |
| 191 |
func = astroid["test"] |
| 192 |
self.assertIsInstance(func.args.annotations[0], nodes.Name) |
| 193 |
self.assertEqual(func.args.annotations[0].name, "int") |
| 194 |
self.assertIsInstance(func.args.annotations[1], nodes.Name) |
| 195 |
self.assertEqual(func.args.annotations[1].name, "str") |
| 196 |
self.assertIsNone(func.returns) |
| 197 |
|
| 198 |
def test_kwonlyargs_annotations_supper(self) -> None: |
| 199 |
node = self.builder.string_build(dedent(""" |
| 200 |
def test(*, a: int, b: str, c: None, d, e): |
| 201 |
pass |
| 202 |
""")) |
| 203 |
func = node["test"] |
| 204 |
arguments = func.args |
| 205 |
self.assertIsInstance(arguments.kwonlyargs_annotations[0], nodes.Name) |
| 206 |
self.assertEqual(arguments.kwonlyargs_annotations[0].name, "int") |
| 207 |
self.assertIsInstance(arguments.kwonlyargs_annotations[1], nodes.Name) |
| 208 |
self.assertEqual(arguments.kwonlyargs_annotations[1].name, "str") |
| 209 |
self.assertIsInstance(arguments.kwonlyargs_annotations[2], nodes.Const) |
| 210 |
self.assertIsNone(arguments.kwonlyargs_annotations[2].value) |
| 211 |
self.assertIsNone(arguments.kwonlyargs_annotations[3]) |
| 212 |
self.assertIsNone(arguments.kwonlyargs_annotations[4]) |
| 213 |
|
| 214 |
def test_annotation_as_string(self) -> None: |
| 215 |
code1 = dedent(""" |
| 216 |
def test(a, b: int = 4, c=2, f: 'lala' = 4) -> 2: |
| 217 |
pass""") |
| 218 |
code2 = dedent(""" |
| 219 |
def test(a: typing.Generic[T], c: typing.Any = 24) -> typing.Iterable: |
| 220 |
pass""") |
| 221 |
for code in (code1, code2): |
| 222 |
func = extract_node(code) |
| 223 |
self.assertEqual(func.as_string(), code) |
| 224 |
|
| 225 |
def test_unpacking_in_dicts(self) -> None: |
| 226 |
code = "{'x': 1, **{'y': 2}}" |
| 227 |
node = extract_node(code) |
| 228 |
self.assertEqual(node.as_string(), code) |
| 229 |
assert isinstance(node, nodes.Dict) |
| 230 |
keys = [key for (key, _) in node.items] |
| 231 |
self.assertIsInstance(keys[0], nodes.Const) |
| 232 |
self.assertIsInstance(keys[1], nodes.DictUnpack) |
| 233 |
|
| 234 |
def test_nested_unpacking_in_dicts(self) -> None: |
| 235 |
code = "{'x': 1, **{'y': 2, **{'z': 3}}}" |
| 236 |
node = extract_node(code) |
| 237 |
self.assertEqual(node.as_string(), code) |
| 238 |
|
| 239 |
@pytest.mark.skipif( |
| 240 |
not PY315_PLUS, reason="PEP 798 unpacking in comprehensions, new in 3.15" |
| 241 |
) |
| 242 |
def test_unpacking_in_comprehensions(self) -> None: |
| 243 |
list_comp = extract_node("[*L for L in lists]") |
| 244 |
self.assertIsInstance(list_comp, nodes.ListComp) |
| 245 |
self.assertIsInstance(list_comp.elt, nodes.Starred) |
| 246 |
|
| 247 |
set_comp = extract_node("{*L for L in lists}") |
| 248 |
self.assertIsInstance(set_comp, nodes.SetComp) |
| 249 |
self.assertIsInstance(set_comp.elt, nodes.Starred) |
| 250 |
|
| 251 |
gen_exp = extract_node("(*L for L in lists)") |
| 252 |
self.assertIsInstance(gen_exp, nodes.GeneratorExp) |
| 253 |
self.assertIsInstance(gen_exp.elt, nodes.Starred) |
| 254 |
|
| 255 |
@pytest.mark.skipif( |
| 256 |
not PY315_PLUS, reason="PEP 798 unpacking in comprehensions, new in 3.15" |
| 257 |
) |
| 258 |
def test_dict_unpacking_in_comprehension(self) -> None: |
| 259 |
# CPython stores the unpacked mapping in ``DictComp.key`` and leaves |
| 260 |
# ``value`` as ``None``; astroid mirrors the ``{**d}`` representation |
| 261 |
# with a ``DictUnpack`` key and the real value. |
| 262 |
node = extract_node("{**d for d in dicts}") |
| 263 |
self.assertIsInstance(node, nodes.DictComp) |
| 264 |
self.assertIsInstance(node.key, nodes.DictUnpack) |
| 265 |
self.assertIsInstance(node.value, nodes.Name) |
| 266 |
self.assertEqual(node.value.name, "d") |
| 267 |
|
| 268 |
@pytest.mark.skipif( |
| 269 |
not PY315_PLUS, reason="PEP 798 unpacking in comprehensions, new in 3.15" |
| 270 |
) |
| 271 |
def test_unpacking_in_comprehensions_as_string(self) -> None: |
| 272 |
for code in ( |
| 273 |
"[*L for L in lists]", |
| 274 |
"{*L for L in lists}", |
| 275 |
"(*L for L in lists)", |
| 276 |
"{**d for d in dicts}", |
| 277 |
): |
| 278 |
self.assertEqual(extract_node(code).as_string(), code) |
| 279 |
|
| 280 |
@pytest.mark.skipif( |
| 281 |
not PY315_PLUS, reason="PEP 798 unpacking in comprehensions, new in 3.15" |
| 282 |
) |
| 283 |
def test_comprehension_target_resolves_inside_starred_elt(self) -> None: |
| 284 |
# The comprehension target is in scope inside the starred element and |
| 285 |
# infers to the iterated items. |
| 286 |
node = extract_node("[*L for L in [[1, 2], [3, 4]]]") |
| 287 |
self.assertIsInstance(node.elt, nodes.Starred) |
| 288 |
inferred = [elt.as_string() for elt in node.elt.value.inferred()] |
| 289 |
self.assertEqual(inferred, ["[1, 2]", "[3, 4]"]) |
| 290 |
|
| 291 |
def test_unpacking_in_dict_getitem(self) -> None: |
| 292 |
node = extract_node("{1:2, **{2:3, 3:4}, **{5: 6}}") |
| 293 |
for key, expected in ((1, 2), (2, 3), (3, 4), (5, 6)): |
| 294 |
value = node.getitem(nodes.Const(key)) |
| 295 |
self.assertIsInstance(value, nodes.Const) |
| 296 |
self.assertEqual(value.value, expected) |
| 297 |
|
| 298 |
@staticmethod |
| 299 |
def test_unpacking_in_dict_getitem_with_ref() -> None: |
| 300 |
node = extract_node(""" |
| 301 |
a = {1: 2} |
| 302 |
{**a, 2: 3} #@ |
| 303 |
""") |
| 304 |
assert isinstance(node, nodes.Dict) |
| 305 |
|
| 306 |
for key, expected in ((1, 2), (2, 3)): |
| 307 |
value = node.getitem(nodes.Const(key)) |
| 308 |
assert isinstance(value, nodes.Const) |
| 309 |
assert value.value == expected |
| 310 |
|
| 311 |
@staticmethod |
| 312 |
def test_unpacking_in_dict_getitem_uninferable() -> None: |
| 313 |
node = extract_node("{**a, 2: 3}") |
| 314 |
assert isinstance(node, nodes.Dict) |
| 315 |
|
| 316 |
with pytest.raises(exceptions.AstroidIndexError): |
| 317 |
node.getitem(nodes.Const(1)) |
| 318 |
|
| 319 |
value = node.getitem(nodes.Const(2)) |
| 320 |
assert isinstance(value, nodes.Const) |
| 321 |
assert value.value == 3 |
| 322 |
|
| 323 |
def test_format_string(self) -> None: |
| 324 |
code = "f'{greetings} {person}'" |
| 325 |
node = extract_node(code) |
| 326 |
self.assertEqual(node.as_string(), code) |
| 327 |
|
| 328 |
def test_underscores_in_numeral_literal(self) -> None: |
| 329 |
pairs = [("10_1000", 101000), ("10_000_000", 10000000), ("0x_FF_FF", 65535)] |
| 330 |
for value, expected in pairs: |
| 331 |
node = extract_node(value) |
| 332 |
inferred = next(node.infer()) |
| 333 |
self.assertIsInstance(inferred, nodes.Const) |
| 334 |
self.assertEqual(inferred.value, expected) |
| 335 |
|
| 336 |
def test_async_comprehensions(self) -> None: |
| 337 |
async_comprehensions = [ |
| 338 |
extract_node( |
| 339 |
"async def f(): return __([i async for i in aiter() if i % 2])" |
| 340 |
), |
| 341 |
extract_node( |
| 342 |
"async def f(): return __({i async for i in aiter() if i % 2})" |
| 343 |
), |
| 344 |
extract_node( |
| 345 |
"async def f(): return __((i async for i in aiter() if i % 2))" |
| 346 |
), |
| 347 |
extract_node( |
| 348 |
"async def f(): return __({i: i async for i in aiter() if i % 2})" |
| 349 |
), |
| 350 |
] |
| 351 |
non_async_comprehensions = [ |
| 352 |
extract_node("async def f(): return __({i: i for i in iter() if i % 2})") |
| 353 |
] |
| 354 |
|
| 355 |
for comp in async_comprehensions: |
| 356 |
self.assertTrue(comp.generators[0].is_async) |
| 357 |
for comp in non_async_comprehensions: |
| 358 |
self.assertFalse(comp.generators[0].is_async) |
| 359 |
|
| 360 |
def test_async_comprehensions_outside_coroutine(self): |
| 361 |
# When async and await will become keywords, async comprehensions |
| 362 |
# will be allowed outside of coroutines body |
| 363 |
comprehensions = [ |
| 364 |
"[i async for i in aiter() if condition(i)]", |
| 365 |
"[await fun() async for fun in funcs]", |
| 366 |
"{await fun() async for fun in funcs}", |
| 367 |
"{fun: await fun() async for fun in funcs}", |
| 368 |
"[await fun() async for fun in funcs if await smth]", |
| 369 |
"{await fun() async for fun in funcs if await smth}", |
| 370 |
"{fun: await fun() async for fun in funcs if await smth}", |
| 371 |
"[await fun() async for fun in funcs]", |
| 372 |
"{await fun() async for fun in funcs}", |
| 373 |
"{fun: await fun() async for fun in funcs}", |
| 374 |
"[await fun() async for fun in funcs if await smth]", |
| 375 |
"{await fun() async for fun in funcs if await smth}", |
| 376 |
"{fun: await fun() async for fun in funcs if await smth}", |
| 377 |
] |
| 378 |
|
| 379 |
for comp in comprehensions: |
| 380 |
node = extract_node(comp) |
| 381 |
self.assertTrue(node.generators[0].is_async) |
| 382 |
|
| 383 |
def test_async_comprehensions_as_string(self) -> None: |
| 384 |
func_bodies = [ |
| 385 |
"return [i async for i in aiter() if condition(i)]", |
| 386 |
"return [await fun() for fun in funcs]", |
| 387 |
"return {await fun() for fun in funcs}", |
| 388 |
"return {fun: await fun() for fun in funcs}", |
| 389 |
"return [await fun() for fun in funcs if await smth]", |
| 390 |
"return {await fun() for fun in funcs if await smth}", |
| 391 |
"return {fun: await fun() for fun in funcs if await smth}", |
| 392 |
"return [await fun() async for fun in funcs]", |
| 393 |
"return {await fun() async for fun in funcs}", |
| 394 |
"return {fun: await fun() async for fun in funcs}", |
| 395 |
"return [await fun() async for fun in funcs if await smth]", |
| 396 |
"return {await fun() async for fun in funcs if await smth}", |
| 397 |
"return {fun: await fun() async for fun in funcs if await smth}", |
| 398 |
] |
| 399 |
for func_body in func_bodies: |
| 400 |
code = dedent(f""" |
| 401 |
async def f(): |
| 402 |
{func_body}""") |
| 403 |
func = extract_node(code) |
| 404 |
self.assertEqual(func.as_string().strip(), code.strip()) |