From e42f66fd061b58597646c6ec9de803ad992a670f Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Fri, 3 Sep 2021 23:27:52 +0200 Subject: [PATCH 1/3] Add typing in the tests/ directory --- tests/resources.py | 10 +- tests/unittest_brain.py | 334 +++++++------- tests/unittest_brain_ctypes.py | 4 +- tests/unittest_brain_dataclasses.py | 2 +- tests/unittest_builder.py | 110 ++--- tests/unittest_helpers.py | 33 +- tests/unittest_inference.py | 681 +++++++++++++++------------- tests/unittest_inference_calls.py | 48 +- tests/unittest_lookup.py | 110 ++--- tests/unittest_manager.py | 69 +-- tests/unittest_modutils.py | 98 ++-- tests/unittest_nodes.py | 215 ++++----- tests/unittest_object_model.py | 58 +-- tests/unittest_objects.py | 42 +- tests/unittest_protocols.py | 72 +-- tests/unittest_python3.py | 46 +- tests/unittest_raw_building.py | 18 +- tests/unittest_regrtest.py | 42 +- tests/unittest_scoped_nodes.py | 231 +++++----- tests/unittest_transforms.py | 49 +- tests/unittest_utils.py | 10 +- 21 files changed, 1184 insertions(+), 1098 deletions(-) diff --git a/tests/resources.py b/tests/resources.py index e01440f293..ebb6f7a424 100644 --- a/tests/resources.py +++ b/tests/resources.py @@ -13,27 +13,29 @@ import os import sys +from typing import Optional from astroid import builder from astroid.manager import AstroidManager +from astroid.nodes.scoped_nodes import Module DATA_DIR = os.path.join("testdata", "python3") RESOURCE_PATH = os.path.join(os.path.dirname(__file__), DATA_DIR, "data") -def find(name): +def find(name: str) -> str: return os.path.normpath(os.path.join(os.path.dirname(__file__), DATA_DIR, name)) -def build_file(path, modname=None): +def build_file(path: str, modname: Optional[str] = None) -> Module: return builder.AstroidBuilder().file_build(find(path), modname) class SysPathSetup: - def setUp(self): + def setUp(self) -> None: sys.path.insert(0, find("")) - def tearDown(self): + def tearDown(self) -> None: del sys.path[0] datadir = find("") for key in list(sys.path_importer_cache): diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index 34a4b43a76..d91cae4018 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -43,13 +43,17 @@ import re import sys import unittest +from typing import Any, List import pytest import astroid from astroid import MANAGER, bases, builder, nodes, objects, test_utils, util +from astroid.bases import Instance from astroid.const import PY37_PLUS from astroid.exceptions import AttributeInferenceError, InferenceError +from astroid.nodes.node_classes import Const +from astroid.nodes.scoped_nodes import ClassDef try: import multiprocessing # pylint: disable=unused-import @@ -88,13 +92,13 @@ HAS_SIX = False -def assertEqualMro(klass, expected_mro): +def assertEqualMro(klass: ClassDef, expected_mro: List[str]) -> None: """Check mro names.""" assert [member.qname() for member in klass.mro()] == expected_mro class HashlibTest(unittest.TestCase): - def _assert_hashlib_class(self, class_obj): + def _assert_hashlib_class(self, class_obj: ClassDef) -> None: self.assertIn("update", class_obj) self.assertIn("digest", class_obj) self.assertIn("hexdigest", class_obj) @@ -106,14 +110,14 @@ def _assert_hashlib_class(self, class_obj): self.assertEqual(len(class_obj["digest"].args.args), 1) self.assertEqual(len(class_obj["hexdigest"].args.args), 1) - def test_hashlib(self): + def test_hashlib(self) -> None: """Tests that brain extensions for hashlib work.""" hashlib_module = MANAGER.ast_from_module_name("hashlib") for class_name in ("md5", "sha1"): class_obj = hashlib_module[class_name] self._assert_hashlib_class(class_obj) - def test_hashlib_py36(self): + def test_hashlib_py36(self) -> None: hashlib_module = MANAGER.ast_from_module_name("hashlib") for class_name in ("sha3_224", "sha3_512", "shake_128"): class_obj = hashlib_module[class_name] @@ -124,7 +128,7 @@ def test_hashlib_py36(self): class CollectionsDequeTests(unittest.TestCase): - def _inferred_queue_instance(self): + def _inferred_queue_instance(self) -> Instance: node = builder.extract_node( """ import collections @@ -134,11 +138,11 @@ def _inferred_queue_instance(self): ) return next(node.infer()) - def test_deque(self): + def test_deque(self) -> None: inferred = self._inferred_queue_instance() self.assertTrue(inferred.getattr("__len__")) - def test_deque_py35methods(self): + def test_deque_py35methods(self) -> None: inferred = self._inferred_queue_instance() self.assertIn("copy", inferred.locals) self.assertIn("insert", inferred.locals) @@ -157,7 +161,7 @@ def test_deque_py39methods(self): class OrderedDictTest(unittest.TestCase): - def _inferred_ordered_dict_instance(self): + def _inferred_ordered_dict_instance(self) -> Instance: node = builder.extract_node( """ import collections @@ -167,13 +171,13 @@ def _inferred_ordered_dict_instance(self): ) return next(node.infer()) - def test_ordered_dict_py34method(self): + def test_ordered_dict_py34method(self) -> None: inferred = self._inferred_ordered_dict_instance() self.assertIn("move_to_end", inferred.locals) class NamedTupleTest(unittest.TestCase): - def test_namedtuple_base(self): + def test_namedtuple_base(self) -> None: klass = builder.extract_node( """ from collections import namedtuple @@ -188,7 +192,7 @@ class X(namedtuple("X", ["a", "b", "c"])): for anc in klass.ancestors(): self.assertFalse(anc.parent is None) - def test_namedtuple_inference(self): + def test_namedtuple_inference(self) -> None: klass = builder.extract_node( """ from collections import namedtuple @@ -202,7 +206,7 @@ class X(namedtuple(name, fields)): base = next(base for base in klass.ancestors() if base.name == "X") self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs)) - def test_namedtuple_inference_failure(self): + def test_namedtuple_inference_failure(self) -> None: klass = builder.extract_node( """ from collections import namedtuple @@ -213,7 +217,7 @@ def foo(fields): ) self.assertIs(util.Uninferable, next(klass.infer())) - def test_namedtuple_advanced_inference(self): + def test_namedtuple_advanced_inference(self) -> None: # urlparse return an object of class ParseResult, which has a # namedtuple call and a mixin as base classes result = builder.extract_node( @@ -231,7 +235,7 @@ def test_namedtuple_advanced_inference(self): self.assertGreaterEqual(len(instance.getattr("geturl")), 1) self.assertEqual(instance.name, "ParseResult") - def test_namedtuple_instance_attrs(self): + def test_namedtuple_instance_attrs(self) -> None: result = builder.extract_node( """ from collections import namedtuple @@ -242,7 +246,7 @@ def test_namedtuple_instance_attrs(self): for name, attr in inferred.instance_attrs.items(): self.assertEqual(attr[0].attrname, name) - def test_namedtuple_uninferable_fields(self): + def test_namedtuple_uninferable_fields(self) -> None: node = builder.extract_node( """ x = [A] * 2 @@ -254,7 +258,7 @@ def test_namedtuple_uninferable_fields(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) - def test_namedtuple_access_class_fields(self): + def test_namedtuple_access_class_fields(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -266,7 +270,7 @@ def test_namedtuple_access_class_fields(self): self.assertIn("field", inferred.locals) self.assertIn("other", inferred.locals) - def test_namedtuple_rename_keywords(self): + def test_namedtuple_rename_keywords(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -278,7 +282,7 @@ def test_namedtuple_rename_keywords(self): self.assertIn("abc", inferred.locals) self.assertIn("_1", inferred.locals) - def test_namedtuple_rename_duplicates(self): + def test_namedtuple_rename_duplicates(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -291,7 +295,7 @@ def test_namedtuple_rename_duplicates(self): self.assertIn("_1", inferred.locals) self.assertIn("_2", inferred.locals) - def test_namedtuple_rename_uninferable(self): + def test_namedtuple_rename_uninferable(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -304,7 +308,7 @@ def test_namedtuple_rename_uninferable(self): self.assertIn("b", inferred.locals) self.assertIn("c", inferred.locals) - def test_namedtuple_func_form(self): + def test_namedtuple_func_form(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -318,7 +322,7 @@ def test_namedtuple_func_form(self): self.assertIn("b", inferred.locals) self.assertIn("c", inferred.locals) - def test_namedtuple_func_form_args_and_kwargs(self): + def test_namedtuple_func_form_args_and_kwargs(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -332,7 +336,7 @@ def test_namedtuple_func_form_args_and_kwargs(self): self.assertIn("b", inferred.locals) self.assertIn("c", inferred.locals) - def test_namedtuple_bases_are_actually_names_not_nodes(self): + def test_namedtuple_bases_are_actually_names_not_nodes(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -345,7 +349,7 @@ def test_namedtuple_bases_are_actually_names_not_nodes(self): self.assertIsInstance(inferred.bases[0], astroid.Name) self.assertEqual(inferred.bases[0].name, "tuple") - def test_invalid_label_does_not_crash_inference(self): + def test_invalid_label_does_not_crash_inference(self) -> None: code = """ import collections a = collections.namedtuple( 'a', ['b c'] ) @@ -357,7 +361,7 @@ def test_invalid_label_does_not_crash_inference(self): assert "b" not in inferred.locals assert "c" not in inferred.locals - def test_no_rename_duplicates_does_not_crash_inference(self): + def test_no_rename_duplicates_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -368,7 +372,7 @@ def test_no_rename_duplicates_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_no_rename_keywords_does_not_crash_inference(self): + def test_no_rename_keywords_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -379,7 +383,7 @@ def test_no_rename_keywords_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_no_rename_nonident_does_not_crash_inference(self): + def test_no_rename_nonident_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -390,7 +394,7 @@ def test_no_rename_nonident_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_no_rename_underscore_does_not_crash_inference(self): + def test_no_rename_underscore_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -401,7 +405,7 @@ def test_no_rename_underscore_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_invalid_typename_does_not_crash_inference(self): + def test_invalid_typename_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -412,7 +416,7 @@ def test_invalid_typename_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_keyword_typename_does_not_crash_inference(self): + def test_keyword_typename_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -423,7 +427,7 @@ def test_keyword_typename_does_not_crash_inference(self): inferred = next(node.infer()) self.assertIs(util.Uninferable, inferred) # would raise ValueError - def test_typeerror_does_not_crash_inference(self): + def test_typeerror_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -436,7 +440,7 @@ def test_typeerror_does_not_crash_inference(self): # and catch on the isidentifier() check self.assertIs(util.Uninferable, inferred) - def test_pathological_str_does_not_crash_inference(self): + def test_pathological_str_does_not_crash_inference(self) -> None: node = builder.extract_node( """ from collections import namedtuple @@ -452,7 +456,7 @@ def __str__(self): class DefaultDictTest(unittest.TestCase): - def test_1(self): + def test_1(self) -> None: node = builder.extract_node( """ from collections import defaultdict @@ -466,7 +470,7 @@ def test_1(self): class ModuleExtenderTest(unittest.TestCase): - def test_extension_modules(self): + def test_extension_modules(self) -> None: transformer = MANAGER._transform for extender, _ in transformer.transforms[nodes.Module]: n = nodes.Module("__main__", None) @@ -500,7 +504,7 @@ def test_nose_tools(self): @unittest.skipUnless(HAS_SIX, "These tests require the six library") class SixBrainTest(unittest.TestCase): - def test_attribute_access(self): + def test_attribute_access(self) -> None: ast_nodes = builder.extract_node( """ import six @@ -542,7 +546,7 @@ def test_attribute_access(self): self.assertIsInstance(urlretrieve, nodes.FunctionDef) self.assertEqual(urlretrieve.qname(), "urllib.request.urlretrieve") - def test_from_imports(self): + def test_from_imports(self) -> None: ast_node = builder.extract_node( """ from six.moves import http_client @@ -554,7 +558,7 @@ def test_from_imports(self): qname = "http.client.HTTPSConnection" self.assertEqual(inferred.qname(), qname) - def test_from_submodule_imports(self): + def test_from_submodule_imports(self) -> None: """Make sure ulrlib submodules can be imported from See PyCQA/pylint#1640 for relevant issue @@ -568,7 +572,7 @@ def test_from_submodule_imports(self): inferred = next(ast_node.infer()) self.assertIsInstance(inferred, nodes.FunctionDef) - def test_with_metaclass_subclasses_inheritance(self): + def test_with_metaclass_subclasses_inheritance(self) -> None: ast_node = builder.extract_node( """ class A(type): @@ -595,8 +599,8 @@ class B(six.with_metaclass(A, C)): self.assertIsInstance(ancestors[1], nodes.ClassDef) self.assertEqual(ancestors[1].name, "object") - def test_six_with_metaclass_with_additional_transform(self): - def transform_class(cls): + def test_six_with_metaclass_with_additional_transform(self) -> None: + def transform_class(cls: Any) -> ClassDef: if cls.name == "A": cls._test_transform = 314 return cls @@ -625,7 +629,7 @@ class A(six.with_metaclass(type, object)): "(Jython for instance)", ) class MultiprocessingBrainTest(unittest.TestCase): - def test_multiprocessing_module_attributes(self): + def test_multiprocessing_module_attributes(self) -> None: # Test that module attributes are working, # especially on Python 3.4+, where they are obtained # from a context. @@ -638,7 +642,7 @@ def test_multiprocessing_module_attributes(self): cpu_count = next(module.igetattr("cpu_count")) self.assertIsInstance(cpu_count, astroid.BoundMethod) - def test_module_name(self): + def test_module_name(self) -> None: module = builder.extract_node( """ import multiprocessing @@ -649,7 +653,7 @@ def test_module_name(self): module = inferred_sync_mgr.root() self.assertEqual(module.name, "multiprocessing.managers") - def test_multiprocessing_manager(self): + def test_multiprocessing_manager(self) -> None: # Test that we have the proper attributes # for a multiprocessing.managers.SyncManager module = builder.parse( @@ -709,7 +713,7 @@ def test_multiprocessing_manager(self): class ThreadingBrainTest(unittest.TestCase): - def test_lock(self): + def test_lock(self) -> None: lock_instance = builder.extract_node( """ import threading @@ -725,16 +729,16 @@ def test_lock(self): assert inferred.getattr("locked") - def test_rlock(self): + def test_rlock(self) -> None: self._test_lock_object("RLock") - def test_semaphore(self): + def test_semaphore(self) -> None: self._test_lock_object("Semaphore") - def test_boundedsemaphore(self): + def test_boundedsemaphore(self) -> None: self._test_lock_object("BoundedSemaphore") - def _test_lock_object(self, object_name): + def _test_lock_object(self, object_name: str) -> None: lock_instance = builder.extract_node( f""" import threading @@ -744,7 +748,7 @@ def _test_lock_object(self, object_name): inferred = next(lock_instance.infer()) self.assert_is_valid_lock(inferred) - def assert_is_valid_lock(self, inferred): + def assert_is_valid_lock(self, inferred: Instance) -> None: self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.root().name, "threading") for method in ("acquire", "release", "__enter__", "__exit__"): @@ -752,7 +756,7 @@ def assert_is_valid_lock(self, inferred): class EnumBrainTest(unittest.TestCase): - def test_simple_enum(self): + def test_simple_enum(self) -> None: module = builder.parse( """ import enum @@ -778,7 +782,7 @@ def mymethod(self, x): meth = one.getattr("mymethod")[0] self.assertIsInstance(meth, astroid.FunctionDef) - def test_looks_like_enum_false_positive(self): + def test_looks_like_enum_false_positive(self) -> None: # Test that a class named Enumeration is not considered a builtin enum. module = builder.parse( """ @@ -792,7 +796,7 @@ def __init__(self, name, enum_list): test = next(enumeration.igetattr("test")) self.assertEqual(test.value, 42) - def test_user_enum_false_positive(self): + def test_user_enum_false_positive(self) -> None: # Test that a user-defined class named Enum is not considered a builtin enum. ast_node = astroid.extract_node( """ @@ -810,7 +814,7 @@ class Color(Enum): self.assertIsInstance(inferred[0], astroid.Const) self.assertEqual(inferred[0].value, 1) - def test_ignores_with_nodes_from_body_of_enum(self): + def test_ignores_with_nodes_from_body_of_enum(self) -> None: code = """ import enum @@ -825,7 +829,7 @@ class Error(enum.Enum): assert "err" in inferred.locals assert len(inferred.locals["err"]) == 1 - def test_enum_multiple_base_classes(self): + def test_enum_multiple_base_classes(self) -> None: module = builder.parse( """ import enum @@ -846,7 +850,7 @@ class MyEnum(Mixin, enum.Enum): "Enum instance should share base classes with generating class", ) - def test_int_enum(self): + def test_int_enum(self) -> None: module = builder.parse( """ import enum @@ -865,7 +869,7 @@ class MyEnum(enum.IntEnum): "IntEnum based enums should be a subtype of int", ) - def test_enum_func_form_is_class_not_instance(self): + def test_enum_func_form_is_class_not_instance(self) -> None: cls, instance = builder.extract_node( """ from enum import Enum @@ -881,7 +885,7 @@ def test_enum_func_form_is_class_not_instance(self): self.assertIsInstance(next(inferred_instance.igetattr("name")), nodes.Const) self.assertIsInstance(next(inferred_instance.igetattr("value")), nodes.Const) - def test_enum_func_form_iterable(self): + def test_enum_func_form_iterable(self) -> None: instance = builder.extract_node( """ from enum import Enum @@ -893,7 +897,7 @@ def test_enum_func_form_iterable(self): self.assertIsInstance(inferred, astroid.Instance) self.assertTrue(inferred.getattr("__iter__")) - def test_enum_func_form_subscriptable(self): + def test_enum_func_form_subscriptable(self) -> None: instance, name = builder.extract_node( """ from enum import Enum @@ -908,7 +912,7 @@ def test_enum_func_form_subscriptable(self): inferred = next(name.infer()) self.assertIsInstance(inferred, astroid.Const) - def test_enum_func_form_has_dunder_members(self): + def test_enum_func_form_has_dunder_members(self) -> None: instance = builder.extract_node( """ from enum import Enum @@ -921,7 +925,7 @@ def test_enum_func_form_has_dunder_members(self): self.assertIsInstance(instance, astroid.Const) self.assertIsInstance(instance.value, str) - def test_infer_enum_value_as_the_right_type(self): + def test_infer_enum_value_as_the_right_type(self) -> None: string_value, int_value = builder.extract_node( """ from enum import Enum @@ -943,7 +947,7 @@ class A(Enum): isinstance(elem, astroid.Const) and elem.value == 1 for elem in inferred_int ) - def test_mingled_single_and_double_quotes_does_not_crash(self): + def test_mingled_single_and_double_quotes_does_not_crash(self) -> None: node = builder.extract_node( """ from enum import Enum @@ -955,7 +959,7 @@ class A(Enum): inferred_string = next(node.infer()) assert inferred_string.value == 'x"y"' - def test_special_characters_does_not_crash(self): + def test_special_characters_does_not_crash(self) -> None: node = builder.extract_node( """ import enum @@ -967,7 +971,7 @@ class Example(enum.Enum): inferred_string = next(node.infer()) assert inferred_string.value == "\N{NULL}" - def test_dont_crash_on_for_loops_in_body(self): + def test_dont_crash_on_for_loops_in_body(self) -> None: node = builder.extract_node( """ @@ -986,7 +990,7 @@ class Commands(IntEnum): inferred = next(node.infer()) assert isinstance(inferred, astroid.ClassDef) - def test_enum_tuple_list_values(self): + def test_enum_tuple_list_values(self) -> None: tuple_node, list_node = builder.extract_node( """ import enum @@ -1005,7 +1009,7 @@ class MyEnum(enum.Enum): assert inferred_tuple_node.as_string() == "(1, 2)" assert inferred_list_node.as_string() == "[2, 4]" - def test_enum_starred_is_skipped(self): + def test_enum_starred_is_skipped(self) -> None: code = """ from enum import Enum class ContentType(Enum): @@ -1015,7 +1019,7 @@ class ContentType(Enum): node = astroid.extract_node(code) next(node.infer()) - def test_enum_name_is_str_on_self(self): + def test_enum_name_is_str_on_self(self) -> None: code = """ from enum import Enum class TestEnum(Enum): @@ -1040,7 +1044,7 @@ def func(self): next(i_value.infer()) next(c_value.infer()) - def test_enum_name_and_value_members_override_dynamicclassattr(self): + def test_enum_name_and_value_members_override_dynamicclassattr(self) -> None: code = """ from enum import Enum class TrickyEnum(Enum): @@ -1069,7 +1073,7 @@ def func(self): assert isinstance(inferred, bases.Instance) assert inferred.pytype() == ".TrickyEnum.value" - def test_enum_subclass_member_name(self): + def test_enum_subclass_member_name(self) -> None: ast_node = astroid.extract_node( """ from enum import Enum @@ -1088,7 +1092,7 @@ class Color(EnumSubclass): self.assertIsInstance(inferred[0], astroid.Const) self.assertEqual(inferred[0].value, "red") - def test_enum_subclass_member_value(self): + def test_enum_subclass_member_value(self) -> None: ast_node = astroid.extract_node( """ from enum import Enum @@ -1107,7 +1111,7 @@ class Color(EnumSubclass): self.assertIsInstance(inferred[0], astroid.Const) self.assertEqual(inferred[0].value, 1) - def test_enum_subclass_member_method(self): + def test_enum_subclass_member_method(self) -> None: # See Pylint issue #2626 ast_node = astroid.extract_node( """ @@ -1128,7 +1132,7 @@ class Color(EnumSubclass): self.assertIsInstance(inferred[0], astroid.Const) self.assertEqual(inferred[0].value, "red") - def test_enum_subclass_different_modules(self): + def test_enum_subclass_different_modules(self) -> None: # See Pylint issue #2626 astroid.extract_node( """ @@ -1169,7 +1173,7 @@ def test_parser(self): class PytestBrainTest(unittest.TestCase): - def test_pytest(self): + def test_pytest(self) -> None: ast_node = builder.extract_node( """ import pytest @@ -1293,7 +1297,7 @@ def check_metaclass_is_abc(node: nodes.ClassDef): class CollectionsBrain(unittest.TestCase): - def test_collections_object_not_subscriptable(self): + def test_collections_object_not_subscriptable(self) -> None: """ Test that unsubscriptable types are detected Hashable is not subscriptable even with python39 @@ -1461,7 +1465,7 @@ class Derived(collections.abc.Hashable, collections.abc.Iterator[int]): class TypingBrain(unittest.TestCase): - def test_namedtuple_base(self): + def test_namedtuple_base(self) -> None: klass = builder.extract_node( """ from typing import NamedTuple @@ -1476,7 +1480,7 @@ class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])): for anc in klass.ancestors(): self.assertFalse(anc.parent is None) - def test_namedtuple_can_correctly_access_methods(self): + def test_namedtuple_can_correctly_access_methods(self) -> None: klass, called = builder.extract_node( """ from typing import NamedTuple @@ -1496,7 +1500,7 @@ def as_integer(self): self.assertIsInstance(inferred, astroid.Const) self.assertEqual(inferred.value, 5) - def test_namedtuple_inference(self): + def test_namedtuple_inference(self) -> None: klass = builder.extract_node( """ from typing import NamedTuple @@ -1508,7 +1512,7 @@ class X(NamedTuple("X", [("a", int), ("b", str), ("c", bytes)])): base = next(base for base in klass.ancestors() if base.name == "X") self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs)) - def test_namedtuple_inference_nonliteral(self): + def test_namedtuple_inference_nonliteral(self) -> None: # Note: NamedTuples in mypy only work with literals. klass = builder.extract_node( """ @@ -1523,7 +1527,7 @@ def test_namedtuple_inference_nonliteral(self): self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.qname(), "typing.NamedTuple") - def test_namedtuple_instance_attrs(self): + def test_namedtuple_instance_attrs(self) -> None: result = builder.extract_node( """ from typing import NamedTuple @@ -1534,7 +1538,7 @@ def test_namedtuple_instance_attrs(self): for name, attr in inferred.instance_attrs.items(): self.assertEqual(attr[0].attrname, name) - def test_namedtuple_simple(self): + def test_namedtuple_simple(self) -> None: result = builder.extract_node( """ from typing import NamedTuple @@ -1545,7 +1549,7 @@ def test_namedtuple_simple(self): self.assertIsInstance(inferred, nodes.ClassDef) self.assertSetEqual({"a", "b", "c"}, set(inferred.instance_attrs)) - def test_namedtuple_few_args(self): + def test_namedtuple_few_args(self) -> None: result = builder.extract_node( """ from typing import NamedTuple @@ -1556,7 +1560,7 @@ def test_namedtuple_few_args(self): self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.qname(), "typing.NamedTuple") - def test_namedtuple_few_fields(self): + def test_namedtuple_few_fields(self) -> None: result = builder.extract_node( """ from typing import NamedTuple @@ -1567,7 +1571,7 @@ def test_namedtuple_few_fields(self): self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.qname(), "typing.NamedTuple") - def test_namedtuple_class_form(self): + def test_namedtuple_class_form(self) -> None: result = builder.extract_node( """ from typing import NamedTuple @@ -1587,7 +1591,7 @@ class Example(NamedTuple): const = next(class_attr.infer()) self.assertEqual(const.value, "class_attr") - def test_namedtuple_inferred_as_class(self): + def test_namedtuple_inferred_as_class(self) -> None: node = builder.extract_node( """ from typing import NamedTuple @@ -1598,7 +1602,7 @@ def test_namedtuple_inferred_as_class(self): assert isinstance(inferred, nodes.ClassDef) assert inferred.name == "NamedTuple" - def test_namedtuple_bug_pylint_4383(self): + def test_namedtuple_bug_pylint_4383(self) -> None: """Inference of 'NamedTuple' function shouldn't cause InferenceError. https://github.com/PyCQA/pylint/issues/4383 @@ -1613,7 +1617,7 @@ def NamedTuple(): ) next(node.infer()) - def test_typing_types(self): + def test_typing_types(self) -> None: ast_nodes = builder.extract_node( """ from typing import TypeVar, Iterable, Tuple, NewType, Dict, Union @@ -1688,7 +1692,7 @@ def __init__(self, value): assert isinstance(slots[0], nodes.Const) assert slots[0].value == "value" - def test_has_dunder_args(self): + def test_has_dunder_args(self) -> None: ast_node = builder.extract_node( """ from typing import Union @@ -1699,7 +1703,7 @@ def test_has_dunder_args(self): inferred = next(ast_node.infer()) assert isinstance(inferred, nodes.Tuple) - def test_typing_namedtuple_dont_crash_on_no_fields(self): + def test_typing_namedtuple_dont_crash_on_no_fields(self) -> None: node = builder.extract_node( """ from typing import NamedTuple @@ -1911,7 +1915,7 @@ def test_typing_object_builtin_subscriptable(self): self.assertIsInstance(inferred, nodes.ClassDef) self.assertIsInstance(inferred.getattr("__iter__")[0], nodes.FunctionDef) - def test_typing_cast(self): + def test_typing_cast(self) -> None: node = builder.extract_node( """ from typing import cast @@ -1927,7 +1931,7 @@ class A: assert isinstance(inferred, nodes.Const) assert inferred.value == 42 - def test_typing_cast_attribute(self): + def test_typing_cast_attribute(self) -> None: node = builder.extract_node( """ import typing @@ -1945,7 +1949,7 @@ class A: class ReBrainTest(unittest.TestCase): - def test_regex_flags(self): + def test_regex_flags(self) -> None: names = [name for name in dir(re) if name.isupper()] re_ast = MANAGER.ast_from_module_name("re") for name in names: @@ -2027,7 +2031,7 @@ def test_re_pattern_subscriptable(self): class BrainFStrings(unittest.TestCase): - def test_no_crash_on_const_reconstruction(self): + def test_no_crash_on_const_reconstruction(self) -> None: node = builder.extract_node( """ max_width = 10 @@ -2044,7 +2048,7 @@ def test_no_crash_on_const_reconstruction(self): class BrainNamedtupleAnnAssignTest(unittest.TestCase): - def test_no_crash_on_ann_assign_in_namedtuple(self): + def test_no_crash_on_ann_assign_in_namedtuple(self) -> None: node = builder.extract_node( """ from enum import Enum @@ -2059,7 +2063,7 @@ class A(Enum): class BrainUUIDTest(unittest.TestCase): - def test_uuid_has_int_member(self): + def test_uuid_has_int_member(self) -> None: node = builder.extract_node( """ import uuid @@ -2073,7 +2077,7 @@ def test_uuid_has_int_member(self): @unittest.skipUnless(HAS_ATTR, "These tests require the attr library") class AttrsTest(unittest.TestCase): - def test_attr_transform(self): + def test_attr_transform(self) -> None: module = astroid.parse( """ import attr @@ -2114,7 +2118,7 @@ class Bai: should_be_unknown = next(module.getattr(name)[0].infer()).getattr("d")[0] self.assertIsInstance(should_be_unknown, astroid.Unknown) - def test_special_attributes(self): + def test_special_attributes(self) -> None: """Make sure special attrs attributes exist""" code = """ @@ -2130,7 +2134,7 @@ class Foo: # Prevents https://github.com/PyCQA/pylint/issues/1884 assert isinstance(attr_node, nodes.Unknown) - def test_dont_consider_assignments_but_without_attrs(self): + def test_dont_consider_assignments_but_without_attrs(self) -> None: code = """ import attr @@ -2144,7 +2148,7 @@ class Foo: """ next(astroid.extract_node(code).infer()) - def test_attrs_with_annotation(self): + def test_attrs_with_annotation(self) -> None: code = """ import attr @@ -2158,7 +2162,7 @@ class Foo: class RandomSampleTest(unittest.TestCase): - def test_inferred_successfully(self): + def test_inferred_successfully(self) -> None: node = astroid.extract_node( """ import random @@ -2170,7 +2174,7 @@ def test_inferred_successfully(self): elems = sorted(elem.value for elem in inferred.elts) self.assertEqual(elems, [1, 2]) - def test_no_crash_on_evaluatedobject(self): + def test_no_crash_on_evaluatedobject(self) -> None: node = astroid.extract_node( """ from random import sample @@ -2186,7 +2190,7 @@ class A: pass class SubprocessTest(unittest.TestCase): """Test subprocess brain""" - def test_subprocess_args(self): + def test_subprocess_args(self) -> None: """Make sure the args attribute exists for Popen Test for https://github.com/PyCQA/pylint/issues/1860""" @@ -2200,7 +2204,7 @@ def test_subprocess_args(self): [inst] = name.inferred() self.assertIsInstance(next(inst.igetattr("args")), nodes.List) - def test_subprcess_check_output(self): + def test_subprcess_check_output(self) -> None: code = """ import subprocess @@ -2223,23 +2227,23 @@ def test_popen_does_not_have_class_getitem(self): class TestIsinstanceInference: """Test isinstance builtin inference""" - def test_type_type(self): + def test_type_type(self) -> None: assert _get_result("isinstance(type, type)") == "True" - def test_object_type(self): + def test_object_type(self) -> None: assert _get_result("isinstance(object, type)") == "True" - def test_type_object(self): + def test_type_object(self) -> None: assert _get_result("isinstance(type, object)") == "True" - def test_isinstance_int_true(self): + def test_isinstance_int_true(self) -> None: """Make sure isinstance can check builtin int types""" assert _get_result("isinstance(1, int)") == "True" - def test_isinstance_int_false(self): + def test_isinstance_int_false(self) -> None: assert _get_result("isinstance('a', int)") == "False" - def test_isinstance_object_true(self): + def test_isinstance_object_true(self) -> None: assert ( _get_result( """ @@ -2251,7 +2255,7 @@ class Bar(object): == "True" ) - def test_isinstance_object_true3(self): + def test_isinstance_object_true3(self) -> None: assert ( _get_result( """ @@ -2263,7 +2267,7 @@ class Bar(object): == "True" ) - def test_isinstance_class_false(self): + def test_isinstance_class_false(self) -> None: assert ( _get_result( """ @@ -2277,7 +2281,7 @@ class Bar(object): == "False" ) - def test_isinstance_type_false(self): + def test_isinstance_type_false(self) -> None: assert ( _get_result( """ @@ -2289,18 +2293,18 @@ class Bar(object): == "False" ) - def test_isinstance_str_true(self): + def test_isinstance_str_true(self) -> None: """Make sure isinstance can check bultin str types""" assert _get_result("isinstance('a', str)") == "True" - def test_isinstance_str_false(self): + def test_isinstance_str_false(self) -> None: assert _get_result("isinstance(1, str)") == "False" - def test_isinstance_tuple_argument(self): + def test_isinstance_tuple_argument(self) -> None: """obj just has to be an instance of ANY class/type on the right""" assert _get_result("isinstance(1, (str, int))") == "True" - def test_isinstance_type_false2(self): + def test_isinstance_type_false2(self) -> None: assert ( _get_result( """ @@ -2310,7 +2314,7 @@ def test_isinstance_type_false2(self): == "False" ) - def test_isinstance_object_true2(self): + def test_isinstance_object_true2(self) -> None: assert ( _get_result( """ @@ -2323,7 +2327,7 @@ class Bar(type): == "True" ) - def test_isinstance_type_true(self): + def test_isinstance_type_true(self) -> None: assert ( _get_result( """ @@ -2336,26 +2340,26 @@ class Bar(type): == "True" ) - def test_isinstance_edge_case(self): + def test_isinstance_edge_case(self) -> None: """isinstance allows bad type short-circuting""" assert _get_result("isinstance(1, (int, 1))") == "True" - def test_uninferable_bad_type(self): + def test_uninferable_bad_type(self) -> None: """The second argument must be a class or a tuple of classes""" with pytest.raises(InferenceError): _get_result_node("isinstance(int, 1)") - def test_uninferable_keywords(self): + def test_uninferable_keywords(self) -> None: """isinstance does not allow keywords""" with pytest.raises(InferenceError): _get_result_node("isinstance(1, class_or_tuple=int)") - def test_too_many_args(self): + def test_too_many_args(self) -> None: """isinstance must have two arguments""" with pytest.raises(InferenceError): _get_result_node("isinstance(1, int, str)") - def test_first_param_is_uninferable(self): + def test_first_param_is_uninferable(self) -> None: with pytest.raises(InferenceError): _get_result_node("isinstance(something, int)") @@ -2363,22 +2367,22 @@ def test_first_param_is_uninferable(self): class TestIssubclassBrain: """Test issubclass() builtin inference""" - def test_type_type(self): + def test_type_type(self) -> None: assert _get_result("issubclass(type, type)") == "True" - def test_object_type(self): + def test_object_type(self) -> None: assert _get_result("issubclass(object, type)") == "False" - def test_type_object(self): + def test_type_object(self) -> None: assert _get_result("issubclass(type, object)") == "True" - def test_issubclass_same_class(self): + def test_issubclass_same_class(self) -> None: assert _get_result("issubclass(int, int)") == "True" - def test_issubclass_not_the_same_class(self): + def test_issubclass_not_the_same_class(self) -> None: assert _get_result("issubclass(str, int)") == "False" - def test_issubclass_object_true(self): + def test_issubclass_object_true(self) -> None: assert ( _get_result( """ @@ -2390,7 +2394,7 @@ class Bar(object): == "True" ) - def test_issubclass_same_user_defined_class(self): + def test_issubclass_same_user_defined_class(self) -> None: assert ( _get_result( """ @@ -2402,7 +2406,7 @@ class Bar(object): == "True" ) - def test_issubclass_different_user_defined_classes(self): + def test_issubclass_different_user_defined_classes(self) -> None: assert ( _get_result( """ @@ -2416,7 +2420,7 @@ class Bar(object): == "False" ) - def test_issubclass_type_false(self): + def test_issubclass_type_false(self) -> None: assert ( _get_result( """ @@ -2428,11 +2432,11 @@ class Bar(object): == "False" ) - def test_isinstance_tuple_argument(self): + def test_isinstance_tuple_argument(self) -> None: """obj just has to be a subclass of ANY class/type on the right""" assert _get_result("issubclass(int, (str, int))") == "True" - def test_isinstance_object_true2(self): + def test_isinstance_object_true2(self) -> None: assert ( _get_result( """ @@ -2444,38 +2448,38 @@ class Bar(type): == "True" ) - def test_issubclass_short_circuit(self): + def test_issubclass_short_circuit(self) -> None: """issubclasss allows bad type short-circuting""" assert _get_result("issubclass(int, (int, 1))") == "True" - def test_uninferable_bad_type(self): + def test_uninferable_bad_type(self) -> None: """The second argument must be a class or a tuple of classes""" # Should I subclass with pytest.raises(InferenceError): _get_result_node("issubclass(int, 1)") - def test_uninferable_keywords(self): + def test_uninferable_keywords(self) -> None: """issubclass does not allow keywords""" with pytest.raises(InferenceError): _get_result_node("issubclass(int, class_or_tuple=int)") - def test_too_many_args(self): + def test_too_many_args(self) -> None: """issubclass must have two arguments""" with pytest.raises(InferenceError): _get_result_node("issubclass(int, int, str)") -def _get_result_node(code): +def _get_result_node(code: str) -> Const: node = next(astroid.extract_node(code).infer()) return node -def _get_result(code): +def _get_result(code: str) -> str: return _get_result_node(code).as_string() class TestLenBuiltinInference: - def test_len_list(self): + def test_len_list(self) -> None: # Uses .elts node = astroid.extract_node( """ @@ -2486,7 +2490,7 @@ def test_len_list(self): assert node.as_string() == "3" assert isinstance(node, nodes.Const) - def test_len_tuple(self): + def test_len_tuple(self) -> None: node = astroid.extract_node( """ len(('a','b','c')) @@ -2495,7 +2499,7 @@ def test_len_tuple(self): node = next(node.infer()) assert node.as_string() == "3" - def test_len_var(self): + def test_len_var(self) -> None: # Make sure argument is inferred node = astroid.extract_node( """ @@ -2506,7 +2510,7 @@ def test_len_var(self): node = next(node.infer()) assert node.as_string() == "5" - def test_len_dict(self): + def test_len_dict(self) -> None: # Uses .items node = astroid.extract_node( """ @@ -2517,7 +2521,7 @@ def test_len_dict(self): node = next(node.infer()) assert node.as_string() == "2" - def test_len_set(self): + def test_len_set(self) -> None: node = astroid.extract_node( """ len({'a'}) @@ -2526,7 +2530,7 @@ def test_len_set(self): inferred_node = next(node.infer()) assert inferred_node.as_string() == "1" - def test_len_object(self): + def test_len_object(self) -> None: """Test len with objects that implement the len protocol""" node = astroid.extract_node( """ @@ -2539,7 +2543,7 @@ def __len__(self): inferred_node = next(node.infer()) assert inferred_node.as_string() == "57" - def test_len_class_with_metaclass(self): + def test_len_class_with_metaclass(self) -> None: """Make sure proper len method is located""" cls_node, inst_node = astroid.extract_node( """ @@ -2558,7 +2562,7 @@ def __len__(self): assert next(cls_node.infer()).as_string() == "57" assert next(inst_node.infer()).as_string() == "4" - def test_len_object_failure(self): + def test_len_object_failure(self) -> None: """If taking the length of a class, do not use an instance method""" node = astroid.extract_node( """ @@ -2571,7 +2575,7 @@ def __len__(self): with pytest.raises(InferenceError): next(node.infer()) - def test_len_string(self): + def test_len_string(self) -> None: node = astroid.extract_node( """ len("uwu") @@ -2579,7 +2583,7 @@ def test_len_string(self): ) assert next(node.infer()).as_string() == "3" - def test_len_generator_failure(self): + def test_len_generator_failure(self) -> None: node = astroid.extract_node( """ def gen(): @@ -2591,7 +2595,7 @@ def gen(): with pytest.raises(InferenceError): next(node.infer()) - def test_len_failure_missing_variable(self): + def test_len_failure_missing_variable(self) -> None: node = astroid.extract_node( """ len(a) @@ -2600,7 +2604,7 @@ def test_len_failure_missing_variable(self): with pytest.raises(InferenceError): next(node.infer()) - def test_len_bytes(self): + def test_len_bytes(self) -> None: node = astroid.extract_node( """ len(b'uwu') @@ -2608,7 +2612,7 @@ def test_len_bytes(self): ) assert next(node.infer()).as_string() == "3" - def test_int_subclass_result(self): + def test_int_subclass_result(self) -> None: """Check that a subclass of an int can still be inferred This test does not properly infer the value passed to the @@ -2641,7 +2645,7 @@ class ListSubclass(list): ) assert next(node.infer()).as_string() == "5" - def test_len_builtin_inference_attribute_error_str(self): + def test_len_builtin_inference_attribute_error_str(self) -> None: """Make sure len builtin doesn't raise an AttributeError on instances of str or bytes @@ -2653,7 +2657,9 @@ def test_len_builtin_inference_attribute_error_str(self): except InferenceError: pass - def test_len_builtin_inference_recursion_error_self_referential_attribute(self): + def test_len_builtin_inference_recursion_error_self_referential_attribute( + self, + ) -> None: """Make sure len calls do not trigger recursion errors for self referential assignment @@ -2674,7 +2680,7 @@ def __init__(self): pytest.fail("Inference call should not trigger a recursion error") -def test_infer_str(): +def test_infer_str() -> None: ast_nodes = astroid.extract_node( """ str(s) #@ @@ -2696,7 +2702,7 @@ def test_infer_str(): assert inferred.qname() == "builtins.str" -def test_infer_int(): +def test_infer_int() -> None: ast_nodes = astroid.extract_node( """ int(0) #@ @@ -2722,7 +2728,7 @@ def test_infer_int(): assert inferred.qname() == "builtins.int" -def test_infer_dict_from_keys(): +def test_infer_dict_from_keys() -> None: bad_nodes = astroid.extract_node( """ dict.fromkeys() #@ @@ -2808,7 +2814,7 @@ def test_infer_dict_from_keys(): class TestFunctoolsPartial: - def test_invalid_functools_partial_calls(self): + def test_invalid_functools_partial_calls(self) -> None: ast_nodes = astroid.extract_node( """ from functools import partial @@ -2834,7 +2840,7 @@ def test(a, b, c): "functools.partial.newfunc", ) - def test_inferred_partial_function_calls(self): + def test_inferred_partial_function_calls(self) -> None: ast_nodes = astroid.extract_node( """ from functools import partial @@ -2862,7 +2868,7 @@ def other_test(a, b, *, c=1): assert isinstance(inferred, astroid.Const) assert inferred.value == expected_value - def test_partial_assignment(self): + def test_partial_assignment(self) -> None: """Make sure partials are not assigned to original scope.""" ast_nodes = astroid.extract_node( """ @@ -2884,7 +2890,7 @@ def test3_scope(a): scope = partial_func3.parent.scope() assert scope.name == "test3_scope", "parented by closure" - def test_partial_does_not_affect_scope(self): + def test_partial_does_not_affect_scope(self) -> None: """Make sure partials are not automatically assigned.""" ast_nodes = astroid.extract_node( """ @@ -2903,7 +2909,7 @@ def scope(): assert set(scope) == {"test2"} -def test_http_client_brain(): +def test_http_client_brain() -> None: node = astroid.extract_node( """ from http.client import OK @@ -2915,7 +2921,7 @@ def test_http_client_brain(): @pytest.mark.skipif(not PY37_PLUS, reason="Needs 3.7+") -def test_http_status_brain(): +def test_http_status_brain() -> None: node = astroid.extract_node( """ import http @@ -2936,7 +2942,7 @@ def test_http_status_brain(): assert isinstance(inferred, astroid.Const) -def test_oserror_model(): +def test_oserror_model() -> None: node = astroid.extract_node( """ try: @@ -2952,7 +2958,7 @@ def test_oserror_model(): @pytest.mark.skipif(not PY37_PLUS, reason="Dynamic module attributes since Python 3.7") -def test_crypt_brain(): +def test_crypt_brain() -> None: module = MANAGER.ast_from_module_name("crypt") dynamic_attrs = [ "METHOD_SHA512", @@ -2980,7 +2986,7 @@ def test_str_and_bytes(code, expected_class, expected_value): assert inferred.value == expected_value -def test_no_recursionerror_on_self_referential_length_check(): +def test_no_recursionerror_on_self_referential_length_check() -> None: """ Regression test for https://github.com/PyCQA/astroid/issues/777 """ diff --git a/tests/unittest_brain_ctypes.py b/tests/unittest_brain_ctypes.py index 87d648bdc6..07201528f3 100644 --- a/tests/unittest_brain_ctypes.py +++ b/tests/unittest_brain_ctypes.py @@ -75,7 +75,7 @@ def test_ctypes_redefined_types_members(c_type, builtin_type, type_code): assert node_inf.value == type_code -def test_cdata_member_access(): +def test_cdata_member_access() -> None: """ Test that the base members are still accessible. Each redefined ctypes type inherits from _SimpleCData which itself inherits from _CData. Checks that _CData members are accessibles @@ -91,7 +91,7 @@ def test_cdata_member_access(): assert node_inf.qname() == "_ctypes._SimpleCData._objects" -def test_other_ctypes_member_untouched(): +def test_other_ctypes_member_untouched() -> None: """ Test that other ctypes members, which are not touched by the brain, are correctly inferred """ diff --git a/tests/unittest_brain_dataclasses.py b/tests/unittest_brain_dataclasses.py index b50d45757f..13a85ed8b3 100644 --- a/tests/unittest_brain_dataclasses.py +++ b/tests/unittest_brain_dataclasses.py @@ -366,7 +366,7 @@ class B(A): assert inferred[1].name == "str" -def test_pydantic_field(): +def test_pydantic_field() -> None: """Test that pydantic.Field attributes are currently Uninferable. (Eventually, we can extend the brain to support pydantic.Field) diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py index 3b625064ff..37b38ca96e 100644 --- a/tests/unittest_builder.py +++ b/tests/unittest_builder.py @@ -29,6 +29,7 @@ import unittest import pytest +from mypy_extensions import NoReturn from astroid import Instance, builder, nodes, test_utils, util from astroid.const import PY38_PLUS @@ -38,15 +39,16 @@ AttributeInferenceError, InferenceError, ) +from astroid.nodes.scoped_nodes import Module from . import resources class FromToLineNoTest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.astroid = resources.build_file("data/format.py") - def test_callfunc_lineno(self): + def test_callfunc_lineno(self) -> None: stmts = self.astroid.body # on line 4: # function('aeozrijz\ @@ -97,7 +99,7 @@ def test_callfunc_lineno(self): self.assertEqual(arg.fromlineno, 10 + i) self.assertEqual(arg.tolineno, 10 + i) - def test_function_lineno(self): + def test_function_lineno(self) -> NoReturn: stmts = self.astroid.body # on line 15: # def definition(a, @@ -117,7 +119,7 @@ def test_function_lineno(self): "(no line number on function args)" ) - def test_decorated_function_lineno(self): + def test_decorated_function_lineno(self) -> None: astroid = builder.parse( """ @decorator @@ -134,7 +136,7 @@ def function( self.assertEqual(function.decorators.fromlineno, 2) self.assertEqual(function.decorators.tolineno, 2) - def test_class_lineno(self): + def test_class_lineno(self) -> None: stmts = self.astroid.body # on line 20: # class debile(dict, @@ -150,7 +152,7 @@ def test_class_lineno(self): self.assertEqual(pass_.fromlineno, 22) self.assertEqual(pass_.tolineno, 22) - def test_if_lineno(self): + def test_if_lineno(self) -> None: stmts = self.astroid.body # on line 20: # if aaaa: pass @@ -165,7 +167,7 @@ def test_if_lineno(self): self.assertEqual(if_.orelse[0].fromlineno, 26) self.assertEqual(if_.orelse[1].tolineno, 27) - def test_for_while_lineno(self): + def test_for_while_lineno(self) -> None: for code in ( """ for a in range(4): @@ -190,7 +192,7 @@ def test_for_while_lineno(self): self.assertEqual(stmt.orelse[0].fromlineno, 6) # XXX self.assertEqual(stmt.orelse[0].tolineno, 6) - def test_try_except_lineno(self): + def test_try_except_lineno(self) -> None: astroid = builder.parse( """ try: @@ -213,7 +215,7 @@ def test_try_except_lineno(self): self.assertEqual(hdlr.tolineno, 5) self.assertEqual(hdlr.blockstart_tolineno, 4) - def test_try_finally_lineno(self): + def test_try_finally_lineno(self) -> None: astroid = builder.parse( """ try: @@ -230,7 +232,7 @@ def test_try_finally_lineno(self): self.assertEqual(try_.finalbody[0].fromlineno, 5) # XXX self.assertEqual(try_.finalbody[0].tolineno, 5) - def test_try_finally_25_lineno(self): + def test_try_finally_25_lineno(self) -> None: astroid = builder.parse( """ try: @@ -249,7 +251,7 @@ def test_try_finally_25_lineno(self): self.assertEqual(try_.finalbody[0].fromlineno, 7) # XXX self.assertEqual(try_.finalbody[0].tolineno, 7) - def test_with_lineno(self): + def test_with_lineno(self) -> None: astroid = builder.parse( """ from __future__ import with_statement @@ -265,27 +267,27 @@ def test_with_lineno(self): class BuilderTest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.manager = test_utils.brainless_manager() self.builder = builder.AstroidBuilder(self.manager) - def test_data_build_null_bytes(self): + def test_data_build_null_bytes(self) -> None: with self.assertRaises(AstroidSyntaxError): self.builder.string_build("\x00") - def test_data_build_invalid_x_escape(self): + def test_data_build_invalid_x_escape(self) -> None: with self.assertRaises(AstroidSyntaxError): self.builder.string_build('"\\x1"') - def test_missing_newline(self): + def test_missing_newline(self) -> None: """check that a file with no trailing new line is parseable""" resources.build_file("data/noendingnewline.py") - def test_missing_file(self): + def test_missing_file(self) -> None: with self.assertRaises(AstroidBuildingError): resources.build_file("data/inexistant.py") - def test_inspect_build0(self): + def test_inspect_build0(self) -> None: """test astroid tree build from a living object""" builtin_ast = self.manager.ast_from_module_name("builtins") # just check type and object are there @@ -305,15 +307,15 @@ def test_inspect_build0(self): self.assertIsInstance(builtin_ast["Exception"], nodes.ClassDef) self.assertIsInstance(builtin_ast["NotImplementedError"], nodes.ClassDef) - def test_inspect_build1(self): + def test_inspect_build1(self) -> None: time_ast = self.manager.ast_from_module_name("time") self.assertTrue(time_ast) self.assertEqual(time_ast["time"].args.defaults, []) - def test_inspect_build3(self): + def test_inspect_build3(self) -> None: self.builder.inspect_build(unittest) - def test_inspect_build_type_object(self): + def test_inspect_build_type_object(self) -> None: builtin_ast = self.manager.ast_from_module_name("builtins") inferred = list(builtin_ast.igetattr("object")) @@ -328,12 +330,12 @@ def test_inspect_build_type_object(self): self.assertEqual(inferred.name, "type") inferred.as_string() # no crash test - def test_inspect_transform_module(self): + def test_inspect_transform_module(self) -> None: # ensure no cached version of the time module self.manager._mod_file_cache.pop(("time", None), None) self.manager.astroid_cache.pop("time", None) - def transform_time(node): + def transform_time(node: Module) -> None: if node.name == "time": node.transformed = True @@ -344,7 +346,7 @@ def transform_time(node): finally: self.manager.unregister_transform(nodes.Module, transform_time) - def test_package_name(self): + def test_package_name(self) -> None: """test base properties and method of an astroid module""" datap = resources.build_file("data/__init__.py", "data") self.assertEqual(datap.name, "data") @@ -356,7 +358,7 @@ def test_package_name(self): self.assertEqual(datap.name, "data.tmp__init__") self.assertEqual(datap.package, 0) - def test_yield_parent(self): + def test_yield_parent(self) -> None: """check if we added discard nodes as yield parent (w/ compiler)""" code = """ def yiell(): #@ @@ -372,11 +374,11 @@ def yiell(): #@ self.assertIsInstance(func.body[1].body[0], nodes.Expr) self.assertIsInstance(func.body[1].body[0].value, nodes.Yield) - def test_object(self): + def test_object(self) -> None: obj_ast = self.builder.inspect_build(object) self.assertIn("__setattr__", obj_ast) - def test_newstyle_detection(self): + def test_newstyle_detection(self) -> None: data = """ class A: "old style" @@ -406,7 +408,7 @@ class F: self.assertTrue(mod_ast["D"].newstyle) self.assertTrue(mod_ast["F"].newstyle) - def test_globals(self): + def test_globals(self) -> None: data = """ CSTE = 1 @@ -428,7 +430,7 @@ def global_no_effect(): with self.assertRaises(InferenceError): next(astroid["global_no_effect"].ilookup("CSTE2")) - def test_socket_build(self): + def test_socket_build(self) -> None: astroid = self.builder.module_build(socket) # XXX just check the first one. Actually 3 objects are inferred (look at # the socket module) but the last one as those attributes dynamically @@ -439,7 +441,7 @@ def test_socket_build(self): self.assertIn("close", fclass) break - def test_gen_expr_var_scope(self): + def test_gen_expr_var_scope(self) -> None: data = "l = list(n for n in range(10))\n" astroid = builder.parse(data, __name__) # n unavailable outside gen expr scope @@ -449,15 +451,15 @@ def test_gen_expr_var_scope(self): self.assertIsNot(n.scope(), astroid) self.assertEqual([i.__class__ for i in n.infer()], [util.Uninferable.__class__]) - def test_no_future_imports(self): + def test_no_future_imports(self) -> None: mod = builder.parse("import sys") self.assertEqual(set(), mod.future_imports) - def test_future_imports(self): + def test_future_imports(self) -> None: mod = builder.parse("from __future__ import print_function") self.assertEqual({"print_function"}, mod.future_imports) - def test_two_future_imports(self): + def test_two_future_imports(self) -> None: mod = builder.parse( """ from __future__ import print_function @@ -466,7 +468,7 @@ def test_two_future_imports(self): ) self.assertEqual({"print_function", "absolute_import"}, mod.future_imports) - def test_inferred_build(self): + def test_inferred_build(self) -> None: code = """ class A: pass A.type = "class" @@ -482,7 +484,7 @@ def A_assign_type(self): self.assertIn("assign_type", lclass.locals) self.assertIn("type", lclass.locals) - def test_infer_can_assign_regular_object(self): + def test_infer_can_assign_regular_object(self) -> None: mod = builder.parse( """ class A: @@ -499,7 +501,7 @@ class A: self.assertIn("value", obj.instance_attrs) self.assertIn("other", obj.instance_attrs) - def test_infer_can_assign_has_slots(self): + def test_infer_can_assign_has_slots(self) -> None: mod = builder.parse( """ class A: @@ -516,7 +518,7 @@ class A: self.assertIn("value", obj.instance_attrs) self.assertNotIn("other", obj.instance_attrs) - def test_infer_can_assign_no_classdict(self): + def test_infer_can_assign_no_classdict(self) -> None: mod = builder.parse( """ a = object() @@ -529,7 +531,7 @@ def test_infer_can_assign_no_classdict(self): self.assertIsInstance(obj, Instance) self.assertNotIn("value", obj.instance_attrs) - def test_augassign_attr(self): + def test_augassign_attr(self) -> None: builder.parse( """ class Counter: @@ -542,7 +544,7 @@ def inc(self): # TODO: Check self.v += 1 generate AugAssign(AssAttr(...)), # not AugAssign(GetAttr(AssName...)) - def test_inferred_dont_pollute(self): + def test_inferred_dont_pollute(self) -> None: code = """ def func(a=None): a.custom_attr = 0 @@ -558,7 +560,7 @@ def func2(a={}): self.assertNotIn("custom_attr", nonetype.locals) self.assertNotIn("custom_attr", nonetype.instance_attrs) - def test_asstuple(self): + def test_asstuple(self) -> None: code = "a, b = range(2)" astroid = builder.parse(code) self.assertIn("b", astroid.locals) @@ -569,7 +571,7 @@ def visit_if(self, node): astroid = builder.parse(code) self.assertIn("body", astroid["visit_if"].locals) - def test_build_constants(self): + def test_build_constants(self) -> None: """test expected values of constants after rebuilding""" code = """ def func(): @@ -585,7 +587,7 @@ def func(): self.assertIsInstance(chain, nodes.Const) self.assertEqual(chain.value, "None") - def test_not_implemented(self): + def test_not_implemented(self) -> None: node = builder.extract_node( """ NotImplemented #@ @@ -597,10 +599,10 @@ def test_not_implemented(self): class FileBuildTest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.module = resources.build_file("data/module.py", "data.module") - def test_module_base_props(self): + def test_module_base_props(self) -> None: """test base properties and method of an astroid module""" module = self.module self.assertEqual(module.name, "data.module") @@ -616,7 +618,7 @@ def test_module_base_props(self): self.assertEqual(module.statement(), module) self.assertEqual(module.statement(), module) - def test_module_locals(self): + def test_module_locals(self) -> None: """test the 'locals' dictionary of an astroid module""" module = self.module _locals = module.locals @@ -637,7 +639,7 @@ def test_module_locals(self): should.sort() self.assertEqual(keys, sorted(should)) - def test_function_base_props(self): + def test_function_base_props(self) -> None: """test base properties and method of an astroid function""" module = self.module function = module["global_access"] @@ -651,14 +653,14 @@ def test_function_base_props(self): self.assertEqual([n.name for n in function.args.args], ["key", "val"]) self.assertEqual(function.type, "function") - def test_function_locals(self): + def test_function_locals(self) -> None: """test the 'locals' dictionary of an astroid function""" _locals = self.module["global_access"].locals self.assertEqual(len(_locals), 4) keys = sorted(_locals.keys()) self.assertEqual(keys, ["i", "key", "local", "val"]) - def test_class_base_props(self): + def test_class_base_props(self) -> None: """test base properties and method of an astroid class""" module = self.module klass = module["YO"] @@ -672,7 +674,7 @@ def test_class_base_props(self): self.assertEqual(klass.basenames, []) self.assertTrue(klass.newstyle) - def test_class_locals(self): + def test_class_locals(self) -> None: """test the 'locals' dictionary of an astroid class""" module = self.module klass1 = module["YO"] @@ -694,21 +696,21 @@ def test_class_locals(self): ] self.assertEqual(sorted(keys), assert_keys) - def test_class_instance_attrs(self): + def test_class_instance_attrs(self) -> None: module = self.module klass1 = module["YO"] klass2 = module["YOUPI"] self.assertEqual(list(klass1.instance_attrs.keys()), ["yo"]) self.assertEqual(list(klass2.instance_attrs.keys()), ["member"]) - def test_class_basenames(self): + def test_class_basenames(self) -> None: module = self.module klass1 = module["YO"] klass2 = module["YOUPI"] self.assertEqual(klass1.basenames, []) self.assertEqual(klass2.basenames, ["YO"]) - def test_method_base_props(self): + def test_method_base_props(self) -> None: """test base properties and method of an astroid method""" klass2 = self.module["YOUPI"] # "normal" method @@ -727,7 +729,7 @@ def test_method_base_props(self): self.assertEqual(method.args.args, []) self.assertEqual(method.type, "staticmethod") - def test_method_locals(self): + def test_method_locals(self) -> None: """test the 'locals' dictionary of an astroid method""" method = self.module["YOUPI"]["method"] _locals = method.locals @@ -736,12 +738,12 @@ def test_method_locals(self): self.assertEqual(len(_locals), 3) self.assertEqual(keys, ["autre", "local", "self"]) - def test_unknown_encoding(self): + def test_unknown_encoding(self) -> None: with self.assertRaises(AstroidSyntaxError): resources.build_file("data/invalid_encoding.py") -def test_module_build_dunder_file(): +def test_module_build_dunder_file() -> None: """Test that module_build() can work with modules that have the *__file__* attribute""" module = builder.AstroidBuilder().module_build(collections) assert module.path[0] == collections.__file__ diff --git a/tests/unittest_helpers.py b/tests/unittest_helpers.py index 715bd388bd..c72c16179a 100644 --- a/tests/unittest_helpers.py +++ b/tests/unittest_helpers.py @@ -15,29 +15,30 @@ from astroid import builder, helpers, manager, raw_building, util from astroid.exceptions import _NonDeducibleTypeHierarchy +from astroid.nodes.scoped_nodes import ClassDef class TestHelpers(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: builtins_name = builtins.__name__ astroid_manager = manager.AstroidManager() self.builtins = astroid_manager.astroid_cache[builtins_name] self.manager = manager.AstroidManager() - def _extract(self, obj_name): + def _extract(self, obj_name: str) -> ClassDef: return self.builtins.getattr(obj_name)[0] - def _build_custom_builtin(self, obj_name): + def _build_custom_builtin(self, obj_name: str) -> ClassDef: proxy = raw_building.build_class(obj_name) proxy.parent = self.builtins return proxy - def assert_classes_equal(self, cls, other): + def assert_classes_equal(self, cls: ClassDef, other: ClassDef) -> None: self.assertEqual(cls.name, other.name) self.assertEqual(cls.parent, other.parent) self.assertEqual(cls.qname(), other.qname()) - def test_object_type(self): + def test_object_type(self) -> None: pairs = [ ("1", self._extract("int")), ("[]", self._extract("list")), @@ -56,7 +57,7 @@ def test_object_type(self): objtype = helpers.object_type(node) self.assert_classes_equal(objtype, expected) - def test_object_type_classes_and_functions(self): + def test_object_type_classes_and_functions(self) -> None: ast_nodes = builder.extract_node( """ def generator(): @@ -105,7 +106,7 @@ def static_method(): pass expected_type = self._build_custom_builtin(expected) self.assert_classes_equal(node_type, expected_type) - def test_object_type_metaclasses(self): + def test_object_type_metaclasses(self) -> None: module = builder.parse( """ import abc @@ -121,7 +122,7 @@ class Meta(metaclass=abc.ABCMeta): instance_type = helpers.object_type(meta_instance) self.assert_classes_equal(instance_type, module["Meta"]) - def test_object_type_most_derived(self): + def test_object_type_most_derived(self) -> None: node = builder.extract_node( """ class A(type): @@ -140,7 +141,7 @@ class D(B , C): #@ obj_type = helpers.object_type(node) self.assertEqual(metaclass, obj_type) - def test_inference_errors(self): + def test_inference_errors(self) -> None: node = builder.extract_node( """ from unknown import Unknown @@ -149,7 +150,7 @@ def test_inference_errors(self): ) self.assertEqual(helpers.object_type(node), util.Uninferable) - def test_object_type_too_many_types(self): + def test_object_type_too_many_types(self) -> None: node = builder.extract_node( """ from unknown import Unknown @@ -163,7 +164,7 @@ def test(x): ) self.assertEqual(helpers.object_type(node), util.Uninferable) - def test_is_subtype(self): + def test_is_subtype(self) -> None: ast_nodes = builder.extract_node( """ class int_subclass(int): @@ -190,7 +191,7 @@ class C(A): pass #@ self.assertFalse(helpers.is_subtype(cls_a, cls_b)) self.assertFalse(helpers.is_subtype(cls_a, cls_b)) - def test_is_subtype_supertype_mro_error(self): + def test_is_subtype_supertype_mro_error(self) -> None: cls_e, cls_f = builder.extract_node( """ class A(object): pass @@ -208,7 +209,7 @@ class F(D, E): pass #@ helpers.is_subtype(cls_f, cls_e) self.assertFalse(helpers.is_supertype(cls_f, cls_e)) - def test_is_subtype_supertype_unknown_bases(self): + def test_is_subtype_supertype_unknown_bases(self) -> None: cls_a, cls_b = builder.extract_node( """ from unknown import Unknown @@ -221,7 +222,7 @@ class B(A): pass #@ with self.assertRaises(_NonDeducibleTypeHierarchy): helpers.is_supertype(cls_a, cls_b) - def test_is_subtype_supertype_unrelated_classes(self): + def test_is_subtype_supertype_unrelated_classes(self) -> None: cls_a, cls_b = builder.extract_node( """ class A(object): pass #@ @@ -233,7 +234,7 @@ class B(object): pass #@ self.assertFalse(helpers.is_supertype(cls_a, cls_b)) self.assertFalse(helpers.is_supertype(cls_b, cls_a)) - def test_is_subtype_supertype_classes_no_type_ancestor(self): + def test_is_subtype_supertype_classes_no_type_ancestor(self) -> None: cls_a = builder.extract_node( """ class A(object): #@ @@ -244,7 +245,7 @@ class A(object): #@ self.assertFalse(helpers.is_supertype(builtin_type, cls_a)) self.assertFalse(helpers.is_subtype(cls_a, builtin_type)) - def test_is_subtype_supertype_classes_metaclasses(self): + def test_is_subtype_supertype_classes_metaclasses(self) -> None: cls_a = builder.extract_node( """ class A(type): #@ diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py index 8653fab6e0..92e9257872 100644 --- a/tests/unittest_inference.py +++ b/tests/unittest_inference.py @@ -40,7 +40,9 @@ import platform import textwrap import unittest +from abc import ABCMeta from functools import partial +from typing import Any, Callable, Dict, List, Tuple, Union from unittest.mock import patch import pytest @@ -48,9 +50,11 @@ from astroid import Slice, arguments from astroid import decorators as decoratorsmod from astroid import helpers, nodes, objects, test_utils, util +from astroid.arguments import CallSite from astroid.bases import BoundMethod, Instance, UnboundMethod from astroid.builder import AstroidBuilder, extract_node, parse from astroid.const import PY38_PLUS, PY39_PLUS +from astroid.context import InferenceContext from astroid.exceptions import ( AstroidTypeError, AttributeInferenceError, @@ -70,7 +74,7 @@ HAS_SIX = False -def get_node_of_class(start_from, klass): +def get_node_of_class(start_from: nodes.FunctionDef, klass: type) -> nodes.Attribute: return next(start_from.nodes_of_class(klass)) @@ -81,8 +85,8 @@ def get_node_of_class(start_from, klass): class InferenceUtilsTest(unittest.TestCase): - def test_path_wrapper(self): - def infer_default(self, *args): + def test_path_wrapper(self) -> None: + def infer_default(self: Any, *args: InferenceContext) -> None: raise InferenceError infer_default = decoratorsmod.path_wrapper(infer_default) @@ -92,7 +96,12 @@ def infer_default(self, *args): self.assertEqual(next(infer_end(1)), 1) -def _assertInferElts(node_type, self, node, elts): +def _assertInferElts( + node_type: ABCMeta, + self: "InferenceTest", + node: Any, + elts: Union[List[int], List[str]], +) -> None: inferred = next(node.infer()) self.assertIsInstance(inferred, node_type) self.assertEqual(sorted(elt.value for elt in inferred.elts), elts) @@ -109,12 +118,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase): # additional assertInfer* method for builtin types - def assertInferConst(self, node, expected): + def assertInferConst(self, node: nodes.Call, expected: str) -> None: inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected) - def assertInferDict(self, node, expected): + def assertInferDict( + self, node: Union[nodes.Call, nodes.Dict], expected: Any + ) -> None: inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Dict) @@ -159,7 +170,7 @@ def meth3(self, d=attr): ast = parse(CODE, __name__) - def test_infer_abstract_property_return_values(self): + def test_infer_abstract_property_return_values(self) -> None: module = parse( """ import abc @@ -177,35 +188,35 @@ def test(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_module_inference(self): + def test_module_inference(self) -> None: inferred = self.ast.infer() obj = next(inferred) self.assertEqual(obj.name, __name__) self.assertEqual(obj.root().name, __name__) self.assertRaises(StopIteration, partial(next, inferred)) - def test_class_inference(self): + def test_class_inference(self) -> None: inferred = self.ast["C"].infer() obj = next(inferred) self.assertEqual(obj.name, "C") self.assertEqual(obj.root().name, __name__) self.assertRaises(StopIteration, partial(next, inferred)) - def test_function_inference(self): + def test_function_inference(self) -> None: inferred = self.ast["C"]["meth1"].infer() obj = next(inferred) self.assertEqual(obj.name, "meth1") self.assertEqual(obj.root().name, __name__) self.assertRaises(StopIteration, partial(next, inferred)) - def test_builtin_name_inference(self): + def test_builtin_name_inference(self) -> None: inferred = self.ast["C"]["meth1"]["var"].infer() var = next(inferred) self.assertEqual(var.name, "object") self.assertEqual(var.root().name, "builtins") self.assertRaises(StopIteration, partial(next, inferred)) - def test_tupleassign_name_inference(self): + def test_tupleassign_name_inference(self) -> None: inferred = self.ast["a"].infer() exc = next(inferred) self.assertIsInstance(exc, Instance) @@ -223,7 +234,7 @@ def test_tupleassign_name_inference(self): self.assertEqual(const.value, "bonjour") self.assertRaises(StopIteration, partial(next, inferred)) - def test_listassign_name_inference(self): + def test_listassign_name_inference(self) -> None: inferred = self.ast["d"].infer() exc = next(inferred) self.assertIsInstance(exc, Instance) @@ -240,7 +251,7 @@ def test_listassign_name_inference(self): self.assertIsInstance(const, nodes.Tuple) self.assertRaises(StopIteration, partial(next, inferred)) - def test_advanced_tupleassign_name_inference1(self): + def test_advanced_tupleassign_name_inference1(self) -> None: inferred = self.ast["g"].infer() const = next(inferred) self.assertIsInstance(const, nodes.Const) @@ -252,7 +263,7 @@ def test_advanced_tupleassign_name_inference1(self): self.assertEqual(var.root().name, "builtins") self.assertRaises(StopIteration, partial(next, inferred)) - def test_advanced_tupleassign_name_inference2(self): + def test_advanced_tupleassign_name_inference2(self) -> None: inferred = self.ast["i"].infer() const = next(inferred) self.assertIsInstance(const, nodes.Const) @@ -269,7 +280,7 @@ def test_advanced_tupleassign_name_inference2(self): self.assertEqual(var.root().name, "builtins") self.assertRaises(StopIteration, partial(next, inferred)) - def test_swap_assign_inference(self): + def test_swap_assign_inference(self) -> None: inferred = self.ast.locals["a"][1].infer() const = next(inferred) self.assertIsInstance(const, nodes.Const) @@ -282,7 +293,7 @@ def test_swap_assign_inference(self): self.assertEqual(exc.root().name, EXC_MODULE) self.assertRaises(StopIteration, partial(next, inferred)) - def test_getattr_inference1(self): + def test_getattr_inference1(self) -> None: inferred = self.ast["ex"].infer() exc = next(inferred) self.assertIsInstance(exc, Instance) @@ -290,28 +301,28 @@ def test_getattr_inference1(self): self.assertEqual(exc.root().name, EXC_MODULE) self.assertRaises(StopIteration, partial(next, inferred)) - def test_getattr_inference2(self): + def test_getattr_inference2(self) -> None: inferred = get_node_of_class(self.ast["C"]["meth2"], nodes.Attribute).infer() meth1 = next(inferred) self.assertEqual(meth1.name, "meth1") self.assertEqual(meth1.root().name, __name__) self.assertRaises(StopIteration, partial(next, inferred)) - def test_getattr_inference3(self): + def test_getattr_inference3(self) -> None: inferred = self.ast["C"]["meth3"]["b"].infer() const = next(inferred) self.assertIsInstance(const, nodes.Const) self.assertEqual(const.value, 4) self.assertRaises(StopIteration, partial(next, inferred)) - def test_getattr_inference4(self): + def test_getattr_inference4(self) -> None: inferred = self.ast["C"]["meth3"]["c"].infer() const = next(inferred) self.assertIsInstance(const, nodes.Const) self.assertEqual(const.value, "hop") self.assertRaises(StopIteration, partial(next, inferred)) - def test_callfunc_inference(self): + def test_callfunc_inference(self) -> None: inferred = self.ast["v"].infer() meth1 = next(inferred) self.assertIsInstance(meth1, Instance) @@ -319,7 +330,7 @@ def test_callfunc_inference(self): self.assertEqual(meth1.root().name, "builtins") self.assertRaises(StopIteration, partial(next, inferred)) - def test_unbound_method_inference(self): + def test_unbound_method_inference(self) -> None: inferred = self.ast["m_unbound"].infer() meth1 = next(inferred) self.assertIsInstance(meth1, UnboundMethod) @@ -327,7 +338,7 @@ def test_unbound_method_inference(self): self.assertEqual(meth1.parent.frame().name, "C") self.assertRaises(StopIteration, partial(next, inferred)) - def test_bound_method_inference(self): + def test_bound_method_inference(self) -> None: inferred = self.ast["m_bound"].infer() meth1 = next(inferred) self.assertIsInstance(meth1, BoundMethod) @@ -335,7 +346,7 @@ def test_bound_method_inference(self): self.assertEqual(meth1.parent.frame().name, "C") self.assertRaises(StopIteration, partial(next, inferred)) - def test_args_default_inference1(self): + def test_args_default_inference1(self) -> None: optarg = test_utils.get_name_node(self.ast["C"]["meth1"], "optarg") inferred = optarg.infer() obj1 = next(inferred) @@ -345,7 +356,7 @@ def test_args_default_inference1(self): self.assertIs(obj1, util.Uninferable, obj1) self.assertRaises(StopIteration, partial(next, inferred)) - def test_args_default_inference2(self): + def test_args_default_inference2(self) -> None: inferred = self.ast["C"]["meth3"].ilookup("d") obj1 = next(inferred) self.assertIsInstance(obj1, nodes.Const) @@ -354,13 +365,13 @@ def test_args_default_inference2(self): self.assertIs(obj1, util.Uninferable, obj1) self.assertRaises(StopIteration, partial(next, inferred)) - def test_inference_restrictions(self): + def test_inference_restrictions(self) -> None: inferred = test_utils.get_name_node(self.ast["C"]["meth1"], "arg1").infer() obj1 = next(inferred) self.assertIs(obj1, util.Uninferable, obj1) self.assertRaises(StopIteration, partial(next, inferred)) - def test_ancestors_inference(self): + def test_ancestors_inference(self) -> None: code = """ class A(object): #@ pass @@ -373,7 +384,7 @@ class A(A): #@ self.assertEqual(len(a2_ancestors), 2) self.assertIs(a2_ancestors[0], a1) - def test_ancestors_inference2(self): + def test_ancestors_inference2(self) -> None: code = """ class A(object): #@ pass @@ -390,7 +401,7 @@ class A(B): #@ self.assertIs(a2_ancestors[0], b) self.assertIs(a2_ancestors[1], a1) - def test_f_arg_f(self): + def test_f_arg_f(self) -> None: code = """ def f(f=1): return f @@ -403,7 +414,7 @@ def f(f=1): self.assertEqual(a_inferred[0].value, 1) self.assertEqual(len(a_inferred), 1) - def test_exc_ancestors(self): + def test_exc_ancestors(self) -> None: code = """ def f(): raise __(NotImplementedError) @@ -415,7 +426,7 @@ def f(): expected = ["RuntimeError", "Exception", "BaseException", "object"] self.assertEqual(nie_ancestors, expected) - def test_except_inference(self): + def test_except_inference(self) -> None: code = """ try: print (hop) @@ -439,14 +450,14 @@ def test_except_inference(self): self.assertEqual(ex2.name, "Exception") self.assertRaises(StopIteration, partial(next, ex2_infer)) - def test_del1(self): + def test_del1(self) -> None: code = """ del undefined_attr """ delete = extract_node(code, __name__) self.assertRaises(InferenceError, next, delete.infer()) - def test_del2(self): + def test_del2(self) -> None: code = """ a = 1 b = a @@ -472,7 +483,7 @@ def test_del2(self): self.assertEqual(inferred.value, 2) self.assertRaises(StopIteration, partial(next, n_infer)) - def test_builtin_types(self): + def test_builtin_types(self) -> None: code = """ l = [1] t = (2,) @@ -535,7 +546,7 @@ class A: clsm = next(ast["A"].igetattr("clsm")) self.assertFalse(clsm.callable()) - def test_bt_ancestor_crash(self): + def test_bt_ancestor_crash(self) -> None: code = """ class Warning(Warning): pass @@ -557,7 +568,7 @@ class Warning(Warning): self.assertEqual(ancestor.root().name, "builtins") self.assertRaises(StopIteration, partial(next, ancestors)) - def test_method_argument(self): + def test_method_argument(self) -> None: code = ''' class ErudiEntitySchema: """an entity has a type, a set of subject and or object relations""" @@ -584,7 +595,7 @@ def meth(self, e_type, *args, **kwargs): arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "kwargs") self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict]) - def test_tuple_then_list(self): + def test_tuple_then_list(self) -> None: code = """ def test_view(rql, vid, tags=()): tags = list(tags) @@ -598,7 +609,7 @@ def test_view(rql, vid, tags=()): with self.assertRaises(StopIteration): next(it) - def test_mulassign_inference(self): + def test_mulassign_inference(self) -> None: code = ''' def first_word(line): """Return the first word of a line""" @@ -647,7 +658,7 @@ def process_line(word_pos): ) ) - def test_float_complex_ambiguity(self): + def test_float_complex_ambiguity(self) -> None: code = ''' def no_conjugate_member(magic_flag): #@ """should not raise E1101 on something.conjugate""" @@ -663,7 +674,7 @@ def no_conjugate_member(magic_flag): #@ self.assertEqual([i.value for i in func.ilookup("something")], [1.0, 1.0j]) self.assertEqual([i.value for i in retval.infer()], [1.0, 1.0j]) - def test_lookup_cond_branches(self): + def test_lookup_cond_branches(self) -> None: code = ''' def no_conjugate_member(magic_flag): """should not raise E1101 on something.conjugate""" @@ -678,7 +689,7 @@ def no_conjugate_member(magic_flag): ] self.assertEqual(values, [1.0, 1.0j]) - def test_simple_subscript(self): + def test_simple_subscript(self) -> None: code = """ class A(object): def __getitem__(self, index): @@ -702,7 +713,7 @@ def __getitem__(self, index): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected_value) - def test_invalid_subscripts(self): + def test_invalid_subscripts(self) -> None: ast_nodes = extract_node( """ class NoGetitem(object): @@ -721,13 +732,13 @@ class InvalidGetitem2(object): for node in ast_nodes: self.assertRaises(InferenceError, next, node.infer()) - def test_bytes_subscript(self): + def test_bytes_subscript(self) -> None: node = extract_node("""b'a'[0]""") inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 97) - def test_subscript_multi_value(self): + def test_subscript_multi_value(self) -> None: code = """ def do_thing_with_subscript(magic_flag): src = [3, 2, 1] @@ -742,7 +753,7 @@ def do_thing_with_subscript(magic_flag): ] self.assertEqual(list(sorted(values)), [1, 3]) - def test_subscript_multi_slice(self): + def test_subscript_multi_slice(self) -> None: code = """ def zero_or_one(magic_flag): if magic_flag: @@ -761,7 +772,7 @@ def do_thing_with_subscript(magic_flag): ] self.assertEqual(list(sorted(values)), [2, 3]) - def test_simple_tuple(self): + def test_simple_tuple(self) -> None: module = parse( """ a = (1,) @@ -775,7 +786,7 @@ def test_simple_tuple(self): self.assertEqual(ast.elts[0].value, 1) self.assertEqual(ast.elts[1].value, 22) - def test_simple_for(self): + def test_simple_for(self) -> None: code = """ for a in [1, 2, 3]: print (a) @@ -802,7 +813,7 @@ def test_simple_for(self): [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3] ) - def test_simple_for_genexpr(self): + def test_simple_for_genexpr(self) -> None: code = """ print ((d,e) for e,d in ([1,2], [3,4])) """ @@ -814,7 +825,7 @@ def test_simple_for_genexpr(self): [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3] ) - def test_builtin_help(self): + def test_builtin_help(self) -> None: code = """ help() """ @@ -826,7 +837,7 @@ def test_builtin_help(self): self.assertIsInstance(inferred[0], Instance) self.assertEqual(inferred[0].name, "_Helper") - def test_builtin_open(self): + def test_builtin_open(self) -> None: code = """ open("toto.txt") """ @@ -839,7 +850,7 @@ def test_builtin_open(self): if platform.python_implementation() == "PyPy": test_builtin_open = unittest.expectedFailure(test_builtin_open) - def test_callfunc_context_func(self): + def test_callfunc_context_func(self) -> None: code = """ def mirror(arg=None): return arg @@ -852,7 +863,7 @@ def mirror(arg=None): self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 1) - def test_callfunc_context_lambda(self): + def test_callfunc_context_lambda(self) -> None: code = """ mirror = lambda x=None: x @@ -867,7 +878,7 @@ def test_callfunc_context_lambda(self): self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 1) - def test_factory_method(self): + def test_factory_method(self) -> None: code = """ class Super(object): @classmethod @@ -886,7 +897,7 @@ def method(self): self.assertIsInstance(inferred[0], Instance) self.assertEqual(inferred[0]._proxied.name, "Sub") - def test_factory_methods_cls_call(self): + def test_factory_methods_cls_call(self) -> None: ast = extract_node( """ class C: @@ -909,7 +920,7 @@ class D(C): self.assertEqual("module.C", should_be_c[0].qname()) self.assertEqual("module.D", should_be_d[0].qname()) - def test_factory_methods_object_new_call(self): + def test_factory_methods_object_new_call(self) -> None: ast = extract_node( """ class C: @@ -947,7 +958,7 @@ def test_factory_methods_inside_binary_operation(self): ) assert next(node.infer()).qname() == "pathlib.Path" - def test_import_as(self): + def test_import_as(self) -> None: code = """ import os.path as osp print (osp.dirname(__file__)) @@ -965,13 +976,15 @@ def test_import_as(self): self.assertIsInstance(inferred[0], nodes.FunctionDef) self.assertEqual(inferred[0].name, "exists") - def _test_const_inferred(self, node, value): + def _test_const_inferred( + self, node: nodes.AssignName, value: Union[float, str] + ) -> None: inferred = list(node.infer()) self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, value) - def test_unary_not(self): + def test_unary_not(self) -> None: for code in ( "a = not (1,); b = not ()", "a = not {1:2}; b = not {}", @@ -985,7 +998,7 @@ def test_unary_not(self): self._test_const_inferred(ast["a"], False) self._test_const_inferred(ast["b"], True) - def test_unary_op_numbers(self): + def test_unary_op_numbers(self) -> None: ast_nodes = extract_node( """ +1 #@ @@ -1000,7 +1013,7 @@ def test_unary_op_numbers(self): inferred = next(node.infer()) self.assertEqual(inferred.value, expected_value) - def test_matmul(self): + def test_matmul(self) -> None: node = extract_node( """ class Array: @@ -1013,43 +1026,43 @@ def __matmul__(self, other): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_binary_op_int_add(self): + def test_binary_op_int_add(self) -> None: ast = builder.string_build("a = 1 + 2", __name__, __file__) self._test_const_inferred(ast["a"], 3) - def test_binary_op_int_sub(self): + def test_binary_op_int_sub(self) -> None: ast = builder.string_build("a = 1 - 2", __name__, __file__) self._test_const_inferred(ast["a"], -1) - def test_binary_op_float_div(self): + def test_binary_op_float_div(self) -> None: ast = builder.string_build("a = 1 / 2.", __name__, __file__) self._test_const_inferred(ast["a"], 1 / 2.0) - def test_binary_op_str_mul(self): + def test_binary_op_str_mul(self) -> None: ast = builder.string_build('a = "*" * 40', __name__, __file__) self._test_const_inferred(ast["a"], "*" * 40) - def test_binary_op_int_bitand(self): + def test_binary_op_int_bitand(self) -> None: ast = builder.string_build("a = 23&20", __name__, __file__) self._test_const_inferred(ast["a"], 23 & 20) - def test_binary_op_int_bitor(self): + def test_binary_op_int_bitor(self) -> None: ast = builder.string_build("a = 23|8", __name__, __file__) self._test_const_inferred(ast["a"], 23 | 8) - def test_binary_op_int_bitxor(self): + def test_binary_op_int_bitxor(self) -> None: ast = builder.string_build("a = 23^9", __name__, __file__) self._test_const_inferred(ast["a"], 23 ^ 9) - def test_binary_op_int_shiftright(self): + def test_binary_op_int_shiftright(self) -> None: ast = builder.string_build("a = 23 >>1", __name__, __file__) self._test_const_inferred(ast["a"], 23 >> 1) - def test_binary_op_int_shiftleft(self): + def test_binary_op_int_shiftleft(self) -> None: ast = builder.string_build("a = 23 <<1", __name__, __file__) self._test_const_inferred(ast["a"], 23 << 1) - def test_binary_op_other_type(self): + def test_binary_op_other_type(self) -> None: ast_nodes = extract_node( """ class A: @@ -1066,7 +1079,7 @@ def __add__(self, other): second = next(ast_nodes[1].infer()) self.assertEqual(second, util.Uninferable) - def test_binary_op_other_type_using_reflected_operands(self): + def test_binary_op_other_type_using_reflected_operands(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -1083,7 +1096,7 @@ def __radd__(self, other): self.assertIsInstance(second, nodes.Const) self.assertEqual(second.value, 43) - def test_binary_op_reflected_and_not_implemented_is_type_error(self): + def test_binary_op_reflected_and_not_implemented_is_type_error(self) -> None: ast_node = extract_node( """ class A(object): @@ -1095,7 +1108,7 @@ def __radd__(self, other): return NotImplemented first = next(ast_node.infer()) self.assertEqual(first, util.Uninferable) - def test_binary_op_list_mul(self): + def test_binary_op_list_mul(self) -> None: for code in ("a = [[]] * 2", "a = 2 * [[]]"): ast = builder.string_build(code, __name__, __file__) inferred = list(ast["a"].infer()) @@ -1105,7 +1118,7 @@ def test_binary_op_list_mul(self): self.assertIsInstance(inferred[0].elts[0], nodes.List) self.assertIsInstance(inferred[0].elts[1], nodes.List) - def test_binary_op_list_mul_none(self): + def test_binary_op_list_mul_none(self) -> None: "test correct handling on list multiplied by None" ast = builder.string_build('a = [1] * None\nb = [1] * "r"') inferred = ast["a"].inferred() @@ -1115,7 +1128,7 @@ def test_binary_op_list_mul_none(self): self.assertEqual(len(inferred), 1) self.assertEqual(inferred[0], util.Uninferable) - def test_binary_op_list_mul_int(self): + def test_binary_op_list_mul_int(self) -> None: "test correct handling on list multiplied by int when there are more than one" code = """ from ctypes import c_int @@ -1128,7 +1141,7 @@ def test_binary_op_list_mul_int(self): self.assertIsInstance(listval, nodes.List) self.assertEqual(len(listval.itered()), 4) - def test_binary_op_on_self(self): + def test_binary_op_on_self(self) -> None: "test correct handling of applying binary operator to self" code = """ import sys @@ -1140,7 +1153,7 @@ def test_binary_op_on_self(self): inferred = ast["path"].inferred() self.assertIsInstance(inferred[0], nodes.List) - def test_binary_op_tuple_add(self): + def test_binary_op_tuple_add(self) -> None: ast = builder.string_build("a = (1,) + (2,)", __name__, __file__) inferred = list(ast["a"].infer()) self.assertEqual(len(inferred), 1) @@ -1149,7 +1162,7 @@ def test_binary_op_tuple_add(self): self.assertEqual(inferred[0].elts[0].value, 1) self.assertEqual(inferred[0].elts[1].value, 2) - def test_binary_op_custom_class(self): + def test_binary_op_custom_class(self) -> None: code = """ class myarray: def __init__(self, array): @@ -1178,7 +1191,7 @@ def randint(maximum): value, ["Instance of %s.myarray" % __name__, "Const.int(value=5)"] ) - def test_nonregr_lambda_arg(self): + def test_nonregr_lambda_arg(self) -> None: code = """ def f(g = lambda: None): __(g()).x @@ -1190,7 +1203,7 @@ def f(g = lambda: None): self.assertIsInstance(inferred[0], nodes.Const) self.assertIsNone(inferred[0].value) - def test_nonregr_getitem_empty_tuple(self): + def test_nonregr_getitem_empty_tuple(self) -> None: code = """ def f(x): a = ()[x] @@ -1200,7 +1213,7 @@ def f(x): self.assertEqual(len(inferred), 1) self.assertEqual(inferred[0], util.Uninferable) - def test_nonregr_instance_attrs(self): + def test_nonregr_instance_attrs(self) -> None: """non regression for instance_attrs infinite loop : pylint / #4""" code = """ @@ -1229,7 +1242,7 @@ def __init__(self): self.assertEqual(len(foo_class.instance_attrs["attr"]), 1) self.assertEqual(bar_class.instance_attrs, {"attr": [assattr]}) - def test_nonregr_multi_referential_addition(self): + def test_nonregr_multi_referential_addition(self) -> None: """Regression test for https://github.com/PyCQA/astroid/issues/483 Make sure issue where referring to the same variable in the same inferred expression caused an uninferable result. @@ -1242,7 +1255,7 @@ def test_nonregr_multi_referential_addition(self): variable_a = extract_node(code) self.assertEqual(variable_a.inferred()[0].value, 2) - def test_nonregr_layed_dictunpack(self): + def test_nonregr_layed_dictunpack(self) -> None: """Regression test for https://github.com/PyCQA/astroid/issues/483 Make sure multiple dictunpack references are inferable """ @@ -1255,7 +1268,7 @@ def test_nonregr_layed_dictunpack(self): ass = extract_node(code) self.assertIsInstance(ass.inferred()[0], nodes.Dict) - def test_nonregr_inference_modifying_col_offset(self): + def test_nonregr_inference_modifying_col_offset(self) -> None: """Make sure inference doesn't improperly modify col_offset Regression test for https://github.com/PyCQA/pylint/issues/1839 @@ -1273,7 +1286,7 @@ def _(self): call.inferred() self.assertEqual(cdef.col_offset, orig_offset) - def test_no_runtime_error_in_repeat_inference(self): + def test_no_runtime_error_in_repeat_inference(self) -> None: """Stop repeat inference attempt causing a RuntimeError in Python3.7 See https://github.com/PyCQA/pylint/issues/2317 @@ -1303,7 +1316,7 @@ def get_context_data(self, **kwargs): assert isinstance(result[0], nodes.Dict) assert result[1] is util.Uninferable - def test_python25_no_relative_import(self): + def test_python25_no_relative_import(self) -> None: ast = resources.build_file("data/package/absimport.py") self.assertTrue(ast.absolute_import_activated(), True) inferred = next( @@ -1312,7 +1325,7 @@ def test_python25_no_relative_import(self): # failed to import since absolute_import is activated self.assertIs(inferred, util.Uninferable) - def test_nonregr_absolute_import(self): + def test_nonregr_absolute_import(self) -> None: ast = resources.build_file("data/absimp/string.py", "data.absimp.string") self.assertTrue(ast.absolute_import_activated(), True) inferred = next(test_utils.get_name_node(ast, "string").infer()) @@ -1320,7 +1333,7 @@ def test_nonregr_absolute_import(self): self.assertEqual(inferred.name, "string") self.assertIn("ascii_letters", inferred.locals) - def test_property(self): + def test_property(self) -> None: code = """ from smtplib import SMTP class SendMailController(object): @@ -1353,7 +1366,7 @@ def me(self): self.assertEqual(propinferred.name, "SendMailController") self.assertEqual(propinferred.root().name, __name__) - def test_im_func_unwrap(self): + def test_im_func_unwrap(self) -> None: code = """ class EnvBasedTC: def pactions(self): @@ -1375,7 +1388,7 @@ class EnvBasedTC2: self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], nodes.FunctionDef) - def test_augassign(self): + def test_augassign(self) -> None: code = """ a = 1 a += 2 @@ -1388,7 +1401,7 @@ def test_augassign(self): self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 3) - def test_nonregr_func_arg(self): + def test_nonregr_func_arg(self) -> None: code = """ def foo(self, bar): def baz(): @@ -1403,7 +1416,7 @@ def qux(): self.assertEqual(len(inferred), 1) self.assertIs(inferred[0], util.Uninferable) - def test_nonregr_func_global(self): + def test_nonregr_func_global(self) -> None: code = """ active_application = None @@ -1436,7 +1449,7 @@ def test(self): else: self.fail("expected to find an instance of Application in %s" % inferred) - def test_list_inference(self): + def test_list_inference(self) -> None: """#20464""" code = """ from unknown import Unknown @@ -1457,7 +1470,7 @@ def test(): self.assertEqual(len(inferred.elts), 1) self.assertIsInstance(inferred.elts[0], nodes.Unknown) - def test__new__(self): + def test__new__(self) -> None: code = """ class NewTest(object): "doc" @@ -1474,7 +1487,7 @@ def __new__(cls, arg): inferred = list(n.igetattr("arg")) self.assertEqual(len(inferred), 1, inferred) - def test__new__bound_methods(self): + def test__new__bound_methods(self) -> None: node = extract_node( """ class cls(object): pass @@ -1485,7 +1498,7 @@ class cls(object): pass self.assertIsInstance(inferred, Instance) self.assertEqual(inferred._proxied, node.root()["cls"]) - def test_two_parents_from_same_module(self): + def test_two_parents_from_same_module(self) -> None: code = """ from data import nonregr class Xxx(nonregr.Aaa, nonregr.Ccc): @@ -1495,7 +1508,7 @@ class Xxx(nonregr.Aaa, nonregr.Ccc): parents = list(ast["Xxx"].ancestors()) self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object - def test_pluggable_inference(self): + def test_pluggable_inference(self) -> None: code = """ from collections import namedtuple A = namedtuple('A', ['a', 'b']) @@ -1511,7 +1524,7 @@ def test_pluggable_inference(self): self.assertIn("a", bclass.instance_attrs) self.assertIn("b", bclass.instance_attrs) - def test_infer_arguments(self): + def test_infer_arguments(self) -> None: code = """ class A(object): def first(self, arg1, arg2): @@ -1548,7 +1561,7 @@ def empty_method(self): empty_list = ast["empty_list"].inferred()[0] self.assertIsInstance(empty_list, nodes.List) - def test_infer_variable_arguments(self): + def test_infer_variable_arguments(self) -> None: code = """ def test(*args, **kwargs): vararg = args @@ -1567,7 +1580,7 @@ def test(*args, **kwargs): self.assertIsInstance(vararg_inferred, nodes.Tuple) self.assertIs(vararg_inferred.parent, func.args) - def test_infer_nested(self): + def test_infer_nested(self) -> None: code = """ def nested(): from threading import Thread @@ -1584,7 +1597,7 @@ def __init__(self): inferred = func.inferred()[0] self.assertIsInstance(inferred, UnboundMethod) - def test_instance_binary_operations(self): + def test_instance_binary_operations(self) -> None: code = """ class A(object): def __mul__(self, other): @@ -1601,7 +1614,7 @@ def __mul__(self, other): self.assertIsInstance(mul, nodes.Const) self.assertEqual(mul.value, 42) - def test_instance_binary_operations_parent(self): + def test_instance_binary_operations_parent(self) -> None: code = """ class A(object): def __mul__(self, other): @@ -1620,7 +1633,7 @@ class B(A): self.assertIsInstance(mul, nodes.Const) self.assertEqual(mul.value, 42) - def test_instance_binary_operations_multiple_methods(self): + def test_instance_binary_operations_multiple_methods(self) -> None: code = """ class A(object): def __mul__(self, other): @@ -1641,7 +1654,7 @@ def __mul__(self, other): self.assertIsInstance(mul.elts[0], nodes.Const) self.assertEqual(mul.elts[0].value, 42) - def test_infer_call_result_crash(self): + def test_infer_call_result_crash(self) -> None: code = """ class A(object): def __mul__(self, other): @@ -1655,12 +1668,12 @@ def __mul__(self, other): node = ast["c"] self.assertEqual(node.inferred(), [util.Uninferable]) - def test_infer_empty_nodes(self): + def test_infer_empty_nodes(self) -> None: # Should not crash when trying to infer EmptyNodes. node = nodes.EmptyNode() self.assertEqual(node.inferred(), [util.Uninferable]) - def test_infinite_loop_for_decorators(self): + def test_infinite_loop_for_decorators(self) -> None: # Issue https://bitbucket.org/logilab/astroid/issue/50 # A decorator that returns itself leads to an infinite loop. code = """ @@ -1677,7 +1690,7 @@ def do_a_thing(): node = ast["do_a_thing"] self.assertEqual(node.type, "function") - def test_no_infinite_ancestor_loop(self): + def test_no_infinite_ancestor_loop(self) -> None: klass = extract_node( """ import datetime @@ -1693,7 +1706,7 @@ class something(datetime.datetime): #@ expected_subset = ["datetime", "date"] self.assertEqual(expected_subset, ancestors[:2]) - def test_stop_iteration_leak(self): + def test_stop_iteration_leak(self) -> None: code = """ class Test: def __init__(self): @@ -1705,7 +1718,7 @@ def __init__(self): with pytest.raises(InferenceError): next(expr.infer()) - def test_tuple_builtin_inference(self): + def test_tuple_builtin_inference(self) -> None: code = """ var = (1, 2) tuple() #@ @@ -1737,7 +1750,7 @@ def test_tuple_builtin_inference(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.tuple") - def test_starred_in_tuple_literal(self): + def test_starred_in_tuple_literal(self) -> None: code = """ var = (1, 2, 3) bar = (5, 6, 7) @@ -1755,7 +1768,7 @@ def test_starred_in_tuple_literal(self): self.assertInferTuple(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8]) self.assertInferTuple(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001]) - def test_starred_in_list_literal(self): + def test_starred_in_list_literal(self) -> None: code = """ var = (1, 2, 3) bar = (5, 6, 7) @@ -1773,7 +1786,7 @@ def test_starred_in_list_literal(self): self.assertInferList(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8]) self.assertInferList(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001]) - def test_starred_in_set_literal(self): + def test_starred_in_set_literal(self) -> None: code = """ var = (1, 2, 3) bar = (5, 6, 7) @@ -1791,7 +1804,7 @@ def test_starred_in_set_literal(self): self.assertInferSet(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8]) self.assertInferSet(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001]) - def test_starred_in_literals_inference_issues(self): + def test_starred_in_literals_inference_issues(self) -> None: code = """ {0, *var} #@ {0, *var, 4} #@ @@ -1804,7 +1817,7 @@ def test_starred_in_literals_inference_issues(self): with self.assertRaises(InferenceError): next(node.infer()) - def test_starred_in_mapping_literal(self): + def test_starred_in_mapping_literal(self) -> None: code = """ var = {1: 'b', 2: 'c'} bar = {4: 'e', 5: 'f'} @@ -1819,7 +1832,7 @@ def test_starred_in_mapping_literal(self): ast[2], {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g"} ) - def test_starred_in_mapping_literal_no_inference_possible(self): + def test_starred_in_mapping_literal_no_inference_possible(self) -> None: node = extract_node( """ from unknown import unknown @@ -1836,7 +1849,7 @@ def func(): ) self.assertEqual(next(node.infer()), util.Uninferable) - def test_starred_in_mapping_inference_issues(self): + def test_starred_in_mapping_inference_issues(self) -> None: code = """ {0: 'a', **var} #@ {0: 'a', **var, 3: 'd'} #@ @@ -1847,7 +1860,7 @@ def test_starred_in_mapping_inference_issues(self): with self.assertRaises(InferenceError): next(node.infer()) - def test_starred_in_mapping_literal_non_const_keys_values(self): + def test_starred_in_mapping_literal_non_const_keys_values(self) -> None: code = """ a, b, c, d, e, f, g, h, i, j = "ABCDEFGHIJ" var = {c: d, e: f} @@ -1859,7 +1872,7 @@ def test_starred_in_mapping_literal_non_const_keys_values(self): self.assertInferDict(ast[0], {"A": "B", "C": "D", "E": "F"}) self.assertInferDict(ast[1], {"A": "B", "C": "D", "E": "F", "G": "H", "I": "J"}) - def test_frozenset_builtin_inference(self): + def test_frozenset_builtin_inference(self) -> None: code = """ var = (1, 2) frozenset() #@ @@ -1890,7 +1903,7 @@ def test_frozenset_builtin_inference(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.frozenset") - def test_set_builtin_inference(self): + def test_set_builtin_inference(self) -> None: code = """ var = (1, 2) set() #@ @@ -1921,7 +1934,7 @@ def test_set_builtin_inference(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.set") - def test_list_builtin_inference(self): + def test_list_builtin_inference(self) -> None: code = """ var = (1, 2) list() #@ @@ -1951,7 +1964,7 @@ def test_list_builtin_inference(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.list") - def test_conversion_of_dict_methods(self): + def test_conversion_of_dict_methods(self) -> None: ast_nodes = extract_node( """ list({1:2, 2:3}.values()) #@ @@ -1967,7 +1980,7 @@ def test_conversion_of_dict_methods(self): self.assertInferTuple(ast_nodes[3], [1, 3]) self.assertInferSet(ast_nodes[4], [1, 2]) - def test_builtin_inference_py3k(self): + def test_builtin_inference_py3k(self) -> None: code = """ list(b"abc") #@ tuple(b"abc") #@ @@ -1978,7 +1991,7 @@ def test_builtin_inference_py3k(self): self.assertInferTuple(ast[1], [97, 98, 99]) self.assertInferSet(ast[2], [97, 98, 99]) - def test_dict_inference(self): + def test_dict_inference(self) -> None: code = """ dict() #@ dict(a=1, b=2, c=3) #@ @@ -2022,11 +2035,11 @@ def using_unknown_kwargs(**kwargs): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.dict") - def test_dict_inference_kwargs(self): + def test_dict_inference_kwargs(self) -> None: ast_node = extract_node("""dict(a=1, b=2, **{'c': 3})""") self.assertInferDict(ast_node, {"a": 1, "b": 2, "c": 3}) - def test_dict_inference_for_multiple_starred(self): + def test_dict_inference_for_multiple_starred(self) -> None: pairs = [ ('dict(a=1, **{"b": 2}, **{"c":3})', {"a": 1, "b": 2, "c": 3}), ('dict(a=1, **{"b": 2}, d=4, **{"c":3})', {"a": 1, "b": 2, "c": 3, "d": 4}), @@ -2036,7 +2049,7 @@ def test_dict_inference_for_multiple_starred(self): node = extract_node(code) self.assertInferDict(node, expected_value) - def test_dict_inference_unpack_repeated_key(self): + def test_dict_inference_unpack_repeated_key(self) -> None: """Make sure astroid does not infer repeated keys in a dictionary Regression test for https://github.com/PyCQA/pylint/issues/1843 @@ -2054,7 +2067,7 @@ def test_dict_inference_unpack_repeated_key(self): for node, final_value in zip(ast, final_values): assert node.targets[0].inferred()[0].as_string() == final_value - def test_dict_invalid_args(self): + def test_dict_invalid_args(self) -> None: invalid_values = ["dict(*1)", "dict(**lala)", "dict(**[])"] for invalid in invalid_values: ast_node = extract_node(invalid) @@ -2062,7 +2075,7 @@ def test_dict_invalid_args(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.qname(), "builtins.dict") - def test_str_methods(self): + def test_str_methods(self) -> None: code = """ ' '.decode() #@ ' '.join('abcd') #@ @@ -2091,7 +2104,7 @@ def test_str_methods(self): for i in range(15, 18): self.assertInferConst(ast[i], 0) - def test_unicode_methods(self): + def test_unicode_methods(self) -> None: code = """ u' '.decode() #@ u' '.join('abcd') #@ @@ -2120,7 +2133,7 @@ def test_unicode_methods(self): for i in range(15, 18): self.assertInferConst(ast[i], 0) - def test_scope_lookup_same_attributes(self): + def test_scope_lookup_same_attributes(self) -> None: code = """ import collections class Second(collections.Counter): @@ -2135,7 +2148,7 @@ def collections(self): self.assertIsInstance(inferred, nodes.ClassDef) self.assertEqual(inferred.qname(), "collections.Counter") - def test_inferring_with_statement_failures(self): + def test_inferring_with_statement_failures(self) -> None: module = parse( """ class NoEnter(object): @@ -2158,7 +2171,7 @@ def __enter__(self): self.assertRaises(InferenceError, next, module["no_method"].infer()) self.assertRaises(InferenceError, next, module["no_elts"].infer()) - def test_inferring_with_statement(self): + def test_inferring_with_statement(self) -> None: module = parse( """ class SelfContext(object): @@ -2211,7 +2224,7 @@ def __enter__(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 2) - def test_inferring_with_contextlib_contextmanager(self): + def test_inferring_with_contextlib_contextmanager(self) -> None: module = parse( """ import contextlib @@ -2266,7 +2279,7 @@ def manager_multiple(): self.assertIsInstance(second, nodes.Const) self.assertEqual(second.value, 42) - def test_inferring_context_manager_skip_index_error(self): + def test_inferring_context_manager_skip_index_error(self) -> None: # Raise an InferenceError when having multiple 'as' bindings # from a context manager, but its result doesn't have those # indices. This is the case of contextlib.nested, where the @@ -2283,7 +2296,7 @@ def __enter__(self): ) self.assertRaises(InferenceError, next, module["a"].infer()) - def test_inferring_context_manager_unpacking_inference_error(self): + def test_inferring_context_manager_unpacking_inference_error(self) -> None: # https://github.com/PyCQA/pylint/issues/1463 module = parse( """ @@ -2301,7 +2314,7 @@ def _select_source(a=None): ) self.assertRaises(InferenceError, next, module["a"].infer()) - def test_inferring_with_contextlib_contextmanager_failures(self): + def test_inferring_with_contextlib_contextmanager_failures(self) -> None: module = parse( """ from contextlib import contextmanager @@ -2327,7 +2340,7 @@ def no_yield_mgr(): self.assertRaises(InferenceError, next, module["other_decorators"].infer()) self.assertRaises(InferenceError, next, module["no_yield"].infer()) - def test_nested_contextmanager(self): + def test_nested_contextmanager(self) -> None: """Make sure contextmanager works with nested functions Previously contextmanager would retrieve @@ -2357,11 +2370,11 @@ def inner(): assert isinstance(context, nodes.FunctionDef) assert isinstance(value, nodes.Const) - def test_unary_op_leaks_stop_iteration(self): + def test_unary_op_leaks_stop_iteration(self) -> None: node = extract_node("+[] #@") self.assertEqual(util.Uninferable, next(node.infer())) - def test_unary_operands(self): + def test_unary_operands(self) -> None: ast_nodes = extract_node( """ import os @@ -2428,7 +2441,7 @@ def __invert__(self): inferred = next(bad_node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_unary_op_instance_method_not_callable(self): + def test_unary_op_instance_method_not_callable(self) -> None: ast_node = extract_node( """ class A: @@ -2438,7 +2451,7 @@ class A: ) self.assertRaises(InferenceError, next, ast_node.infer()) - def test_binary_op_type_errors(self): + def test_binary_op_type_errors(self) -> None: ast_nodes = extract_node( """ import collections @@ -2519,7 +2532,7 @@ def __radd__(self, other): error = errors[0] self.assertEqual(str(error), expected_value) - def test_unary_type_errors(self): + def test_unary_type_errors(self) -> None: ast_nodes = extract_node( """ import collections @@ -2563,7 +2576,7 @@ class A(object): pass error = errors[0] self.assertEqual(str(error), expected_value) - def test_unary_empty_type_errors(self): + def test_unary_empty_type_errors(self) -> None: # These aren't supported right now ast_nodes = extract_node( """ @@ -2580,13 +2593,13 @@ def test_unary_empty_type_errors(self): self.assertEqual(len(errors), 1, (expected, node)) self.assertEqual(str(errors[0]), expected_value) - def test_unary_type_errors_for_non_instance_objects(self): + def test_unary_type_errors_for_non_instance_objects(self) -> None: node = extract_node("~slice(1, 2, 3)") errors = node.type_errors() self.assertEqual(len(errors), 1) self.assertEqual(str(errors[0]), "bad operand type for unary ~: slice") - def test_bool_value_recursive(self): + def test_bool_value_recursive(self) -> None: pairs = [ ("{}", False), ("{1:2}", True), @@ -2602,11 +2615,11 @@ def test_bool_value_recursive(self): inferred = next(node.infer()) self.assertEqual(inferred.bool_value(), expected) - def test_genexpr_bool_value(self): + def test_genexpr_bool_value(self) -> None: node = extract_node("""(x for x in range(10))""") self.assertTrue(node.bool_value()) - def test_name_bool_value(self): + def test_name_bool_value(self) -> None: node = extract_node( """ x = 42 @@ -2616,7 +2629,7 @@ def test_name_bool_value(self): ) self.assertIs(node.bool_value(), util.Uninferable) - def test_bool_value(self): + def test_bool_value(self) -> None: # Verify the truth value of nodes. module = parse( """ @@ -2677,7 +2690,7 @@ def true_value(): compare = module["compare"].parent.value self.assertEqual(compare.bool_value(), util.Uninferable) - def test_bool_value_instances(self): + def test_bool_value_instances(self) -> None: instances = extract_node( f""" class FalseBoolInstance(object): @@ -2715,7 +2728,7 @@ class NonMethods(object): inferred = next(node.infer()) self.assertEqual(inferred.bool_value(), expected_value) - def test_bool_value_variable(self): + def test_bool_value_variable(self) -> None: instance = extract_node( f""" class VariableBoolInstance(object): @@ -2730,7 +2743,7 @@ def {BOOL_SPECIAL_METHOD}(self): inferred = next(instance.infer()) self.assertIs(inferred.bool_value(), util.Uninferable) - def test_infer_coercion_rules_for_floats_complex(self): + def test_infer_coercion_rules_for_floats_complex(self) -> None: ast_nodes = extract_node( """ 1 + 1.0 #@ @@ -2748,7 +2761,7 @@ def test_infer_coercion_rules_for_floats_complex(self): inferred = next(node.infer()) self.assertEqual(inferred.value, expected) - def test_binop_list_with_elts(self): + def test_binop_list_with_elts(self) -> None: ast_node = extract_node( """ x = [A] * 1 @@ -2761,7 +2774,7 @@ def test_binop_list_with_elts(self): self.assertIsInstance(inferred.elts[0], nodes.Const) self.assertIsInstance(inferred.elts[1], nodes.Unknown) - def test_binop_same_types(self): + def test_binop_same_types(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -2779,7 +2792,7 @@ def __add__(self, other): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected) - def test_binop_different_types_reflected_only(self): + def test_binop_different_types_reflected_only(self) -> None: node = extract_node( """ class A(object): @@ -2794,7 +2807,7 @@ def __radd__(self, other): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_binop_different_types_unknown_bases(self): + def test_binop_different_types_unknown_bases(self) -> None: node = extract_node( """ from foo import bar @@ -2810,7 +2823,7 @@ def __radd__(self, other): inferred = next(node.infer()) self.assertIs(inferred, util.Uninferable) - def test_binop_different_types_normal_not_implemented_and_reflected(self): + def test_binop_different_types_normal_not_implemented_and_reflected(self) -> None: node = extract_node( """ class A(object): @@ -2826,7 +2839,7 @@ def __radd__(self, other): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_binop_different_types_no_method_implemented(self): + def test_binop_different_types_no_method_implemented(self) -> None: node = extract_node( """ class A(object): @@ -2838,7 +2851,7 @@ class B(object): pass inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_binop_different_types_reflected_and_normal_not_implemented(self): + def test_binop_different_types_reflected_and_normal_not_implemented(self) -> None: node = extract_node( """ class A(object): @@ -2851,7 +2864,7 @@ def __radd__(self, other): return NotImplemented inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_binop_subtype(self): + def test_binop_subtype(self) -> None: node = extract_node( """ class A(object): pass @@ -2864,7 +2877,7 @@ def __add__(self, other): return other self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_binop_subtype_implemented_in_parent(self): + def test_binop_subtype_implemented_in_parent(self) -> None: node = extract_node( """ class A(object): @@ -2877,7 +2890,7 @@ class B(A): pass self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_binop_subtype_not_implemented(self): + def test_binop_subtype_not_implemented(self) -> None: node = extract_node( """ class A(object): @@ -2890,7 +2903,7 @@ def __add__(self, other): return NotImplemented inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_binop_supertype(self): + def test_binop_supertype(self) -> None: node = extract_node( """ class A(object): @@ -2905,7 +2918,7 @@ def __radd__(self, other): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_binop_supertype_rop_not_implemented(self): + def test_binop_supertype_rop_not_implemented(self) -> None: node = extract_node( """ class A(object): @@ -2921,7 +2934,7 @@ def __radd__(self, other): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "B") - def test_binop_supertype_both_not_implemented(self): + def test_binop_supertype_both_not_implemented(self) -> None: node = extract_node( """ class A(object): @@ -2935,7 +2948,7 @@ def __radd__(self, other): inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_binop_inference_errors(self): + def test_binop_inference_errors(self) -> None: ast_nodes = extract_node( """ from unknown import Unknown @@ -2952,7 +2965,7 @@ def __add__(self, other): return Unknown for node in ast_nodes: self.assertEqual(next(node.infer()), util.Uninferable) - def test_binop_ambiguity(self): + def test_binop_ambiguity(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -2977,7 +2990,7 @@ def __radd__(self, other): for node in ast_nodes: self.assertEqual(next(node.infer()), util.Uninferable) - def test_metaclass__getitem__(self): + def test_metaclass__getitem__(self) -> None: ast_node = extract_node( """ class Meta(type): @@ -3011,7 +3024,7 @@ class A(six.with_metaclass(Meta)): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 24) - def test_bin_op_classes(self): + def test_bin_op_classes(self) -> None: ast_node = extract_node( """ class Meta(type): @@ -3045,7 +3058,7 @@ class A(six.with_metaclass(Meta)): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 24) - def test_bin_op_supertype_more_complicated_example(self): + def test_bin_op_supertype_more_complicated_example(self) -> None: ast_node = extract_node( """ class A(object): @@ -3067,7 +3080,7 @@ def __radd__(self, other): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(int(inferred.value), 45) - def test_aug_op_same_type_not_implemented(self): + def test_aug_op_same_type_not_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3078,7 +3091,7 @@ def __add__(self, other): return NotImplemented ) self.assertEqual(next(ast_node.infer()), util.Uninferable) - def test_aug_op_same_type_aug_implemented(self): + def test_aug_op_same_type_aug_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3091,7 +3104,7 @@ def __iadd__(self, other): return other self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_aug_op_same_type_aug_not_implemented_normal_implemented(self): + def test_aug_op_same_type_aug_not_implemented_normal_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3105,7 +3118,7 @@ def __add__(self, other): return 42 self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_aug_op_subtype_both_not_implemented(self): + def test_aug_op_subtype_both_not_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3119,7 +3132,7 @@ class B(A): ) self.assertEqual(next(ast_node.infer()), util.Uninferable) - def test_aug_op_subtype_aug_op_is_implemented(self): + def test_aug_op_subtype_aug_op_is_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3134,7 +3147,7 @@ class B(A): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_aug_op_subtype_normal_op_is_implemented(self): + def test_aug_op_subtype_normal_op_is_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3149,7 +3162,7 @@ class B(A): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_aug_different_types_no_method_implemented(self): + def test_aug_different_types_no_method_implemented(self) -> None: ast_node = extract_node( """ class A(object): pass @@ -3160,7 +3173,7 @@ class B(object): pass ) self.assertEqual(next(ast_node.infer()), util.Uninferable) - def test_aug_different_types_augop_implemented(self): + def test_aug_different_types_augop_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3174,7 +3187,7 @@ class B(object): pass self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "B") - def test_aug_different_types_aug_not_implemented(self): + def test_aug_different_types_aug_not_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3189,7 +3202,7 @@ class B(object): pass self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "B") - def test_aug_different_types_aug_not_implemented_rop_fallback(self): + def test_aug_different_types_aug_not_implemented_rop_fallback(self) -> None: ast_node = extract_node( """ class A(object): @@ -3205,7 +3218,7 @@ def __radd__(self, other): return other self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_augop_supertypes_none_implemented(self): + def test_augop_supertypes_none_implemented(self) -> None: ast_node = extract_node( """ class A(object): pass @@ -3216,7 +3229,7 @@ class B(object): pass ) self.assertEqual(next(ast_node.infer()), util.Uninferable) - def test_augop_supertypes_not_implemented_returned_for_all(self): + def test_augop_supertypes_not_implemented_returned_for_all(self) -> None: ast_node = extract_node( """ class A(object): @@ -3230,7 +3243,7 @@ def __add__(self, other): return NotImplemented ) self.assertEqual(next(ast_node.infer()), util.Uninferable) - def test_augop_supertypes_augop_implemented(self): + def test_augop_supertypes_augop_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3244,7 +3257,7 @@ class B(A): pass self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "B") - def test_augop_supertypes_reflected_binop_implemented(self): + def test_augop_supertypes_reflected_binop_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3259,7 +3272,7 @@ def __radd__(self, other): return other self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "A") - def test_augop_supertypes_normal_binop_implemented(self): + def test_augop_supertypes_normal_binop_implemented(self) -> None: ast_node = extract_node( """ class A(object): @@ -3290,7 +3303,7 @@ def test_string_interpolation(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected_value) - def test_mul_list_supports__index__(self): + def test_mul_list_supports__index__(self) -> None: ast_nodes = extract_node( """ class Index(object): @@ -3311,7 +3324,7 @@ def __index__(self): return None inferred = next(rest.infer()) self.assertEqual(inferred, util.Uninferable) - def test_subscript_supports__index__(self): + def test_subscript_supports__index__(self) -> None: ast_nodes = extract_node( """ class Index(object): @@ -3336,7 +3349,7 @@ class NonIndex(object): self.assertEqual(second.value, 2) self.assertRaises(InferenceError, next, ast_nodes[2].infer()) - def test_special_method_masquerading_as_another(self): + def test_special_method_masquerading_as_another(self) -> None: ast_node = extract_node( """ class Info(object): @@ -3352,7 +3365,7 @@ def __add__(self, other): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, "lala") - def test_unary_op_assignment(self): + def test_unary_op_assignment(self) -> None: ast_node = extract_node( """ class A(object): pass @@ -3367,7 +3380,7 @@ def pos(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_unary_op_classes(self): + def test_unary_op_classes(self) -> None: ast_node = extract_node( """ class Meta(type): @@ -3399,14 +3412,30 @@ class A(six.with_metaclass(Meta)): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def _slicing_test_helper(self, pairs, cls, get_elts): + def _slicing_test_helper( + self, + pairs: Tuple[ + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + Tuple[str, Union[List[int], str]], + ], + cls: Union[ABCMeta, type], + get_elts: Callable, + ) -> None: for code, expected in pairs: ast_node = extract_node(code) inferred = next(ast_node.infer()) self.assertIsInstance(inferred, cls) self.assertEqual(get_elts(inferred), expected, ast_node.as_string()) - def test_slicing_list(self): + def test_slicing_list(self) -> None: pairs = ( ("[1, 2, 3][:] #@", [1, 2, 3]), ("[1, 2, 3][0:] #@", [1, 2, 3]), @@ -3425,7 +3454,7 @@ def test_slicing_list(self): pairs, nodes.List, lambda inferred: [elt.value for elt in inferred.elts] ) - def test_slicing_tuple(self): + def test_slicing_tuple(self) -> None: pairs = ( ("(1, 2, 3)[:] #@", [1, 2, 3]), ("(1, 2, 3)[0:] #@", [1, 2, 3]), @@ -3444,7 +3473,7 @@ def test_slicing_tuple(self): pairs, nodes.Tuple, lambda inferred: [elt.value for elt in inferred.elts] ) - def test_slicing_str(self): + def test_slicing_str(self) -> None: pairs = ( ("'123'[:] #@", "123"), ("'123'[0:] #@", "123"), @@ -3461,7 +3490,7 @@ def test_slicing_str(self): ) self._slicing_test_helper(pairs, nodes.Const, lambda inferred: inferred.value) - def test_invalid_slicing_primaries(self): + def test_invalid_slicing_primaries(self) -> None: examples = [ "(lambda x: x)[1:2]", "1[2]", @@ -3474,7 +3503,7 @@ def test_invalid_slicing_primaries(self): node = extract_node(code) self.assertRaises(InferenceError, next, node.infer()) - def test_instance_slicing(self): + def test_instance_slicing(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -3491,7 +3520,7 @@ def __getitem__(self, index): self.assertIsInstance(inferred, nodes.List) self.assertEqual([elt.value for elt in inferred.elts], expected) - def test_instance_slicing_slices(self): + def test_instance_slicing_slices(self) -> None: ast_node = extract_node( """ class A(object): @@ -3505,7 +3534,7 @@ def __getitem__(self, index): self.assertEqual(inferred.lower.value, 1) self.assertIsNone(inferred.upper) - def test_instance_slicing_fails(self): + def test_instance_slicing_fails(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -3518,7 +3547,7 @@ def __getitem__(self, index): for node in ast_nodes: self.assertEqual(next(node.infer()), util.Uninferable) - def test_type__new__with_metaclass(self): + def test_type__new__with_metaclass(self) -> None: ast_node = extract_node( """ class Metaclass(type): @@ -3542,7 +3571,7 @@ class Entity(object): self.assertIsInstance(attributes[0], nodes.Const) self.assertEqual(attributes[0].value, 1) - def test_type__new__not_enough_arguments(self): + def test_type__new__not_enough_arguments(self) -> None: ast_nodes = extract_node( """ type.__new__(type, 'foo') #@ @@ -3554,7 +3583,7 @@ def test_type__new__not_enough_arguments(self): with pytest.raises(InferenceError): next(node.infer()) - def test_type__new__invalid_mcs_argument(self): + def test_type__new__invalid_mcs_argument(self) -> None: ast_nodes = extract_node( """ class Class(object): pass @@ -3566,7 +3595,7 @@ class Class(object): pass with pytest.raises(InferenceError): next(node.infer()) - def test_type__new__invalid_name(self): + def test_type__new__invalid_name(self) -> None: ast_nodes = extract_node( """ class Class(type): pass @@ -3579,7 +3608,7 @@ class Class(type): pass with pytest.raises(InferenceError): next(node.infer()) - def test_type__new__invalid_bases(self): + def test_type__new__invalid_bases(self) -> None: ast_nodes = extract_node( """ type.__new__(type, 'a', 1, 2) #@ @@ -3593,7 +3622,7 @@ def test_type__new__invalid_bases(self): with pytest.raises(InferenceError): next(node.infer()) - def test_type__new__invalid_attrs(self): + def test_type__new__invalid_attrs(self) -> None: type_error_nodes = extract_node( """ type.__new__(type, 'a', (), ()) #@ @@ -3616,7 +3645,7 @@ def test_type__new__invalid_attrs(self): inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.ClassDef) - def test_type__new__metaclass_lookup(self): + def test_type__new__metaclass_lookup(self) -> None: ast_node = extract_node( """ class Metaclass(type): @@ -3644,7 +3673,7 @@ def test1(cls): pass self.assertIsInstance(attr[0], nodes.Const) self.assertEqual(attr[0].value, 42) - def test_type__new__metaclass_and_ancestors_lookup(self): + def test_type__new__metaclass_and_ancestors_lookup(self) -> None: ast_node = extract_node( """ class Book(object): @@ -3688,7 +3717,7 @@ class Book(object, metaclass=metaclass_function): self.assertIsInstance(author, nodes.Const) self.assertEqual(author.value, "Rushdie") - def test_subscript_inference_error(self): + def test_subscript_inference_error(self) -> None: # Used to raise StopIteration ast_node = extract_node( """ @@ -3703,7 +3732,7 @@ def __getitem__(self, name): ) self.assertIsNone(helpers.safe_infer(ast_node.targets[0])) - def test_classmethod_inferred_by_context(self): + def test_classmethod_inferred_by_context(self) -> None: ast_node = extract_node( """ class Super(object): @@ -3724,7 +3753,7 @@ def method(self): self.assertIsInstance(inferred, Instance) self.assertEqual(inferred.name, "Sub") - def test_infer_call_result_invalid_dunder_call_on_instance(self): + def test_infer_call_result_invalid_dunder_call_on_instance(self) -> None: ast_nodes = extract_node( """ class A: @@ -3742,7 +3771,7 @@ class C: inferred = next(node.infer()) self.assertRaises(InferenceError, next, inferred.infer_call_result(node)) - def test_context_call_for_context_managers(self): + def test_context_call_for_context_managers(self) -> None: ast_nodes = extract_node( """ class A: @@ -3773,7 +3802,7 @@ def __enter__(self): self.assertIsInstance(third_c, Instance) self.assertEqual(third_c.name, "A") - def test_metaclass_subclasses_arguments_are_classes_not_instances(self): + def test_metaclass_subclasses_arguments_are_classes_not_instances(self) -> None: ast_node = extract_node( """ class A(type): @@ -3825,7 +3854,7 @@ class B(with_metaclass(A)): self.assertIsInstance(inferred, nodes.ClassDef) self.assertEqual(inferred.name, "B") - def test_infer_cls_in_class_methods(self): + def test_infer_cls_in_class_methods(self) -> None: ast_nodes = extract_node( """ class A(type): @@ -3855,7 +3884,7 @@ def test(cls): return cls self.assertIsInstance(inferred, nodes.ClassDef) self.assertEqual(inferred.name, "A") - def test_metaclass_with_keyword_args(self): + def test_metaclass_with_keyword_args(self) -> None: ast_node = extract_node( """ class TestMetaKlass(type): @@ -3869,7 +3898,7 @@ class TestKlass(metaclass=TestMetaKlass, kwo_arg=42): #@ inferred = next(ast_node.infer()) self.assertIsInstance(inferred, nodes.ClassDef) - def test_metaclass_custom_dunder_call(self): + def test_metaclass_custom_dunder_call(self) -> None: """The Metaclass __call__ should take precedence over the default metaclass type call (initialization) @@ -3893,7 +3922,7 @@ def __call__(self): ) assert val == 1 - def test_metaclass_custom_dunder_call_boundnode(self): + def test_metaclass_custom_dunder_call_boundnode(self) -> None: """The boundnode should be the calling class""" cls = extract_node( """ @@ -3907,7 +3936,7 @@ class Clazz(metaclass=_Meta): ).inferred()[0] assert isinstance(cls, nodes.ClassDef) and cls.name == "Clazz" - def test_infer_subclass_attr_outer_class(self): + def test_infer_subclass_attr_outer_class(self) -> None: node = extract_node( """ class Outer: @@ -3922,7 +3951,7 @@ class Test(Outer): assert isinstance(inferred, nodes.Const) assert inferred.value == 123 - def test_infer_subclass_attr_inner_class_works_indirectly(self): + def test_infer_subclass_attr_inner_class_works_indirectly(self) -> None: node = extract_node( """ class Outer: @@ -3939,7 +3968,7 @@ class Test(Inner): assert isinstance(inferred, nodes.Const) assert inferred.value == 123 - def test_infer_subclass_attr_inner_class(self): + def test_infer_subclass_attr_inner_class(self) -> None: clsdef_node, attr_node = extract_node( """ class Outer: @@ -3966,7 +3995,7 @@ class Test(Outer.Inner): assert isinstance(inferred, nodes.Const) assert inferred.value == 123 - def test_delayed_attributes_without_slots(self): + def test_delayed_attributes_without_slots(self) -> None: ast_node = extract_node( """ class A(object): @@ -3982,7 +4011,7 @@ class A(object): inferred.getattr("teta") inferred.getattr("a") - def test_lambda_as_methods(self): + def test_lambda_as_methods(self) -> None: ast_node = extract_node( """ class X: @@ -3996,7 +4025,7 @@ class X: self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 28) - def test_inner_value_redefined_by_subclass(self): + def test_inner_value_redefined_by_subclass(self) -> None: ast_node = extract_node( """ class X(object): @@ -4042,7 +4071,7 @@ def blurb(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 25) - def test_getitem_of_class_raised_type_error(self): + def test_getitem_of_class_raised_type_error(self) -> None: # Test that we wrap an AttributeInferenceError # and reraise it as a TypeError in Class.getitem node = extract_node( @@ -4056,7 +4085,7 @@ def test(): with self.assertRaises(AstroidTypeError): inferred.getitem(nodes.Const("4")) - def test_infer_arg_called_type_is_uninferable(self): + def test_infer_arg_called_type_is_uninferable(self) -> None: node = extract_node( """ def func(type): @@ -4066,7 +4095,7 @@ def func(type): inferred = next(node.infer()) assert inferred is util.Uninferable - def test_infer_arg_called_object_when_used_as_index_is_uninferable(self): + def test_infer_arg_called_object_when_used_as_index_is_uninferable(self) -> None: node = extract_node( """ def func(object): @@ -4120,7 +4149,7 @@ def inner(): assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type assert inferred is util.Uninferable - def test_infer_subclass_attr_instance_attr_indirect(self): + def test_infer_subclass_attr_instance_attr_indirect(self) -> None: node = extract_node( """ class Parent: @@ -4139,7 +4168,7 @@ class Test(Parent): assert isinstance(const, nodes.Const) assert const.value == 123 - def test_infer_subclass_attr_instance_attr(self): + def test_infer_subclass_attr_instance_attr(self) -> None: node = extract_node( """ class Parent: @@ -4158,7 +4187,7 @@ class Test(Parent): class GetattrTest(unittest.TestCase): - def test_yes_when_unknown(self): + def test_yes_when_unknown(self) -> None: ast_nodes = extract_node( """ from missing import Missing @@ -4180,7 +4209,7 @@ def test_yes_when_unknown(self): inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable, node) - def test_attrname_not_string(self): + def test_attrname_not_string(self) -> None: ast_nodes = extract_node( """ getattr(1, 1) #@ @@ -4191,7 +4220,7 @@ def test_attrname_not_string(self): for node in ast_nodes: self.assertRaises(InferenceError, next, node.infer()) - def test_attribute_missing(self): + def test_attribute_missing(self) -> None: ast_nodes = extract_node( """ getattr(1, 'ala') #@ @@ -4203,7 +4232,7 @@ def test_attribute_missing(self): for node in ast_nodes: self.assertRaises(InferenceError, next, node.infer()) - def test_default(self): + def test_default(self) -> None: ast_nodes = extract_node( """ getattr(1, 'ala', None) #@ @@ -4223,7 +4252,7 @@ def test_default(self): self.assertIsInstance(third, nodes.Const) self.assertIsNone(third.value) - def test_lookup(self): + def test_lookup(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -4269,7 +4298,7 @@ def test(self): self.assertIsInstance(fifth, BoundMethod) self.assertEqual(fifth.bound.name, "X") - def test_lambda(self): + def test_lambda(self) -> None: node = extract_node( """ getattr(lambda x: x, 'f') #@ @@ -4280,7 +4309,7 @@ def test_lambda(self): class HasattrTest(unittest.TestCase): - def test_inference_errors(self): + def test_inference_errors(self) -> None: ast_nodes = extract_node( """ from missing import Missing @@ -4295,7 +4324,7 @@ def test_inference_errors(self): inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_attribute_is_missing(self): + def test_attribute_is_missing(self) -> None: ast_nodes = extract_node( """ class A: pass @@ -4309,7 +4338,7 @@ class A: pass self.assertIsInstance(inferred, nodes.Const) self.assertFalse(inferred.value) - def test_attribute_is_not_missing(self): + def test_attribute_is_not_missing(self) -> None: ast_nodes = extract_node( """ class A(object): @@ -4335,7 +4364,7 @@ def test(self): self.assertIsInstance(inferred, nodes.Const) self.assertTrue(inferred.value) - def test_lambda(self): + def test_lambda(self) -> None: node = extract_node( """ hasattr(lambda x: x, 'f') #@ @@ -4346,7 +4375,7 @@ def test_lambda(self): class BoolOpTest(unittest.TestCase): - def test_bool_ops(self): + def test_bool_ops(self) -> None: expected = [ ("1 and 2", 2), ("0 and 2", 0), @@ -4369,7 +4398,7 @@ def test_bool_ops(self): inferred = next(node.infer()) self.assertEqual(inferred.value, expected_value) - def test_yes_when_unknown(self): + def test_yes_when_unknown(self) -> None: ast_nodes = extract_node( """ from unknown import unknown, any, not_any @@ -4382,7 +4411,7 @@ def test_yes_when_unknown(self): inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_other_nodes(self): + def test_other_nodes(self) -> None: ast_nodes = extract_node( """ def test(): pass @@ -4398,7 +4427,7 @@ def test(): pass class TestCallable(unittest.TestCase): - def test_callable(self): + def test_callable(self) -> None: expected = [ ("callable(len)", True), ('callable("a")', False), @@ -4425,7 +4454,7 @@ def meth(self): pass inferred = next(node.infer()) self.assertEqual(inferred.value, expected_value) - def test_callable_methods(self): + def test_callable_methods(self) -> None: ast_nodes = extract_node( """ class C: @@ -4459,7 +4488,7 @@ class NotReallyCallableDueToPythonMisfeature(object): inferred = next(node.infer()) self.assertTrue(inferred) - def test_inference_errors(self): + def test_inference_errors(self) -> None: ast_nodes = extract_node( """ from unknown import unknown @@ -4473,7 +4502,7 @@ def test(): inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_not_callable(self): + def test_not_callable(self) -> None: ast_nodes = extract_node( """ callable("") #@ @@ -4487,7 +4516,7 @@ def test_not_callable(self): class TestBool(unittest.TestCase): - def test_bool(self): + def test_bool(self) -> None: pairs = [ ("bool()", False), ("bool(1)", True), @@ -4508,7 +4537,7 @@ def test_bool(self): else: self.assertEqual(inferred.value, expected) - def test_bool_bool_special_method(self): + def test_bool_bool_special_method(self) -> None: ast_nodes = extract_node( f""" class FalseClass: @@ -4544,7 +4573,7 @@ def foo(self): return 0 inferred = next(node.infer()) self.assertEqual(inferred.value, expected_value) - def test_bool_instance_not_callable(self): + def test_bool_instance_not_callable(self) -> None: ast_nodes = extract_node( f""" class BoolInvalid(object): @@ -4561,7 +4590,7 @@ class LenInvalid(object): class TestType(unittest.TestCase): - def test_type(self): + def test_type(self) -> None: pairs = [ ("type(1)", "int"), ("type(type)", "type"), @@ -4580,16 +4609,18 @@ def test_type(self): class ArgumentsTest(unittest.TestCase): @staticmethod - def _get_dict_value(inferred): + def _get_dict_value( + inferred: Dict, + ) -> Union[List[Tuple[str, int]], List[Tuple[str, str]]]: items = inferred.items return sorted((key.value, value.value) for key, value in items) @staticmethod - def _get_tuple_value(inferred): + def _get_tuple_value(inferred: Tuple) -> Tuple[int, ...]: elts = inferred.elts return tuple(elt.value for elt in elts) - def test_args(self): + def test_args(self) -> None: expected_values = [ (), (1,), @@ -4643,7 +4674,7 @@ def func(a, b, c=42, *args): self.assertIsInstance(inferred, nodes.Tuple) self.assertEqual(self._get_tuple_value(inferred), expected_value) - def test_multiple_starred_args(self): + def test_multiple_starred_args(self) -> None: expected_values = [(1, 2, 3), (1, 4, 2, 3, 5, 6, 7)] ast_nodes = extract_node( """ @@ -4658,7 +4689,7 @@ def func(a, b, *args): self.assertIsInstance(inferred, nodes.Tuple) self.assertEqual(self._get_tuple_value(inferred), expected_value) - def test_defaults(self): + def test_defaults(self) -> None: expected_values = [42, 3, 41, 42] ast_nodes = extract_node( """ @@ -4675,7 +4706,7 @@ def func(a, b, c=42, *args): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected_value) - def test_kwonly_args(self): + def test_kwonly_args(self) -> None: expected_values = [24, 24, 42, 23, 24, 24, 54] ast_nodes = extract_node( """ @@ -4698,7 +4729,7 @@ def test(a, b, c=42, *args, f=24): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected_value) - def test_kwargs(self): + def test_kwargs(self) -> None: expected = [[("a", 1), ("b", 2), ("c", 3)], [("a", 1)], [("a", "b")]] ast_nodes = extract_node( """ @@ -4715,7 +4746,7 @@ def test(**kwargs): value = self._get_dict_value(inferred) self.assertEqual(value, expected_value) - def test_kwargs_and_other_named_parameters(self): + def test_kwargs_and_other_named_parameters(self) -> None: ast_nodes = extract_node( """ def test(a=42, b=24, **kwargs): @@ -4738,7 +4769,7 @@ def test(a=42, b=24, **kwargs): value = self._get_dict_value(inferred) self.assertEqual(value, expected_value) - def test_kwargs_access_by_name(self): + def test_kwargs_access_by_name(self) -> None: expected_values = [42, 42, 42, 24] ast_nodes = extract_node( """ @@ -4757,7 +4788,7 @@ def test(f=42, **kwargs): self.assertIsInstance(inferred, nodes.Const, inferred) self.assertEqual(inferred.value, value) - def test_multiple_kwargs(self): + def test_multiple_kwargs(self) -> None: expected_value = [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("f", 42)] ast_node = extract_node( """ @@ -4771,7 +4802,7 @@ def test(**kwargs): value = self._get_dict_value(inferred) self.assertEqual(value, expected_value) - def test_kwargs_are_overridden(self): + def test_kwargs_are_overridden(self) -> None: ast_nodes = extract_node( """ def test(f): @@ -4786,7 +4817,7 @@ def test(f=None): inferred = next(ast_node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_fail_to_infer_args(self): + def test_fail_to_infer_args(self) -> None: ast_nodes = extract_node( """ def test(a, **kwargs): return a @@ -4818,7 +4849,7 @@ def test(*args): return args inferred = next(node.infer()) self.assertEqual(inferred, util.Uninferable) - def test_args_overwritten(self): + def test_args_overwritten(self) -> None: # https://github.com/PyCQA/astroid/issues/180 node = extract_node( """ @@ -4838,7 +4869,7 @@ def test(): class SliceTest(unittest.TestCase): - def test_slice(self): + def test_slice(self) -> None: ast_nodes = [ ("[1, 2, 3][slice(None)]", [1, 2, 3]), ("[1, 2, 3][slice(None, None)]", [1, 2, 3]), @@ -4854,7 +4885,7 @@ def test_slice(self): self.assertIsInstance(inferred, nodes.List) self.assertEqual([elt.value for elt in inferred.elts], expected_value) - def test_slice_inference_error(self): + def test_slice_inference_error(self) -> None: ast_nodes = extract_node( """ from unknown import unknown @@ -4871,7 +4902,7 @@ def test_slice_inference_error(self): for node in ast_nodes: self.assertRaises(InferenceError, next, node.infer()) - def test_slice_attributes(self): + def test_slice_attributes(self) -> None: ast_nodes = [ ("slice(2, 3, 4)", (2, 3, 4)), ("slice(None, None, 4)", (None, None, 4)), @@ -4893,7 +4924,7 @@ def test_slice_attributes(self): self.assertEqual(step_value.value, step) self.assertEqual(inferred.pytype(), "builtins.slice") - def test_slice_type(self): + def test_slice_type(self) -> None: ast_node = extract_node("type(slice(None, None, None))") inferred = next(ast_node.infer()) self.assertIsInstance(inferred, nodes.ClassDef) @@ -4902,10 +4933,12 @@ def test_slice_type(self): class CallSiteTest(unittest.TestCase): @staticmethod - def _call_site_from_call(call): + def _call_site_from_call(call: nodes.Call) -> CallSite: return arguments.CallSite.from_call(call) - def _test_call_site_pair(self, code, expected_args, expected_keywords): + def _test_call_site_pair( + self, code: str, expected_args: List[int], expected_keywords: Dict[str, int] + ) -> None: ast_node = extract_node(code) call_site = self._call_site_from_call(ast_node) self.assertEqual(len(call_site.positional_arguments), len(expected_args)) @@ -4917,11 +4950,13 @@ def _test_call_site_pair(self, code, expected_args, expected_keywords): self.assertIn(keyword, call_site.keyword_arguments) self.assertEqual(call_site.keyword_arguments[keyword].value, value) - def _test_call_site(self, pairs): + def _test_call_site( + self, pairs: List[Tuple[str, List[int], Dict[str, int]]] + ) -> None: for pair in pairs: self._test_call_site_pair(*pair) - def test_call_site_starred_args(self): + def test_call_site_starred_args(self) -> None: pairs = [ ( "f(*(1, 2), *(2, 3), *(3, 4), **{'a':1}, **{'b': 2})", @@ -4938,7 +4973,7 @@ def test_call_site_starred_args(self): ] self._test_call_site(pairs) - def test_call_site(self): + def test_call_site(self) -> None: pairs = [ ("f(1, 2)", [1, 2], {}), ("f(1, 2, *(1, 2))", [1, 2, 1, 2], {}), @@ -4946,26 +4981,26 @@ def test_call_site(self): ] self._test_call_site(pairs) - def _test_call_site_valid_arguments(self, values, invalid): + def _test_call_site_valid_arguments(self, values: List[str], invalid: bool) -> None: for value in values: ast_node = extract_node(value) call_site = self._call_site_from_call(ast_node) self.assertEqual(call_site.has_invalid_arguments(), invalid) - def test_call_site_valid_arguments(self): + def test_call_site_valid_arguments(self) -> None: values = ["f(*lala)", "f(*1)", "f(*object)"] self._test_call_site_valid_arguments(values, invalid=True) values = ["f()", "f(*(1, ))", "f(1, 2, *(2, 3))"] self._test_call_site_valid_arguments(values, invalid=False) - def test_duplicated_keyword_arguments(self): + def test_duplicated_keyword_arguments(self) -> None: ast_node = extract_node('f(f=24, **{"f": 25})') site = self._call_site_from_call(ast_node) self.assertIn("f", site.duplicated_keywords) class ObjectDunderNewTest(unittest.TestCase): - def test_object_dunder_new_is_inferred_if_decorator(self): + def test_object_dunder_new_is_inferred_if_decorator(self) -> None: node = extract_node( """ @object.__new__ @@ -4977,7 +5012,7 @@ class instance(object): self.assertIsInstance(inferred, Instance) -def test_augassign_recursion(): +def test_augassign_recursion() -> None: """Make sure inference doesn't throw a RecursionError Regression test for augmented assign dropping context.path @@ -4996,7 +5031,7 @@ def rec(): assert next(cls_node.infer()) is util.Uninferable -def test_infer_custom_inherit_from_property(): +def test_infer_custom_inherit_from_property() -> None: node = extract_node( """ class custom_property(property): @@ -5015,7 +5050,7 @@ def my_prop(self): assert inferred.value == 1 -def test_cannot_infer_call_result_for_builtin_methods(): +def test_cannot_infer_call_result_for_builtin_methods() -> None: node = extract_node( """ a = "fast" @@ -5028,7 +5063,7 @@ def test_cannot_infer_call_result_for_builtin_methods(): next(lenmeth.infer_call_result(None, None)) -def test_unpack_dicts_in_assignment(): +def test_unpack_dicts_in_assignment() -> None: ast_nodes = extract_node( """ a, b = {1:2, 2:3} @@ -5044,7 +5079,7 @@ def test_unpack_dicts_in_assignment(): assert second_inferred.value == 2 -def test_slice_inference_in_for_loops(): +def test_slice_inference_in_for_loops() -> None: node = extract_node( """ for a, (c, *b) in [(1, (2, 3, 4)), (4, (5, 6))]: @@ -5076,7 +5111,7 @@ def test_slice_inference_in_for_loops(): assert inferred.as_string() == "[]" -def test_slice_inference_in_for_loops_not_working(): +def test_slice_inference_in_for_loops_not_working() -> None: ast_nodes = extract_node( """ from unknown import Unknown @@ -5093,7 +5128,7 @@ def test_slice_inference_in_for_loops_not_working(): assert inferred == util.Uninferable -def test_unpacking_starred_and_dicts_in_assignment(): +def test_unpacking_starred_and_dicts_in_assignment() -> None: node = extract_node( """ a, *b = {1:2, 2:3, 3:4} @@ -5115,7 +5150,7 @@ def test_unpacking_starred_and_dicts_in_assignment(): assert inferred.as_string() == "[]" -def test_unpacking_starred_empty_list_in_assignment(): +def test_unpacking_starred_empty_list_in_assignment() -> None: node = extract_node( """ a, *b, c = [1, 2] @@ -5127,7 +5162,7 @@ def test_unpacking_starred_empty_list_in_assignment(): assert inferred.as_string() == "[]" -def test_regression_infinite_loop_decorator(): +def test_regression_infinite_loop_decorator() -> None: """Make sure decorators with the same names as a decorated method do not cause an infinite loop @@ -5148,7 +5183,7 @@ def lru_cache(self, value): assert result.value == 1 -def test_stop_iteration_in_int(): +def test_stop_iteration_in_int() -> None: """Handle StopIteration error in infer_int.""" code = """ def f(lst): @@ -5166,7 +5201,7 @@ def f(lst): assert second_result.name == "int" -def test_call_on_instance_with_inherited_dunder_call_method(): +def test_call_on_instance_with_inherited_dunder_call_method() -> None: """Stop inherited __call__ method from incorrectly returning wrong class See https://github.com/PyCQA/pylint/issues/2199 @@ -5208,7 +5243,7 @@ def test(a, b, c): ) assert next(n.infer()).as_string() == "16" - def test_call_starargs_propagation(self): + def test_call_starargs_propagation(self) -> None: code = """ def foo(*args): return args @@ -5218,7 +5253,7 @@ def bar(*args): """ assert next(extract_node(code).infer()).as_string() == "(4, 5, 6, 7)" - def test_call_kwargs_propagation(self): + def test_call_kwargs_propagation(self) -> None: code = """ def b(**kwargs): return kwargs @@ -5229,7 +5264,7 @@ def f(**kwargs): assert next(extract_node(code).infer()).as_string() == "{'f': 1}" -def test_limit_inference_result_amount(): +def test_limit_inference_result_amount() -> None: """Test setting limit inference result amount""" code = """ args = [] @@ -5258,7 +5293,7 @@ def test_limit_inference_result_amount(): assert util.Uninferable in result_limited -def test_attribute_inference_should_not_access_base_classes(): +def test_attribute_inference_should_not_access_base_classes() -> None: """attributes of classes should mask ancestor attribues""" code = """ type.__new__ #@ @@ -5268,7 +5303,7 @@ def test_attribute_inference_should_not_access_base_classes(): assert res[0].parent.name == "type" -def test_attribute_mro_object_inference(): +def test_attribute_mro_object_inference() -> None: """ Inference should only infer results from the first available method """ @@ -5287,7 +5322,7 @@ def foo(self): assert inferred[0].value == 2 -def test_inferred_sequence_unpacking_works(): +def test_inferred_sequence_unpacking_works() -> None: inferred = next( extract_node( """ @@ -5302,7 +5337,7 @@ def test(*args): assert [value.value for value in inferred.elts] == [1, 2] -def test_recursion_error_inferring_slice(): +def test_recursion_error_inferring_slice() -> None: node = extract_node( """ class MyClass: @@ -5320,7 +5355,7 @@ def test(self): assert isinstance(inferred, Slice) -def test_exception_lookup_last_except_handler_wins(): +def test_exception_lookup_last_except_handler_wins() -> None: node = extract_node( """ try: @@ -5358,7 +5393,7 @@ def test_exception_lookup_last_except_handler_wins(): assert inferred_exc.name == "ValueError" -def test_exception_lookup_name_bound_in_except_handler(): +def test_exception_lookup_name_bound_in_except_handler() -> None: node = extract_node( """ try: @@ -5379,7 +5414,7 @@ def test_exception_lookup_name_bound_in_except_handler(): assert inferred_exc.value == 2 -def test_builtin_inference_list_of_exceptions(): +def test_builtin_inference_list_of_exceptions() -> None: node = extract_node( """ tuple([ValueError, TypeError]) @@ -5409,7 +5444,7 @@ def test_builtin_inference_list_of_exceptions(): assert as_string.strip() == "(ValueError, TypeError)" -def test_cannot_getattr_ann_assigns(): +def test_cannot_getattr_ann_assigns() -> None: node = extract_node( """ class Cls: @@ -5432,7 +5467,7 @@ class Cls: assert len(values) == 1 -def test_prevent_recursion_error_in_igetattr_and_context_manager_inference(): +def test_prevent_recursion_error_in_igetattr_and_context_manager_inference() -> None: code = """ class DummyContext(object): def __enter__(self): @@ -5456,7 +5491,7 @@ def __exit__(self, ex_type, ex_value, ex_tb): next(node.infer()) -def test_infer_context_manager_with_unknown_args(): +def test_infer_context_manager_with_unknown_args() -> None: code = """ class client_log(object): def __init__(self, client): @@ -5513,7 +5548,7 @@ def test_subclass_of_exception(code): assert isinstance(args, nodes.Tuple) -def test_ifexp_inference(): +def test_ifexp_inference() -> None: code = """ def truth_branch(): return 1 if True else 2 @@ -5542,7 +5577,7 @@ def both_branches(): assert [third[0].value, third[1].value] == [1, 2] -def test_assert_last_function_returns_none_on_inference(): +def test_assert_last_function_returns_none_on_inference() -> None: code = """ def check_equal(a, b): res = do_something_with_these(a, b) @@ -5557,7 +5592,7 @@ def check_equal(a, b): @test_utils.require_version(minver="3.8") -def test_posonlyargs_inference(): +def test_posonlyargs_inference() -> None: code = """ class A: method = lambda self, b, /, c: b + c @@ -5582,7 +5617,7 @@ def __init__(self, other=(), /, **kw): assert inferred.type == "method" -def test_infer_args_unpacking_of_self(): +def test_infer_args_unpacking_of_self() -> None: code = """ class A: def __init__(*args, **kwargs): @@ -5601,7 +5636,7 @@ def __init__(*args, **kwargs): assert inferred_data.as_string() == "{1: 2}" -def test_infer_exception_instance_attributes(): +def test_infer_exception_instance_attributes() -> None: code = """ class UnsupportedFormatCharacter(Exception): def __init__(self, index): @@ -5673,7 +5708,7 @@ def test_inference_is_limited_to_the_boundnode(code, instance_name): assert inferred.name == instance_name -def test_property_inference(): +def test_property_inference() -> None: code = """ class A: @property @@ -5725,7 +5760,7 @@ def test(self, value): assert isinstance(inferred, nodes.FunctionDef) -def test_property_as_string(): +def test_property_as_string() -> None: code = """ class A: @property @@ -5747,7 +5782,7 @@ def test(self): assert inferred.as_string().strip() == property_body.strip() -def test_property_callable_inference(): +def test_property_callable_inference() -> None: code = """ class A: def func(self): @@ -5772,7 +5807,7 @@ class A: assert inferred.value == 42 -def test_recursion_error_inferring_builtin_containers(): +def test_recursion_error_inferring_builtin_containers() -> None: node = extract_node( """ class Foo: @@ -5786,7 +5821,7 @@ class Foo: helpers.safe_infer(node.targets[0]) -def test_inferaugassign_picking_parent_instead_of_stmt(): +def test_inferaugassign_picking_parent_instead_of_stmt() -> None: code = """ from collections import namedtuple SomeClass = namedtuple('SomeClass', ['name']) @@ -5804,7 +5839,7 @@ def test_inferaugassign_picking_parent_instead_of_stmt(): assert inferred.name == "SomeClass" -def test_classmethod_from_builtins_inferred_as_bound(): +def test_classmethod_from_builtins_inferred_as_bound() -> None: code = """ import builtins @@ -5825,7 +5860,7 @@ def bar2(cls, text): assert isinstance(next(second_node.infer()), BoundMethod) -def test_infer_dict_passes_context(): +def test_infer_dict_passes_context() -> None: code = """ k = {} (_ for k in __(dict(**k))) @@ -5964,7 +5999,7 @@ class ProxyConfig: assert infer_val.pytype() == ".ProxyConfig" -def test_self_reference_infer_does_not_trigger_recursion_error(): +def test_self_reference_infer_does_not_trigger_recursion_error() -> None: # Prevents https://github.com/PyCQA/pylint/issues/1285 code = """ def func(elems): @@ -5981,7 +6016,7 @@ def __init__(self, *args, **kwargs): assert inferred is util.Uninferable -def test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times(): +def test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times() -> None: code = """ class A: @property @@ -6003,7 +6038,7 @@ def a(self): assert len(a_locals) == 2 -def test_getattr_fails_on_empty_values(): +def test_getattr_fails_on_empty_values() -> None: code = """ import collections collections @@ -6017,7 +6052,7 @@ def test_getattr_fails_on_empty_values(): inferred.getattr("") -def test_infer_first_argument_of_static_method_in_metaclass(): +def test_infer_first_argument_of_static_method_in_metaclass() -> None: code = """ class My(type): @staticmethod @@ -6029,7 +6064,7 @@ def test(args): assert inferred is util.Uninferable -def test_recursion_error_metaclass_monkeypatching(): +def test_recursion_error_metaclass_monkeypatching() -> None: module = resources.build_file( "data/metaclass_recursion/monkeypatch.py", "data.metaclass_recursion" ) @@ -6039,7 +6074,7 @@ def test_recursion_error_metaclass_monkeypatching(): @pytest.mark.xfail(reason="Cannot fully infer all the base classes properly.") -def test_recursion_error_self_reference_type_call(): +def test_recursion_error_self_reference_type_call() -> None: # Fix for https://github.com/PyCQA/astroid/issues/199 code = """ class A(object): @@ -6058,7 +6093,7 @@ def __init__(self): assert [cls.name for cls in inferred.mro()] == ["B", "A", "object"] -def test_allow_retrieving_instance_attrs_and_special_attrs_for_functions(): +def test_allow_retrieving_instance_attrs_and_special_attrs_for_functions() -> None: code = """ class A: def test(self): @@ -6074,7 +6109,7 @@ def test(self): assert len(attrs) == 2 -def test_implicit_parameters_bound_method(): +def test_implicit_parameters_bound_method() -> None: code = """ class A(type): @classmethod @@ -6095,7 +6130,7 @@ def __new__(cls, name, bases, dictionary): assert dunder_new.implicit_parameters() == 0 -def test_super_inference_of_abstract_property(): +def test_super_inference_of_abstract_property() -> None: code = """ from abc import abstractmethod @@ -6123,7 +6158,7 @@ def test(self): assert len(test) == 2 -def test_infer_generated_setter(): +def test_infer_generated_setter() -> None: code = """ class A: @property @@ -6140,7 +6175,7 @@ def test(self): assert list(inferred.nodes_of_class(nodes.Const)) == [] -def test_infer_list_of_uninferables_does_not_crash(): +def test_infer_list_of_uninferables_does_not_crash() -> None: code = """ x = [A] * 1 f = [x, [A] * 2] @@ -6155,7 +6190,7 @@ def test_infer_list_of_uninferables_does_not_crash(): # https://github.com/PyCQA/astroid/issues/926 -def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable(): +def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable() -> None: code = """ pair = [1, 2] ex = pair[0] @@ -6173,7 +6208,7 @@ def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable(): # https://github.com/PyCQA/astroid/issues/926 -def test_issue926_binop_referencing_same_name_is_not_uninferable(): +def test_issue926_binop_referencing_same_name_is_not_uninferable() -> None: code = """ pair = [1, 2] ex = pair[0] + pair[1] @@ -6186,7 +6221,7 @@ def test_issue926_binop_referencing_same_name_is_not_uninferable(): assert inferred[0].value == 3 -def test_pylint_issue_4692_attribute_inference_error_in_infer_import_from(): +def test_pylint_issue_4692_attribute_inference_error_in_infer_import_from() -> None: """https://github.com/PyCQA/pylint/issues/4692""" code = """ import click @@ -6200,7 +6235,7 @@ def test_pylint_issue_4692_attribute_inference_error_in_infer_import_from(): list(node.infer()) -def test_issue_1090_infer_yield_type_base_class(): +def test_issue_1090_infer_yield_type_base_class() -> None: code = """ import contextlib diff --git a/tests/unittest_inference_calls.py b/tests/unittest_inference_calls.py index c14a8619a8..3ffcca2ab8 100644 --- a/tests/unittest_inference_calls.py +++ b/tests/unittest_inference_calls.py @@ -4,7 +4,7 @@ from astroid.util import Uninferable -def test_no_return(): +def test_no_return() -> None: """Test function with no return statements""" node = builder.extract_node( """ @@ -19,7 +19,7 @@ def f(): assert inferred[0] is Uninferable -def test_one_return(): +def test_one_return() -> None: """Test function with a single return that always executes""" node = builder.extract_node( """ @@ -35,7 +35,7 @@ def f(): assert inferred[0].value == 1 -def test_one_return_possible(): +def test_one_return_possible() -> None: """Test function with a single return that only sometimes executes Note: currently, inference doesn't handle this type of control flow @@ -55,7 +55,7 @@ def f(x): assert inferred[0].value == 1 -def test_multiple_returns(): +def test_multiple_returns() -> None: """Test function with multiple returns""" node = builder.extract_node( """ @@ -76,7 +76,7 @@ def f(x): assert {node.value for node in inferred} == {1, 2, 3} -def test_argument(): +def test_argument() -> None: """Test function whose return value uses its arguments""" node = builder.extract_node( """ @@ -92,7 +92,7 @@ def f(x, y): assert inferred[0].value == 3 -def test_inner_call(): +def test_inner_call() -> None: """Test function where return value is the result of a separate function call""" node = builder.extract_node( """ @@ -111,7 +111,7 @@ def g(): assert inferred[0].value == 1 -def test_inner_call_with_const_argument(): +def test_inner_call_with_const_argument() -> None: """Test function where return value is the result of a separate function call, with a constant value passed to the inner function. """ @@ -132,7 +132,7 @@ def g(y): assert inferred[0].value == 3 -def test_inner_call_with_dynamic_argument(): +def test_inner_call_with_dynamic_argument() -> None: """Test function where return value is the result of a separate function call, with a dynamic value passed to the inner function. @@ -154,7 +154,7 @@ def g(y): assert inferred[0] is Uninferable -def test_method_const_instance_attr(): +def test_method_const_instance_attr() -> None: """Test method where the return value is based on an instance attribute with a constant value. """ @@ -176,7 +176,7 @@ def get_x(self): assert inferred[0].value == 1 -def test_method_const_instance_attr_multiple(): +def test_method_const_instance_attr_multiple() -> None: """Test method where the return value is based on an instance attribute with multiple possible constant values, across different methods. """ @@ -204,7 +204,7 @@ def get_x(self): assert {node.value for node in inferred} == {1, 2, 3} -def test_method_const_instance_attr_same_method(): +def test_method_const_instance_attr_same_method() -> None: """Test method where the return value is based on an instance attribute with multiple possible constant values, including in the method being called. @@ -237,7 +237,7 @@ def get_x(self): assert {node.value for node in inferred} == {1, 2, 3, 4} -def test_method_dynamic_instance_attr_1(): +def test_method_dynamic_instance_attr_1() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in a different method. @@ -260,7 +260,7 @@ def get_x(self): assert inferred[0] is Uninferable -def test_method_dynamic_instance_attr_2(): +def test_method_dynamic_instance_attr_2() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in the same method. """ @@ -282,7 +282,7 @@ def get_x(self, x): assert inferred[0].value == 1 -def test_method_dynamic_instance_attr_3(): +def test_method_dynamic_instance_attr_3() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in a different method. @@ -305,7 +305,7 @@ def set_x(self, x): assert inferred[0] is Uninferable # not 10! -def test_method_dynamic_instance_attr_4(): +def test_method_dynamic_instance_attr_4() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in a different method, and is passed a constant value. @@ -331,7 +331,7 @@ def set_x(self, x): assert inferred[0] is Uninferable -def test_method_dynamic_instance_attr_5(): +def test_method_dynamic_instance_attr_5() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in a different method, and is passed a constant value. @@ -361,7 +361,7 @@ def set_x(self, x): assert inferred[0] is Uninferable -def test_method_dynamic_instance_attr_6(): +def test_method_dynamic_instance_attr_6() -> None: """Test method where the return value is based on an instance attribute with a dynamically-set value in a different method, and is passed a dynamic value. @@ -387,7 +387,7 @@ def set_x(self, x): assert inferred[0] is Uninferable -def test_dunder_getitem(): +def test_dunder_getitem() -> None: """Test for the special method __getitem__ (used by Instance.getitem). This is currently Uninferable, until we can infer instance attribute values through @@ -411,7 +411,7 @@ def __getitem__(self, i): assert inferred[0] is Uninferable -def test_instance_method(): +def test_instance_method() -> None: """Tests for instance method, both bound and unbound.""" nodes_ = builder.extract_node( """ @@ -433,7 +433,7 @@ def method(self, x): assert inferred[0].value == 42 -def test_class_method(): +def test_class_method() -> None: """Tests for class method calls, both instance and with the class.""" nodes_ = builder.extract_node( """ @@ -455,7 +455,7 @@ def method(cls, x): assert inferred[0].value == 42 -def test_static_method(): +def test_static_method() -> None: """Tests for static method calls, both instance and with the class.""" nodes_ = builder.extract_node( """ @@ -476,7 +476,7 @@ def method(x): assert inferred[0].value == 42 -def test_instance_method_inherited(): +def test_instance_method_inherited() -> None: """Tests for instance methods that are inherited from a superclass. Based on https://github.com/PyCQA/astroid/issues/1008. @@ -506,7 +506,7 @@ class B(A): assert inferred[0].name == expected -def test_class_method_inherited(): +def test_class_method_inherited() -> None: """Tests for class methods that are inherited from a superclass. Based on https://github.com/PyCQA/astroid/issues/1008. @@ -536,7 +536,7 @@ class B(A): assert inferred[0].name == expected -def test_chained_attribute_inherited(): +def test_chained_attribute_inherited() -> None: """Tests for class methods that are inherited from a superclass. Based on https://github.com/PyCQA/pylint/issues/4220. diff --git a/tests/unittest_lookup.py b/tests/unittest_lookup.py index fcd33a42b4..8de88b831d 100644 --- a/tests/unittest_lookup.py +++ b/tests/unittest_lookup.py @@ -29,13 +29,13 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase): - def setUp(self): + def setUp(self) -> None: super().setUp() self.module = resources.build_file("data/module.py", "data.module") self.module2 = resources.build_file("data/module2.py", "data.module2") self.nonregr = resources.build_file("data/nonregr.py", "data.nonregr") - def test_limit(self): + def test_limit(self) -> None: code = """ l = [a for a,b in list] @@ -65,7 +65,7 @@ def func(): func = astroid.locals["func"][0] self.assertEqual(len(func.lookup("c")[1]), 1) - def test_module(self): + def test_module(self) -> None: astroid = builder.parse("pass", __name__) # built-in objects none = next(astroid.ilookup("None")) @@ -80,7 +80,7 @@ def test_module(self): # XXX self.assertEqual(len(list(self.nonregr.ilookup("enumerate"))), 2) - def test_class_ancestor_name(self): + def test_class_ancestor_name(self) -> None: code = """ class A: pass @@ -95,7 +95,7 @@ class A(A): self.assertEqual(next(name.infer()), cls1) ### backport those test to inline code - def test_method(self): + def test_method(self) -> None: method = self.module["YOUPI"]["method"] my_dict = next(method.ilookup("MY_DICT")) self.assertTrue(isinstance(my_dict, nodes.Dict), my_dict) @@ -105,14 +105,14 @@ def test_method(self): InferenceError, functools.partial(next, method.ilookup("YOAA")) ) - def test_function_argument_with_default(self): + def test_function_argument_with_default(self) -> None: make_class = self.module2["make_class"] base = next(make_class.ilookup("base")) self.assertTrue(isinstance(base, nodes.ClassDef), base.__class__) self.assertEqual(base.name, "YO") self.assertEqual(base.root().name, "data.module") - def test_class(self): + def test_class(self) -> None: klass = self.module["YOUPI"] my_dict = next(klass.ilookup("MY_DICT")) self.assertIsInstance(my_dict, nodes.Dict) @@ -125,11 +125,11 @@ def test_class(self): InferenceError, functools.partial(next, klass.ilookup("YOAA")) ) - def test_inner_classes(self): + def test_inner_classes(self) -> None: ddd = list(self.nonregr["Ccc"].ilookup("Ddd")) self.assertEqual(ddd[0].name, "Ddd") - def test_loopvar_hiding(self): + def test_loopvar_hiding(self) -> None: astroid = builder.parse( """ x = 10 @@ -148,7 +148,7 @@ def test_loopvar_hiding(self): self.assertEqual(len(xnames[1].lookup("x")[1]), 2) self.assertEqual(len(xnames[2].lookup("x")[1]), 2) - def test_list_comps(self): + def test_list_comps(self) -> None: astroid = builder.parse( """ print ([ i for i in range(10) ]) @@ -165,7 +165,7 @@ def test_list_comps(self): self.assertEqual(len(xnames[2].lookup("i")[1]), 1) self.assertEqual(xnames[2].lookup("i")[1][0].lineno, 4) - def test_list_comp_target(self): + def test_list_comp_target(self) -> None: """test the list comprehension target""" astroid = builder.parse( """ @@ -176,7 +176,7 @@ def test_list_comp_target(self): var = astroid.body[1].value self.assertRaises(NameInferenceError, var.inferred) - def test_dict_comps(self): + def test_dict_comps(self) -> None: astroid = builder.parse( """ print ({ i: j for i in range(10) for j in range(10) }) @@ -196,7 +196,7 @@ def test_dict_comps(self): self.assertEqual(len(xnames[1].lookup("i")[1]), 1) self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3) - def test_set_comps(self): + def test_set_comps(self) -> None: astroid = builder.parse( """ print ({ i for i in range(10) }) @@ -210,7 +210,7 @@ def test_set_comps(self): self.assertEqual(len(xnames[1].lookup("i")[1]), 1) self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3) - def test_set_comp_closure(self): + def test_set_comp_closure(self) -> None: astroid = builder.parse( """ ten = { var for var in range(10) } @@ -220,7 +220,7 @@ def test_set_comp_closure(self): var = astroid.body[1].value self.assertRaises(NameInferenceError, var.inferred) - def test_list_comp_nested(self): + def test_list_comp_nested(self) -> None: astroid = builder.parse( """ x = [[i + j for j in range(20)] @@ -232,7 +232,7 @@ def test_list_comp_nested(self): self.assertEqual(len(xnames[0].lookup("i")[1]), 1) self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3) - def test_dict_comp_nested(self): + def test_dict_comp_nested(self) -> None: astroid = builder.parse( """ x = {i: {i: j for j in range(20)} @@ -248,7 +248,7 @@ def test_dict_comp_nested(self): self.assertEqual(len(xnames[1].lookup("i")[1]), 1) self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3) - def test_set_comp_nested(self): + def test_set_comp_nested(self) -> None: astroid = builder.parse( """ x = [{i + j for j in range(20)} # Can't do nested sets @@ -260,7 +260,7 @@ def test_set_comp_nested(self): self.assertEqual(len(xnames[0].lookup("i")[1]), 1) self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3) - def test_lambda_nested(self): + def test_lambda_nested(self) -> None: astroid = builder.parse( """ f = lambda x: ( @@ -271,7 +271,7 @@ def test_lambda_nested(self): self.assertEqual(len(xnames[0].lookup("x")[1]), 1) self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2) - def test_function_nested(self): + def test_function_nested(self) -> None: astroid = builder.parse( """ def f1(x): @@ -285,7 +285,7 @@ def f2(y): self.assertEqual(len(xnames[0].lookup("x")[1]), 1) self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2) - def test_class_variables(self): + def test_class_variables(self) -> None: # Class variables are NOT available within nested scopes. astroid = builder.parse( """ @@ -308,7 +308,7 @@ class _Inner: for name in names: self.assertRaises(NameInferenceError, name.inferred) - def test_class_in_function(self): + def test_class_in_function(self) -> None: # Function variables are available within classes, including methods astroid = builder.parse( """ @@ -334,7 +334,7 @@ class _Inner: self.assertEqual(len(name.lookup("x")[1]), 1, repr(name)) self.assertEqual(name.lookup("x")[1][0].lineno, 3, repr(name)) - def test_generator_attributes(self): + def test_generator_attributes(self) -> None: tree = builder.parse( """ def count(): @@ -352,7 +352,7 @@ def count(): self.assertIsInstance(gener.getattr("throw")[0], nodes.FunctionDef) self.assertIsInstance(gener.getattr("close")[0], nodes.FunctionDef) - def test_explicit___name__(self): + def test_explicit___name__(self) -> None: code = """ class Pouet: __name__ = "pouet" @@ -373,7 +373,7 @@ class NoName: pass p3 = next(astroid["p3"].infer()) self.assertRaises(AttributeInferenceError, p3.getattr, "__name__") - def test_function_module_special(self): + def test_function_module_special(self) -> None: astroid = builder.parse( ''' def initialize(linter): @@ -387,7 +387,7 @@ def initialize(linter): ] self.assertEqual(len(path.lookup("__path__")[1]), 1) - def test_builtin_lookup(self): + def test_builtin_lookup(self) -> None: self.assertEqual(nodes.builtin_lookup("__dict__")[1], ()) intstmts = nodes.builtin_lookup("int")[1] self.assertEqual(len(intstmts), 1) @@ -396,7 +396,7 @@ def test_builtin_lookup(self): # pylint: disable=no-member; Infers two potential values self.assertIs(intstmts[0], nodes.const_factory(1)._proxied) - def test_decorator_arguments_lookup(self): + def test_decorator_arguments_lookup(self) -> None: code = """ def decorator(value): def wrapper(function): @@ -420,7 +420,7 @@ def test(self): self.assertEqual(obj.value, 10) self.assertRaises(StopIteration, functools.partial(next, it)) - def test_inner_decorator_member_lookup(self): + def test_inner_decorator_member_lookup(self) -> None: code = """ class FileA: def decorator(bla): @@ -436,7 +436,7 @@ def funcA(): self.assertIsInstance(obj, nodes.FunctionDef) self.assertRaises(StopIteration, functools.partial(next, it)) - def test_static_method_lookup(self): + def test_static_method_lookup(self) -> None: code = """ class FileA: @staticmethod @@ -456,7 +456,7 @@ def __init__(self): self.assertIsInstance(obj, nodes.ClassDef) self.assertRaises(StopIteration, functools.partial(next, it)) - def test_global_delete(self): + def test_global_delete(self) -> None: code = """ def run2(): f = Frobble() @@ -480,7 +480,7 @@ def run1(): class LookupControlFlowTest(unittest.TestCase): """Tests for lookup capabilities and control flow""" - def test_consecutive_assign(self): + def test_consecutive_assign(self) -> None: """When multiple assignment statements are in the same block, only the last one is returned. """ @@ -495,7 +495,7 @@ def test_consecutive_assign(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 3) - def test_assign_after_use(self): + def test_assign_after_use(self) -> None: """An assignment statement appearing after the variable is not returned.""" code = """ print(x) @@ -506,7 +506,7 @@ def test_assign_after_use(self): _, stmts = x_name.lookup("x") self.assertEqual(len(stmts), 0) - def test_del_removes_prior(self): + def test_del_removes_prior(self) -> None: """Delete statement removes any prior assignments""" code = """ x = 10 @@ -518,7 +518,7 @@ def test_del_removes_prior(self): _, stmts = x_name.lookup("x") self.assertEqual(len(stmts), 0) - def test_del_no_effect_after(self): + def test_del_no_effect_after(self) -> None: """Delete statement doesn't remove future assignments""" code = """ x = 10 @@ -532,7 +532,7 @@ def test_del_no_effect_after(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 4) - def test_if_assign(self): + def test_if_assign(self) -> None: """Assignment in if statement is added to lookup results, but does not replace prior assignments. """ @@ -549,7 +549,7 @@ def f(b): self.assertEqual(len(stmts), 2) self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5]) - def test_if_assigns_same_branch(self): + def test_if_assigns_same_branch(self) -> None: """When if branch has multiple assignment statements, only the last one is added. """ @@ -567,7 +567,7 @@ def f(b): self.assertEqual(len(stmts), 2) self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6]) - def test_if_assigns_different_branch(self): + def test_if_assigns_different_branch(self) -> None: """When different branches have assignment statements, the last one in each branch is added. """ @@ -589,7 +589,7 @@ def f(b): self.assertEqual(len(stmts), 4) self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6, 8, 10]) - def test_assign_exclusive(self): + def test_assign_exclusive(self) -> None: """When the variable appears inside a branch of an if statement, no assignment statements from other branches are returned. """ @@ -612,7 +612,7 @@ def f(b): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 3) - def test_assign_not_exclusive(self): + def test_assign_not_exclusive(self) -> None: """When the variable appears inside a branch of an if statement, only the last assignment statement in the same branch is returned. """ @@ -636,7 +636,7 @@ def f(b): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 10) - def test_if_else(self): + def test_if_else(self) -> None: """When an assignment statement appears in both an if and else branch, both are added. This does NOT replace an assignment statement appearing before the if statement. (See issue #213) @@ -656,7 +656,7 @@ def f(b): self.assertEqual(len(stmts), 3) self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5, 7]) - def test_if_variable_in_condition_1(self): + def test_if_variable_in_condition_1(self) -> None: """Test lookup works correctly when a variable appears in an if condition.""" code = """ x = 10 @@ -678,7 +678,7 @@ def test_if_variable_in_condition_1(self): self.assertEqual(len(stmts2), 1) self.assertEqual(stmts2[0].lineno, 2) - def test_if_variable_in_condition_2(self): + def test_if_variable_in_condition_2(self) -> None: """Test lookup works correctly when a variable appears in an if condition, and the variable is reassigned in each branch. @@ -704,7 +704,7 @@ def test_if_variable_in_condition_2(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 2) - def test_del_not_exclusive(self): + def test_del_not_exclusive(self) -> None: """A delete statement in an if statement branch removes all previous assignment statements when the delete statement is not exclusive with the variable (e.g., when the variable is used below the if statement). @@ -726,7 +726,7 @@ def f(b): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 9) - def test_del_exclusive(self): + def test_del_exclusive(self) -> None: """A delete statement in an if statement branch that is exclusive with the variable does not remove previous assignment statements. """ @@ -746,7 +746,7 @@ def f(b): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 3) - def test_assign_after_param(self): + def test_assign_after_param(self) -> None: """When an assignment statement overwrites a function parameter, only the assignment is returned, even when the variable and assignment do not have the same parent. @@ -773,7 +773,7 @@ def f2(x): self.assertEqual(len(stmts2), 1) self.assertEqual(stmts2[0].lineno, 7) - def test_assign_after_kwonly_param(self): + def test_assign_after_kwonly_param(self) -> None: """When an assignment statement overwrites a function keyword-only parameter, only the assignment is returned, even when the variable and assignment do not have the same parent. @@ -828,7 +828,7 @@ def f2(x, /): self.assertEqual(len(stmts2), 1) self.assertEqual(stmts2[0].lineno, 7) - def test_assign_after_args_param(self): + def test_assign_after_args_param(self) -> None: """When an assignment statement overwrites a function parameter, only the assignment is returned. """ @@ -852,7 +852,7 @@ def f(*args, **kwargs): self.assertEqual(len(stmts2), 1) self.assertEqual(stmts2[0].lineno, 4) - def test_except_var_in_block(self): + def test_except_var_in_block(self) -> None: """When the variable bound to an exception in an except clause, it is returned when that variable is used inside the except block. """ @@ -868,7 +868,7 @@ def test_except_var_in_block(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 4) - def test_except_var_in_block_overwrites(self): + def test_except_var_in_block_overwrites(self) -> None: """When the variable bound to an exception in an except clause, it is returned when that variable is used inside the except block, and replaces any previous assignments. @@ -886,7 +886,7 @@ def test_except_var_in_block_overwrites(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 5) - def test_except_var_in_multiple_blocks(self): + def test_except_var_in_multiple_blocks(self) -> None: """When multiple variables with the same name are bound to an exception in an except clause, and the variable is used inside the except block, only the assignment from the corresponding except clause is returned. @@ -911,7 +911,7 @@ def test_except_var_in_multiple_blocks(self): self.assertEqual(len(stmts2), 1) self.assertEqual(stmts2[0].lineno, 7) - def test_except_var_after_block_single(self): + def test_except_var_after_block_single(self) -> None: """When the variable bound to an exception in an except clause, it is NOT returned when that variable is used after the except block. """ @@ -927,7 +927,7 @@ def test_except_var_after_block_single(self): _, stmts = x_name.lookup("e") self.assertEqual(len(stmts), 0) - def test_except_var_after_block_multiple(self): + def test_except_var_after_block_multiple(self) -> None: """When the variable bound to an exception in multiple except clauses, it is NOT returned when that variable is used after the except blocks. """ @@ -945,7 +945,7 @@ def test_except_var_after_block_multiple(self): _, stmts = x_name.lookup("e") self.assertEqual(len(stmts), 0) - def test_except_assign_in_block(self): + def test_except_assign_in_block(self) -> None: """When a variable is assigned in an except block, it is returned when that variable is used in the except block. """ @@ -962,7 +962,7 @@ def test_except_assign_in_block(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 5) - def test_except_assign_in_block_multiple(self): + def test_except_assign_in_block_multiple(self) -> None: """When a variable is assigned in multiple except blocks, and the variable is used in one of the blocks, only the assignments in that block are returned. """ @@ -981,7 +981,7 @@ def test_except_assign_in_block_multiple(self): self.assertEqual(len(stmts), 1) self.assertEqual(stmts[0].lineno, 7) - def test_except_assign_after_block(self): + def test_except_assign_after_block(self) -> None: """When a variable is assigned in an except clause, it is returned when that variable is used after the except block. """ @@ -1000,7 +1000,7 @@ def test_except_assign_after_block(self): self.assertEqual(len(stmts), 2) self.assertCountEqual([stmt.lineno for stmt in stmts], [5, 7]) - def test_except_assign_after_block_overwritten(self): + def test_except_assign_after_block_overwritten(self) -> None: """When a variable is assigned in an except clause, it is not returned when it is reassigned and used after the except block. """ diff --git a/tests/unittest_manager.py b/tests/unittest_manager.py index b81513b191..43563de6cc 100644 --- a/tests/unittest_manager.py +++ b/tests/unittest_manager.py @@ -27,6 +27,7 @@ import time import unittest from contextlib import contextmanager +from typing import Iterator import pkg_resources @@ -37,7 +38,7 @@ from . import resources -def _get_file_from_object(obj): +def _get_file_from_object(obj) -> str: if platform.python_implementation() == "Jython": return obj.__file__.split("$py.class")[0] + ".py" return obj.__file__ @@ -46,35 +47,35 @@ def _get_file_from_object(obj): class AstroidManagerTest( resources.SysPathSetup, resources.AstroidCacheSetupMixin, unittest.TestCase ): - def setUp(self): + def setUp(self) -> None: super().setUp() self.manager = test_utils.brainless_manager() - def test_ast_from_file(self): + def test_ast_from_file(self) -> None: filepath = unittest.__file__ ast = self.manager.ast_from_file(filepath) self.assertEqual(ast.name, "unittest") self.assertIn("unittest", self.manager.astroid_cache) - def test_ast_from_file_cache(self): + def test_ast_from_file_cache(self) -> None: filepath = unittest.__file__ self.manager.ast_from_file(filepath) ast = self.manager.ast_from_file("unhandledName", "unittest") self.assertEqual(ast.name, "unittest") self.assertIn("unittest", self.manager.astroid_cache) - def test_ast_from_file_astro_builder(self): + def test_ast_from_file_astro_builder(self) -> None: filepath = unittest.__file__ ast = self.manager.ast_from_file(filepath, None, True, True) self.assertEqual(ast.name, "unittest") self.assertIn("unittest", self.manager.astroid_cache) - def test_ast_from_file_name_astro_builder_exception(self): + def test_ast_from_file_name_astro_builder_exception(self) -> None: self.assertRaises( AstroidBuildingError, self.manager.ast_from_file, "unhandledName" ) - def test_ast_from_string(self): + def test_ast_from_string(self) -> None: filepath = unittest.__file__ dirname = os.path.dirname(filepath) modname = os.path.basename(dirname) @@ -85,30 +86,30 @@ def test_ast_from_string(self): self.assertEqual(ast.file, filepath) self.assertIn("unittest", self.manager.astroid_cache) - def test_do_not_expose_main(self): + def test_do_not_expose_main(self) -> None: obj = self.manager.ast_from_module_name("__main__") self.assertEqual(obj.name, "__main__") self.assertEqual(obj.items(), []) - def test_ast_from_module_name(self): + def test_ast_from_module_name(self) -> None: ast = self.manager.ast_from_module_name("unittest") self.assertEqual(ast.name, "unittest") self.assertIn("unittest", self.manager.astroid_cache) - def test_ast_from_module_name_not_python_source(self): + def test_ast_from_module_name_not_python_source(self) -> None: ast = self.manager.ast_from_module_name("time") self.assertEqual(ast.name, "time") self.assertIn("time", self.manager.astroid_cache) self.assertEqual(ast.pure_python, False) - def test_ast_from_module_name_astro_builder_exception(self): + def test_ast_from_module_name_astro_builder_exception(self) -> None: self.assertRaises( AstroidBuildingError, self.manager.ast_from_module_name, "unhandledModule", ) - def _test_ast_from_old_namespace_package_protocol(self, root): + def _test_ast_from_old_namespace_package_protocol(self, root: str) -> None: origpath = sys.path[:] paths = [resources.find(f"data/path_{root}_{index}") for index in range(1, 4)] sys.path.extend(paths) @@ -119,13 +120,13 @@ def _test_ast_from_old_namespace_package_protocol(self, root): finally: sys.path = origpath - def test_ast_from_namespace_pkgutil(self): + def test_ast_from_namespace_pkgutil(self) -> None: self._test_ast_from_old_namespace_package_protocol("pkgutil") - def test_ast_from_namespace_pkg_resources(self): + def test_ast_from_namespace_pkg_resources(self) -> None: self._test_ast_from_old_namespace_package_protocol("pkg_resources") - def test_implicit_namespace_package(self): + def test_implicit_namespace_package(self) -> None: data_dir = os.path.dirname(resources.find("data/namespace_pep_420")) contribute = os.path.join(data_dir, "contribute_to_namespace") for value in (data_dir, contribute): @@ -142,7 +143,7 @@ def test_implicit_namespace_package(self): for _ in range(2): sys.path.pop(0) - def test_namespace_package_pth_support(self): + def test_namespace_package_pth_support(self) -> None: pth = "foogle_fax-0.12.5-py2.7-nspkg.pth" site.addpackage(resources.RESOURCE_PATH, pth, []) pkg_resources._namespace_packages["foogle"] = [] @@ -158,7 +159,7 @@ def test_namespace_package_pth_support(self): del pkg_resources._namespace_packages["foogle"] sys.modules.pop("foogle") - def test_nested_namespace_import(self): + def test_nested_namespace_import(self) -> None: pth = "foogle_fax-0.12.5-py2.7-nspkg.pth" site.addpackage(resources.RESOURCE_PATH, pth, []) pkg_resources._namespace_packages["foogle"] = ["foogle.crank"] @@ -169,7 +170,7 @@ def test_nested_namespace_import(self): del pkg_resources._namespace_packages["foogle"] sys.modules.pop("foogle") - def test_namespace_and_file_mismatch(self): + def test_namespace_and_file_mismatch(self) -> None: filepath = unittest.__file__ ast = self.manager.ast_from_file(filepath) self.assertEqual(ast.name, "unittest") @@ -183,7 +184,7 @@ def test_namespace_and_file_mismatch(self): del pkg_resources._namespace_packages["foogle"] sys.modules.pop("foogle") - def _test_ast_from_zip(self, archive): + def _test_ast_from_zip(self, archive: str) -> None: sys.modules.pop("mypypa", None) archive_path = resources.find(archive) sys.path.insert(0, archive_path) @@ -195,7 +196,7 @@ def _test_ast_from_zip(self, archive): ) @contextmanager - def _restore_package_cache(self): + def _restore_package_cache(self) -> Iterator: orig_path = sys.path[:] orig_pathcache = sys.path_importer_cache.copy() orig_modcache = self.manager.astroid_cache.copy() @@ -208,37 +209,37 @@ def _restore_package_cache(self): sys.path_importer_cache = orig_pathcache sys.path = orig_path - def test_ast_from_module_name_egg(self): + def test_ast_from_module_name_egg(self) -> None: with self._restore_package_cache(): self._test_ast_from_zip( os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.egg")]) ) - def test_ast_from_module_name_zip(self): + def test_ast_from_module_name_zip(self) -> None: with self._restore_package_cache(): self._test_ast_from_zip( os.path.sep.join(["data", os.path.normcase("MyPyPa-0.1.0-py2.5.zip")]) ) - def test_zip_import_data(self): + def test_zip_import_data(self) -> None: """check if zip_import_data works""" with self._restore_package_cache(): filepath = resources.find("data/MyPyPa-0.1.0-py2.5.zip/mypypa") ast = self.manager.zip_import_data(filepath) self.assertEqual(ast.name, "mypypa") - def test_zip_import_data_without_zipimport(self): + def test_zip_import_data_without_zipimport(self) -> None: """check if zip_import_data return None without zipimport""" self.assertEqual(self.manager.zip_import_data("path"), None) - def test_file_from_module(self): + def test_file_from_module(self) -> None: """check if the unittest filepath is equals to the result of the method""" self.assertEqual( _get_file_from_object(unittest), self.manager.file_from_module_name("unittest", None).location, ) - def test_file_from_module_name_astro_building_exception(self): + def test_file_from_module_name_astro_building_exception(self) -> None: """check if the method raises an exception with a wrong module name""" self.assertRaises( AstroidBuildingError, @@ -247,19 +248,19 @@ def test_file_from_module_name_astro_building_exception(self): None, ) - def test_ast_from_module(self): + def test_ast_from_module(self) -> None: ast = self.manager.ast_from_module(unittest) self.assertEqual(ast.pure_python, True) ast = self.manager.ast_from_module(time) self.assertEqual(ast.pure_python, False) - def test_ast_from_module_cache(self): + def test_ast_from_module_cache(self) -> None: """check if the module is in the cache manager""" ast = self.manager.ast_from_module(unittest) self.assertEqual(ast.name, "unittest") self.assertIn("unittest", self.manager.astroid_cache) - def test_ast_from_class(self): + def test_ast_from_class(self) -> None: ast = self.manager.ast_from_class(int) self.assertEqual(ast.name, "int") self.assertEqual(ast.parent.frame().name, "builtins") @@ -269,7 +270,7 @@ def test_ast_from_class(self): self.assertEqual(ast.parent.frame().name, "builtins") self.assertIn("__setattr__", ast) - def test_ast_from_class_with_module(self): + def test_ast_from_class_with_module(self) -> None: """check if the method works with the module name""" ast = self.manager.ast_from_class(int, int.__module__) self.assertEqual(ast.name, "int") @@ -280,12 +281,12 @@ def test_ast_from_class_with_module(self): self.assertEqual(ast.parent.frame().name, "builtins") self.assertIn("__setattr__", ast) - def test_ast_from_class_attr_error(self): + def test_ast_from_class_attr_error(self) -> None: """give a wrong class at the ast_from_class method""" self.assertRaises(AstroidBuildingError, self.manager.ast_from_class, None) - def test_failed_import_hooks(self): - def hook(modname): + def test_failed_import_hooks(self) -> None: + def hook(modname: str): if modname == "foo.bar": return unittest @@ -302,7 +303,7 @@ def hook(modname): class BorgAstroidManagerTC(unittest.TestCase): - def test_borg(self): + def test_borg(self) -> None: """test that the AstroidManager is really a borg, i.e. that two different instances has same cache""" first_manager = manager.AstroidManager() diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py index 6edc94d13a..a8107f7095 100644 --- a/tests/unittest_modutils.py +++ b/tests/unittest_modutils.py @@ -40,19 +40,19 @@ from . import resources -def _get_file_from_object(obj): +def _get_file_from_object(obj) -> str: return modutils._path_from_filename(obj.__file__) class ModuleFileTest(unittest.TestCase): package = "mypypa" - def tearDown(self): + def tearDown(self) -> None: for k in list(sys.path_importer_cache): if "MyPyPa" in k: del sys.path_importer_cache[k] - def test_find_zipped_module(self): + def test_find_zipped_module(self) -> None: found_spec = spec.find_spec( [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.zip")] ) @@ -62,7 +62,7 @@ def test_find_zipped_module(self): ["data", "MyPyPa-0.1.0-py2.5.zip", self.package], ) - def test_find_egg_module(self): + def test_find_egg_module(self) -> None: found_spec = spec.find_spec( [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.egg")] ) @@ -72,7 +72,7 @@ def test_find_egg_module(self): ["data", "MyPyPa-0.1.0-py2.5.egg", self.package], ) - def test_find_distutils_submodules_in_virtualenv(self): + def test_find_distutils_submodules_in_virtualenv(self) -> None: found_spec = spec.find_spec(["distutils", "version"]) self.assertEqual(found_spec.location, distutils.version.__file__) @@ -80,13 +80,13 @@ def test_find_distutils_submodules_in_virtualenv(self): class LoadModuleFromNameTest(unittest.TestCase): """load a python module from it's name""" - def test_known_values_load_module_from_name_1(self): + def test_known_values_load_module_from_name_1(self) -> None: self.assertEqual(modutils.load_module_from_name("sys"), sys) - def test_known_values_load_module_from_name_2(self): + def test_known_values_load_module_from_name_2(self) -> None: self.assertEqual(modutils.load_module_from_name("os.path"), os.path) - def test_raise_load_module_from_name_1(self): + def test_raise_load_module_from_name_1(self) -> None: self.assertRaises( ImportError, modutils.load_module_from_name, "_this_module_does_not_exist_" ) @@ -95,33 +95,33 @@ def test_raise_load_module_from_name_1(self): class GetModulePartTest(unittest.TestCase): """given a dotted name return the module part of the name""" - def test_known_values_get_module_part_1(self): + def test_known_values_get_module_part_1(self) -> None: self.assertEqual( modutils.get_module_part("astroid.modutils"), "astroid.modutils" ) - def test_known_values_get_module_part_2(self): + def test_known_values_get_module_part_2(self) -> None: self.assertEqual( modutils.get_module_part("astroid.modutils.get_module_part"), "astroid.modutils", ) - def test_known_values_get_module_part_3(self): + def test_known_values_get_module_part_3(self) -> None: """relative import from given file""" self.assertEqual( modutils.get_module_part("nodes.node_classes.AssName", modutils.__file__), "nodes.node_classes", ) - def test_known_values_get_compiled_module_part(self): + def test_known_values_get_compiled_module_part(self) -> None: self.assertEqual(modutils.get_module_part("math.log10"), "math") self.assertEqual(modutils.get_module_part("math.log10", __file__), "math") - def test_known_values_get_builtin_module_part(self): + def test_known_values_get_builtin_module_part(self) -> None: self.assertEqual(modutils.get_module_part("sys.path"), "sys") self.assertEqual(modutils.get_module_part("sys.path", "__file__"), "sys") - def test_get_module_part_exception(self): + def test_get_module_part_exception(self) -> None: self.assertRaises( ImportError, modutils.get_module_part, "unknown.module", modutils.__file__ ) @@ -130,16 +130,16 @@ def test_get_module_part_exception(self): class ModPathFromFileTest(unittest.TestCase): """given an absolute file path return the python module's path as a list""" - def test_known_values_modpath_from_file_1(self): + def test_known_values_modpath_from_file_1(self) -> None: self.assertEqual( modutils.modpath_from_file(ElementTree.__file__), ["xml", "etree", "ElementTree"], ) - def test_raise_modpath_from_file_exception(self): + def test_raise_modpath_from_file_exception(self) -> None: self.assertRaises(Exception, modutils.modpath_from_file, "/turlututu") - def test_import_symlink_with_source_outside_of_path(self): + def test_import_symlink_with_source_outside_of_path(self) -> None: with tempfile.NamedTemporaryFile() as tmpfile: linked_file_name = "symlinked_file.py" try: @@ -150,7 +150,7 @@ def test_import_symlink_with_source_outside_of_path(self): finally: os.remove(linked_file_name) - def test_import_symlink_both_outside_of_path(self): + def test_import_symlink_both_outside_of_path(self) -> None: with tempfile.NamedTemporaryFile() as tmpfile: linked_file_name = os.path.join(tempfile.gettempdir(), "symlinked_file.py") try: @@ -161,7 +161,7 @@ def test_import_symlink_both_outside_of_path(self): finally: os.remove(linked_file_name) - def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self): + def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self) -> None: # constants tmp = tempfile.gettempdir() deployment_path = os.path.join(tmp, "deployment") @@ -195,7 +195,7 @@ def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self): class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase): - def test_do_not_load_twice(self): + def test_do_not_load_twice(self) -> None: modutils.load_module_from_modpath(["data", "lmfp", "foo"]) modutils.load_module_from_modpath(["data", "lmfp"]) # pylint: disable=no-member; just-once is added by a test file dynamically. @@ -208,38 +208,38 @@ class FileFromModPathTest(resources.SysPathSetup, unittest.TestCase): corresponding file, giving priority to source file over precompiled file if it exists""" - def test_site_packages(self): + def test_site_packages(self) -> None: filename = _get_file_from_object(modutils) result = modutils.file_from_modpath(["astroid", "modutils"]) self.assertEqual(os.path.realpath(result), os.path.realpath(filename)) - def test_std_lib(self): + def test_std_lib(self) -> None: path = modutils.file_from_modpath(["os", "path"]).replace(".pyc", ".py") self.assertEqual( os.path.realpath(path), os.path.realpath(os.path.__file__.replace(".pyc", ".py")), ) - def test_builtin(self): + def test_builtin(self) -> None: self.assertIsNone(modutils.file_from_modpath(["sys"])) - def test_unexisting(self): + def test_unexisting(self) -> None: self.assertRaises(ImportError, modutils.file_from_modpath, ["turlututu"]) - def test_unicode_in_package_init(self): + def test_unicode_in_package_init(self) -> None: # file_from_modpath should not crash when reading an __init__ # file with unicode characters. modutils.file_from_modpath(["data", "unicode_package", "core"]) class GetSourceFileTest(unittest.TestCase): - def test(self): + def test(self) -> None: filename = _get_file_from_object(os.path) self.assertEqual( modutils.get_source_file(os.path.__file__), os.path.normpath(filename) ) - def test_raise(self): + def test_raise(self) -> None: self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, "whatever") @@ -249,26 +249,26 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase): library """ - def test_datetime(self): + def test_datetime(self) -> None: # This is an interesting example, since datetime, on pypy, # is under lib_pypy, rather than the usual Lib directory. self.assertTrue(modutils.is_standard_module("datetime")) - def test_builtins(self): + def test_builtins(self) -> None: self.assertFalse(modutils.is_standard_module("__builtin__")) self.assertTrue(modutils.is_standard_module("builtins")) - def test_builtin(self): + def test_builtin(self) -> None: self.assertTrue(modutils.is_standard_module("sys")) self.assertTrue(modutils.is_standard_module("marshal")) - def test_nonstandard(self): + def test_nonstandard(self) -> None: self.assertFalse(modutils.is_standard_module("astroid")) - def test_unknown(self): + def test_unknown(self) -> None: self.assertFalse(modutils.is_standard_module("unknown")) - def test_4(self): + def test_4(self) -> None: self.assertTrue(modutils.is_standard_module("hashlib")) self.assertTrue(modutils.is_standard_module("pickle")) self.assertTrue(modutils.is_standard_module("email")) @@ -276,7 +276,7 @@ def test_4(self): self.assertFalse(modutils.is_standard_module("StringIO")) self.assertTrue(modutils.is_standard_module("unicodedata")) - def test_custom_path(self): + def test_custom_path(self) -> None: datadir = resources.find("") if any(datadir.startswith(p) for p in modutils.EXT_LIB_DIRS): self.skipTest("known breakage of is_standard_module on installed package") @@ -286,7 +286,7 @@ def test_custom_path(self): modutils.is_standard_module("data.module", (os.path.abspath(datadir),)) ) - def test_failing_edge_cases(self): + def test_failing_edge_cases(self) -> None: # using a subpackage/submodule path as std_path argument self.assertFalse(modutils.is_standard_module("xml.etree", etree.__path__)) # using a module + object name as modname argument @@ -297,44 +297,44 @@ def test_failing_edge_cases(self): class IsRelativeTest(unittest.TestCase): - def test_known_values_is_relative_1(self): + def test_known_values_is_relative_1(self) -> None: self.assertTrue(modutils.is_relative("utils", email.__path__[0])) - def test_known_values_is_relative_3(self): + def test_known_values_is_relative_3(self) -> None: self.assertFalse(modutils.is_relative("astroid", astroid.__path__[0])) - def test_known_values_is_relative_4(self): + def test_known_values_is_relative_4(self) -> None: self.assertTrue( modutils.is_relative("util", astroid.interpreter._import.spec.__file__) ) - def test_known_values_is_relative_5(self): + def test_known_values_is_relative_5(self) -> None: self.assertFalse( modutils.is_relative( "objectmodel", astroid.interpreter._import.spec.__file__ ) ) - def test_deep_relative(self): + def test_deep_relative(self) -> None: self.assertTrue(modutils.is_relative("ElementTree", xml.etree.__path__[0])) - def test_deep_relative2(self): + def test_deep_relative2(self) -> None: self.assertFalse(modutils.is_relative("ElementTree", xml.__path__[0])) - def test_deep_relative3(self): + def test_deep_relative3(self) -> None: self.assertTrue(modutils.is_relative("etree.ElementTree", xml.__path__[0])) - def test_deep_relative4(self): + def test_deep_relative4(self) -> None: self.assertTrue(modutils.is_relative("etree.gibberish", xml.__path__[0])) - def test_is_relative_bad_path(self): + def test_is_relative_bad_path(self) -> None: self.assertFalse( modutils.is_relative("ElementTree", os.path.join(xml.__path__[0], "ftree")) ) class GetModuleFilesTest(unittest.TestCase): - def test_get_module_files_1(self): + def test_get_module_files_1(self) -> None: package = resources.find("data/find_test") modules = set(modutils.get_module_files(package, [])) expected = [ @@ -346,13 +346,13 @@ def test_get_module_files_1(self): ] self.assertEqual(modules, {os.path.join(package, x) for x in expected}) - def test_get_all_files(self): + def test_get_all_files(self) -> None: """test that list_all returns all Python files from given location""" non_package = resources.find("data/notamodule") modules = modutils.get_module_files(non_package, [], list_all=True) self.assertEqual(modules, [os.path.join(non_package, "file.py")]) - def test_load_module_set_attribute(self): + def test_load_module_set_attribute(self) -> None: del xml.etree.ElementTree del sys.modules["xml.etree.ElementTree"] m = modutils.load_module_from_modpath(["xml", "etree", "ElementTree"]) @@ -362,7 +362,7 @@ def test_load_module_set_attribute(self): class ExtensionPackageWhitelistTest(unittest.TestCase): - def test_is_module_name_part_of_extension_package_whitelist_true(self): + def test_is_module_name_part_of_extension_package_whitelist_true(self) -> None: """Test that the is_module_name_part_of_extension_package_whitelist function returns True when needed""" self.assertTrue( modutils.is_module_name_part_of_extension_package_whitelist( @@ -380,7 +380,7 @@ def test_is_module_name_part_of_extension_package_whitelist_true(self): ) ) - def test_is_module_name_part_of_extension_package_whitelist_success(self): + def test_is_module_name_part_of_extension_package_whitelist_success(self) -> None: """Test that the is_module_name_part_of_extension_package_whitelist function returns False when needed""" self.assertFalse( modutils.is_module_name_part_of_extension_package_whitelist( diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py index 3e9bcc2888..f76c7fcc5c 100644 --- a/tests/unittest_nodes.py +++ b/tests/unittest_nodes.py @@ -33,8 +33,10 @@ import sys import textwrap import unittest +from typing import Any, Optional import pytest +from mypy_extensions import NoReturn import astroid from astroid import ( @@ -54,6 +56,15 @@ AstroidSyntaxError, AttributeInferenceError, ) +from astroid.nodes.node_classes import ( + AssignAttr, + AssignName, + Attribute, + Call, + ImportFrom, + Tuple, +) +from astroid.nodes.scoped_nodes import ClassDef, FunctionDef, GeneratorExp, Module from . import resources @@ -68,8 +79,8 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase): - def test_tuple_as_string(self): - def build(string): + def test_tuple_as_string(self) -> None: + def build(string: str) -> Tuple: return abuilder.string_build(string).body[0].value self.assertEqual(build("1,").as_string(), "(1, )") @@ -77,7 +88,7 @@ def build(string): self.assertEqual(build("(1, )").as_string(), "(1, )") self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)") - def test_func_signature_issue_185(self): + def test_func_signature_issue_185(self) -> None: code = textwrap.dedent( """ def test(a, b, c=42, *, x=42, **kwargs): @@ -87,7 +98,7 @@ def test(a, b, c=42, *, x=42, **kwargs): node = parse(code) self.assertEqual(node.as_string().strip(), code.strip()) - def test_as_string_for_list_containing_uninferable(self): + def test_as_string_for_list_containing_uninferable(self) -> None: node = builder.extract_node( """ def foo(): @@ -99,7 +110,7 @@ def foo(): self.assertEqual(inferred.as_string(), "[Uninferable]") self.assertEqual(binop.as_string(), "[arg] * 1") - def test_frozenset_as_string(self): + def test_frozenset_as_string(self) -> None: ast_nodes = builder.extract_node( """ frozenset((1, 2, 3)) #@ @@ -119,23 +130,23 @@ def test_frozenset_as_string(self): self.assertNotEqual(ast_nodes[3].as_string(), "frozenset(None)") self.assertNotEqual(ast_nodes[4].as_string(), "frozenset(1)") - def test_varargs_kwargs_as_string(self): + def test_varargs_kwargs_as_string(self) -> None: ast = abuilder.string_build("raise_string(*args, **kwargs)").body[0] self.assertEqual(ast.as_string(), "raise_string(*args, **kwargs)") - def test_module_as_string(self): + def test_module_as_string(self) -> None: """check as_string on a whole module prepared to be returned identically""" module = resources.build_file("data/module.py", "data.module") with open(resources.find("data/module.py"), encoding="utf-8") as fobj: self.assertMultiLineEqual(module.as_string(), fobj.read()) - def test_module2_as_string(self): + def test_module2_as_string(self) -> None: """check as_string on a whole module prepared to be returned identically""" module2 = resources.build_file("data/module2.py", "data.module2") with open(resources.find("data/module2.py"), encoding="utf-8") as fobj: self.assertMultiLineEqual(module2.as_string(), fobj.read()) - def test_as_string(self): + def test_as_string(self) -> None: """check as_string for python syntax >= 2.7""" code = """one_two = {1, 2} b = {v: k for (k, v) in enumerate('string')} @@ -143,7 +154,7 @@ def test_as_string(self): ast = abuilder.string_build(code) self.assertMultiLineEqual(ast.as_string(), code) - def test_3k_as_string(self): + def test_3k_as_string(self) -> None: """check as_string for python 3k syntax""" code = """print() @@ -158,7 +169,7 @@ def function(var): ast = abuilder.string_build(code) self.assertEqual(ast.as_string(), code) - def test_3k_annotations_and_metaclass(self): + def test_3k_annotations_and_metaclass(self) -> None: code = ''' def function(var: int): nonlocal counter @@ -178,11 +189,11 @@ class Language(metaclass=Natural): ast = abuilder.string_build(code_annotations) self.assertEqual(ast.as_string().strip(), expected) - def test_ellipsis(self): + def test_ellipsis(self) -> None: ast = abuilder.string_build("a[...]").body[0] self.assertEqual(ast.as_string(), "a[...]") - def test_slices(self): + def test_slices(self) -> None: for code in ( "a[0]", "a[1:3]", @@ -196,7 +207,7 @@ def test_slices(self): ast = abuilder.string_build(code).body[0] self.assertEqual(ast.as_string(), code) - def test_slice_and_subscripts(self): + def test_slice_and_subscripts(self) -> None: code = """a[:1] = bord[2:] a[:1] = bord[2:] del bree[3:d] @@ -215,7 +226,7 @@ def test_slice_and_subscripts(self): ast = abuilder.string_build(code) self.assertEqual(ast.as_string(), code) - def test_int_attribute(self): + def test_int_attribute(self) -> None: code = """ x = (-3).real y = (3).imag @@ -223,13 +234,13 @@ def test_int_attribute(self): ast = abuilder.string_build(code) self.assertEqual(ast.as_string().strip(), code.strip()) - def test_operator_precedence(self): + def test_operator_precedence(self) -> None: with open(resources.find("data/operator_precedence.py"), encoding="utf-8") as f: for code in f: self.check_as_string_ast_equality(code) @staticmethod - def check_as_string_ast_equality(code): + def check_as_string_ast_equality(code: str) -> None: """ Check that as_string produces source code with exactly the same semantics as the source it was originally parsed from @@ -243,7 +254,7 @@ def check_as_string_ast_equality(code): assert pre_repr == post_repr assert pre.as_string().strip() == code.strip() - def test_class_def(self): + def test_class_def(self) -> None: code = """ import abc @@ -296,7 +307,7 @@ class _NodeTest(unittest.TestCase): CODE = "" @property - def astroid(self): + def astroid(self) -> Module: try: return self.__class__.__dict__["CODE_Astroid"] except KeyError: @@ -332,7 +343,7 @@ class IfNodeTest(_NodeTest): raise """ - def test_if_elif_else_node(self): + def test_if_elif_else_node(self) -> None: """test transformation for If node""" self.assertEqual(len(self.astroid.body), 4) for stmt in self.astroid.body: @@ -342,7 +353,7 @@ def test_if_elif_else_node(self): self.assertIsInstance(self.astroid.body[2].orelse[0], nodes.If) # If / elif self.assertIsInstance(self.astroid.body[3].orelse[0].orelse[0], nodes.If) - def test_block_range(self): + def test_block_range(self) -> None: # XXX ensure expected values self.assertEqual(self.astroid.block_range(1), (0, 22)) self.assertEqual(self.astroid.block_range(10), (0, 22)) # XXX (10, 22) ? @@ -352,7 +363,7 @@ def test_block_range(self): self.assertEqual(self.astroid.body[1].orelse[0].block_range(8), (8, 8)) @staticmethod - def test_if_sys_guard(): + def test_if_sys_guard() -> None: code = builder.extract_node( """ import sys @@ -377,7 +388,7 @@ def test_if_sys_guard(): assert code[2].is_sys_guard() is False @staticmethod - def test_if_typing_guard(): + def test_if_typing_guard() -> None: code = builder.extract_node( """ import typing @@ -422,7 +433,7 @@ class TryExceptNodeTest(_NodeTest): print() """ - def test_block_range(self): + def test_block_range(self) -> None: # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 8)) self.assertEqual(self.astroid.body[0].block_range(2), (2, 2)) @@ -442,7 +453,7 @@ class TryFinallyNodeTest(_NodeTest): print ('pouet') """ - def test_block_range(self): + def test_block_range(self) -> None: # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 4)) self.assertEqual(self.astroid.body[0].block_range(2), (2, 2)) @@ -460,7 +471,7 @@ class TryExceptFinallyNodeTest(_NodeTest): print ('pouet') """ - def test_block_range(self): + def test_block_range(self) -> None: # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 6)) self.assertEqual(self.astroid.body[0].block_range(2), (2, 2)) @@ -471,19 +482,19 @@ def test_block_range(self): class ImportNodeTest(resources.SysPathSetup, unittest.TestCase): - def setUp(self): + def setUp(self) -> None: super().setUp() self.module = resources.build_file("data/module.py", "data.module") self.module2 = resources.build_file("data/module2.py", "data.module2") - def test_import_self_resolve(self): + def test_import_self_resolve(self) -> None: myos = next(self.module2.igetattr("myos")) self.assertTrue(isinstance(myos, nodes.Module), myos) self.assertEqual(myos.name, "os") self.assertEqual(myos.qname(), "os") self.assertEqual(myos.pytype(), "builtins.module") - def test_from_self_resolve(self): + def test_from_self_resolve(self) -> None: namenode = next(self.module.igetattr("NameNode")) self.assertTrue(isinstance(namenode, nodes.ClassDef), namenode) self.assertEqual(namenode.root().name, "astroid.nodes.node_classes") @@ -500,7 +511,7 @@ def test_from_self_resolve(self): # AssertionError: 'os.path._abspath_fallback' != 'os.path.abspath' self.assertEqual(abspath.qname(), "os.path.abspath") - def test_real_name(self): + def test_real_name(self) -> None: from_ = self.module["NameNode"] self.assertEqual(from_.real_name("NameNode"), "Name") imp_ = self.module["os"] @@ -513,7 +524,7 @@ def test_real_name(self): self.assertEqual(imp_.real_name("YO"), "YO") self.assertRaises(AttributeInferenceError, imp_.real_name, "data") - def test_as_string(self): + def test_as_string(self) -> None: ast = self.module["modutils"] self.assertEqual(ast.as_string(), "from astroid import modutils") ast = self.module["NameNode"] @@ -529,7 +540,7 @@ def test_as_string(self): ast = abuilder.string_build(code) self.assertMultiLineEqual(ast.as_string(), code) - def test_bad_import_inference(self): + def test_bad_import_inference(self) -> None: # Explication of bug """When we import PickleError from nonexistent, a call to the infer method of this From node will be made by unpack_infer. @@ -561,7 +572,7 @@ def test_bad_import_inference(self): self.assertEqual(excs[0].name, "PickleError") self.assertIs(excs[-1], util.Uninferable) - def test_absolute_import(self): + def test_absolute_import(self) -> None: module = resources.build_file("data/absimport.py") ctx = InferenceContext() # will fail if absolute import failed @@ -571,13 +582,13 @@ def test_absolute_import(self): m = next(module["email"].infer(ctx)) self.assertFalse(m.file.startswith(os.path.join("data", "email.py"))) - def test_more_absolute_import(self): + def test_more_absolute_import(self) -> None: module = resources.build_file("data/module1abs/__init__.py", "data.module1abs") self.assertIn("sys", module.locals) _pickle_names = ("dump",) # "dumps", "load", "loads") - def test_conditional(self): + def test_conditional(self) -> None: module = resources.build_file("data/conditional_import/__init__.py") ctx = InferenceContext() @@ -586,7 +597,7 @@ def test_conditional(self): some = list(module[name].infer(ctx)) assert Uninferable not in some, name - def test_conditional_import(self): + def test_conditional_import(self) -> None: module = resources.build_file("data/conditional.py") ctx = InferenceContext() @@ -597,13 +608,13 @@ def test_conditional_import(self): class CmpNodeTest(unittest.TestCase): - def test_as_string(self): + def test_as_string(self) -> None: ast = abuilder.string_build("a == 2").body[0] self.assertEqual(ast.as_string(), "a == 2") class ConstNodeTest(unittest.TestCase): - def _test(self, value): + def _test(self, value: Any) -> None: node = nodes.const_factory(value) # pylint: disable=no-member; Infers two potential values self.assertIsInstance(node._proxied, nodes.ClassDef) @@ -612,25 +623,25 @@ def _test(self, value): self.assertTrue(node._proxied.parent) self.assertEqual(node._proxied.root().name, value.__class__.__module__) - def test_none(self): + def test_none(self) -> None: self._test(None) - def test_bool(self): + def test_bool(self) -> None: self._test(True) - def test_int(self): + def test_int(self) -> None: self._test(1) - def test_float(self): + def test_float(self) -> None: self._test(1.0) - def test_complex(self): + def test_complex(self) -> None: self._test(1.0j) - def test_str(self): + def test_str(self) -> None: self._test("a") - def test_unicode(self): + def test_unicode(self) -> None: self._test("a") @pytest.mark.skipif( @@ -646,7 +657,7 @@ def test_str_kind(self): assert node.value.value == "foo" assert node.value.kind, "u" - def test_copy(self): + def test_copy(self) -> None: """ Make sure copying a Const object doesn't result in infinite recursion """ @@ -655,7 +666,7 @@ def test_copy(self): class NameNodeTest(unittest.TestCase): - def test_assign_to_true(self): + def test_assign_to_true(self) -> None: """Test that True and False assignments don't crash""" code = """ True = False @@ -668,7 +679,7 @@ def hello(False): class AnnAssignNodeTest(unittest.TestCase): - def test_primitive(self): + def test_primitive(self) -> None: code = textwrap.dedent( """ test: int = 5 @@ -681,7 +692,7 @@ def test_primitive(self): self.assertEqual(assign.value.value, 5) self.assertEqual(assign.simple, 1) - def test_primitive_without_initial_value(self): + def test_primitive_without_initial_value(self) -> None: code = textwrap.dedent( """ test: str @@ -693,7 +704,7 @@ def test_primitive_without_initial_value(self): self.assertEqual(assign.annotation.name, "str") self.assertEqual(assign.value, None) - def test_complex(self): + def test_complex(self) -> None: code = textwrap.dedent( """ test: Dict[List[str]] = {} @@ -705,7 +716,7 @@ def test_complex(self): self.assertIsInstance(assign.annotation, astroid.Subscript) self.assertIsInstance(assign.value, astroid.Dict) - def test_as_string(self): + def test_as_string(self) -> None: code = textwrap.dedent( """ print() @@ -719,7 +730,7 @@ def test_as_string(self): class ArgumentsNodeTC(unittest.TestCase): - def test_linenumbering(self): + def test_linenumbering(self) -> NoReturn: ast = builder.parse( """ def func(a, @@ -738,7 +749,7 @@ def func(a, "(no line number on function args)" ) - def test_kwoargs(self): + def test_kwoargs(self) -> None: ast = builder.parse( """ def func(*, x): @@ -765,7 +776,7 @@ def func(x, /, y): class UnboundMethodNodeTest(unittest.TestCase): - def test_no_super_getattr(self): + def test_no_super_getattr(self) -> None: # This is a test for issue # https://bitbucket.org/logilab/astroid/issue/91, which tests # that UnboundMethod doesn't call super when doing .getattr. @@ -787,7 +798,7 @@ def test(self): class BoundMethodNodeTest(unittest.TestCase): - def test_is_property(self): + def test_is_property(self) -> None: ast = builder.parse( """ import abc @@ -851,52 +862,52 @@ def decorated_with_lazy(self): return 42 class AliasesTest(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.transformer = transforms.TransformVisitor() - def parse_transform(self, code): + def parse_transform(self, code: str) -> Module: module = parse(code, apply_transforms=False) return self.transformer.visit(module) - def test_aliases(self): - def test_from(node): + def test_aliases(self) -> None: + def test_from(node: ImportFrom) -> ImportFrom: node.names = node.names + [("absolute_import", None)] return node - def test_class(node): + def test_class(node: ClassDef) -> ClassDef: node.name = "Bar" return node - def test_function(node): + def test_function(node: FunctionDef) -> FunctionDef: node.name = "another_test" return node - def test_callfunc(node): + def test_callfunc(node: Call) -> Optional[Call]: if node.func.name == "Foo": node.func.name = "Bar" return node return None - def test_assname(node): + def test_assname(node: AssignName) -> Optional[AssignName]: if node.name == "foo": return nodes.AssignName( "bar", node.lineno, node.col_offset, node.parent ) return None - def test_assattr(node): + def test_assattr(node: AssignAttr) -> AssignAttr: if node.attrname == "a": node.attrname = "b" return node return None - def test_getattr(node): + def test_getattr(node: Attribute) -> Attribute: if node.attrname == "a": node.attrname = "b" return node return None - def test_genexpr(node): + def test_genexpr(node: GeneratorExp) -> GeneratorExp: if node.elt.value == 1: node.elt = nodes.Const(2, node.lineno, node.col_offset, node.parent) return node @@ -946,7 +957,7 @@ def test(a): return a class Python35AsyncTest(unittest.TestCase): - def test_async_await_keywords(self): + def test_async_await_keywords(self) -> None: async_def, async_for, async_with, await_node = builder.extract_node( """ async def func(): #@ @@ -962,11 +973,11 @@ async def func(): #@ self.assertIsInstance(await_node, nodes.Await) self.assertIsInstance(await_node.value, nodes.Name) - def _test_await_async_as_string(self, code): + def _test_await_async_as_string(self, code: str) -> None: ast_node = parse(code) self.assertEqual(ast_node.as_string().strip(), code.strip()) - def test_await_as_string(self): + def test_await_as_string(self) -> None: code = textwrap.dedent( """ async def function(): @@ -978,7 +989,7 @@ async def function(): ) self._test_await_async_as_string(code) - def test_asyncwith_as_string(self): + def test_asyncwith_as_string(self) -> None: code = textwrap.dedent( """ async def function(): @@ -988,7 +999,7 @@ async def function(): ) self._test_await_async_as_string(code) - def test_asyncfor_as_string(self): + def test_asyncfor_as_string(self) -> None: code = textwrap.dedent( """ async def function(): @@ -998,7 +1009,7 @@ async def function(): ) self._test_await_async_as_string(code) - def test_decorated_async_def_as_string(self): + def test_decorated_async_def_as_string(self) -> None: code = textwrap.dedent( """ @decorator @@ -1011,51 +1022,51 @@ async def function(): class ContextTest(unittest.TestCase): - def test_subscript_load(self): + def test_subscript_load(self) -> None: node = builder.extract_node("f[1]") self.assertIs(node.ctx, Context.Load) - def test_subscript_del(self): + def test_subscript_del(self) -> None: node = builder.extract_node("del f[1]") self.assertIs(node.targets[0].ctx, Context.Del) - def test_subscript_store(self): + def test_subscript_store(self) -> None: node = builder.extract_node("f[1] = 2") subscript = node.targets[0] self.assertIs(subscript.ctx, Context.Store) - def test_list_load(self): + def test_list_load(self) -> None: node = builder.extract_node("[]") self.assertIs(node.ctx, Context.Load) - def test_list_del(self): + def test_list_del(self) -> None: node = builder.extract_node("del []") self.assertIs(node.targets[0].ctx, Context.Del) - def test_list_store(self): + def test_list_store(self) -> None: with self.assertRaises(AstroidSyntaxError): builder.extract_node("[0] = 2") - def test_tuple_load(self): + def test_tuple_load(self) -> None: node = builder.extract_node("(1, )") self.assertIs(node.ctx, Context.Load) - def test_tuple_store(self): + def test_tuple_store(self) -> None: with self.assertRaises(AstroidSyntaxError): builder.extract_node("(1, ) = 3") - def test_starred_load(self): + def test_starred_load(self) -> None: node = builder.extract_node("a = *b") starred = node.value self.assertIs(starred.ctx, Context.Load) - def test_starred_store(self): + def test_starred_store(self) -> None: node = builder.extract_node("a, *b = 1, 2") starred = node.targets[0].elts[1] self.assertIs(starred.ctx, Context.Store) -def test_unknown(): +def test_unknown() -> None: """Test Unknown node""" assert isinstance(next(nodes.Unknown().infer()), type(util.Uninferable)) assert isinstance(nodes.Unknown().name, str) @@ -1063,7 +1074,7 @@ def test_unknown(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_with(): +def test_type_comments_with() -> None: module = builder.parse( """ with a as b: # type: int @@ -1080,7 +1091,7 @@ def test_type_comments_with(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_for(): +def test_type_comments_for() -> None: module = builder.parse( """ for a, b in [1, 2, 3]: # type: List[int] @@ -1098,7 +1109,7 @@ def test_type_comments_for(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_coments_assign(): +def test_type_coments_assign() -> None: module = builder.parse( """ a, b = [1, 2, 3] # type: List[int] @@ -1114,7 +1125,7 @@ def test_type_coments_assign(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_invalid_expression(): +def test_type_comments_invalid_expression() -> None: module = builder.parse( """ a, b = [1, 2, 3] # type: something completely invalid @@ -1127,7 +1138,7 @@ def test_type_comments_invalid_expression(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_invalid_function_comments(): +def test_type_comments_invalid_function_comments() -> None: module = builder.parse( """ def func(): @@ -1147,7 +1158,7 @@ def func2(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_function(): +def test_type_comments_function() -> None: module = builder.parse( """ def func(): @@ -1178,7 +1189,7 @@ def func2(): @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_type_comments_arguments(): +def test_type_comments_arguments() -> None: module = builder.parse( """ def func( @@ -1220,7 +1231,7 @@ def func2( @pytest.mark.skipif( not PY38_PLUS, reason="needs to be able to parse positional only arguments" ) -def test_type_comments_posonly_arguments(): +def test_type_comments_posonly_arguments() -> None: module = builder.parse( """ def f_arg_comment( @@ -1256,7 +1267,7 @@ def f_arg_comment( @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_correct_function_type_comment_parent(): +def test_correct_function_type_comment_parent() -> None: data = """ def f(a): # type: (A) -> A @@ -1268,7 +1279,7 @@ def f(a): assert f.type_comment_returns.parent is f -def test_is_generator_for_yield_assignments(): +def test_is_generator_for_yield_assignments() -> None: node = astroid.extract_node( """ class A: @@ -1322,7 +1333,7 @@ async def a_iter(n): assert inferred.display_type() == "Generator" -def test_f_string_correct_line_numbering(): +def test_f_string_correct_line_numbering() -> None: """Test that we generate correct line numbers for f-strings""" node = astroid.extract_node( """ @@ -1338,7 +1349,7 @@ def func_foo(arg_bar, arg_foo): @pytest.mark.skipif(not PY38_PLUS, reason="needs assignment expressions") -def test_assignment_expression(): +def test_assignment_expression() -> None: code = """ if __(a := 1): pass @@ -1360,7 +1371,7 @@ def test_assignment_expression(): assert second.as_string() == "b := test" -def test_get_doc(): +def test_get_doc() -> None: node = astroid.extract_node( """ def func(): @@ -1381,14 +1392,14 @@ def func(): @test_utils.require_version(minver="3.8") -def test_parse_fstring_debug_mode(): +def test_parse_fstring_debug_mode() -> None: node = astroid.extract_node('f"{3=}"') assert isinstance(node, nodes.JoinedStr) assert node.as_string() == "f'3={3!r}'" @pytest.mark.skipif(not HAS_TYPED_AST, reason="requires typed_ast") -def test_parse_type_comments_with_proper_parent(): +def test_parse_type_comments_with_proper_parent() -> None: code = """ class D: #@ @staticmethod @@ -1408,7 +1419,7 @@ def g( assert isinstance(type_comment.parent.parent, astroid.Arguments) -def test_const_itered(): +def test_const_itered() -> None: code = 'a = "string"' node = astroid.extract_node(code).value assert isinstance(node, astroid.Const) @@ -1417,7 +1428,7 @@ def test_const_itered(): assert [elem.value for elem in itered] == list("string") -def test_is_generator_for_yield_in_while(): +def test_is_generator_for_yield_in_while() -> None: code = """ def paused_iter(iterable): while True: @@ -1429,7 +1440,7 @@ def paused_iter(iterable): assert bool(node.is_generator()) -def test_is_generator_for_yield_in_if(): +def test_is_generator_for_yield_in_if() -> None: code = """ import asyncio @@ -1442,7 +1453,7 @@ def paused_iter(iterable): assert bool(node.is_generator()) -def test_is_generator_for_yield_in_aug_assign(): +def test_is_generator_for_yield_in_aug_assign() -> None: code = """ def test(): buf = '' diff --git a/tests/unittest_object_model.py b/tests/unittest_object_model.py index e0b66d215c..4018f79821 100644 --- a/tests/unittest_object_model.py +++ b/tests/unittest_object_model.py @@ -22,7 +22,7 @@ class InstanceModelTest(unittest.TestCase): - def test_instance_special_model(self): + def test_instance_special_model(self) -> None: ast_nodes = builder.extract_node( """ class A: @@ -74,7 +74,7 @@ def __dict__(self): class BoundMethodModelTest(unittest.TestCase): - def test_bound_method_model(self): + def test_bound_method_model(self) -> None: ast_nodes = builder.extract_node( """ class A: @@ -95,7 +95,7 @@ def test(self): pass class UnboundMethodModelTest(unittest.TestCase): - def test_unbound_method_model(self): + def test_unbound_method_model(self) -> None: ast_nodes = builder.extract_node( """ class A: @@ -130,7 +130,7 @@ def test(self): pass class ClassModelTest(unittest.TestCase): - def test_priority_to_local_defined_values(self): + def test_priority_to_local_defined_values(self) -> None: ast_node = builder.extract_node( """ class A: @@ -142,7 +142,7 @@ class A: self.assertIsInstance(inferred, astroid.Const) self.assertEqual(inferred.value, "first") - def test_class_model_correct_mro_subclasses_proxied(self): + def test_class_model_correct_mro_subclasses_proxied(self) -> None: ast_nodes = builder.extract_node( """ class A(object): @@ -158,7 +158,7 @@ class A(object): self.assertIsInstance(inferred.bound, astroid.ClassDef) self.assertEqual(inferred.bound.name, "type") - def test_class_model(self): + def test_class_model(self) -> None: ast_nodes = builder.extract_node( """ class A(object): @@ -221,7 +221,7 @@ class C(A): pass class ModuleModelTest(unittest.TestCase): - def test_priority_to_local_defined_values(self): + def test_priority_to_local_defined_values(self) -> None: ast_node = astroid.parse( """ __file__ = "mine" @@ -231,7 +231,7 @@ def test_priority_to_local_defined_values(self): self.assertIsInstance(file_value, astroid.Const) self.assertEqual(file_value.value, "mine") - def test__path__not_a_package(self): + def test__path__not_a_package(self) -> None: ast_node = builder.extract_node( """ import sys @@ -241,7 +241,7 @@ def test__path__not_a_package(self): with self.assertRaises(InferenceError): next(ast_node.infer()) - def test_module_model(self): + def test_module_model(self) -> None: ast_nodes = builder.extract_node( """ import xml @@ -287,7 +287,7 @@ def test_module_model(self): class FunctionModelTest(unittest.TestCase): - def test_partial_descriptor_support(self): + def test_partial_descriptor_support(self) -> None: bound, result = builder.extract_node( """ class A(object): pass @@ -304,7 +304,7 @@ def test(self): return 42 self.assertIsInstance(result, astroid.Const) self.assertEqual(result.value, 42) - def test___get__has_extra_params_defined(self): + def test___get__has_extra_params_defined(self) -> None: node = builder.extract_node( """ def test(self): return 42 @@ -345,7 +345,7 @@ def test(self): return self.x self.assertIsInstance(result, astroid.Const) self.assertEqual(result.value, 42) - def test_descriptors_binding_invalid(self): + def test_descriptors_binding_invalid(self) -> None: ast_nodes = builder.extract_node( """ class A: pass @@ -358,7 +358,7 @@ def test(self): return 42 with self.assertRaises(InferenceError): next(node.infer()) - def test_descriptor_error_regression(self): + def test_descriptor_error_regression(self) -> None: """Make sure the following code does node cause an exception""" node = builder.extract_node( @@ -380,7 +380,7 @@ def mymethod2(self): [const] = node.inferred() assert const.value == "MyText" - def test_function_model(self): + def test_function_model(self) -> None: ast_nodes = builder.extract_node( ''' def func(a=1, b=2): @@ -427,7 +427,7 @@ def func(a=1, b=2): for ast_node in ast_nodes[7:9]: self.assertIs(next(ast_node.infer()), astroid.Uninferable) - def test_empty_return_annotation(self): + def test_empty_return_annotation(self) -> None: ast_node = builder.extract_node( """ def test(): pass @@ -438,7 +438,9 @@ def test(): pass self.assertIsInstance(annotations, astroid.Dict) self.assertEqual(len(annotations.items), 0) - def test_builtin_dunder_init_does_not_crash_when_accessing_annotations(self): + def test_builtin_dunder_init_does_not_crash_when_accessing_annotations( + self, + ) -> None: ast_node = builder.extract_node( """ class Class: @@ -451,7 +453,7 @@ def class_method(cls): self.assertIsInstance(inferred, astroid.Dict) self.assertEqual(len(inferred.items), 0) - def test_annotations_kwdefaults(self): + def test_annotations_kwdefaults(self) -> None: ast_node = builder.extract_node( """ def test(a: 1, *args: 2, f:4='lala', **kwarg:3)->2: pass @@ -494,7 +496,7 @@ def test(a: 1, b: 2, /, c: 3): pass class GeneratorModelTest(unittest.TestCase): - def test_model(self): + def test_model(self) -> None: ast_nodes = builder.extract_node( """ def test(): @@ -529,7 +531,7 @@ def test(): class ExceptionModelTest(unittest.TestCase): - def test_valueerror_py3(self): + def test_valueerror_py3(self) -> None: ast_nodes = builder.extract_node( """ try: @@ -550,7 +552,7 @@ def test_valueerror_py3(self): with self.assertRaises(InferenceError): next(ast_nodes[2].infer()) - def test_syntax_error(self): + def test_syntax_error(self) -> None: ast_node = builder.extract_node( """ try: @@ -562,7 +564,7 @@ def test_syntax_error(self): inferred = next(ast_node.infer()) assert isinstance(inferred, astroid.Const) - def test_oserror(self): + def test_oserror(self) -> None: ast_nodes = builder.extract_node( """ try: @@ -579,7 +581,7 @@ def test_oserror(self): assert isinstance(inferred, astroid.Const) assert inferred.value == value - def test_unicodedecodeerror(self): + def test_unicodedecodeerror(self) -> None: code = """ try: raise UnicodeDecodeError("utf-8", "blob", 0, 1, "reason") @@ -590,7 +592,7 @@ def test_unicodedecodeerror(self): inferred = next(node.infer()) assert isinstance(inferred, astroid.Const) - def test_import_error(self): + def test_import_error(self) -> None: ast_nodes = builder.extract_node( """ try: @@ -605,7 +607,7 @@ def test_import_error(self): assert isinstance(inferred, astroid.Const) assert inferred.value == "" - def test_exception_instance_correctly_instantiated(self): + def test_exception_instance_correctly_instantiated(self) -> None: ast_node = builder.extract_node( """ try: @@ -621,13 +623,13 @@ def test_exception_instance_correctly_instantiated(self): class DictObjectModelTest(unittest.TestCase): - def test__class__(self): + def test__class__(self) -> None: ast_node = builder.extract_node("{}.__class__") inferred = next(ast_node.infer()) self.assertIsInstance(inferred, astroid.ClassDef) self.assertEqual(inferred.name, "dict") - def test_attributes_inferred_as_methods(self): + def test_attributes_inferred_as_methods(self) -> None: ast_nodes = builder.extract_node( """ {}.values #@ @@ -639,7 +641,7 @@ def test_attributes_inferred_as_methods(self): inferred = next(node.infer()) self.assertIsInstance(inferred, astroid.BoundMethod) - def test_wrapper_objects_for_dict_methods_python3(self): + def test_wrapper_objects_for_dict_methods_python3(self) -> None: ast_nodes = builder.extract_node( """ {1:1, 2:3}.values() #@ @@ -658,7 +660,7 @@ def test_wrapper_objects_for_dict_methods_python3(self): class LruCacheModelTest(unittest.TestCase): - def test_lru_cache(self): + def test_lru_cache(self) -> None: ast_nodes = builder.extract_node( """ import functools diff --git a/tests/unittest_objects.py b/tests/unittest_objects.py index 3c7ac52b86..699f3b12a0 100644 --- a/tests/unittest_objects.py +++ b/tests/unittest_objects.py @@ -12,13 +12,15 @@ import unittest +from typing import List from astroid import bases, builder, nodes, objects from astroid.exceptions import AttributeInferenceError, InferenceError, SuperError +from astroid.objects import Super class ObjectsTest(unittest.TestCase): - def test_frozenset(self): + def test_frozenset(self) -> None: node = builder.extract_node( """ frozenset({1: 2, 2: 3}) #@ @@ -40,7 +42,7 @@ def test_frozenset(self): class SuperTests(unittest.TestCase): - def test_inferring_super_outside_methods(self): + def test_inferring_super_outside_methods(self) -> None: ast_nodes = builder.extract_node( """ class Module(object): @@ -68,7 +70,7 @@ def static(): self.assertIsInstance(no_arguments, bases.Instance) self.assertEqual(no_arguments.qname(), "builtins.super") - def test_inferring_unbound_super_doesnt_work(self): + def test_inferring_unbound_super_doesnt_work(self) -> None: node = builder.extract_node( """ class Test(object): @@ -80,7 +82,7 @@ def __init__(self): self.assertIsInstance(unbounded, bases.Instance) self.assertEqual(unbounded.qname(), "builtins.super") - def test_use_default_inference_on_not_inferring_args(self): + def test_use_default_inference_on_not_inferring_args(self) -> None: ast_nodes = builder.extract_node( """ class Test(object): @@ -97,7 +99,7 @@ def __init__(self): self.assertIsInstance(second, bases.Instance) self.assertEqual(second.qname(), "builtins.super") - def test_no_arguments_super(self): + def test_no_arguments_super(self) -> None: ast_nodes = builder.extract_node( """ class First(object): pass @@ -123,7 +125,7 @@ def test_classmethod(cls): self.assertIsInstance(second.mro_pointer, nodes.ClassDef) self.assertEqual(second.mro_pointer.name, "Second") - def test_super_simple_cases(self): + def test_super_simple_cases(self) -> None: ast_nodes = builder.extract_node( """ class First(object): pass @@ -187,7 +189,7 @@ class Fourth(Third): self.assertIsInstance(fifth.mro_pointer, nodes.ClassDef) self.assertEqual(fifth.mro_pointer.name, "Fourth") - def test_super_infer(self): + def test_super_infer(self) -> None: node = builder.extract_node( """ class Super(object): @@ -201,7 +203,7 @@ def __init__(self): self.assertIsInstance(reinferred, objects.Super) self.assertIs(inferred, reinferred) - def test_inferring_invalid_supers(self): + def test_inferring_invalid_supers(self) -> None: ast_nodes = builder.extract_node( """ class Super(object): @@ -229,7 +231,7 @@ class Bupper(Super): inferred.super_mro() self.assertIsInstance(cm.exception.super_.type, invalid_type) - def test_proxied(self): + def test_proxied(self) -> None: node = builder.extract_node( """ class Super(object): @@ -242,7 +244,7 @@ def __init__(self): self.assertEqual(proxied.qname(), "builtins.super") self.assertIsInstance(proxied, nodes.ClassDef) - def test_super_bound_model(self): + def test_super_bound_model(self) -> None: ast_nodes = builder.extract_node( """ class First(object): @@ -297,7 +299,7 @@ def method(self): self.assertEqual(sixth.bound.name, "First") self.assertEqual(sixth.type, "classmethod") - def test_super_getattr_single_inheritance(self): + def test_super_getattr_single_inheritance(self) -> None: ast_nodes = builder.extract_node( """ class First(object): @@ -345,7 +347,7 @@ def __init__(self): self.assertEqual(second_unbound.name, "test") self.assertEqual(second_unbound.parent.name, "First") - def test_super_invalid_mro(self): + def test_super_invalid_mro(self) -> None: node = builder.extract_node( """ class A(object): @@ -359,7 +361,7 @@ def __init__(self): with self.assertRaises(AttributeInferenceError): next(inferred.getattr("test")) - def test_super_complex_mro(self): + def test_super_complex_mro(self) -> None: ast_nodes = builder.extract_node( """ class A(object): @@ -396,7 +398,7 @@ def __init__(self): self.assertIsInstance(static, nodes.FunctionDef) self.assertEqual(static.parent.scope().name, "A") - def test_super_data_model(self): + def test_super_data_model(self) -> None: ast_nodes = builder.extract_node( """ class X(object): pass @@ -433,10 +435,10 @@ def __init__(self): selfclass = third.getattr("__self_class__")[0] self.assertEqual(selfclass.name, "A") - def assertEqualMro(self, klass, expected_mro): + def assertEqualMro(self, klass: Super, expected_mro: List[str]) -> None: self.assertEqual([member.name for member in klass.super_mro()], expected_mro) - def test_super_mro(self): + def test_super_mro(self) -> None: ast_nodes = builder.extract_node( """ class A(object): pass @@ -466,7 +468,7 @@ def __init__(self): with self.assertRaises(SuperError): fifth.super_mro() - def test_super_yes_objects(self): + def test_super_yes_objects(self) -> None: ast_nodes = builder.extract_node( """ from collections import Missing @@ -481,7 +483,7 @@ def __init__(self): second = next(ast_nodes[1].infer()) self.assertIsInstance(second, bases.Instance) - def test_super_invalid_types(self): + def test_super_invalid_types(self) -> None: node = builder.extract_node( """ import collections @@ -496,7 +498,7 @@ def __init__(self): with self.assertRaises(SuperError): inferred.super_mro() - def test_super_properties(self): + def test_super_properties(self) -> None: node = builder.extract_node( """ class Foo(object): @@ -516,7 +518,7 @@ def dict(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_super_qname(self): + def test_super_qname(self) -> None: """Make sure a Super object generates a qname equivalent to super.__qname__ """ diff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py index 6c8849deec..6dac89af5f 100644 --- a/tests/unittest_protocols.py +++ b/tests/unittest_protocols.py @@ -15,17 +15,25 @@ import contextlib import unittest +from typing import Any, Callable, Iterator, List, Optional, Union import pytest import astroid -from astroid import extract_node, nodes, util +from astroid import extract_node, nodes from astroid.const import PY38_PLUS, PY310_PLUS from astroid.exceptions import InferenceError +from astroid.manager import AstroidManager +from astroid.util import Uninferable @contextlib.contextmanager -def _add_transform(manager, node, transform, predicate=None): +def _add_transform( + manager: AstroidManager, + node: type, + transform: Callable, + predicate: Optional[Any] = None, +) -> Iterator: manager.register_transform(node, transform, predicate) try: yield @@ -34,21 +42,25 @@ def _add_transform(manager, node, transform, predicate=None): class ProtocolTests(unittest.TestCase): - def assertConstNodesEqual(self, nodes_list_expected, nodes_list_got): + def assertConstNodesEqual( + self, nodes_list_expected: List[int], nodes_list_got: List[nodes.Const] + ) -> None: self.assertEqual(len(nodes_list_expected), len(nodes_list_got)) for node in nodes_list_got: self.assertIsInstance(node, nodes.Const) for node, expected_value in zip(nodes_list_got, nodes_list_expected): self.assertEqual(expected_value, node.value) - def assertNameNodesEqual(self, nodes_list_expected, nodes_list_got): + def assertNameNodesEqual( + self, nodes_list_expected: List[str], nodes_list_got: List[nodes.Name] + ) -> None: self.assertEqual(len(nodes_list_expected), len(nodes_list_got)) for node in nodes_list_got: self.assertIsInstance(node, nodes.Name) for node, expected_name in zip(nodes_list_got, nodes_list_expected): self.assertEqual(expected_name, node.name) - def test_assigned_stmts_simple_for(self): + def test_assigned_stmts_simple_for(self) -> None: assign_stmts = extract_node( """ for a in (1, 2, 3): #@ @@ -66,7 +78,7 @@ def test_assigned_stmts_simple_for(self): for2_assnode = next(assign_stmts[1].nodes_of_class(nodes.AssignName)) self.assertRaises(InferenceError, list, for2_assnode.assigned_stmts()) - def test_assigned_stmts_starred_for(self): + def test_assigned_stmts_starred_for(self) -> None: assign_stmts = extract_node( """ for *a, b in ((1, 2, 3), (4, 5, 6, 7)): #@ @@ -79,27 +91,27 @@ def test_assigned_stmts_starred_for(self): assert isinstance(assigned, astroid.List) assert assigned.as_string() == "[1, 2]" - def _get_starred_stmts(self, code): + def _get_starred_stmts(self, code: str) -> Union[List, Uninferable]: assign_stmt = extract_node(f"{code} #@") starred = next(assign_stmt.nodes_of_class(nodes.Starred)) return next(starred.assigned_stmts()) - def _helper_starred_expected_const(self, code, expected): + def _helper_starred_expected_const(self, code: str, expected: List[int]) -> None: stmts = self._get_starred_stmts(code) self.assertIsInstance(stmts, nodes.List) stmts = stmts.elts self.assertConstNodesEqual(expected, stmts) - def _helper_starred_expected(self, code, expected): + def _helper_starred_expected(self, code: str, expected: Uninferable) -> None: stmts = self._get_starred_stmts(code) self.assertEqual(expected, stmts) - def _helper_starred_inference_error(self, code): + def _helper_starred_inference_error(self, code: str) -> None: assign_stmt = extract_node(f"{code} #@") starred = next(assign_stmt.nodes_of_class(nodes.Starred)) self.assertRaises(InferenceError, list, starred.assigned_stmts()) - def test_assigned_stmts_starred_assnames(self): + def test_assigned_stmts_starred_assnames(self) -> None: self._helper_starred_expected_const("a, *b = (1, 2, 3, 4) #@", [2, 3, 4]) self._helper_starred_expected_const("*a, b = (1, 2, 3) #@", [1, 2]) self._helper_starred_expected_const("a, *b, c = (1, 2, 3, 4, 5) #@", [2, 3, 4]) @@ -107,24 +119,24 @@ def test_assigned_stmts_starred_assnames(self): self._helper_starred_expected_const("*b, a = (1, 2) #@", [1]) self._helper_starred_expected_const("[*b] = (1, 2) #@", [1, 2]) - def test_assigned_stmts_starred_yes(self): + def test_assigned_stmts_starred_yes(self) -> None: # Not something iterable and known - self._helper_starred_expected("a, *b = range(3) #@", util.Uninferable) + self._helper_starred_expected("a, *b = range(3) #@", Uninferable) # Not something inferrable - self._helper_starred_expected("a, *b = balou() #@", util.Uninferable) + self._helper_starred_expected("a, *b = balou() #@", Uninferable) # In function, unknown. self._helper_starred_expected( """ def test(arg): head, *tail = arg #@""", - util.Uninferable, + Uninferable, ) # These cases aren't worth supporting. self._helper_starred_expected( - "a, (*b, c), d = (1, (2, 3, 4), 5) #@", util.Uninferable + "a, (*b, c), d = (1, (2, 3, 4), 5) #@", Uninferable ) - def test_assign_stmts_starred_fails(self): + def test_assign_stmts_starred_fails(self) -> None: # Too many starred self._helper_starred_inference_error("a, *b, *c = (1, 2, 3) #@") # This could be solved properly, but it complicates needlessly the @@ -133,7 +145,7 @@ def test_assign_stmts_starred_fails(self): "(*a, b), (c, *d) = (1, 2, 3), (4, 5, 6) #@" ) - def test_assigned_stmts_assignments(self): + def test_assigned_stmts_assignments(self) -> None: assign_stmts = extract_node( """ c = a #@ @@ -154,7 +166,7 @@ def test_assigned_stmts_assignments(self): assigned = list(simple_mul_assnode_2.assigned_stmts()) self.assertNameNodesEqual(["c"], assigned) - def test_assigned_stmts_annassignments(self): + def test_assigned_stmts_annassignments(self) -> None: annassign_stmts = extract_node( """ a: str = "abc" #@ @@ -172,10 +184,10 @@ def test_assigned_stmts_annassignments(self): empty_annassign_node = next(annassign_stmts[1].nodes_of_class(nodes.AssignName)) assigned = list(empty_annassign_node.assigned_stmts()) self.assertEqual(1, len(assigned)) - self.assertIs(assigned[0], util.Uninferable) + self.assertIs(assigned[0], Uninferable) - def test_sequence_assigned_stmts_not_accepting_empty_node(self): - def transform(node): + def test_sequence_assigned_stmts_not_accepting_empty_node(self) -> None: + def transform(node: nodes.Assign) -> None: node.root().locals["__all__"] = [node.value] manager = astroid.MANAGER @@ -187,9 +199,9 @@ def transform(node): ) module.wildcard_import_names() - def test_not_passing_uninferable_in_seq_inference(self): + def test_not_passing_uninferable_in_seq_inference(self) -> None: class Visitor: - def visit(self, node): + def visit(self, node: Union[nodes.Assign, nodes.BinOp, nodes.List]) -> Any: for child in node.get_children(): child.accept(self) @@ -200,7 +212,7 @@ def visit(self, node): visit_const = visit visit_name = visit - def visit_assignname(self, node): + def visit_assignname(self, node: nodes.AssignName) -> None: for _ in node.infer(): pass @@ -214,7 +226,7 @@ def visit_assignname(self, node): @pytest.mark.skipif(not PY38_PLUS, reason="needs assignment expressions") -def test_named_expr_inference(): +def test_named_expr_inference() -> None: code = """ if (a := 2) == 2: a #@ @@ -287,7 +299,7 @@ def test_assigned_stmts_match_mapping(): match_mapping: nodes.MatchMapping = assign_stmts.pattern # type: ignore assert match_mapping.rest assigned = next(match_mapping.rest.assigned_stmts()) - assert assigned == util.Uninferable + assert assigned == Uninferable @staticmethod def test_assigned_stmts_match_star(): @@ -307,7 +319,7 @@ def test_assigned_stmts_match_star(): match_star = match_sequence.patterns[2] assert isinstance(match_star, nodes.MatchStar) and match_star.name assigned = next(match_star.name.assigned_stmts()) - assert assigned == util.Uninferable + assert assigned == Uninferable @staticmethod def test_assigned_stmts_match_as(): @@ -332,11 +344,11 @@ def test_assigned_stmts_match_as(): match_or_1 = match_or.patterns[1] assert isinstance(match_or_1, nodes.MatchAs) and match_or_1.name assigned_match_or_1 = next(match_or_1.name.assigned_stmts()) - assert assigned_match_or_1 == util.Uninferable + assert assigned_match_or_1 == Uninferable assert match_as_with_pattern.name and match_as_with_pattern.pattern assigned_match_as_pattern = next(match_as_with_pattern.name.assigned_stmts()) - assert assigned_match_as_pattern == util.Uninferable + assert assigned_match_as_pattern == Uninferable assert match_as.name assigned_match_as = next(match_as.name.assigned_stmts()) diff --git a/tests/unittest_python3.py b/tests/unittest_python3.py index 045ce90bb0..7534316e25 100644 --- a/tests/unittest_python3.py +++ b/tests/unittest_python3.py @@ -28,7 +28,7 @@ class Python3TC(unittest.TestCase): def setUpClass(cls): cls.builder = AstroidBuilder() - def test_starred_notation(self): + def test_starred_notation(self) -> None: astroid = self.builder.string_build("*a, b = [1, 2, 3]", "test", "test") # Get the star node @@ -36,7 +36,7 @@ def test_starred_notation(self): self.assertTrue(isinstance(node.assign_type(), nodes.Assign)) - def test_yield_from(self): + def test_yield_from(self) -> None: body = dedent( """ def func(): @@ -52,7 +52,7 @@ def func(): self.assertIsInstance(yieldfrom_stmt.value, nodes.YieldFrom) self.assertEqual(yieldfrom_stmt.as_string(), "yield from iter([1, 2])") - def test_yield_from_is_generator(self): + def test_yield_from_is_generator(self) -> None: body = dedent( """ def func(): @@ -64,7 +64,7 @@ def func(): self.assertIsInstance(func, nodes.FunctionDef) self.assertTrue(func.is_generator()) - def test_yield_from_as_string(self): + def test_yield_from_as_string(self) -> None: body = dedent( """ def func(): @@ -78,7 +78,7 @@ def func(): # metaclass tests - def test_simple_metaclass(self): + def test_simple_metaclass(self) -> None: astroid = self.builder.string_build("class Test(metaclass=type): pass") klass = astroid.body[0] @@ -86,12 +86,12 @@ def test_simple_metaclass(self): self.assertIsInstance(metaclass, nodes.ClassDef) self.assertEqual(metaclass.name, "type") - def test_metaclass_error(self): + def test_metaclass_error(self) -> None: astroid = self.builder.string_build("class Test(metaclass=typ): pass") klass = astroid.body[0] self.assertFalse(klass.metaclass()) - def test_metaclass_imported(self): + def test_metaclass_imported(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -105,7 +105,7 @@ class Test(metaclass=ABCMeta): pass""" self.assertIsInstance(metaclass, nodes.ClassDef) self.assertEqual(metaclass.name, "ABCMeta") - def test_metaclass_multiple_keywords(self): + def test_metaclass_multiple_keywords(self) -> None: astroid = self.builder.string_build( "class Test(magic=None, metaclass=type): pass" ) @@ -115,7 +115,7 @@ def test_metaclass_multiple_keywords(self): self.assertIsInstance(metaclass, nodes.ClassDef) self.assertEqual(metaclass.name, "type") - def test_as_string(self): + def test_as_string(self) -> None: body = dedent( """ from abc import ABCMeta @@ -128,7 +128,7 @@ class Test(metaclass=ABCMeta): pass""" klass.as_string(), "\n\nclass Test(metaclass=ABCMeta):\n pass\n" ) - def test_old_syntax_works(self): + def test_old_syntax_works(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -142,7 +142,7 @@ class SubTest(Test): pass metaclass = klass.metaclass() self.assertIsNone(metaclass) - def test_metaclass_yes_leak(self): + def test_metaclass_yes_leak(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -156,7 +156,7 @@ class Meta(metaclass=ABCMeta): pass klass = astroid["Meta"] self.assertIsNone(klass.metaclass()) - def test_parent_metaclass(self): + def test_parent_metaclass(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -172,7 +172,7 @@ class SubTest(Test): pass self.assertIsInstance(metaclass, nodes.ClassDef) self.assertEqual(metaclass.name, "ABCMeta") - def test_metaclass_ancestors(self): + def test_metaclass_ancestors(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -200,7 +200,7 @@ class ThirdImpl(Simple, SecondMeta): self.assertIsInstance(meta, nodes.ClassDef) self.assertEqual(meta.name, metaclass) - def test_annotation_support(self): + def test_annotation_support(self) -> None: astroid = self.builder.string_build( dedent( """ @@ -242,7 +242,7 @@ def test(a: int=1, b: str=2): self.assertEqual(func.args.annotations[1].name, "str") self.assertIsNone(func.returns) - def test_kwonlyargs_annotations_supper(self): + def test_kwonlyargs_annotations_supper(self) -> None: node = self.builder.string_build( dedent( """ @@ -262,7 +262,7 @@ def test(*, a: int, b: str, c: None, d, e): self.assertIsNone(arguments.kwonlyargs_annotations[3]) self.assertIsNone(arguments.kwonlyargs_annotations[4]) - def test_annotation_as_string(self): + def test_annotation_as_string(self) -> None: code1 = dedent( """ def test(a, b: int = 4, c=2, f: 'lala' = 4) -> 2: @@ -277,7 +277,7 @@ def test(a: typing.Generic[T], c: typing.Any = 24) -> typing.Iterable: func = extract_node(code) self.assertEqual(func.as_string(), code) - def test_unpacking_in_dicts(self): + def test_unpacking_in_dicts(self) -> None: code = "{'x': 1, **{'y': 2}}" node = extract_node(code) self.assertEqual(node.as_string(), code) @@ -286,24 +286,24 @@ def test_unpacking_in_dicts(self): self.assertIsInstance(keys[0], nodes.Const) self.assertIsInstance(keys[1], nodes.DictUnpack) - def test_nested_unpacking_in_dicts(self): + def test_nested_unpacking_in_dicts(self) -> None: code = "{'x': 1, **{'y': 2, **{'z': 3}}}" node = extract_node(code) self.assertEqual(node.as_string(), code) - def test_unpacking_in_dict_getitem(self): + def test_unpacking_in_dict_getitem(self) -> None: node = extract_node("{1:2, **{2:3, 3:4}, **{5: 6}}") for key, expected in ((1, 2), (2, 3), (3, 4), (5, 6)): value = node.getitem(nodes.Const(key)) self.assertIsInstance(value, nodes.Const) self.assertEqual(value.value, expected) - def test_format_string(self): + def test_format_string(self) -> None: code = "f'{greetings} {person}'" node = extract_node(code) self.assertEqual(node.as_string(), code) - def test_underscores_in_numeral_literal(self): + def test_underscores_in_numeral_literal(self) -> None: pairs = [("10_1000", 101000), ("10_000_000", 10000000), ("0x_FF_FF", 65535)] for value, expected in pairs: node = extract_node(value) @@ -311,7 +311,7 @@ def test_underscores_in_numeral_literal(self): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, expected) - def test_async_comprehensions(self): + def test_async_comprehensions(self) -> None: async_comprehensions = [ extract_node( "async def f(): return __([i async for i in aiter() if i % 2])" @@ -359,7 +359,7 @@ def test_async_comprehensions_outside_coroutine(self): node = extract_node(comp) self.assertTrue(node.generators[0].is_async) - def test_async_comprehensions_as_string(self): + def test_async_comprehensions_as_string(self) -> None: func_bodies = [ "return [i async for i in aiter() if condition(i)]", "return [await fun() for fun in funcs]", diff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py index ed9b75831d..dececbcbce 100644 --- a/tests/unittest_raw_building.py +++ b/tests/unittest_raw_building.py @@ -29,51 +29,51 @@ class RawBuildingTC(unittest.TestCase): - def test_attach_dummy_node(self): + def test_attach_dummy_node(self) -> None: node = build_module("MyModule") attach_dummy_node(node, "DummyNode") self.assertEqual(1, len(list(node.get_children()))) - def test_build_module(self): + def test_build_module(self) -> None: node = build_module("MyModule") self.assertEqual(node.name, "MyModule") self.assertEqual(node.pure_python, False) self.assertEqual(node.package, False) self.assertEqual(node.parent, None) - def test_build_class(self): + def test_build_class(self) -> None: node = build_class("MyClass") self.assertEqual(node.name, "MyClass") self.assertEqual(node.doc, None) - def test_build_function(self): + def test_build_function(self) -> None: node = build_function("MyFunction") self.assertEqual(node.name, "MyFunction") self.assertEqual(node.doc, None) - def test_build_function_args(self): + def test_build_function_args(self) -> None: args = ["myArgs1", "myArgs2"] node = build_function("MyFunction", args) self.assertEqual("myArgs1", node.args.args[0].name) self.assertEqual("myArgs2", node.args.args[1].name) self.assertEqual(2, len(node.args.args)) - def test_build_function_defaults(self): + def test_build_function_defaults(self) -> None: defaults = ["defaults1", "defaults2"] node = build_function(name="MyFunction", args=None, defaults=defaults) self.assertEqual(2, len(node.args.defaults)) - def test_build_function_posonlyargs(self): + def test_build_function_posonlyargs(self) -> None: node = build_function(name="MyFunction", posonlyargs=["a", "b"]) self.assertEqual(2, len(node.args.posonlyargs)) - def test_build_function_kwonlyargs(self): + def test_build_function_kwonlyargs(self) -> None: node = build_function(name="MyFunction", kwonlyargs=["a", "b"]) assert len(node.args.kwonlyargs) == 2 assert node.args.kwonlyargs[0].name == "a" assert node.args.kwonlyargs[1].name == "b" - def test_build_from_import(self): + def test_build_from_import(self) -> None: names = ["exceptions, inference, inspector"] node = build_from_import("astroid", names) self.assertEqual(len(names), len(node.names)) diff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py index 5d00ecf022..8b079c4465 100644 --- a/tests/unittest_regrtest.py +++ b/tests/unittest_regrtest.py @@ -37,16 +37,16 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin, unittest.TestCase): - def setUp(self): + def setUp(self) -> None: sys.path.insert(0, resources.find("data")) MANAGER.always_load_extensions = True - def tearDown(self): + def tearDown(self) -> None: MANAGER.always_load_extensions = False sys.path.pop(0) sys.path_importer_cache.pop(resources.find("data"), None) - def test_module_path(self): + def test_module_path(self) -> None: man = test_utils.brainless_manager() mod = man.ast_from_module_name("package.import_package_subpackage_module") package = next(mod.igetattr("package")) @@ -58,7 +58,7 @@ def test_module_path(self): module = next(subpackage.igetattr("module")) self.assertEqual(module.name, "package.subpackage.module") - def test_package_sidepackage(self): + def test_package_sidepackage(self) -> None: manager = test_utils.brainless_manager() assert "package.sidepackage" not in MANAGER.astroid_cache package = manager.ast_from_module_name("absimp") @@ -69,7 +69,7 @@ def test_package_sidepackage(self): self.assertTrue(subpackage.package) self.assertEqual(subpackage.name, "absimp.sidepackage") - def test_living_property(self): + def test_living_property(self) -> None: builder = AstroidBuilder() builder._done = {} builder._module = sys.modules[__name__] @@ -91,7 +91,7 @@ def test_numpy_crash(self): inferred = callfunc.inferred() self.assertEqual(len(inferred), 1) - def test_nameconstant(self): + def test_nameconstant(self) -> None: # used to fail for Python 3.4 builder = AstroidBuilder() astroid = builder.string_build("def test(x=True): pass") @@ -99,7 +99,7 @@ def test_nameconstant(self): self.assertEqual(default.name, "x") self.assertEqual(next(default.infer()).value, True) - def test_recursion_regression_issue25(self): + def test_recursion_regression_issue25(self) -> None: builder = AstroidBuilder() data = """ import recursion as base @@ -120,7 +120,7 @@ def run(): # triggers the _is_metaclass call klass.type # pylint: disable=pointless-statement - def test_decorator_callchain_issue42(self): + def test_decorator_callchain_issue42(self) -> None: builder = AstroidBuilder() data = """ @@ -138,7 +138,7 @@ def crash(): astroid = builder.string_build(data, __name__, __file__) self.assertEqual(astroid["crash"].type, "function") - def test_filter_stmts_scoping(self): + def test_filter_stmts_scoping(self) -> None: builder = AstroidBuilder() data = """ def test(): @@ -155,7 +155,7 @@ class B(compiler.__class__): base = next(result._proxied.bases[0].infer()) self.assertEqual(base.name, "int") - def test_ancestors_patching_class_recursion(self): + def test_ancestors_patching_class_recursion(self) -> None: node = AstroidBuilder().string_build( textwrap.dedent( """ @@ -180,7 +180,7 @@ def test(x=False): ancestors = list(klass.ancestors()) self.assertEqual(ancestors[0].qname(), "string.Template") - def test_ancestors_yes_in_bases(self): + def test_ancestors_yes_in_bases(self) -> None: # Test for issue https://bitbucket.org/logilab/astroid/issue/84 # This used to crash astroid with a TypeError, because an Uninferable # node was present in the bases @@ -202,7 +202,7 @@ class A(with_metaclass(object, lala.lala)): #@ self.assertEqual(len(ancestors), 1) self.assertEqual(ancestors[0].qname(), "builtins.object") - def test_ancestors_missing_from_function(self): + def test_ancestors_missing_from_function(self) -> None: # Test for https://www.logilab.org/ticket/122793 node = extract_node( """ @@ -213,7 +213,7 @@ def gen(): yield ) self.assertRaises(InferenceError, next, node.infer()) - def test_unicode_in_docstring(self): + def test_unicode_in_docstring(self) -> None: # Crashed for astroid==1.4.1 # Test for https://bitbucket.org/logilab/astroid/issues/273/ @@ -233,7 +233,7 @@ def method(self): next(node.value.infer()).as_string() - def test_binop_generates_nodes_with_parents(self): + def test_binop_generates_nodes_with_parents(self) -> None: node = extract_node( """ def no_op(*args): @@ -249,7 +249,7 @@ def inner(*more_args): self.assertIsNotNone(inferred.parent) self.assertIsInstance(inferred.parent, nodes.BinOp) - def test_decorator_names_inference_error_leaking(self): + def test_decorator_names_inference_error_leaking(self) -> None: node = extract_node( """ class Parent(object): @@ -266,7 +266,7 @@ def foo(self): #@ inferred = next(node.infer()) self.assertEqual(inferred.decoratornames(), {".Parent.foo.getter"}) - def test_ssl_protocol(self): + def test_ssl_protocol(self) -> None: node = extract_node( """ import ssl @@ -276,7 +276,7 @@ def test_ssl_protocol(self): inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const) - def test_recursive_property_method(self): + def test_recursive_property_method(self) -> None: node = extract_node( """ class APropert(): @@ -288,7 +288,7 @@ def property(self): ) next(node.infer()) - def test_uninferable_string_argument_of_namedtuple(self): + def test_uninferable_string_argument_of_namedtuple(self) -> None: node = extract_node( """ import collections @@ -297,7 +297,7 @@ def test_uninferable_string_argument_of_namedtuple(self): ) next(node.infer()) - def test_regression_inference_of_self_in_lambda(self): + def test_regression_inference_of_self_in_lambda(self) -> None: code = """ class A: @b(lambda self: __(self)) @@ -314,7 +314,7 @@ class Whatever: a = property(lambda x: x, lambda x: x) # type: ignore -def test_ancestor_looking_up_redefined_function(): +def test_ancestor_looking_up_redefined_function() -> None: code = """ class Foo: def _format(self): @@ -333,7 +333,7 @@ def format(self): assert isinstance(found[0], nodes.FunctionDef) -def test_crash_in_dunder_inference_prevented(): +def test_crash_in_dunder_inference_prevented() -> None: code = """ class MyClass(): def fu(self, objects): diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py index 502d34d271..71ce2f1b2b 100644 --- a/tests/unittest_scoped_nodes.py +++ b/tests/unittest_scoped_nodes.py @@ -37,6 +37,7 @@ import textwrap import unittest from functools import partial +from typing import Any, List, Union import pytest @@ -65,7 +66,9 @@ HAS_SIX = False -def _test_dict_interface(self, node, test_attr): +def _test_dict_interface( + self: Any, node: Union[nodes.ClassDef, nodes.FunctionDef, nodes.Module], test_attr: str +) -> None: self.assertIs(node[test_attr], node[test_attr]) self.assertIn(test_attr, node) node.keys() @@ -75,7 +78,7 @@ def _test_dict_interface(self, node, test_attr): class ModuleLoader(resources.SysPathSetup): - def setUp(self): + def setUp(self) -> None: super().setUp() self.module = resources.build_file("data/module.py", "data.module") self.module2 = resources.build_file("data/module2.py", "data.module2") @@ -84,7 +87,7 @@ def setUp(self): class ModuleNodeTest(ModuleLoader, unittest.TestCase): - def test_special_attributes(self): + def test_special_attributes(self) -> None: self.assertEqual(len(self.module.getattr("__name__")), 1) self.assertIsInstance(self.module.getattr("__name__")[0], nodes.Const) self.assertEqual(self.module.getattr("__name__")[0].value, "data.module") @@ -105,10 +108,10 @@ def test_special_attributes(self): self.assertEqual(len(self.pack.getattr("__path__")), 1) self.assertIsInstance(self.pack.getattr("__path__")[0], nodes.List) - def test_dict_interface(self): + def test_dict_interface(self) -> None: _test_dict_interface(self, self.module, "YO") - def test_getattr(self): + def test_getattr(self) -> None: yo = self.module.getattr("YO")[0] self.assertIsInstance(yo, nodes.ClassDef) self.assertEqual(yo.name, "YO") @@ -130,14 +133,14 @@ def test_getattr(self): self.assertEqual(len(self.nonregr.getattr("enumerate")), 2) self.assertRaises(InferenceError, self.nonregr.igetattr, "YOAA") - def test_wildcard_import_names(self): + def test_wildcard_import_names(self) -> None: m = resources.build_file("data/all.py", "all") self.assertEqual(m.wildcard_import_names(), ["Aaa", "_bla", "name"]) m = resources.build_file("data/notall.py", "notall") res = sorted(m.wildcard_import_names()) self.assertEqual(res, ["Aaa", "func", "name", "other"]) - def test_public_names(self): + def test_public_names(self) -> None: m = builder.parse( """ name = 'a' @@ -182,7 +185,7 @@ def func(): return 'yo' res = sorted(m.public_names()) self.assertEqual(res, ["test", "tzop"]) - def test_module_getattr(self): + def test_module_getattr(self) -> None: data = """ appli = application appli += 2 @@ -192,7 +195,7 @@ def test_module_getattr(self): # test del statement not returned by getattr self.assertEqual(len(astroid.getattr("appli")), 2, astroid.getattr("appli")) - def test_relative_to_absolute_name(self): + def test_relative_to_absolute_name(self) -> None: # package mod = nodes.Module("very.multi.package", "doc") mod.package = True @@ -216,7 +219,7 @@ def test_relative_to_absolute_name(self): modname = mod.relative_to_absolute_name("", 1) self.assertEqual(modname, "very.multi") - def test_relative_to_absolute_name_beyond_top_level(self): + def test_relative_to_absolute_name_beyond_top_level(self) -> None: mod = nodes.Module("a.b.c", "") mod.package = True for level in (5, 4): @@ -229,7 +232,7 @@ def test_relative_to_absolute_name_beyond_top_level(self): ) self.assertEqual(expected, str(cm.exception)) - def test_import_1(self): + def test_import_1(self) -> None: data = """from . import subpackage""" sys.path.insert(0, resources.find("data")) astroid = builder.parse(data, "package", "data/package/__init__.py") @@ -242,7 +245,7 @@ def test_import_1(self): finally: del sys.path[0] - def test_import_2(self): + def test_import_2(self) -> None: data = """from . import subpackage as pouet""" astroid = builder.parse(data, "package", "data/package/__init__.py") sys.path.insert(0, resources.find("data")) @@ -255,27 +258,27 @@ def test_import_2(self): finally: del sys.path[0] - def test_file_stream_in_memory(self): + def test_file_stream_in_memory(self) -> None: data = """irrelevant_variable is irrelevant""" astroid = builder.parse(data, "in_memory") with astroid.stream() as stream: self.assertEqual(stream.read().decode(), data) - def test_file_stream_physical(self): + def test_file_stream_physical(self) -> None: path = resources.find("data/all.py") astroid = builder.AstroidBuilder().file_build(path, "all") with open(path, "rb") as file_io: with astroid.stream() as stream: self.assertEqual(stream.read(), file_io.read()) - def test_file_stream_api(self): + def test_file_stream_api(self) -> None: path = resources.find("data/all.py") file_build = builder.AstroidBuilder().file_build(path, "all") with self.assertRaises(AttributeError): # pylint: disable=pointless-statement, no-member file_build.file_stream - def test_stream_api(self): + def test_stream_api(self) -> None: path = resources.find("data/all.py") astroid = builder.AstroidBuilder().file_build(path, "all") stream = astroid.stream() @@ -286,7 +289,7 @@ def test_stream_api(self): class FunctionNodeTest(ModuleLoader, unittest.TestCase): - def test_special_attributes(self): + def test_special_attributes(self) -> None: func = self.module2["make_class"] self.assertEqual(len(func.getattr("__name__")), 1) self.assertIsInstance(func.getattr("__name__")[0], nodes.Const) @@ -300,10 +303,10 @@ def test_special_attributes(self): self.assertEqual(len(self.module.getattr("__dict__")), 1) self.assertIsInstance(self.module.getattr("__dict__")[0], nodes.Dict) - def test_dict_interface(self): + def test_dict_interface(self) -> None: _test_dict_interface(self, self.module["global_access"], "local") - def test_default_value(self): + def test_default_value(self) -> None: func = self.module2["make_class"] self.assertIsInstance(func.args.default_value("base"), nodes.Attribute) self.assertRaises(NoDefault, func.args.default_value, "args") @@ -313,7 +316,7 @@ def test_default_value(self): # self.assertIsInstance(func.mularg_class('kwargs'), nodes.Dict) # self.assertIsNone(func.mularg_class('base')) - def test_navigation(self): + def test_navigation(self) -> None: function = self.module["global_access"] self.assertEqual(function.statement(), function) l_sibling = function.previous_sibling() @@ -331,13 +334,13 @@ def test_navigation(self): first = l_sibling.root().body[0] self.assertIsNone(first.previous_sibling()) - def test_four_args(self): + def test_four_args(self) -> None: func = self.module["four_args"] local = sorted(func.keys()) self.assertEqual(local, ["a", "b", "c", "d"]) self.assertEqual(func.type, "function") - def test_format_args(self): + def test_format_args(self) -> None: func = self.module2["make_class"] self.assertEqual( func.args.format_args(), "any, base=data.module.YO, *args, **kwargs" @@ -345,7 +348,7 @@ def test_format_args(self): func = self.module["four_args"] self.assertEqual(func.args.format_args(), "a, b, c, d") - def test_format_args_keyword_only_args(self): + def test_format_args_keyword_only_args(self) -> None: node = ( builder.parse( """ @@ -359,12 +362,12 @@ def test(a: int, *, b: dict): formatted = node.format_args() self.assertEqual(formatted, "a: int, *, b: dict") - def test_is_generator(self): + def test_is_generator(self) -> None: self.assertTrue(self.module2["generator"].is_generator()) self.assertFalse(self.module2["not_a_generator"].is_generator()) self.assertFalse(self.module2["make_class"].is_generator()) - def test_is_abstract(self): + def test_is_abstract(self) -> None: method = self.module2["AbstractClass"]["to_override"] self.assertTrue(method.is_abstract(pass_is_abstract=False)) self.assertEqual(method.qname(), "data.module2.AbstractClass.to_override") @@ -375,7 +378,7 @@ def test_is_abstract(self): func = self.module2["raise_string"] self.assertFalse(func.is_abstract(pass_is_abstract=False)) - def test_is_abstract_decorated(self): + def test_is_abstract_decorated(self) -> None: methods = builder.extract_node( """ import abc @@ -410,7 +413,7 @@ def method2(self): #@ ## self.assertEqual([str(term) for term in method.returns()], ## ["Const('toto')", "Const(None)"]) - def test_lambda_pytype(self): + def test_lambda_pytype(self) -> None: data = """ def f(): g = lambda: None @@ -419,11 +422,11 @@ def f(): g = list(astroid["f"].ilookup("g"))[0] self.assertEqual(g.pytype(), "builtins.function") - def test_lambda_qname(self): + def test_lambda_qname(self) -> None: astroid = builder.parse("lmbd = lambda: None", __name__) self.assertEqual("%s." % __name__, astroid["lmbd"].parent.value.qname()) - def test_is_method(self): + def test_is_method(self) -> None: data = """ class A: def meth1(self): @@ -449,12 +452,12 @@ def sfunction(): self.assertFalse(astroid["function"].is_method()) self.assertFalse(astroid["sfunction"].is_method()) - def test_argnames(self): + def test_argnames(self) -> None: code = "def f(a, b, c, *args, **kwargs): pass" astroid = builder.parse(code, __name__) self.assertEqual(astroid["f"].argnames(), ["a", "b", "c", "args", "kwargs"]) - def test_return_nothing(self): + def test_return_nothing(self) -> None: """test inferred value on a function with empty return""" data = """ def func(): @@ -469,7 +472,7 @@ def func(): self.assertIsInstance(func_vals[0], nodes.Const) self.assertIsNone(func_vals[0].value) - def test_no_returns_is_implicitly_none(self): + def test_no_returns_is_implicitly_none(self) -> None: code = """ def f(): print('non-empty, non-pass, no return statements') @@ -481,7 +484,7 @@ def f(): assert isinstance(inferred, nodes.Const) assert inferred.value is None - def test_only_raises_is_not_implicitly_none(self): + def test_only_raises_is_not_implicitly_none(self) -> None: code = """ def f(): raise SystemExit() @@ -491,7 +494,7 @@ def f(): inferred = next(node.infer()) assert inferred is util.Uninferable - def test_abstract_methods_are_not_implicitly_none(self): + def test_abstract_methods_are_not_implicitly_none(self) -> None: code = """ from abc import ABCMeta, abstractmethod @@ -518,7 +521,7 @@ def foo(self): assert isinstance(inferred, nodes.Const) assert inferred.value == value - def test_func_instance_attr(self): + def test_func_instance_attr(self) -> None: """test instance attributes for functions""" data = """ def test(): @@ -535,7 +538,7 @@ def test(): self.assertIsInstance(one, nodes.Const) self.assertEqual(one.value, 1) - def test_type_builtin_descriptor_subclasses(self): + def test_type_builtin_descriptor_subclasses(self) -> None: astroid = builder.parse( """ class classonlymethod(classmethod): @@ -564,7 +567,7 @@ def stcmethod(cls): self.assertEqual(node.locals["staticmethod_subclass"][0].type, "staticmethod") self.assertEqual(node.locals["stcmethod"][0].type, "staticmethod") - def test_decorator_builtin_descriptors(self): + def test_decorator_builtin_descriptors(self) -> None: astroid = builder.parse( """ def static_decorator(platform=None, order=50): @@ -638,7 +641,7 @@ def long_classmethod(cls): self.assertEqual(node.locals["staticmethod_wrapped"][0].type, "staticmethod") self.assertEqual(node.locals["long_classmethod"][0].type, "classmethod") - def test_igetattr(self): + def test_igetattr(self) -> None: func = builder.extract_node( """ def test(): @@ -654,7 +657,7 @@ def test(): self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_return_annotation_is_not_the_last(self): + def test_return_annotation_is_not_the_last(self) -> None: func = builder.extract_node( """ def test() -> bytes: @@ -667,7 +670,7 @@ def test() -> bytes: self.assertIsInstance(last_child, nodes.Return) self.assertEqual(func.tolineno, 5) - def test_method_init_subclass(self): + def test_method_init_subclass(self) -> None: klass = builder.extract_node( """ class MyClass: @@ -679,7 +682,7 @@ def __init_subclass__(cls): self.assertEqual([n.name for n in method.args.args], ["cls"]) self.assertEqual(method.type, "classmethod") - def test_dunder_class_local_to_method(self): + def test_dunder_class_local_to_method(self) -> None: node = builder.extract_node( """ class MyClass: @@ -691,7 +694,7 @@ def test(self): self.assertIsInstance(inferred, nodes.ClassDef) self.assertEqual(inferred.name, "MyClass") - def test_dunder_class_local_to_function(self): + def test_dunder_class_local_to_function(self) -> None: node = builder.extract_node( """ def test(self): @@ -701,7 +704,7 @@ def test(self): with self.assertRaises(NameInferenceError): next(node.infer()) - def test_dunder_class_local_to_classmethod(self): + def test_dunder_class_local_to_classmethod(self) -> None: node = builder.extract_node( """ class MyClass: @@ -716,10 +719,10 @@ def test(cls): class ClassNodeTest(ModuleLoader, unittest.TestCase): - def test_dict_interface(self): + def test_dict_interface(self) -> None: _test_dict_interface(self, self.module["YOUPI"], "method") - def test_cls_special_attributes_1(self): + def test_cls_special_attributes_1(self) -> None: cls = self.module["YO"] self.assertEqual(len(cls.getattr("__bases__")), 1) self.assertEqual(len(cls.getattr("__name__")), 1) @@ -748,7 +751,7 @@ def test_cls_special_attributes_1(self): self.assertEqual(len(cls.getattr("__dict__")), 1) self.assertEqual(len(cls.getattr("__mro__")), 1) - def test__mro__attribute(self): + def test__mro__attribute(self) -> None: node = builder.extract_node( """ class A(object): pass @@ -760,7 +763,7 @@ class C(A, B): pass self.assertIsInstance(mro, nodes.Tuple) self.assertEqual(mro.elts, node.mro()) - def test__bases__attribute(self): + def test__bases__attribute(self) -> None: node = builder.extract_node( """ class A(object): pass @@ -775,7 +778,7 @@ class D(C): pass self.assertIsInstance(bases.elts[0], nodes.ClassDef) self.assertEqual(bases.elts[0].name, "C") - def test_cls_special_attributes_2(self): + def test_cls_special_attributes_2(self) -> None: astroid = builder.parse( """ class A(object): pass @@ -789,7 +792,7 @@ class B(object): pass self.assertIsInstance(astroid["A"].getattr("__bases__")[1], nodes.Tuple) self.assertIsInstance(astroid["A"].getattr("__bases__")[0], nodes.AssignAttr) - def test_instance_special_attributes(self): + def test_instance_special_attributes(self) -> None: for inst in (Instance(self.module["YO"]), nodes.List(), nodes.Const(1)): self.assertRaises(AttributeInferenceError, inst.getattr, "__mro__") self.assertRaises(AttributeInferenceError, inst.getattr, "__bases__") @@ -797,7 +800,7 @@ def test_instance_special_attributes(self): self.assertEqual(len(inst.getattr("__dict__")), 1) self.assertEqual(len(inst.getattr("__doc__")), 1) - def test_navigation(self): + def test_navigation(self) -> None: klass = self.module["YO"] self.assertEqual(klass.statement(), klass) l_sibling = klass.previous_sibling() @@ -807,7 +810,7 @@ def test_navigation(self): self.assertIsInstance(r_sibling, nodes.ClassDef) self.assertEqual(r_sibling.name, "YOUPI") - def test_local_attr_ancestors(self): + def test_local_attr_ancestors(self) -> None: module = builder.parse( """ class A(): @@ -841,7 +844,7 @@ class E(F, D): pass self.assertEqual(anc_klass.name, "object") self.assertRaises(StopIteration, partial(next, it)) - def test_local_attr_mro(self): + def test_local_attr_mro(self) -> None: module = builder.parse( """ class A(object): @@ -865,7 +868,7 @@ class D(C, B): pass ancestors = list(dclass.local_attr_ancestors("__init__")) self.assertEqual([node.name for node in ancestors], ["B", "A", "object"]) - def test_instance_attr_ancestors(self): + def test_instance_attr_ancestors(self) -> None: klass2 = self.module["YOUPI"] it = klass2.instance_attr_ancestors("yo") anc_klass = next(it) @@ -876,7 +879,7 @@ def test_instance_attr_ancestors(self): it = klass2.instance_attr_ancestors("member") self.assertRaises(StopIteration, partial(next, it)) - def test_methods(self): + def test_methods(self) -> None: expected_methods = {"__init__", "class_method", "method", "static_method"} klass2 = self.module["YOUPI"] methods = {m.name for m in klass2.methods()} @@ -901,13 +904,13 @@ def test_methods(self): # self.assertIsInstance(value, nodes.Const) # self.assertEqual(value.value, 1) - def test_ancestors(self): + def test_ancestors(self) -> None: klass = self.module["YOUPI"] self.assertEqual(["YO", "object"], [a.name for a in klass.ancestors()]) klass = self.module2["Specialization"] self.assertEqual(["YOUPI", "YO", "object"], [a.name for a in klass.ancestors()]) - def test_type(self): + def test_type(self) -> None: klass = self.module["YOUPI"] self.assertEqual(klass.type, "class") klass = self.module2["Metaclass"] @@ -922,11 +925,11 @@ def test_type(self): klass = self.module2["NotMetaclass"] self.assertEqual(klass.type, "class") - def test_inner_classes(self): + def test_inner_classes(self) -> None: eee = self.nonregr["Ccc"]["Eee"] self.assertEqual([n.name for n in eee.ancestors()], ["Ddd", "Aaa", "object"]) - def test_classmethod_attributes(self): + def test_classmethod_attributes(self) -> None: data = """ class WebAppObject(object): def registered(cls, application): @@ -948,7 +951,7 @@ def registered(cls, application): ] self.assertEqual(sorted(cls.locals.keys()), assert_keys) - def test_class_getattr(self): + def test_class_getattr(self) -> None: data = """ class WebAppObject(object): appli = application @@ -960,7 +963,7 @@ class WebAppObject(object): # test del statement not returned by getattr self.assertEqual(len(cls.getattr("appli")), 2) - def test_instance_getattr(self): + def test_instance_getattr(self) -> None: data = """ class WebAppObject(object): def __init__(self, application): @@ -973,7 +976,7 @@ def __init__(self, application): # test del statement not returned by getattr self.assertEqual(len(inst.getattr("appli")), 2) - def test_instance_getattr_with_class_attr(self): + def test_instance_getattr_with_class_attr(self) -> None: data = """ class Parent: aa = 1 @@ -997,7 +1000,7 @@ def incr(self, val): self.assertEqual(len(inst.getattr("bb")), 1, inst.getattr("bb")) self.assertEqual(len(inst.getattr("cc")), 2, inst.getattr("cc")) - def test_getattr_method_transform(self): + def test_getattr_method_transform(self) -> None: data = """ class Clazz(object): @@ -1027,7 +1030,7 @@ def func(arg1, arg2): self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], nodes.FunctionDef) - def test_getattr_from_grandpa(self): + def test_getattr_from_grandpa(self) -> None: data = """ class Future: attr = 1 @@ -1046,7 +1049,7 @@ class Past(Present): self.assertIsInstance(attr1, nodes.AssignName) self.assertEqual(attr1.name, "attr") - def test_function_with_decorator_lineno(self): + def test_function_with_decorator_lineno(self) -> None: data = """ @f(a=2, b=3) @@ -1064,7 +1067,7 @@ def g2(): self.assertEqual(astroid["g2"].fromlineno, 9) self.assertEqual(astroid["g2"].tolineno, 10) - def test_metaclass_error(self): + def test_metaclass_error(self) -> None: astroid = builder.parse( """ class Test(object): @@ -1074,7 +1077,7 @@ class Test(object): klass = astroid["Test"] self.assertFalse(klass.metaclass()) - def test_metaclass_yes_leak(self): + def test_metaclass_yes_leak(self) -> None: astroid = builder.parse( """ # notice `ab` instead of `abc` @@ -1087,7 +1090,7 @@ class Meta(object): klass = astroid["Meta"] self.assertIsNone(klass.metaclass()) - def test_metaclass_type(self): + def test_metaclass_type(self) -> None: klass = builder.extract_node( """ def with_metaclass(meta, base=object): @@ -1101,7 +1104,7 @@ class ClassWithMeta(with_metaclass(type)): #@ ["NewBase", "object"], [base.name for base in klass.ancestors()] ) - def test_no_infinite_metaclass_loop(self): + def test_no_infinite_metaclass_loop(self) -> None: klass = builder.extract_node( """ class SSS(object): @@ -1125,7 +1128,7 @@ class BBB(AAA.JJJ): self.assertIn("object", ancestors) self.assertIn("JJJ", ancestors) - def test_no_infinite_metaclass_loop_with_redefine(self): + def test_no_infinite_metaclass_loop_with_redefine(self) -> None: ast_nodes = builder.extract_node( """ import datetime @@ -1158,7 +1161,7 @@ class WithMeta(six.with_metaclass(type, object)): #@ self.assertEqual(["object"], [base.name for base in klass.ancestors()]) self.assertEqual("type", klass.metaclass().name) - def test_add_metaclass(self): + def test_add_metaclass(self) -> None: klass = builder.extract_node( """ import abc @@ -1185,7 +1188,7 @@ class Invalid(object): inferred = next(klass.infer()) self.assertIsNone(inferred.metaclass()) - def test_nonregr_infer_callresult(self): + def test_nonregr_infer_callresult(self) -> None: astroid = builder.parse( """ class Delegate(object): @@ -1204,7 +1207,7 @@ class CompositeBuilder(object): # https://bitbucket.org/logilab/astroid/issue/17 self.assertEqual(list(instance.infer()), [util.Uninferable]) - def test_slots(self): + def test_slots(self) -> None: astroid = builder.parse( """ from collections import deque @@ -1251,7 +1254,7 @@ class Ten(object): #@ else: self.assertEqual(list(expected_value), [node.value for node in slots]) - def test_slots_for_dict_keys(self): + def test_slots_for_dict_keys(self) -> None: module = builder.parse( """ class Issue(object): @@ -1265,7 +1268,7 @@ class Issue(object): self.assertEqual(slots[0].value, "id") self.assertEqual(slots[1].value, "id1") - def test_slots_empty_list_of_slots(self): + def test_slots_empty_list_of_slots(self) -> None: module = builder.parse( """ class Klass(object): @@ -1275,7 +1278,7 @@ class Klass(object): cls = module["Klass"] self.assertEqual(cls.slots(), []) - def test_slots_taken_from_parents(self): + def test_slots_taken_from_parents(self) -> None: module = builder.parse( """ class FirstParent(object): @@ -1292,7 +1295,7 @@ class Third(SecondParent): sorted({slot.value for slot in slots}), ["a", "b", "c", "d", "e"] ) - def test_all_ancestors_need_slots(self): + def test_all_ancestors_need_slots(self) -> None: module = builder.parse( """ class A(object): @@ -1307,7 +1310,7 @@ class C(B): cls = module["B"] self.assertIsNone(cls.slots()) - def test_slots_added_dynamically_still_inferred(self): + def test_slots_added_dynamically_still_inferred(self) -> None: code = """ class NodeBase(object): __slots__ = "a", "b" @@ -1322,10 +1325,10 @@ class NodeBase(object): assert len(slots) == 3, slots assert [slot.value for slot in slots] == ["a", "b", "c"] - def assertEqualMro(self, klass, expected_mro): + def assertEqualMro(self, klass: nodes.ClassDef, expected_mro: List[str]) -> None: self.assertEqual([member.name for member in klass.mro()], expected_mro) - def assertEqualMroQName(self, klass, expected_mro): + def assertEqualMroQName(self, klass: nodes.ClassDef, expected_mro: List[str]) -> None: self.assertEqual([member.qname() for member in klass.mro()], expected_mro) @unittest.skipUnless(HAS_SIX, "These tests require the six library") @@ -1344,7 +1347,7 @@ class A(six.with_metaclass(type, B)): ) self.assertEqualMro(astroid["A"], ["A", "B", "C", "object"]) - def test_mro(self): + def test_mro(self) -> None: astroid = builder.parse( """ class C(object): pass @@ -1436,7 +1439,7 @@ class Duplicates(str, str): pass self.assertIsInstance(cm.exception, MroError) self.assertIsInstance(cm.exception, ResolveError) - def test_mro_with_factories(self): + def test_mro_with_factories(self) -> None: cls = builder.extract_node( """ def MixinFactory(cls): @@ -1475,7 +1478,7 @@ def __init__(self): ], ) - def test_mro_with_attribute_classes(self): + def test_mro_with_attribute_classes(self) -> None: cls = builder.extract_node( """ class A: @@ -1629,7 +1632,7 @@ class B(A[T], A[T]): ... with self.assertRaises(DuplicateBasesError): cls.mro() - def test_generator_from_infer_call_result_parent(self): + def test_generator_from_infer_call_result_parent(self) -> None: func = builder.extract_node( """ import contextlib @@ -1643,7 +1646,7 @@ def test(): #@ self.assertIsInstance(result, Generator) self.assertEqual(result.parent, func) - def test_type_three_arguments(self): + def test_type_three_arguments(self) -> None: classes = builder.extract_node( """ type('A', (object, ), {"a": 1, "b": 2, missing: 3}) #@ @@ -1660,7 +1663,7 @@ def test_type_three_arguments(self): with self.assertRaises(AttributeInferenceError): first.getattr("missing") - def test_implicit_metaclass(self): + def test_implicit_metaclass(self) -> None: cls = builder.extract_node( """ class A(object): @@ -1670,7 +1673,7 @@ class A(object): type_cls = nodes.builtin_lookup("type")[1][0] self.assertEqual(cls.implicit_metaclass(), type_cls) - def test_implicit_metaclass_lookup(self): + def test_implicit_metaclass_lookup(self) -> None: cls = builder.extract_node( """ class A(object): @@ -1682,7 +1685,7 @@ class A(object): self.assertEqual(len(func), 1) self.assertRaises(AttributeInferenceError, instance.getattr, "mro") - def test_metaclass_lookup_using_same_class(self): + def test_metaclass_lookup_using_same_class(self) -> None: # Check that we don't have recursive attribute access for metaclass cls = builder.extract_node( """ @@ -1691,7 +1694,7 @@ class A(object): pass ) self.assertEqual(len(cls.getattr("mro")), 1) - def test_metaclass_lookup_inference_errors(self): + def test_metaclass_lookup_inference_errors(self) -> None: module = builder.parse( """ class Metaclass(type): @@ -1703,7 +1706,7 @@ class B(object, metaclass=Metaclass): pass cls = module["B"] self.assertEqual(util.Uninferable, next(cls.igetattr("foo"))) - def test_metaclass_lookup(self): + def test_metaclass_lookup(self) -> None: module = builder.parse( """ class Metaclass(type): @@ -1753,7 +1756,7 @@ class A(object, metaclass=Metaclass): static = next(acls.igetattr("static")) self.assertIsInstance(static, nodes.FunctionDef) - def test_local_attr_invalid_mro(self): + def test_local_attr_invalid_mro(self) -> None: cls = builder.extract_node( """ # A has an invalid MRO, local_attr should fallback @@ -1769,7 +1772,7 @@ class B(A): #@ self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 42) - def test_has_dynamic_getattr(self): + def test_has_dynamic_getattr(self) -> None: module = builder.parse( """ class Getattr(object): @@ -1794,7 +1797,7 @@ class ParentGetattr(Getattr): module = astroid_builder.module_build(datetime) self.assertFalse(module["timedelta"].has_dynamic_getattr()) - def test_duplicate_bases_namedtuple(self): + def test_duplicate_bases_namedtuple(self) -> None: module = builder.parse( """ import collections @@ -1810,7 +1813,7 @@ class B(A): pass class_names = [i.name for i in mro] self.assertEqual(names, class_names) - def test_instance_bound_method_lambdas(self): + def test_instance_bound_method_lambdas(self) -> None: ast_nodes = builder.extract_node( """ class Test(object): #@ @@ -1829,7 +1832,7 @@ class Test(object): #@ not_method = next(instance.igetattr("not_method")) self.assertIsInstance(not_method, nodes.Lambda) - def test_instance_bound_method_lambdas_2(self): + def test_instance_bound_method_lambdas_2(self) -> None: """ Test the fact that a method which is a lambda built from a factory is well inferred as a bound method (bug pylint 2594) @@ -1852,7 +1855,7 @@ class MyClass(object): #@ f2 = next(instance.igetattr("f2")) self.assertIsInstance(f2, BoundMethod) - def test_class_extra_decorators_frame_is_not_class(self): + def test_class_extra_decorators_frame_is_not_class(self) -> None: ast_node = builder.extract_node( """ def ala(): @@ -1862,7 +1865,7 @@ def bala(): #@ ) self.assertEqual(ast_node.extra_decorators, []) - def test_class_extra_decorators_only_callfunc_are_considered(self): + def test_class_extra_decorators_only_callfunc_are_considered(self) -> None: ast_node = builder.extract_node( """ class Ala(object): @@ -1873,7 +1876,7 @@ def func(self): #@ ) self.assertEqual(ast_node.extra_decorators, []) - def test_class_extra_decorators_only_assignment_names_are_considered(self): + def test_class_extra_decorators_only_assignment_names_are_considered(self) -> None: ast_node = builder.extract_node( """ class Ala(object): @@ -1886,7 +1889,7 @@ def __init__(self): ) self.assertEqual(ast_node.extra_decorators, []) - def test_class_extra_decorators_only_same_name_considered(self): + def test_class_extra_decorators_only_same_name_considered(self) -> None: ast_node = builder.extract_node( """ class Ala(object): @@ -1898,7 +1901,7 @@ def func(self): #@ self.assertEqual(ast_node.extra_decorators, []) self.assertEqual(ast_node.type, "method") - def test_class_extra_decorators(self): + def test_class_extra_decorators(self) -> None: static_method, clsmethod = builder.extract_node( """ class Ala(object): @@ -1915,7 +1918,7 @@ def class_method(self): #@ self.assertEqual(len(static_method.extra_decorators), 1) self.assertEqual(static_method.type, "staticmethod") - def test_extra_decorators_only_class_level_assignments(self): + def test_extra_decorators_only_class_level_assignments(self) -> None: node = builder.extract_node( """ def _bind(arg): @@ -1940,7 +1943,7 @@ def irelevant(self): parent = bind.scope() self.assertEqual(len(parent.extra_decorators), 0) - def test_class_keywords(self): + def test_class_keywords(self) -> None: data = """ class TestKlass(object, metaclass=TestMetaKlass, foo=42, bar='baz'): @@ -1957,7 +1960,7 @@ class TestKlass(object, metaclass=TestMetaKlass, assert children[1].arg == "foo" assert children[2].arg == "bar" - def test_kite_graph(self): + def test_kite_graph(self) -> None: data = """ A = type('A', (object,), {}) @@ -1975,7 +1978,7 @@ def update(self): builder.parse(data) -def test_issue940_metaclass_subclass_property(): +def test_issue940_metaclass_subclass_property() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -1994,7 +1997,7 @@ class Derived(Parent): assert [c.value for c in inferred.elts] == ["a", "property"] -def test_issue940_property_grandchild(): +def test_issue940_property_grandchild() -> None: node = builder.extract_node( """ class Grandparent: @@ -2013,7 +2016,7 @@ class Child(Parent): assert [c.value for c in inferred.elts] == ["a", "property"] -def test_issue940_metaclass_property(): +def test_issue940_metaclass_property() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -2030,7 +2033,7 @@ class Parent(metaclass=BaseMeta): assert [c.value for c in inferred.elts] == ["a", "property"] -def test_issue940_with_metaclass_class_context_property(): +def test_issue940_with_metaclass_class_context_property() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -2049,7 +2052,7 @@ class Derived(Parent): assert isinstance(inferred, objects.Property) -def test_issue940_metaclass_values_funcdef(): +def test_issue940_metaclass_values_funcdef() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -2065,7 +2068,7 @@ class Parent(metaclass=BaseMeta): assert [c.value for c in inferred.elts] == ["a", "func"] -def test_issue940_metaclass_derived_funcdef(): +def test_issue940_metaclass_derived_funcdef() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -2083,7 +2086,7 @@ class Derived(Parent): assert [c.value for c in inferred_result.elts] == ["a", "func"] -def test_issue940_metaclass_funcdef_is_not_datadescriptor(): +def test_issue940_metaclass_funcdef_is_not_datadescriptor() -> None: node = builder.extract_node( """ class BaseMeta(type): @@ -2106,7 +2109,7 @@ class Derived(Parent): assert isinstance(inferred, objects.Property) -def test_issue940_enums_as_a_real_world_usecase(): +def test_issue940_enums_as_a_real_world_usecase() -> None: node = builder.extract_node( """ from enum import Enum @@ -2122,7 +2125,7 @@ class Sounds(Enum): assert sorted(actual) == ["bee", "cat"] -def test_metaclass_cannot_infer_call_yields_an_instance(): +def test_metaclass_cannot_infer_call_yields_an_instance() -> None: node = builder.extract_node( """ from undefined import Undefined @@ -2191,7 +2194,7 @@ def test_posonlyargs_python_38(func): @test_utils.require_version("3.8") -def test_posonlyargs_default_value(): +def test_posonlyargs_default_value() -> None: ast_node = builder.extract_node( """ def func(a, b=1, /, c=2): pass @@ -2207,7 +2210,7 @@ def func(a, b=1, /, c=2): pass @test_utils.require_version(minver="3.7") -def test_ancestor_with_generic(): +def test_ancestor_with_generic() -> None: # https://github.com/PyCQA/astroid/issues/942 tree = builder.parse( """ @@ -2232,7 +2235,7 @@ class C(B[str]): pass ] -def test_slots_duplicate_bases_issue_1089(): +def test_slots_duplicate_bases_issue_1089() -> None: astroid = builder.parse( """ class First(object, object): #@ diff --git a/tests/unittest_transforms.py b/tests/unittest_transforms.py index e1a91a1931..63ac10dd29 100644 --- a/tests/unittest_transforms.py +++ b/tests/unittest_transforms.py @@ -14,12 +14,21 @@ import contextlib import time import unittest +from typing import Callable, Iterator, Optional from astroid import MANAGER, builder, nodes, parse, transforms +from astroid.manager import AstroidManager +from astroid.nodes.node_classes import Call, Compare, Const, Name +from astroid.nodes.scoped_nodes import FunctionDef, Module @contextlib.contextmanager -def add_transform(manager, node, transform, predicate=None): +def add_transform( + manager: AstroidManager, + node: type, + transform: Callable, + predicate: Optional[Callable] = None, +) -> Iterator: manager.register_transform(node, transform, predicate) try: yield @@ -28,15 +37,15 @@ def add_transform(manager, node, transform, predicate=None): class TestTransforms(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.transformer = transforms.TransformVisitor() - def parse_transform(self, code): + def parse_transform(self, code: str) -> Module: module = parse(code, apply_transforms=False) return self.transformer.visit(module) - def test_function_inlining_transform(self): - def transform_call(node): + def test_function_inlining_transform(self) -> None: + def transform_call(node: Call) -> Const: # Let's do some function inlining inferred = next(node.infer()) return inferred @@ -54,17 +63,17 @@ def test(): return 42 self.assertIsInstance(module.body[1].value, nodes.Const) self.assertEqual(module.body[1].value.value, 42) - def test_recursive_transforms_into_astroid_fields(self): + def test_recursive_transforms_into_astroid_fields(self) -> None: # Test that the transformer walks properly the tree # by going recursively into the _astroid_fields per each node. - def transform_compare(node): + def transform_compare(node: Compare) -> Const: # Let's check the values of the ops _, right = node.ops[0] # Assume they are Consts and they were transformed before # us. return nodes.const_factory(node.left.value < right.value) - def transform_name(node): + def transform_name(node: Name) -> Const: # Should be Consts return next(node.infer()) @@ -83,8 +92,8 @@ def transform_name(node): self.assertIsInstance(module.body[2].value, nodes.Const) self.assertFalse(module.body[2].value.value) - def test_transform_patches_locals(self): - def transform_function(node): + def test_transform_patches_locals(self) -> None: + def transform_function(node: FunctionDef) -> None: assign = nodes.Assign() name = nodes.AssignName(name="value") assign.targets = [name] @@ -105,12 +114,12 @@ def test(): self.assertIsInstance(func.body[1], nodes.Assign) self.assertEqual(func.body[1].as_string(), "value = 42") - def test_predicates(self): - def transform_call(node): + def test_predicates(self) -> None: + def transform_call(node: Call) -> Const: inferred = next(node.infer()) return inferred - def should_inline(node): + def should_inline(node: Call) -> bool: return node.func.name.startswith("inlineme") self.transformer.register_transform(nodes.Call, transform_call, should_inline) @@ -138,13 +147,13 @@ def inlineme_2(): self.assertIsInstance(values[2].value, nodes.Const) self.assertEqual(values[2].value.value, 2) - def test_transforms_are_separated(self): + def test_transforms_are_separated(self) -> None: # Test that the transforming is done at a separate # step, which means that we are not doing inference # on a partially constructed tree anymore, which was the # source of crashes in the past when certain inference rules # were used in a transform. - def transform_function(node): + def transform_function(node: FunctionDef) -> Const: if node.decorators: for decorator in node.decorators.nodes: inferred = next(decorator.infer()) @@ -178,16 +187,16 @@ def bala(self): self.assertIsInstance(bala, nodes.Const) self.assertEqual(bala.value, 42) - def test_transforms_are_called_for_builtin_modules(self): + def test_transforms_are_called_for_builtin_modules(self) -> None: # Test that transforms are called for builtin modules. - def transform_function(node): + def transform_function(node: FunctionDef) -> FunctionDef: name = nodes.AssignName(name="value") node.args.args = [name] return node manager = MANAGER - def predicate(node): + def predicate(node: FunctionDef) -> bool: return node.root().name == "time" with add_transform(manager, nodes.FunctionDef, transform_function, predicate): @@ -199,7 +208,7 @@ def predicate(node): self.assertIsInstance(asctime.args.args[0], nodes.AssignName) self.assertEqual(asctime.args.args[0].name, "value") - def test_builder_apply_transforms(self): + def test_builder_apply_transforms(self) -> None: def transform_function(node): return nodes.const_factory(42) @@ -211,7 +220,7 @@ def transform_function(node): # The transform wasn't applied. self.assertIsInstance(module.body[0], nodes.FunctionDef) - def test_transform_crashes_on_is_subtype_of(self): + def test_transform_crashes_on_is_subtype_of(self) -> None: # Test that we don't crash when having is_subtype_of # in a transform, as per issue #188. This happened # before, when the transforms weren't in their own step. diff --git a/tests/unittest_utils.py b/tests/unittest_utils.py index ea5d036210..fd2026fda3 100644 --- a/tests/unittest_utils.py +++ b/tests/unittest_utils.py @@ -18,7 +18,7 @@ class InferenceUtil(unittest.TestCase): - def test_not_exclusive(self): + def test_not_exclusive(self) -> None: module = builder.parse( """ x = 10 @@ -39,7 +39,7 @@ def test_not_exclusive(self): self.assertEqual(nodes.are_exclusive(xass1, xnames[1]), False) self.assertEqual(nodes.are_exclusive(xass1, xnames[2]), False) - def test_if(self): + def test_if(self) -> None: module = builder.parse( """ if 1: @@ -66,7 +66,7 @@ def test_if(self): self.assertEqual(nodes.are_exclusive(a3, a4), False) self.assertEqual(nodes.are_exclusive(a5, a6), False) - def test_try_except(self): + def test_try_except(self) -> None: module = builder.parse( """ try: @@ -98,7 +98,7 @@ def exclusive_func2(): self.assertEqual(nodes.are_exclusive(f4, f1), False) self.assertEqual(nodes.are_exclusive(f4, f2), True) - def test_unpack_infer_uninferable_nodes(self): + def test_unpack_infer_uninferable_nodes(self) -> None: node = builder.extract_node( """ x = [A] * 1 @@ -111,7 +111,7 @@ def test_unpack_infer_uninferable_nodes(self): self.assertEqual(len(unpacked), 3) self.assertTrue(all(elt is Uninferable for elt in unpacked)) - def test_unpack_infer_empty_tuple(self): + def test_unpack_infer_empty_tuple(self) -> None: node = builder.extract_node( """ () From b793f9bfeacca9ba7dd498bb195a981df8f61e23 Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Sat, 4 Sep 2021 16:44:38 +0200 Subject: [PATCH 2/3] Add some assert for mypy's sake --- tests/unittest_brain.py | 12 +++++ tests/unittest_brain_ctypes.py | 4 ++ tests/unittest_brain_dataclasses.py | 3 ++ tests/unittest_helpers.py | 5 +- tests/unittest_inference.py | 24 +++++++++- tests/unittest_inference_calls.py | 25 +++++++++- tests/unittest_nodes.py | 2 +- tests/unittest_object_model.py | 20 ++++---- tests/unittest_objects.py | 11 +++++ tests/unittest_protocols.py | 1 + tests/unittest_scoped_nodes.py | 74 ++++++++++++++++++++++------- 11 files changed, 152 insertions(+), 29 deletions(-) diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index d91cae4018..fd3cfae7c0 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -186,6 +186,7 @@ class X(namedtuple("X", ["a", "b", "c"])): pass """ ) + assert isinstance(klass, nodes.ClassDef) self.assertEqual( [anc.name for anc in klass.ancestors()], ["X", "tuple", "object"] ) @@ -203,6 +204,7 @@ class X(namedtuple(name, fields)): pass """ ) + assert isinstance(klass, nodes.ClassDef) base = next(base for base in klass.ancestors() if base.name == "X") self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs)) @@ -490,6 +492,7 @@ def test_nose_tools(self): assert_equals = assert_equals #@ """ ) + assert isinstance(methods, list) assert_equal = next(methods[0].value.infer()) assert_true = next(methods[1].value.infer()) assert_equals = next(methods[2].value.infer()) @@ -514,6 +517,7 @@ def test_attribute_access(self) -> None: six.moves.urllib.request #@ """ ) + assert isinstance(ast_nodes, list) http_client = next(ast_nodes[0].infer()) self.assertIsInstance(http_client, nodes.Module) self.assertEqual(http_client.name, "http.client") @@ -638,6 +642,7 @@ def test_multiprocessing_module_attributes(self) -> None: import multiprocessing """ ) + assert isinstance(module, nodes.Import) module = module.do_import_module("multiprocessing") cpu_count = next(module.igetattr("cpu_count")) self.assertIsInstance(cpu_count, astroid.BoundMethod) @@ -809,6 +814,7 @@ class Color(Enum): Color.red #@ """ ) + assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], astroid.Const) @@ -1087,6 +1093,7 @@ class Color(EnumSubclass): Color.red.name #@ """ ) + assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], astroid.Const) @@ -1106,6 +1113,7 @@ class Color(EnumSubclass): Color.red.value #@ """ ) + assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], astroid.Const) @@ -1127,6 +1135,7 @@ class Color(EnumSubclass): Color.red.hello_pylint() #@ """ ) + assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], astroid.Const) @@ -1153,6 +1162,7 @@ class Color(EnumSubclass): Color.red.value #@ """ ) + assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], astroid.Const) @@ -1271,6 +1281,7 @@ def test_invalid_type_subscript(self): self.assertEqual(val_inf.name, "str") with self.assertRaises(AttributeInferenceError): # pylint: disable=expression-not-assigned + # noinspection PyStatementEffect val_inf.getattr("__class_getitem__")[0] @test_utils.require_version(minver="3.9") @@ -2999,6 +3010,7 @@ def __len__(self) -> int: len(Crash()) #@ """ ) + assert isinstance(node, nodes.NodeNG) node.inferred() diff --git a/tests/unittest_brain_ctypes.py b/tests/unittest_brain_ctypes.py index 07201528f3..ee0213d4f1 100644 --- a/tests/unittest_brain_ctypes.py +++ b/tests/unittest_brain_ctypes.py @@ -61,6 +61,7 @@ def test_ctypes_redefined_types_members(c_type, builtin_type, type_code): x.value """ node = extract_node(src) + assert isinstance(node, nodes.NodeNG) node_inf = node.inferred()[0] assert node_inf.pytype() == f"builtins.{builtin_type}" @@ -70,6 +71,7 @@ def test_ctypes_redefined_types_members(c_type, builtin_type, type_code): x._type_ """ node = extract_node(src) + assert isinstance(node, nodes.NodeNG) node_inf = node.inferred()[0] assert isinstance(node_inf, nodes.Const) assert node_inf.value == type_code @@ -86,6 +88,7 @@ def test_cdata_member_access() -> None: x._objects """ node = extract_node(src) + assert isinstance(node, nodes.NodeNG) node_inf = node.inferred()[0] assert node_inf.display_type() == "Class" assert node_inf.qname() == "_ctypes._SimpleCData._objects" @@ -100,6 +103,7 @@ def test_other_ctypes_member_untouched() -> None: ctypes.ARRAY(3, 2) """ node = extract_node(src) + assert isinstance(node, nodes.NodeNG) node_inf = node.inferred()[0] assert isinstance(node_inf, nodes.Const) assert node_inf.value == 6 diff --git a/tests/unittest_brain_dataclasses.py b/tests/unittest_brain_dataclasses.py index 13a85ed8b3..97ec18eca6 100644 --- a/tests/unittest_brain_dataclasses.py +++ b/tests/unittest_brain_dataclasses.py @@ -187,6 +187,7 @@ class A: # Both the class and instance can still access the attribute for node in (klass, instance): + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -218,6 +219,7 @@ class A: # Both the class and instance can still access the attribute for node in (klass, instance): + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -249,6 +251,7 @@ class A: # Both the class and instance can still access the attribute for node in (klass, instance): + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) diff --git a/tests/unittest_helpers.py b/tests/unittest_helpers.py index c72c16179a..44b88130bc 100644 --- a/tests/unittest_helpers.py +++ b/tests/unittest_helpers.py @@ -13,7 +13,7 @@ import builtins import unittest -from astroid import builder, helpers, manager, raw_building, util +from astroid import builder, helpers, manager, nodes, raw_building, util from astroid.exceptions import _NonDeducibleTypeHierarchy from astroid.nodes.scoped_nodes import ClassDef @@ -81,6 +81,7 @@ def static_method(): pass generator() #@ """ ) + assert isinstance(ast_nodes, list) from_self = helpers.object_type(ast_nodes[0]) cls = next(ast_nodes[1].infer()) self.assert_classes_equal(from_self, cls) @@ -136,6 +137,7 @@ class D(B , C): #@ pass """ ) + assert isinstance(node, nodes.NodeNG) metaclass = node.metaclass() self.assertEqual(metaclass.name, "A") obj_type = helpers.object_type(node) @@ -175,6 +177,7 @@ class C(A): pass #@ int_subclass() #@ """ ) + assert isinstance(ast_nodes, list) cls_a = ast_nodes[0] cls_b = ast_nodes[1] cls_c = ast_nodes[2] diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py index 92e9257872..e2502539f9 100644 --- a/tests/unittest_inference.py +++ b/tests/unittest_inference.py @@ -124,7 +124,7 @@ def assertInferConst(self, node: nodes.Call, expected: str) -> None: self.assertEqual(inferred.value, expected) def assertInferDict( - self, node: Union[nodes.Call, nodes.Dict], expected: Any + self, node: Union[nodes.Call, nodes.Dict, nodes.NodeNG], expected: Any ) -> None: inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Dict) @@ -1072,6 +1072,7 @@ def __add__(self, other): 1 + A() #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.Const) self.assertEqual(first.value, 43) @@ -1089,6 +1090,7 @@ def __radd__(self, other): 1 + A() #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertEqual(first, util.Uninferable) @@ -1311,6 +1313,7 @@ def get_context_data(self, **kwargs): return ctx """ node = extract_node(code) + assert isinstance(node, nodes.NodeNG) result = node.inferred() assert len(result) == 2 assert isinstance(result[0], nodes.Dict) @@ -1666,11 +1669,13 @@ def __mul__(self, other): """ ast = parse(code, __name__) node = ast["c"] + assert isinstance(node, nodes.NodeNG) self.assertEqual(node.inferred(), [util.Uninferable]) def test_infer_empty_nodes(self) -> None: # Should not crash when trying to infer EmptyNodes. node = nodes.EmptyNode() + assert isinstance(node, nodes.NodeNG) self.assertEqual(node.inferred(), [util.Uninferable]) def test_infinite_loop_for_decorators(self) -> None: @@ -1974,6 +1979,7 @@ def test_conversion_of_dict_methods(self) -> None: set({1:2, 2:4}.keys()) #@ """ ) + assert isinstance(ast_nodes, list) self.assertInferList(ast_nodes[0], [2, 3]) self.assertInferList(ast_nodes[1], [1, 2]) self.assertInferTuple(ast_nodes[2], [2, 3]) @@ -3317,6 +3323,7 @@ def __index__(self): return None a * NotIndex2() #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.List) self.assertEqual([node.value for node in first.itered()], [1, 2, 1, 2]) @@ -3341,6 +3348,7 @@ class NonIndex(object): a[NonIndex()] #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.Const) self.assertEqual(first.value, 3) @@ -3792,6 +3800,7 @@ def __enter__(self): c #@ """ ) + assert isinstance(ast_nodes, list) first_a = next(ast_nodes[0].infer()) self.assertIsInstance(first_a, Instance) self.assertEqual(first_a.name, "A") @@ -3865,6 +3874,7 @@ def __call__(cls): cls #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.ClassDef) second = next(ast_nodes[1].infer()) @@ -4240,6 +4250,7 @@ def test_default(self) -> None: getattr(int, 'bala', getattr(int, 'portocala', None)) #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.Const) self.assertIsNone(first.value) @@ -4273,7 +4284,7 @@ def test(self): getattr(self, 'test') #@ """ ) - + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, BoundMethod) self.assertEqual(first.bound.name, "A") @@ -4419,6 +4430,7 @@ def test(): pass 1 and test #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertEqual(first.value, 0) second = next(ast_nodes[1].infer()) @@ -4862,6 +4874,7 @@ def test(): wrapper()() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], nodes.Const, inferred[0]) @@ -5071,6 +5084,7 @@ def test_unpack_dicts_in_assignment() -> None: b #@ """ ) + assert isinstance(ast_nodes, list) first_inferred = next(ast_nodes[0].infer()) second_inferred = next(ast_nodes[1].infer()) assert isinstance(first_inferred, nodes.Const) @@ -5179,6 +5193,7 @@ def lru_cache(self, value): Foo().lru_cache(1) """ node = extract_node(code) + assert isinstance(node, nodes.NodeNG) [result] = node.inferred() assert result.value == 1 @@ -5219,6 +5234,7 @@ class Sub(Base): val #@ """ ) + assert isinstance(node, nodes.NodeNG) [val] = node.inferred() assert isinstance(val, Instance) assert val.name == "Sub" @@ -5368,6 +5384,7 @@ def test_exception_lookup_last_except_handler_wins() -> None: exc #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 inferred_exc = inferred[0] @@ -5386,6 +5403,7 @@ def test_exception_lookup_last_except_handler_wins() -> None: exc #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 inferred_exc = inferred[0] @@ -5407,6 +5425,7 @@ def test_exception_lookup_name_bound_in_except_handler() -> None: name #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 inferred_exc = inferred[0] @@ -5564,6 +5583,7 @@ def both_branches(): both_branches() #@ """ ast_nodes = extract_node(code) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) assert isinstance(first, nodes.Const) assert first.value == 1 diff --git a/tests/unittest_inference_calls.py b/tests/unittest_inference_calls.py index 3ffcca2ab8..bb487d0277 100644 --- a/tests/unittest_inference_calls.py +++ b/tests/unittest_inference_calls.py @@ -14,6 +14,7 @@ def f(): f() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -29,6 +30,7 @@ def f(): f() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -49,6 +51,7 @@ def f(x): f(1) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -70,6 +73,7 @@ def f(x): f(100) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 3 assert all(isinstance(node, nodes.Const) for node in inferred) @@ -86,6 +90,7 @@ def f(x, y): f(1, 2) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -105,6 +110,7 @@ def g(): f() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -126,6 +132,7 @@ def g(y): f() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -149,6 +156,7 @@ def g(y): f(1) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -170,6 +178,7 @@ def get_x(self): A().get_x() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -198,6 +207,7 @@ def get_x(self): A().get_x() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 3 assert all(isinstance(node, nodes.Const) for node in inferred) @@ -231,6 +241,7 @@ def get_x(self): A().get_x() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 4 assert all(isinstance(node, nodes.Const) for node in inferred) @@ -255,6 +266,7 @@ def get_x(self): A(1).get_x() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -276,6 +288,7 @@ def get_x(self, x): A().get_x(1) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -300,6 +313,7 @@ def set_x(self, x): A().get_x(10) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable # not 10! @@ -326,6 +340,7 @@ def set_x(self, x): A().get_x() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -356,6 +371,7 @@ def set_x(self, x): A().get_x(1) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -382,6 +398,7 @@ def set_x(self, x): A().get_x(1) #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -405,7 +422,7 @@ def __getitem__(self, i): A(1)[2] #@ """ ) - + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert inferred[0] is Uninferable @@ -427,6 +444,7 @@ def method(self, x): ) for node in nodes_: + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) @@ -449,6 +467,7 @@ def method(cls, x): ) for node in nodes_: + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const), node @@ -470,6 +489,7 @@ def method(x): ) for node in nodes_: + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const), node @@ -500,6 +520,7 @@ class B(A): ) expected = ["A", "A", "B", "B", "B"] for node, expected in zip(nodes_, expected): + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], bases.Instance) @@ -530,6 +551,7 @@ class B(A): ) expected = ["A", "A", "B", "B"] for node, expected in zip(nodes_, expected): + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.ClassDef) @@ -560,6 +582,7 @@ def f(self): B().a.f() #@ """ ) + assert isinstance(node, nodes.NodeNG) inferred = node.inferred() assert len(inferred) == 1 assert isinstance(inferred[0], nodes.Const) diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py index f76c7fcc5c..67b1134c51 100644 --- a/tests/unittest_nodes.py +++ b/tests/unittest_nodes.py @@ -122,7 +122,7 @@ def test_frozenset_as_string(self) -> None: """ ) ast_nodes = [next(node.infer()) for node in ast_nodes] - + assert isinstance(ast_nodes, list) self.assertEqual(ast_nodes[0].as_string(), "frozenset((1, 2, 3))") self.assertEqual(ast_nodes[1].as_string(), "frozenset({1, 2, 3})") self.assertEqual(ast_nodes[2].as_string(), "frozenset([1, 2, 3])") diff --git a/tests/unittest_object_model.py b/tests/unittest_object_model.py index 4018f79821..374d92020c 100644 --- a/tests/unittest_object_model.py +++ b/tests/unittest_object_model.py @@ -17,7 +17,7 @@ import pytest import astroid -from astroid import builder, objects, test_utils, util +from astroid import builder, nodes, objects, test_utils, util from astroid.exceptions import InferenceError @@ -37,7 +37,7 @@ def __init__(self): """, module_name="fake_module", ) - + assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) self.assertIsInstance(cls, astroid.ClassDef) self.assertEqual(cls.name, "A") @@ -84,7 +84,7 @@ def test(self): pass a.test.__self__ #@ """ ) - + assert isinstance(ast_nodes, list) func = next(ast_nodes[0].infer()) self.assertIsInstance(func, astroid.FunctionDef) self.assertEqual(func.name, "test") @@ -109,7 +109,7 @@ def test(self): pass t.im_self #@ """ ) - + assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) self.assertIsInstance(cls, astroid.ClassDef) unbound_name = "function" @@ -180,7 +180,7 @@ class C(A): pass """, module_name="fake_module", ) - + assert isinstance(ast_nodes, list) module = next(ast_nodes[0].infer()) self.assertIsInstance(module, astroid.Const) self.assertEqual(module.value, "fake_module") @@ -256,7 +256,7 @@ def test_module_model(self) -> None: xml.__dict__ #@ """ ) - + assert isinstance(ast_nodes, list) path = next(ast_nodes[0].infer()) self.assertIsInstance(path, astroid.List) self.assertIsInstance(path.elts[0], astroid.Const) @@ -377,6 +377,7 @@ def mymethod2(self): cl #@ """ ) + assert isinstance(node, nodes.NodeNG) [const] = node.inferred() assert const.value == "MyText" @@ -397,7 +398,7 @@ def func(a=1, b=2): ''', module_name="fake_module", ) - + assert isinstance(ast_nodes, list) name = next(ast_nodes[0].infer()) self.assertIsInstance(name, astroid.Const) self.assertEqual(name.value, "func") @@ -511,7 +512,7 @@ def test(): gen.send #@ """ ) - + assert isinstance(ast_nodes, list) name = next(ast_nodes[0].infer()) self.assertEqual(name.value, "test") @@ -543,6 +544,7 @@ def test_valueerror_py3(self) -> None: err.message #@ """ ) + assert isinstance(ast_nodes, list) args = next(ast_nodes[0].infer()) self.assertIsInstance(args, astroid.Tuple) tb = next(ast_nodes[1].infer()) @@ -649,6 +651,7 @@ def test_wrapper_objects_for_dict_methods_python3(self) -> None: {1:1, 2:3}.items() #@ """ ) + assert isinstance(ast_nodes, list) values = next(ast_nodes[0].infer()) self.assertIsInstance(values, objects.DictValues) self.assertEqual([elt.value for elt in values.elts], [1, 3]) @@ -674,6 +677,7 @@ def foo(): f.foo.cache_info() #@ """ ) + assert isinstance(ast_nodes, list) cache_clear = next(ast_nodes[0].infer()) self.assertIsInstance(cache_clear, astroid.BoundMethod) wrapped = next(ast_nodes[1].infer()) diff --git a/tests/unittest_objects.py b/tests/unittest_objects.py index 699f3b12a0..a792dc71de 100644 --- a/tests/unittest_objects.py +++ b/tests/unittest_objects.py @@ -58,6 +58,7 @@ def static(): super() #@ """ ) + assert isinstance(ast_nodes, list) in_static = next(ast_nodes[0].value.infer()) self.assertIsInstance(in_static, bases.Instance) self.assertEqual(in_static.qname(), "builtins.super") @@ -91,6 +92,7 @@ def __init__(self): super(Test, lala) #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.Instance) self.assertEqual(first.qname(), "builtins.super") @@ -111,6 +113,7 @@ def test_classmethod(cls): super() #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) self.assertIsInstance(first.type, bases.Instance) @@ -150,6 +153,7 @@ class Fourth(Third): # the lookup should be done. # super(Third, self) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) self.assertIsInstance(first.type, bases.Instance) @@ -218,6 +222,7 @@ class Bupper(Super): pass """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) with self.assertRaises(SuperError) as cm: @@ -269,6 +274,7 @@ def method(self): """ ) # Super(type, type) is the same for both functions and classmethods. + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, nodes.FunctionDef) self.assertEqual(first.name, "method") @@ -321,6 +327,7 @@ def __init__(self): """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.BoundMethod) self.assertEqual(first.bound.name, "Second") @@ -383,6 +390,7 @@ def __init__(self): super(E, self).static #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.BoundMethod) self.assertEqual(first.bound.name, "C") @@ -409,6 +417,7 @@ def __init__(self): super(X, A) #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) thisclass = first.getattr("__thisclass__")[0] self.assertIsInstance(thisclass, nodes.ClassDef) @@ -454,6 +463,7 @@ def __init__(self): super(1, B) #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertEqualMro(first, ["C", "B", "A", "object"]) second = next(ast_nodes[1].infer()) @@ -478,6 +488,7 @@ def __init__(self): super(A, Missing) #@ """ ) + assert isinstance(ast_nodes, list) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.Instance) second = next(ast_nodes[1].infer()) diff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py index 6dac89af5f..9d8445ed54 100644 --- a/tests/unittest_protocols.py +++ b/tests/unittest_protocols.py @@ -252,6 +252,7 @@ def test(value=(p := 24)): return p x #@ """ ast_nodes = extract_node(code) + assert isinstance(ast_nodes, list) node = next(ast_nodes[0].infer()) assert isinstance(node, nodes.Const) assert node.value == 2 diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py index 71ce2f1b2b..0408246954 100644 --- a/tests/unittest_scoped_nodes.py +++ b/tests/unittest_scoped_nodes.py @@ -67,7 +67,9 @@ def _test_dict_interface( - self: Any, node: Union[nodes.ClassDef, nodes.FunctionDef, nodes.Module], test_attr: str + self: Any, + node: Union[nodes.ClassDef, nodes.FunctionDef, nodes.Module], + test_attr: str, ) -> None: self.assertIs(node[test_attr], node[test_attr]) self.assertIn(test_attr, node) @@ -398,20 +400,30 @@ def method2(self): #@ pass """ ) - self.assertTrue(methods[0].is_abstract(pass_is_abstract=False)) - self.assertTrue(methods[1].is_abstract(pass_is_abstract=False)) - self.assertFalse(methods[2].is_abstract(pass_is_abstract=False)) + assert len(methods) == 3 + prop, method1, method2 = methods + assert isinstance(prop, nodes.FunctionDef) + assert prop.is_abstract(pass_is_abstract=False) - ## def test_raises(self): - ## method = self.module2['AbstractClass']['to_override'] - ## self.assertEqual([str(term) for term in method.raises()], - ## ["Call(Name('NotImplementedError'), [], None, None)"] ) + assert isinstance(method1, nodes.FunctionDef) + assert method1.is_abstract(pass_is_abstract=False) - ## def test_returns(self): - ## method = self.module2['AbstractClass']['return_something'] - ## # use string comp since Node doesn't handle __cmp__ - ## self.assertEqual([str(term) for term in method.returns()], - ## ["Const('toto')", "Const(None)"]) + assert isinstance(method2, nodes.FunctionDef) + assert not method2.is_abstract(pass_is_abstract=False) + + # def test_raises(self): + # method = self.module2["AbstractClass"]["to_override"] + # self.assertEqual( + # [str(term) for term in method.raises()], + # ["Call(Name('NotImplementedError'), [], None, None)"], + # ) + + # def test_returns(self): + # method = self.module2["AbstractClass"]["return_something"] + # # use string comp since Node doesn't handle __cmp__ + # self.assertEqual( + # [str(term) for term in method.returns()], ["Const('toto')", "Const(None)"] + # ) def test_lambda_pytype(self) -> None: data = """ @@ -490,7 +502,8 @@ def f(): raise SystemExit() f() """ - node = builder.extract_node(code) # type: nodes.Call + node = builder.extract_node(code) + assert isinstance(node, nodes.Call) inferred = next(node.infer()) assert inferred is util.Uninferable @@ -648,6 +661,7 @@ def test(): pass """ ) + assert isinstance(func, nodes.FunctionDef) func.instance_attrs["value"] = [nodes.Const(42)] value = func.getattr("value") self.assertEqual(len(value), 1) @@ -759,6 +773,7 @@ class B(object): pass class C(A, B): pass """ ) + assert isinstance(node, nodes.ClassDef) mro = node.getattr("__mro__")[0] self.assertIsInstance(mro, nodes.Tuple) self.assertEqual(mro.elts, node.mro()) @@ -772,6 +787,7 @@ class C(A, B): pass class D(C): pass """ ) + assert isinstance(node, nodes.ClassDef) bases = node.getattr("__bases__")[0] self.assertIsInstance(bases, nodes.Tuple) self.assertEqual(len(bases.elts), 1) @@ -1100,6 +1116,7 @@ class ClassWithMeta(with_metaclass(type)): #@ pass """ ) + assert isinstance(klass, nodes.ClassDef) self.assertEqual( ["NewBase", "object"], [base.name for base in klass.ancestors()] ) @@ -1123,6 +1140,7 @@ class BBB(AAA.JJJ): pass """ ) + assert isinstance(klass, nodes.ClassDef) self.assertFalse(_is_metaclass(klass)) ancestors = [base.name for base in klass.ancestors()] self.assertIn("object", ancestors) @@ -1158,6 +1176,7 @@ class WithMeta(six.with_metaclass(type, object)): #@ pass """ ) + assert isinstance(klass, nodes.ClassDef) self.assertEqual(["object"], [base.name for base in klass.ancestors()]) self.assertEqual("type", klass.metaclass().name) @@ -1170,6 +1189,7 @@ class WithMeta(object, metaclass=abc.ABCMeta): pass """ ) + assert isinstance(klass, nodes.ClassDef) inferred = next(klass.infer()) metaclass = inferred.metaclass() self.assertIsInstance(metaclass, nodes.ClassDef) @@ -1328,7 +1348,9 @@ class NodeBase(object): def assertEqualMro(self, klass: nodes.ClassDef, expected_mro: List[str]) -> None: self.assertEqual([member.name for member in klass.mro()], expected_mro) - def assertEqualMroQName(self, klass: nodes.ClassDef, expected_mro: List[str]) -> None: + def assertEqualMroQName( + self, klass: nodes.ClassDef, expected_mro: List[str] + ) -> None: self.assertEqual([member.qname() for member in klass.mro()], expected_mro) @unittest.skipUnless(HAS_SIX, "These tests require the six library") @@ -1463,6 +1485,7 @@ def __init__(self): self.name = 'x' """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMro( cls, [ @@ -1494,6 +1517,7 @@ class C(scope.A, scope.B): pass """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMro(cls, ["C", "A", "B", "object"]) @test_utils.require_version(minver="3.7") @@ -1507,6 +1531,7 @@ class B: ... class C(A[T], B): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".C", ".A", "typing.Generic", ".B", "builtins.object"] ) @@ -1522,6 +1547,7 @@ class B(Generic[T]): ... class C(Generic[T], A, B[T]): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"] ) @@ -1538,6 +1564,7 @@ class C(Generic[T]): ... class D(B[T], C[T], Generic[T]): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".D", ".B", ".A", ".C", "typing.Generic", "builtins.object"] ) @@ -1553,6 +1580,7 @@ class B(Generic[T]): ... class C(A, Generic[T], B[T]): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"] ) @@ -1569,6 +1597,7 @@ class B(Generic[T2]): ... class C(A[T1], B[T2]): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"] ) @@ -1585,6 +1614,7 @@ class B(TGeneric[T]): ... class C(A, B[T]): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".C", ".A", ".Generic", ".B", "typing.Generic", "builtins.object"] ) @@ -1602,6 +1632,7 @@ class D: ... class E(C[str], D): ... """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqualMroQName( cls, [".E", ".C", ".A", ".B", "typing.Generic", ".D", "builtins.object"] ) @@ -1616,6 +1647,7 @@ def test_mro_generic_error_1(self): class A(Generic[T1], Generic[T2]): ... """ ) + assert isinstance(cls, nodes.ClassDef) with self.assertRaises(DuplicateBasesError): cls.mro() @@ -1629,6 +1661,7 @@ class A(Generic[T]): ... class B(A[T], A[T]): ... """ ) + assert isinstance(cls, nodes.ClassDef) with self.assertRaises(DuplicateBasesError): cls.mro() @@ -1642,6 +1675,7 @@ def test(): #@ yield """ ) + assert isinstance(func, nodes.FunctionDef) result = next(func.infer_call_result()) self.assertIsInstance(result, Generator) self.assertEqual(result.parent, func) @@ -1652,6 +1686,7 @@ def test_type_three_arguments(self) -> None: type('A', (object, ), {"a": 1, "b": 2, missing: 3}) #@ """ ) + assert isinstance(classes, nodes.Call) first = next(classes.infer()) self.assertIsInstance(first, nodes.ClassDef) self.assertEqual(first.name, "A") @@ -1670,6 +1705,7 @@ class A(object): pass """ ) + assert isinstance(cls, nodes.ClassDef) type_cls = nodes.builtin_lookup("type")[1][0] self.assertEqual(cls.implicit_metaclass(), type_cls) @@ -1680,18 +1716,20 @@ class A(object): pass """ ) + assert isinstance(cls, nodes.ClassDef) instance = cls.instantiate_class() func = cls.getattr("mro") self.assertEqual(len(func), 1) self.assertRaises(AttributeInferenceError, instance.getattr, "mro") def test_metaclass_lookup_using_same_class(self) -> None: - # Check that we don't have recursive attribute access for metaclass + """Check that we don't have recursive attribute access for metaclass""" cls = builder.extract_node( """ class A(object): pass """ ) + assert isinstance(cls, nodes.ClassDef) self.assertEqual(len(cls.getattr("mro")), 1) def test_metaclass_lookup_inference_errors(self) -> None: @@ -1767,6 +1805,7 @@ class B(A): #@ pass """ ) + assert isinstance(cls, nodes.ClassDef) local = cls.local_attr("test")[0] inferred = next(local.infer()) self.assertIsInstance(inferred, nodes.Const) @@ -1822,6 +1861,7 @@ class Test(object): #@ Test() #@ """ ) + assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) self.assertIsInstance(next(cls.igetattr("lam")), nodes.Lambda) self.assertIsInstance(next(cls.igetattr("not_method")), nodes.Lambda) @@ -1848,6 +1888,7 @@ class MyClass(object): #@ MyClass() #@ """ ) + assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) self.assertIsInstance(next(cls.igetattr("f2")), nodes.Lambda) @@ -1863,6 +1904,7 @@ def bala(): #@ func = 42 """ ) + assert isinstance(ast_node, nodes.FunctionDef) self.assertEqual(ast_node.extra_decorators, []) def test_class_extra_decorators_only_callfunc_are_considered(self) -> None: From a91360b4c8c2d6a6bdee72478c6bd30e511914af Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Sat, 4 Sep 2021 18:25:55 +0200 Subject: [PATCH 3/3] Avoid adding mypy_extension by using pytest skip --- tests/unittest_builder.py | 10 ++++------ tests/unittest_nodes.py | 10 ++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py index 37b38ca96e..2ae6ce81b2 100644 --- a/tests/unittest_builder.py +++ b/tests/unittest_builder.py @@ -29,7 +29,6 @@ import unittest import pytest -from mypy_extensions import NoReturn from astroid import Instance, builder, nodes, test_utils, util from astroid.const import PY38_PLUS @@ -99,7 +98,10 @@ def test_callfunc_lineno(self) -> None: self.assertEqual(arg.fromlineno, 10 + i) self.assertEqual(arg.tolineno, 10 + i) - def test_function_lineno(self) -> NoReturn: + @pytest.mark.skip( + "FIXME http://bugs.python.org/issue10445 (no line number on function args)" + ) + def test_function_lineno(self) -> None: stmts = self.astroid.body # on line 15: # def definition(a, @@ -114,10 +116,6 @@ def test_function_lineno(self) -> NoReturn: self.assertIsInstance(return_, nodes.Return) self.assertEqual(return_.fromlineno, 18) self.assertEqual(return_.tolineno, 18) - self.skipTest( - "FIXME http://bugs.python.org/issue10445 " - "(no line number on function args)" - ) def test_decorated_function_lineno(self) -> None: astroid = builder.parse( diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py index 67b1134c51..9cc9465659 100644 --- a/tests/unittest_nodes.py +++ b/tests/unittest_nodes.py @@ -36,7 +36,6 @@ from typing import Any, Optional import pytest -from mypy_extensions import NoReturn import astroid from astroid import ( @@ -729,8 +728,11 @@ def test_as_string(self) -> None: self.assertEqual(ast.as_string().strip(), code.strip()) +@pytest.mark.skip( + "FIXME http://bugs.python.org/issue10445 (no line number on function args)" +) class ArgumentsNodeTC(unittest.TestCase): - def test_linenumbering(self) -> NoReturn: + def test_linenumbering(self) -> None: ast = builder.parse( """ def func(a, @@ -744,10 +746,6 @@ def func(a, self.assertEqual(xlambda.args.fromlineno, 4) self.assertEqual(xlambda.args.tolineno, 4) self.assertFalse(xlambda.args.is_statement) - self.skipTest( - "FIXME http://bugs.python.org/issue10445 " - "(no line number on function args)" - ) def test_kwoargs(self) -> None: ast = builder.parse(