summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--tests/resources.py10
-rw-r--r--tests/unittest_brain.py346
-rw-r--r--tests/unittest_brain_ctypes.py8
-rw-r--r--tests/unittest_brain_dataclasses.py5
-rw-r--r--tests/unittest_builder.py116
-rw-r--r--tests/unittest_helpers.py38
-rw-r--r--tests/unittest_inference.py703
-rw-r--r--tests/unittest_inference_calls.py73
-rw-r--r--tests/unittest_lookup.py110
-rw-r--r--tests/unittest_manager.py71
-rw-r--r--tests/unittest_modutils.py98
-rw-r--r--tests/unittest_nodes.py223
-rw-r--r--tests/unittest_object_model.py78
-rw-r--r--tests/unittest_objects.py53
-rw-r--r--tests/unittest_protocols.py73
-rw-r--r--tests/unittest_python3.py46
-rw-r--r--tests/unittest_raw_building.py18
-rw-r--r--tests/unittest_regrtest.py42
-rw-r--r--tests/unittest_scoped_nodes.py301
-rw-r--r--tests/unittest_transforms.py49
-rw-r--r--tests/unittest_utils.py10
21 files changed, 1338 insertions, 1133 deletions
diff --git a/tests/resources.py b/tests/resources.py
index e01440f2..ebb6f7a4 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 a45b8710..c87fa0d0 100644
--- a/tests/unittest_brain.py
+++ b/tests/unittest_brain.py
@@ -43,13 +43,17 @@ import queue
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 @@ except ImportError:
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 @@ class HashlibTest(unittest.TestCase):
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 @@ class HashlibTest(unittest.TestCase):
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 @@ class CollectionsDequeTests(unittest.TestCase):
)
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 @@ class CollectionsDequeTests(unittest.TestCase):
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 @@ class OrderedDictTest(unittest.TestCase):
)
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
@@ -182,13 +186,14 @@ class NamedTupleTest(unittest.TestCase):
pass
"""
)
+ assert isinstance(klass, nodes.ClassDef)
self.assertEqual(
[anc.name for anc in klass.ancestors()], ["X", "tuple", "object"]
)
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
@@ -199,10 +204,11 @@ class NamedTupleTest(unittest.TestCase):
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))
- def test_namedtuple_inference_failure(self):
+ def test_namedtuple_inference_failure(self) -> None:
klass = builder.extract_node(
"""
from collections import namedtuple
@@ -213,7 +219,7 @@ class NamedTupleTest(unittest.TestCase):
)
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 +237,7 @@ class NamedTupleTest(unittest.TestCase):
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 +248,7 @@ class NamedTupleTest(unittest.TestCase):
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 +260,7 @@ class NamedTupleTest(unittest.TestCase):
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 +272,7 @@ class NamedTupleTest(unittest.TestCase):
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 +284,7 @@ class NamedTupleTest(unittest.TestCase):
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 +297,7 @@ class NamedTupleTest(unittest.TestCase):
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 +310,7 @@ class NamedTupleTest(unittest.TestCase):
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 +324,7 @@ class NamedTupleTest(unittest.TestCase):
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 +338,7 @@ class NamedTupleTest(unittest.TestCase):
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 +351,7 @@ class NamedTupleTest(unittest.TestCase):
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 +363,7 @@ class NamedTupleTest(unittest.TestCase):
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 +374,7 @@ class NamedTupleTest(unittest.TestCase):
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 +385,7 @@ class NamedTupleTest(unittest.TestCase):
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 +396,7 @@ class NamedTupleTest(unittest.TestCase):
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 +407,7 @@ class NamedTupleTest(unittest.TestCase):
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 +418,7 @@ class NamedTupleTest(unittest.TestCase):
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 +429,7 @@ class NamedTupleTest(unittest.TestCase):
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 +442,7 @@ class NamedTupleTest(unittest.TestCase):
# 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 +458,7 @@ class NamedTupleTest(unittest.TestCase):
class DefaultDictTest(unittest.TestCase):
- def test_1(self):
+ def test_1(self) -> None:
node = builder.extract_node(
"""
from collections import defaultdict
@@ -466,7 +472,7 @@ class DefaultDictTest(unittest.TestCase):
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)
@@ -486,6 +492,7 @@ class NoseBrainTest(unittest.TestCase):
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())
@@ -500,7 +507,7 @@ class NoseBrainTest(unittest.TestCase):
@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
@@ -510,6 +517,7 @@ class SixBrainTest(unittest.TestCase):
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")
@@ -542,7 +550,7 @@ class SixBrainTest(unittest.TestCase):
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 +562,7 @@ class SixBrainTest(unittest.TestCase):
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 +576,7 @@ class SixBrainTest(unittest.TestCase):
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 +603,8 @@ class SixBrainTest(unittest.TestCase):
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 +633,7 @@ class SixBrainTest(unittest.TestCase):
"(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.
@@ -634,11 +642,12 @@ class MultiprocessingBrainTest(unittest.TestCase):
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)
- def test_module_name(self):
+ def test_module_name(self) -> None:
module = builder.extract_node(
"""
import multiprocessing
@@ -649,7 +658,7 @@ class MultiprocessingBrainTest(unittest.TestCase):
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 +718,7 @@ class MultiprocessingBrainTest(unittest.TestCase):
class ThreadingBrainTest(unittest.TestCase):
- def test_lock(self):
+ def test_lock(self) -> None:
lock_instance = builder.extract_node(
"""
import threading
@@ -725,16 +734,16 @@ class ThreadingBrainTest(unittest.TestCase):
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 +753,7 @@ class ThreadingBrainTest(unittest.TestCase):
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 +761,7 @@ class ThreadingBrainTest(unittest.TestCase):
class EnumBrainTest(unittest.TestCase):
- def test_simple_enum(self):
+ def test_simple_enum(self) -> None:
module = builder.parse(
"""
import enum
@@ -778,7 +787,7 @@ class EnumBrainTest(unittest.TestCase):
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 +801,7 @@ class EnumBrainTest(unittest.TestCase):
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(
"""
@@ -805,12 +814,13 @@ class EnumBrainTest(unittest.TestCase):
Color.red #@
"""
)
+ assert isinstance(ast_node, nodes.NodeNG)
inferred = ast_node.inferred()
self.assertEqual(len(inferred), 1)
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 +835,7 @@ class EnumBrainTest(unittest.TestCase):
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 +856,7 @@ class EnumBrainTest(unittest.TestCase):
"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 +875,7 @@ class EnumBrainTest(unittest.TestCase):
"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 +891,7 @@ class EnumBrainTest(unittest.TestCase):
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 +903,7 @@ class EnumBrainTest(unittest.TestCase):
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 +918,7 @@ class EnumBrainTest(unittest.TestCase):
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 +931,7 @@ class EnumBrainTest(unittest.TestCase):
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 +953,7 @@ class EnumBrainTest(unittest.TestCase):
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 +965,7 @@ class EnumBrainTest(unittest.TestCase):
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 +977,7 @@ class EnumBrainTest(unittest.TestCase):
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 +996,7 @@ class EnumBrainTest(unittest.TestCase):
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 +1015,7 @@ class EnumBrainTest(unittest.TestCase):
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 +1025,7 @@ class EnumBrainTest(unittest.TestCase):
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 +1050,7 @@ class EnumBrainTest(unittest.TestCase):
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 +1079,7 @@ class EnumBrainTest(unittest.TestCase):
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
@@ -1083,12 +1093,13 @@ class EnumBrainTest(unittest.TestCase):
Color.red.name #@
"""
)
+ assert isinstance(ast_node, nodes.NodeNG)
inferred = ast_node.inferred()
self.assertEqual(len(inferred), 1)
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
@@ -1102,12 +1113,13 @@ class EnumBrainTest(unittest.TestCase):
Color.red.value #@
"""
)
+ assert isinstance(ast_node, nodes.NodeNG)
inferred = ast_node.inferred()
self.assertEqual(len(inferred), 1)
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(
"""
@@ -1123,12 +1135,13 @@ class EnumBrainTest(unittest.TestCase):
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)
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(
"""
@@ -1149,6 +1162,7 @@ class EnumBrainTest(unittest.TestCase):
Color.red.value #@
"""
)
+ assert isinstance(ast_node, nodes.NodeNG)
inferred = ast_node.inferred()
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], astroid.Const)
@@ -1169,7 +1183,7 @@ class DateutilBrainTest(unittest.TestCase):
class PytestBrainTest(unittest.TestCase):
- def test_pytest(self):
+ def test_pytest(self) -> None:
ast_node = builder.extract_node(
"""
import pytest
@@ -1267,6 +1281,7 @@ class TypeBrain(unittest.TestCase):
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")
@@ -1293,7 +1308,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 +1476,7 @@ class CollectionsBrain(unittest.TestCase):
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 +1491,7 @@ class TypingBrain(unittest.TestCase):
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 +1511,7 @@ class TypingBrain(unittest.TestCase):
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 +1523,7 @@ class TypingBrain(unittest.TestCase):
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 +1538,7 @@ class TypingBrain(unittest.TestCase):
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 +1549,7 @@ class TypingBrain(unittest.TestCase):
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 +1560,7 @@ class TypingBrain(unittest.TestCase):
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 +1571,7 @@ class TypingBrain(unittest.TestCase):
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 +1582,7 @@ class TypingBrain(unittest.TestCase):
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 +1602,7 @@ class TypingBrain(unittest.TestCase):
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 +1613,7 @@ class TypingBrain(unittest.TestCase):
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 +1628,7 @@ class TypingBrain(unittest.TestCase):
)
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
@@ -1709,7 +1724,7 @@ class TypingBrain(unittest.TestCase):
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
@@ -1720,7 +1735,7 @@ class TypingBrain(unittest.TestCase):
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
@@ -1932,7 +1947,7 @@ class TypingBrain(unittest.TestCase):
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
@@ -1948,7 +1963,7 @@ class TypingBrain(unittest.TestCase):
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
@@ -1966,7 +1981,7 @@ class TypingBrain(unittest.TestCase):
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:
@@ -2048,7 +2063,7 @@ class ReBrainTest(unittest.TestCase):
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
@@ -2065,7 +2080,7 @@ class BrainFStrings(unittest.TestCase):
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
@@ -2080,7 +2095,7 @@ class BrainNamedtupleAnnAssignTest(unittest.TestCase):
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
@@ -2094,7 +2109,7 @@ class BrainUUIDTest(unittest.TestCase):
@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
@@ -2135,7 +2150,7 @@ class AttrsTest(unittest.TestCase):
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 = """
@@ -2151,7 +2166,7 @@ class AttrsTest(unittest.TestCase):
# 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
@@ -2165,7 +2180,7 @@ class AttrsTest(unittest.TestCase):
"""
next(astroid.extract_node(code).infer())
- def test_attrs_with_annotation(self):
+ def test_attrs_with_annotation(self) -> None:
code = """
import attr
@@ -2179,7 +2194,7 @@ class AttrsTest(unittest.TestCase):
class RandomSampleTest(unittest.TestCase):
- def test_inferred_successfully(self):
+ def test_inferred_successfully(self) -> None:
node = astroid.extract_node(
"""
import random
@@ -2191,7 +2206,7 @@ class RandomSampleTest(unittest.TestCase):
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
@@ -2207,7 +2222,7 @@ class RandomSampleTest(unittest.TestCase):
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"""
@@ -2221,7 +2236,7 @@ class SubprocessTest(unittest.TestCase):
[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
@@ -2244,23 +2259,23 @@ class SubprocessTest(unittest.TestCase):
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(
"""
@@ -2272,7 +2287,7 @@ class TestIsinstanceInference:
== "True"
)
- def test_isinstance_object_true3(self):
+ def test_isinstance_object_true3(self) -> None:
assert (
_get_result(
"""
@@ -2284,7 +2299,7 @@ class TestIsinstanceInference:
== "True"
)
- def test_isinstance_class_false(self):
+ def test_isinstance_class_false(self) -> None:
assert (
_get_result(
"""
@@ -2298,7 +2313,7 @@ class TestIsinstanceInference:
== "False"
)
- def test_isinstance_type_false(self):
+ def test_isinstance_type_false(self) -> None:
assert (
_get_result(
"""
@@ -2310,18 +2325,18 @@ class TestIsinstanceInference:
== "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(
"""
@@ -2331,7 +2346,7 @@ class TestIsinstanceInference:
== "False"
)
- def test_isinstance_object_true2(self):
+ def test_isinstance_object_true2(self) -> None:
assert (
_get_result(
"""
@@ -2344,7 +2359,7 @@ class TestIsinstanceInference:
== "True"
)
- def test_isinstance_type_true(self):
+ def test_isinstance_type_true(self) -> None:
assert (
_get_result(
"""
@@ -2357,26 +2372,26 @@ class TestIsinstanceInference:
== "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)")
@@ -2384,22 +2399,22 @@ class TestIsinstanceInference:
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(
"""
@@ -2411,7 +2426,7 @@ class TestIssubclassBrain:
== "True"
)
- def test_issubclass_same_user_defined_class(self):
+ def test_issubclass_same_user_defined_class(self) -> None:
assert (
_get_result(
"""
@@ -2423,7 +2438,7 @@ class TestIssubclassBrain:
== "True"
)
- def test_issubclass_different_user_defined_classes(self):
+ def test_issubclass_different_user_defined_classes(self) -> None:
assert (
_get_result(
"""
@@ -2437,7 +2452,7 @@ class TestIssubclassBrain:
== "False"
)
- def test_issubclass_type_false(self):
+ def test_issubclass_type_false(self) -> None:
assert (
_get_result(
"""
@@ -2449,11 +2464,11 @@ class TestIssubclassBrain:
== "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(
"""
@@ -2465,38 +2480,38 @@ class TestIssubclassBrain:
== "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(
"""
@@ -2507,7 +2522,7 @@ class TestLenBuiltinInference:
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'))
@@ -2516,7 +2531,7 @@ class TestLenBuiltinInference:
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(
"""
@@ -2527,7 +2542,7 @@ class TestLenBuiltinInference:
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(
"""
@@ -2538,7 +2553,7 @@ class TestLenBuiltinInference:
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'})
@@ -2547,7 +2562,7 @@ class TestLenBuiltinInference:
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(
"""
@@ -2560,7 +2575,7 @@ class TestLenBuiltinInference:
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(
"""
@@ -2579,7 +2594,7 @@ class TestLenBuiltinInference:
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(
"""
@@ -2592,7 +2607,7 @@ class TestLenBuiltinInference:
with pytest.raises(InferenceError):
next(node.infer())
- def test_len_string(self):
+ def test_len_string(self) -> None:
node = astroid.extract_node(
"""
len("uwu")
@@ -2600,7 +2615,7 @@ class TestLenBuiltinInference:
)
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():
@@ -2612,7 +2627,7 @@ class TestLenBuiltinInference:
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)
@@ -2621,7 +2636,7 @@ class TestLenBuiltinInference:
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')
@@ -2629,7 +2644,7 @@ class TestLenBuiltinInference:
)
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
@@ -2662,7 +2677,7 @@ class TestLenBuiltinInference:
)
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
@@ -2674,7 +2689,9 @@ class TestLenBuiltinInference:
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
@@ -2695,7 +2712,7 @@ class TestLenBuiltinInference:
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) #@
@@ -2717,7 +2734,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) #@
@@ -2743,7 +2760,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() #@
@@ -2829,7 +2846,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
@@ -2855,7 +2872,7 @@ class TestFunctoolsPartial:
"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
@@ -2883,7 +2900,7 @@ class TestFunctoolsPartial:
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(
"""
@@ -2905,7 +2922,7 @@ class TestFunctoolsPartial:
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(
"""
@@ -2924,7 +2941,7 @@ class TestFunctoolsPartial:
assert set(scope) == {"test2"}
-def test_http_client_brain():
+def test_http_client_brain() -> None:
node = astroid.extract_node(
"""
from http.client import OK
@@ -2936,7 +2953,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
@@ -2957,7 +2974,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:
@@ -2973,7 +2990,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",
@@ -3001,7 +3018,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
"""
@@ -3014,6 +3031,7 @@ def test_no_recursionerror_on_self_referential_length_check():
len(Crash()) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
node.inferred()
diff --git a/tests/unittest_brain_ctypes.py b/tests/unittest_brain_ctypes.py
index 87d648bd..ee0213d4 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,12 +71,13 @@ 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
-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
@@ -86,12 +88,13 @@ def test_cdata_member_access():
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"
-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
"""
@@ -100,6 +103,7 @@ def test_other_ctypes_member_untouched():
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 6710009b..62c0af7a 100644
--- a/tests/unittest_brain_dataclasses.py
+++ b/tests/unittest_brain_dataclasses.py
@@ -187,6 +187,7 @@ def test_inference_no_annotation(module: str):
# 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 @@ def test_inference_class_var(module: str):
# 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 @@ def test_inference_init_var(module: str):
# 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)
@@ -366,7 +369,7 @@ def test_inference_inherited(module: str):
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 3b625064..2ae6ce81 100644
--- a/tests/unittest_builder.py
+++ b/tests/unittest_builder.py
@@ -38,15 +38,16 @@ from astroid.exceptions import (
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 +98,10 @@ class FromToLineNoTest(unittest.TestCase):
self.assertEqual(arg.fromlineno, 10 + i)
self.assertEqual(arg.tolineno, 10 + i)
- def test_function_lineno(self):
+ @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,
@@ -112,12 +116,8 @@ class FromToLineNoTest(unittest.TestCase):
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):
+ def test_decorated_function_lineno(self) -> None:
astroid = builder.parse(
"""
@decorator
@@ -134,7 +134,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +150,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +165,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +190,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +213,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +230,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +249,7 @@ class FromToLineNoTest(unittest.TestCase):
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 +265,27 @@ class FromToLineNoTest(unittest.TestCase):
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 +305,15 @@ class BuilderTest(unittest.TestCase):
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 +328,12 @@ class BuilderTest(unittest.TestCase):
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 +344,7 @@ class BuilderTest(unittest.TestCase):
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 +356,7 @@ class BuilderTest(unittest.TestCase):
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 +372,11 @@ class BuilderTest(unittest.TestCase):
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 +406,7 @@ class BuilderTest(unittest.TestCase):
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 +428,7 @@ class BuilderTest(unittest.TestCase):
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 +439,7 @@ class BuilderTest(unittest.TestCase):
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 +449,15 @@ class BuilderTest(unittest.TestCase):
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 +466,7 @@ class BuilderTest(unittest.TestCase):
)
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 +482,7 @@ class BuilderTest(unittest.TestCase):
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 +499,7 @@ class BuilderTest(unittest.TestCase):
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 +516,7 @@ class BuilderTest(unittest.TestCase):
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 +529,7 @@ class BuilderTest(unittest.TestCase):
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 +542,7 @@ class BuilderTest(unittest.TestCase):
# 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 +558,7 @@ class BuilderTest(unittest.TestCase):
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 +569,7 @@ class BuilderTest(unittest.TestCase):
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 +585,7 @@ class BuilderTest(unittest.TestCase):
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 +597,10 @@ class BuilderTest(unittest.TestCase):
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 +616,7 @@ class FileBuildTest(unittest.TestCase):
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 +637,7 @@ class FileBuildTest(unittest.TestCase):
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 +651,14 @@ class FileBuildTest(unittest.TestCase):
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 +672,7 @@ class FileBuildTest(unittest.TestCase):
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 +694,21 @@ class FileBuildTest(unittest.TestCase):
]
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 +727,7 @@ class FileBuildTest(unittest.TestCase):
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 +736,12 @@ class FileBuildTest(unittest.TestCase):
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 715bd388..44b88130 100644
--- a/tests/unittest_helpers.py
+++ b/tests/unittest_helpers.py
@@ -13,31 +13,32 @@
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
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 @@ class TestHelpers(unittest.TestCase):
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():
@@ -80,6 +81,7 @@ class TestHelpers(unittest.TestCase):
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)
@@ -105,7 +107,7 @@ class TestHelpers(unittest.TestCase):
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 +123,7 @@ class TestHelpers(unittest.TestCase):
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):
@@ -135,12 +137,13 @@ class TestHelpers(unittest.TestCase):
pass
"""
)
+ assert isinstance(node, nodes.NodeNG)
metaclass = node.metaclass()
self.assertEqual(metaclass.name, "A")
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 +152,7 @@ class TestHelpers(unittest.TestCase):
)
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 +166,7 @@ class TestHelpers(unittest.TestCase):
)
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):
@@ -174,6 +177,7 @@ class TestHelpers(unittest.TestCase):
int_subclass() #@
"""
)
+ assert isinstance(ast_nodes, list)
cls_a = ast_nodes[0]
cls_b = ast_nodes[1]
cls_c = ast_nodes[2]
@@ -190,7 +194,7 @@ class TestHelpers(unittest.TestCase):
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 +212,7 @@ class TestHelpers(unittest.TestCase):
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 +225,7 @@ class TestHelpers(unittest.TestCase):
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 +237,7 @@ class TestHelpers(unittest.TestCase):
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 +248,7 @@ class TestHelpers(unittest.TestCase):
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 8653fab6..e2502539 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 @@ import pytest
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 @@ except ImportError:
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 @@ BOOL_SPECIAL_METHOD = "__bool__"
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 @@ class InferenceUtilsTest(unittest.TestCase):
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, nodes.NodeNG], expected: Any
+ ) -> None:
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Dict)
@@ -159,7 +170,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
)
- 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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
]
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
]
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
]
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
[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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
[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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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:
@@ -1059,6 +1072,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
1 + A() #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.Const)
self.assertEqual(first.value, 43)
@@ -1066,7 +1080,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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):
@@ -1076,6 +1090,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
1 + A() #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertEqual(first, util.Uninferable)
@@ -1083,7 +1098,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1110,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1120,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1130,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1143,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1155,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1164,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1193,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1205,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1215,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1244,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1257,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1270,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1288,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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
@@ -1298,12 +1313,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
return ctx
"""
node = extract_node(code)
+ assert isinstance(node, nodes.NodeNG)
result = node.inferred()
assert len(result) == 2
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 +1328,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
# 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 +1336,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1369,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1391,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1404,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1419,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1452,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1473,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1490,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1501,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1511,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1527,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1564,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1583,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1600,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1617,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1636,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1657,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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):
@@ -1653,14 +1669,16 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
"""
ast = parse(code, __name__)
node = ast["c"]
+ assert isinstance(node, nodes.NodeNG)
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()
+ assert isinstance(node, nodes.NodeNG)
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 +1695,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1711,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1723,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1755,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1773,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1791,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1809,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1822,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1837,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1854,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +1865,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1877,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1908,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1939,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +1969,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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()) #@
@@ -1961,13 +1979,14 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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])
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 +1997,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2041,11 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2055,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2073,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2081,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2110,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2139,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2154,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2177,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2230,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2285,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2302,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +2320,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +2346,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2376,11 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2447,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2457,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +2538,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2582,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2599,13 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2621,11 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2635,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +2696,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2734,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2749,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2767,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2780,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2798,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2813,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2829,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2845,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2857,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2870,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2883,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2896,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2909,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2924,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2940,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2954,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2971,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +2996,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3030,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3064,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3086,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3097,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3110,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3124,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3138,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3153,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3168,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3179,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3193,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3208,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3224,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3235,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3249,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3263,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3278,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3309,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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):
@@ -3304,6 +3323,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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])
@@ -3311,7 +3331,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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):
@@ -3328,6 +3348,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
a[NonIndex()] #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.Const)
self.assertEqual(first.value, 3)
@@ -3336,7 +3357,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3373,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3388,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3420,30 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3462,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3481,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3498,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3511,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3528,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3542,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3555,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3579,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3591,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3603,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3616,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3630,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3653,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3681,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3725,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3740,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3761,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3779,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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:
@@ -3763,6 +3800,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
c #@
"""
)
+ assert isinstance(ast_nodes, list)
first_a = next(ast_nodes[0].infer())
self.assertIsInstance(first_a, Instance)
self.assertEqual(first_a.name, "A")
@@ -3773,7 +3811,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3863,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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):
@@ -3836,6 +3874,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
cls #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, nodes.ClassDef)
second = next(ast_nodes[1].infer())
@@ -3855,7 +3894,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3908,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3932,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
)
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 +3946,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
).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 +3961,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +3978,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4005,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4021,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4035,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4081,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4095,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4105,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4159,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4178,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4197,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
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 +4219,7 @@ class GetattrTest(unittest.TestCase):
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 +4230,7 @@ class GetattrTest(unittest.TestCase):
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 +4242,7 @@ class GetattrTest(unittest.TestCase):
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) #@
@@ -4211,6 +4250,7 @@ class GetattrTest(unittest.TestCase):
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)
@@ -4223,7 +4263,7 @@ class GetattrTest(unittest.TestCase):
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):
@@ -4244,7 +4284,7 @@ class GetattrTest(unittest.TestCase):
getattr(self, 'test') #@
"""
)
-
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, BoundMethod)
self.assertEqual(first.bound.name, "A")
@@ -4269,7 +4309,7 @@ class GetattrTest(unittest.TestCase):
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 +4320,7 @@ class GetattrTest(unittest.TestCase):
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 +4335,7 @@ class HasattrTest(unittest.TestCase):
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 +4349,7 @@ class HasattrTest(unittest.TestCase):
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 +4375,7 @@ class HasattrTest(unittest.TestCase):
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 +4386,7 @@ class HasattrTest(unittest.TestCase):
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 +4409,7 @@ class BoolOpTest(unittest.TestCase):
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 +4422,7 @@ class BoolOpTest(unittest.TestCase):
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
@@ -4390,6 +4430,7 @@ class BoolOpTest(unittest.TestCase):
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())
@@ -4398,7 +4439,7 @@ class BoolOpTest(unittest.TestCase):
class TestCallable(unittest.TestCase):
- def test_callable(self):
+ def test_callable(self) -> None:
expected = [
("callable(len)", True),
('callable("a")', False),
@@ -4425,7 +4466,7 @@ class TestCallable(unittest.TestCase):
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 +4500,7 @@ class TestCallable(unittest.TestCase):
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 +4514,7 @@ class TestCallable(unittest.TestCase):
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 +4528,7 @@ class TestCallable(unittest.TestCase):
class TestBool(unittest.TestCase):
- def test_bool(self):
+ def test_bool(self) -> None:
pairs = [
("bool()", False),
("bool(1)", True),
@@ -4508,7 +4549,7 @@ class TestBool(unittest.TestCase):
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 +4585,7 @@ class TestBool(unittest.TestCase):
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 +4602,7 @@ class TestBool(unittest.TestCase):
class TestType(unittest.TestCase):
- def test_type(self):
+ def test_type(self) -> None:
pairs = [
("type(1)", "int"),
("type(type)", "type"),
@@ -4580,16 +4621,18 @@ class TestType(unittest.TestCase):
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 +4686,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4701,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4718,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4741,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4758,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4781,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4800,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4814,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4829,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4861,7 @@ class ArgumentsTest(unittest.TestCase):
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(
"""
@@ -4831,6 +4874,7 @@ class ArgumentsTest(unittest.TestCase):
wrapper()() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], nodes.Const, inferred[0])
@@ -4838,7 +4882,7 @@ class ArgumentsTest(unittest.TestCase):
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 +4898,7 @@ class SliceTest(unittest.TestCase):
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 +4915,7 @@ class SliceTest(unittest.TestCase):
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 +4937,7 @@ class SliceTest(unittest.TestCase):
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 +4946,12 @@ class SliceTest(unittest.TestCase):
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 +4963,13 @@ class CallSiteTest(unittest.TestCase):
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 +4986,7 @@ class CallSiteTest(unittest.TestCase):
]
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 +4994,26 @@ class CallSiteTest(unittest.TestCase):
]
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 +5025,7 @@ class ObjectDunderNewTest(unittest.TestCase):
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 +5044,7 @@ def test_augassign_recursion():
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 +5063,7 @@ def test_infer_custom_inherit_from_property():
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 +5076,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}
@@ -5036,6 +5084,7 @@ def test_unpack_dicts_in_assignment():
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)
@@ -5044,7 +5093,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 +5125,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 +5142,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 +5164,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 +5176,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
@@ -5144,11 +5193,12 @@ def test_regression_infinite_loop_decorator():
Foo().lru_cache(1)
"""
node = extract_node(code)
+ assert isinstance(node, nodes.NodeNG)
[result] = node.inferred()
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 +5216,7 @@ def test_stop_iteration_in_int():
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
@@ -5184,6 +5234,7 @@ def test_call_on_instance_with_inherited_dunder_call_method():
val #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
[val] = node.inferred()
assert isinstance(val, Instance)
assert val.name == "Sub"
@@ -5208,7 +5259,7 @@ class TestInferencePropagation:
)
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 +5269,7 @@ class TestInferencePropagation:
"""
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 +5280,7 @@ class TestInferencePropagation:
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 +5309,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 +5319,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 +5338,7 @@ def test_attribute_mro_object_inference():
assert inferred[0].value == 2
-def test_inferred_sequence_unpacking_works():
+def test_inferred_sequence_unpacking_works() -> None:
inferred = next(
extract_node(
"""
@@ -5302,7 +5353,7 @@ def test_inferred_sequence_unpacking_works():
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 +5371,7 @@ def test_recursion_error_inferring_slice():
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:
@@ -5333,6 +5384,7 @@ def test_exception_lookup_last_except_handler_wins():
exc #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
inferred_exc = inferred[0]
@@ -5351,6 +5403,7 @@ def test_exception_lookup_last_except_handler_wins():
exc #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
inferred_exc = inferred[0]
@@ -5358,7 +5411,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:
@@ -5372,6 +5425,7 @@ def test_exception_lookup_name_bound_in_except_handler():
name #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
inferred_exc = inferred[0]
@@ -5379,7 +5433,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 +5463,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 +5486,7 @@ def test_cannot_getattr_ann_assigns():
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 +5510,7 @@ def test_prevent_recursion_error_in_igetattr_and_context_manager_inference():
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 +5567,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
@@ -5529,6 +5583,7 @@ def test_ifexp_inference():
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
@@ -5542,7 +5597,7 @@ def test_ifexp_inference():
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 +5612,7 @@ def test_assert_last_function_returns_none_on_inference():
@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 +5637,7 @@ def test_posonlyargs_inference():
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 +5656,7 @@ def test_infer_args_unpacking_of_self():
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 +5728,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 +5780,7 @@ def test_property_inference():
assert isinstance(inferred, nodes.FunctionDef)
-def test_property_as_string():
+def test_property_as_string() -> None:
code = """
class A:
@property
@@ -5747,7 +5802,7 @@ def test_property_as_string():
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 +5827,7 @@ def test_property_callable_inference():
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 +5841,7 @@ def test_recursion_error_inferring_builtin_containers():
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 +5859,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 +5880,7 @@ def test_classmethod_from_builtins_inferred_as_bound():
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 +6019,7 @@ def test_dataclasses_subscript_inference_recursion_error_39():
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 +6036,7 @@ def test_self_reference_infer_does_not_trigger_recursion_error():
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 +6058,7 @@ def test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_time
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 +6072,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 +6084,7 @@ def test_infer_first_argument_of_static_method_in_metaclass():
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 +6094,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 +6113,7 @@ def test_recursion_error_self_reference_type_call():
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 +6129,7 @@ def test_allow_retrieving_instance_attrs_and_special_attrs_for_functions():
assert len(attrs) == 2
-def test_implicit_parameters_bound_method():
+def test_implicit_parameters_bound_method() -> None:
code = """
class A(type):
@classmethod
@@ -6095,7 +6150,7 @@ def test_implicit_parameters_bound_method():
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 +6178,7 @@ def test_super_inference_of_abstract_property():
assert len(test) == 2
-def test_infer_generated_setter():
+def test_infer_generated_setter() -> None:
code = """
class A:
@property
@@ -6140,7 +6195,7 @@ def test_infer_generated_setter():
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 +6210,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 +6228,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 +6241,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 +6255,7 @@ for name, item in click.__dict__.items():
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 c14a8619..bb487d02 100644
--- a/tests/unittest_inference_calls.py
+++ b/tests/unittest_inference_calls.py
@@ -4,7 +4,7 @@ from astroid import bases, builder, nodes
from astroid.util import Uninferable
-def test_no_return():
+def test_no_return() -> None:
"""Test function with no return statements"""
node = builder.extract_node(
"""
@@ -14,12 +14,13 @@ def test_no_return():
f() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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(
"""
@@ -29,13 +30,14 @@ def test_one_return():
f() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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
@@ -49,13 +51,14 @@ def test_one_return_possible():
f(1) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == 1
-def test_multiple_returns():
+def test_multiple_returns() -> None:
"""Test function with multiple returns"""
node = builder.extract_node(
"""
@@ -70,13 +73,14 @@ def test_multiple_returns():
f(100) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 3
assert all(isinstance(node, nodes.Const) for node in inferred)
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(
"""
@@ -86,13 +90,14 @@ def test_argument():
f(1, 2) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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(
"""
@@ -105,13 +110,14 @@ def test_inner_call():
f() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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.
"""
@@ -126,13 +132,14 @@ def test_inner_call_with_const_argument():
f() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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.
@@ -149,12 +156,13 @@ def test_inner_call_with_dynamic_argument():
f(1) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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.
"""
@@ -170,13 +178,14 @@ def test_method_const_instance_attr():
A().get_x() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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.
"""
@@ -198,13 +207,14 @@ def test_method_const_instance_attr_multiple():
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)
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.
@@ -231,13 +241,14 @@ def test_method_const_instance_attr_same_method():
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)
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.
@@ -255,12 +266,13 @@ def test_method_dynamic_instance_attr_1():
A(1).get_x() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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.
"""
@@ -276,13 +288,14 @@ def test_method_dynamic_instance_attr_2():
A().get_x(1) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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.
@@ -300,12 +313,13 @@ def test_method_dynamic_instance_attr_3():
A().get_x(10) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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.
@@ -326,12 +340,13 @@ def test_method_dynamic_instance_attr_4():
A().get_x() #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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.
@@ -356,12 +371,13 @@ def test_method_dynamic_instance_attr_5():
A().get_x(1) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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.
@@ -382,12 +398,13 @@ def test_method_dynamic_instance_attr_6():
A().get_x(1) #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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
@@ -405,13 +422,13 @@ def test_dunder_getitem():
A(1)[2] #@
"""
)
-
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
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(
"""
@@ -427,13 +444,14 @@ def test_instance_method():
)
for node in nodes_:
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
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(
"""
@@ -449,13 +467,14 @@ def test_class_method():
)
for node in nodes_:
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const), node
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(
"""
@@ -470,13 +489,14 @@ def test_static_method():
)
for node in nodes_:
+ assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const), node
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.
@@ -500,13 +520,14 @@ def test_instance_method_inherited():
)
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)
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.
@@ -530,13 +551,14 @@ def test_class_method_inherited():
)
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)
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.
@@ -560,6 +582,7 @@ def test_chained_attribute_inherited():
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_lookup.py b/tests/unittest_lookup.py
index fcd33a42..8de88b83 100644
--- a/tests/unittest_lookup.py
+++ b/tests/unittest_lookup.py
@@ -29,13 +29,13 @@ from . import resources
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
# 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 LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 LookupTest(resources.SysPathSetup, unittest.TestCase):
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 LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
]
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
# 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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
_, 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 @@ class LookupControlFlowTest(unittest.TestCase):
_, 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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
_, 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 @@ class LookupControlFlowTest(unittest.TestCase):
_, 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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 @@ class LookupControlFlowTest(unittest.TestCase):
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 a8103595..5db1740f 100644
--- a/tests/unittest_manager.py
+++ b/tests/unittest_manager.py
@@ -27,6 +27,7 @@ import sys
import time
import unittest
from contextlib import contextmanager
+from typing import Iterator
import pkg_resources
@@ -37,7 +38,7 @@ from astroid.exceptions import AstroidBuildingError, AstroidImportError
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
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 @@ class AstroidManagerTest(
)
@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,19 +209,19 @@ class AstroidManagerTest(
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_ast_from_module_name_pyz(self):
+ def test_ast_from_module_name_pyz(self) -> None:
try:
linked_file_name = os.path.join(
resources.RESOURCE_PATH, "MyPyPa-0.1.0-py2.5.pyz"
@@ -235,25 +236,25 @@ class AstroidManagerTest(
finally:
os.remove(linked_file_name)
- 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,
@@ -262,19 +263,19 @@ class AstroidManagerTest(
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")
@@ -284,7 +285,7 @@ class AstroidManagerTest(
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")
@@ -295,12 +296,12 @@ class AstroidManagerTest(
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
@@ -317,7 +318,7 @@ class AstroidManagerTest(
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 6edc94d1..a8107f70 100644
--- a/tests/unittest_modutils.py
+++ b/tests/unittest_modutils.py
@@ -40,19 +40,19 @@ from astroid.interpreter._import import spec
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 @@ class ModuleFileTest(unittest.TestCase):
["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 @@ class ModuleFileTest(unittest.TestCase):
["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 @@ class ModuleFileTest(unittest.TestCase):
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 @@ class LoadModuleFromNameTest(unittest.TestCase):
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 @@ class GetModulePartTest(unittest.TestCase):
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 @@ class ModPathFromFileTest(unittest.TestCase):
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 @@ class ModPathFromFileTest(unittest.TestCase):
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 @@ class ModPathFromFileTest(unittest.TestCase):
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 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):
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 @@ class GetModuleFilesTest(unittest.TestCase):
]
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 @@ class GetModuleFilesTest(unittest.TestCase):
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 @@ class ExtensionPackageWhitelistTest(unittest.TestCase):
)
)
- 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 3e9bcc28..9cc94656 100644
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -33,6 +33,7 @@ import platform
import sys
import textwrap
import unittest
+from typing import Any, Optional
import pytest
@@ -54,6 +55,15 @@ from astroid.exceptions import (
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 +78,8 @@ except ImportError:
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 +87,7 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase):
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 +97,7 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase):
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 +109,7 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase):
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)) #@
@@ -111,7 +121,7 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase):
"""
)
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])")
@@ -119,23 +129,23 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase):
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 +153,7 @@ cdd = {k for k in b}\n\n"""
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 +168,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 +188,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 +206,7 @@ class Language(metaclass=Natural):
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 +225,7 @@ if all[1] == bord[0:]:
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 +233,13 @@ y = (3).imag
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 +253,7 @@ y = (3).imag
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 +306,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 +342,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 +352,7 @@ class IfNodeTest(_NodeTest):
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 +362,7 @@ class IfNodeTest(_NodeTest):
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 +387,7 @@ class IfNodeTest(_NodeTest):
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 +432,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 +452,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 +470,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 +481,19 @@ class TryExceptFinallyNodeTest(_NodeTest):
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 +510,7 @@ class ImportNodeTest(resources.SysPathSetup, unittest.TestCase):
# 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 +523,7 @@ class ImportNodeTest(resources.SysPathSetup, unittest.TestCase):
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 +539,7 @@ from ..cave import wine\n\n"""
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 +571,7 @@ from ..cave import wine\n\n"""
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 +581,13 @@ from ..cave import wine\n\n"""
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 +596,7 @@ from ..cave import wine\n\n"""
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 +607,13 @@ from ..cave import wine\n\n"""
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 +622,25 @@ class ConstNodeTest(unittest.TestCase):
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 +656,7 @@ class ConstNodeTest(unittest.TestCase):
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 +665,7 @@ class ConstNodeTest(unittest.TestCase):
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 +678,7 @@ class NameNodeTest(unittest.TestCase):
class AnnAssignNodeTest(unittest.TestCase):
- def test_primitive(self):
+ def test_primitive(self) -> None:
code = textwrap.dedent(
"""
test: int = 5
@@ -681,7 +691,7 @@ class AnnAssignNodeTest(unittest.TestCase):
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 +703,7 @@ class AnnAssignNodeTest(unittest.TestCase):
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 +715,7 @@ class AnnAssignNodeTest(unittest.TestCase):
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()
@@ -718,8 +728,11 @@ class AnnAssignNodeTest(unittest.TestCase):
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):
+ def test_linenumbering(self) -> None:
ast = builder.parse(
"""
def func(a,
@@ -733,12 +746,8 @@ class ArgumentsNodeTC(unittest.TestCase):
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):
+ def test_kwoargs(self) -> None:
ast = builder.parse(
"""
def func(*, x):
@@ -765,7 +774,7 @@ class ArgumentsNodeTC(unittest.TestCase):
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 +796,7 @@ class UnboundMethodNodeTest(unittest.TestCase):
class BoundMethodNodeTest(unittest.TestCase):
- def test_is_property(self):
+ def test_is_property(self) -> None:
ast = builder.parse(
"""
import abc
@@ -851,52 +860,52 @@ class BoundMethodNodeTest(unittest.TestCase):
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 +955,7 @@ class AliasesTest(unittest.TestCase):
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 +971,11 @@ class Python35AsyncTest(unittest.TestCase):
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 +987,7 @@ class Python35AsyncTest(unittest.TestCase):
)
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 +997,7 @@ class Python35AsyncTest(unittest.TestCase):
)
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 +1007,7 @@ class Python35AsyncTest(unittest.TestCase):
)
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 +1020,51 @@ class Python35AsyncTest(unittest.TestCase):
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 +1072,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 +1089,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 +1107,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 +1123,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 +1136,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 +1156,7 @@ def test_type_comments_invalid_function_comments():
@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 +1187,7 @@ def test_type_comments_function():
@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 +1229,7 @@ def test_type_comments_arguments():
@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 +1265,7 @@ def test_type_comments_posonly_arguments():
@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 +1277,7 @@ def test_correct_function_type_comment_parent():
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 +1331,7 @@ class AsyncGeneratorTest:
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 +1347,7 @@ def test_f_string_correct_line_numbering():
@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 +1369,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 +1390,14 @@ def test_get_doc():
@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 +1417,7 @@ def test_parse_type_comments_with_proper_parent():
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 +1426,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 +1438,7 @@ def test_is_generator_for_yield_in_while():
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 +1451,7 @@ def test_is_generator_for_yield_in_if():
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 e0b66d21..374d9202 100644
--- a/tests/unittest_object_model.py
+++ b/tests/unittest_object_model.py
@@ -17,12 +17,12 @@ import xml
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
class InstanceModelTest(unittest.TestCase):
- def test_instance_special_model(self):
+ def test_instance_special_model(self) -> None:
ast_nodes = builder.extract_node(
"""
class A:
@@ -37,7 +37,7 @@ class InstanceModelTest(unittest.TestCase):
""",
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")
@@ -74,7 +74,7 @@ class InstanceModelTest(unittest.TestCase):
class BoundMethodModelTest(unittest.TestCase):
- def test_bound_method_model(self):
+ def test_bound_method_model(self) -> None:
ast_nodes = builder.extract_node(
"""
class A:
@@ -84,7 +84,7 @@ class BoundMethodModelTest(unittest.TestCase):
a.test.__self__ #@
"""
)
-
+ assert isinstance(ast_nodes, list)
func = next(ast_nodes[0].infer())
self.assertIsInstance(func, astroid.FunctionDef)
self.assertEqual(func.name, "test")
@@ -95,7 +95,7 @@ class BoundMethodModelTest(unittest.TestCase):
class UnboundMethodModelTest(unittest.TestCase):
- def test_unbound_method_model(self):
+ def test_unbound_method_model(self) -> None:
ast_nodes = builder.extract_node(
"""
class A:
@@ -109,7 +109,7 @@ class UnboundMethodModelTest(unittest.TestCase):
t.im_self #@
"""
)
-
+ assert isinstance(ast_nodes, list)
cls = next(ast_nodes[0].infer())
self.assertIsInstance(cls, astroid.ClassDef)
unbound_name = "function"
@@ -130,7 +130,7 @@ class UnboundMethodModelTest(unittest.TestCase):
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 ClassModelTest(unittest.TestCase):
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 ClassModelTest(unittest.TestCase):
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):
@@ -180,7 +180,7 @@ class ClassModelTest(unittest.TestCase):
""",
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")
@@ -221,7 +221,7 @@ class ClassModelTest(unittest.TestCase):
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 @@ class ModuleModelTest(unittest.TestCase):
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 @@ class ModuleModelTest(unittest.TestCase):
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
@@ -256,7 +256,7 @@ class ModuleModelTest(unittest.TestCase):
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)
@@ -287,7 +287,7 @@ class ModuleModelTest(unittest.TestCase):
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 @@ class FunctionModelTest(unittest.TestCase):
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 @@ class FunctionModelTest(unittest.TestCase):
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 @@ class FunctionModelTest(unittest.TestCase):
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(
@@ -377,10 +377,11 @@ class FunctionModelTest(unittest.TestCase):
cl #@
"""
)
+ assert isinstance(node, nodes.NodeNG)
[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):
@@ -397,7 +398,7 @@ class FunctionModelTest(unittest.TestCase):
''',
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")
@@ -427,7 +428,7 @@ class FunctionModelTest(unittest.TestCase):
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 +439,9 @@ class FunctionModelTest(unittest.TestCase):
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 +454,7 @@ class FunctionModelTest(unittest.TestCase):
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 +497,7 @@ class FunctionModelTest(unittest.TestCase):
class GeneratorModelTest(unittest.TestCase):
- def test_model(self):
+ def test_model(self) -> None:
ast_nodes = builder.extract_node(
"""
def test():
@@ -509,7 +512,7 @@ class GeneratorModelTest(unittest.TestCase):
gen.send #@
"""
)
-
+ assert isinstance(ast_nodes, list)
name = next(ast_nodes[0].infer())
self.assertEqual(name.value, "test")
@@ -529,7 +532,7 @@ class GeneratorModelTest(unittest.TestCase):
class ExceptionModelTest(unittest.TestCase):
- def test_valueerror_py3(self):
+ def test_valueerror_py3(self) -> None:
ast_nodes = builder.extract_node(
"""
try:
@@ -541,6 +544,7 @@ class ExceptionModelTest(unittest.TestCase):
err.message #@
"""
)
+ assert isinstance(ast_nodes, list)
args = next(ast_nodes[0].infer())
self.assertIsInstance(args, astroid.Tuple)
tb = next(ast_nodes[1].infer())
@@ -550,7 +554,7 @@ class ExceptionModelTest(unittest.TestCase):
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 +566,7 @@ class ExceptionModelTest(unittest.TestCase):
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 +583,7 @@ class ExceptionModelTest(unittest.TestCase):
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 +594,7 @@ class ExceptionModelTest(unittest.TestCase):
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 +609,7 @@ class ExceptionModelTest(unittest.TestCase):
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 +625,13 @@ class ExceptionModelTest(unittest.TestCase):
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 +643,7 @@ class DictObjectModelTest(unittest.TestCase):
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() #@
@@ -647,6 +651,7 @@ class DictObjectModelTest(unittest.TestCase):
{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])
@@ -658,7 +663,7 @@ class DictObjectModelTest(unittest.TestCase):
class LruCacheModelTest(unittest.TestCase):
- def test_lru_cache(self):
+ def test_lru_cache(self) -> None:
ast_nodes = builder.extract_node(
"""
import functools
@@ -672,6 +677,7 @@ class LruCacheModelTest(unittest.TestCase):
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 3c7ac52b..a792dc71 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 @@ class ObjectsTest(unittest.TestCase):
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):
@@ -56,6 +58,7 @@ class SuperTests(unittest.TestCase):
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")
@@ -68,7 +71,7 @@ class SuperTests(unittest.TestCase):
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 +83,7 @@ class SuperTests(unittest.TestCase):
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):
@@ -89,6 +92,7 @@ class SuperTests(unittest.TestCase):
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")
@@ -97,7 +101,7 @@ class SuperTests(unittest.TestCase):
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
@@ -109,6 +113,7 @@ class SuperTests(unittest.TestCase):
super() #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, objects.Super)
self.assertIsInstance(first.type, bases.Instance)
@@ -123,7 +128,7 @@ class SuperTests(unittest.TestCase):
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
@@ -148,6 +153,7 @@ class SuperTests(unittest.TestCase):
# 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)
@@ -187,7 +193,7 @@ class SuperTests(unittest.TestCase):
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 +207,7 @@ class SuperTests(unittest.TestCase):
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):
@@ -216,6 +222,7 @@ class SuperTests(unittest.TestCase):
pass
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, objects.Super)
with self.assertRaises(SuperError) as cm:
@@ -229,7 +236,7 @@ class SuperTests(unittest.TestCase):
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 +249,7 @@ class SuperTests(unittest.TestCase):
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):
@@ -267,6 +274,7 @@ class SuperTests(unittest.TestCase):
"""
)
# 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")
@@ -297,7 +305,7 @@ class SuperTests(unittest.TestCase):
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):
@@ -319,6 +327,7 @@ class SuperTests(unittest.TestCase):
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
self.assertIsInstance(first, bases.BoundMethod)
self.assertEqual(first.bound.name, "Second")
@@ -345,7 +354,7 @@ class SuperTests(unittest.TestCase):
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 +368,7 @@ class SuperTests(unittest.TestCase):
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):
@@ -381,6 +390,7 @@ class SuperTests(unittest.TestCase):
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")
@@ -396,7 +406,7 @@ class SuperTests(unittest.TestCase):
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
@@ -407,6 +417,7 @@ class SuperTests(unittest.TestCase):
super(X, A) #@
"""
)
+ assert isinstance(ast_nodes, list)
first = next(ast_nodes[0].infer())
thisclass = first.getattr("__thisclass__")[0]
self.assertIsInstance(thisclass, nodes.ClassDef)
@@ -433,10 +444,10 @@ class SuperTests(unittest.TestCase):
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
@@ -452,6 +463,7 @@ class SuperTests(unittest.TestCase):
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())
@@ -466,7 +478,7 @@ class SuperTests(unittest.TestCase):
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
@@ -476,12 +488,13 @@ class SuperTests(unittest.TestCase):
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())
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 +509,7 @@ class SuperTests(unittest.TestCase):
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 +529,7 @@ class SuperTests(unittest.TestCase):
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 6c8849de..9d8445ed 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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
"(*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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
)
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 @@ class ProtocolTests(unittest.TestCase):
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 @@ class ProtocolTests(unittest.TestCase):
@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 #@
@@ -240,6 +252,7 @@ def test_named_expr_inference():
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
@@ -287,7 +300,7 @@ class TestPatternMatching:
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 +320,7 @@ class TestPatternMatching:
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 +345,11 @@ class TestPatternMatching:
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 045ce90b..7534316e 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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
# 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 @@ class Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 @@ class Python3TC(unittest.TestCase):
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 ed9b7583..dececbcb 100644
--- a/tests/unittest_raw_building.py
+++ b/tests/unittest_raw_building.py
@@ -29,51 +29,51 @@ from astroid.raw_building import (
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 5d00ecf0..8b079c44 100644
--- a/tests/unittest_regrtest.py
+++ b/tests/unittest_regrtest.py
@@ -37,16 +37,16 @@ else:
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 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin, unittest.TestCase):
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 @@ class NonRegressionTests(resources.AstroidCacheSetupMixin, unittest.TestCase):
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 @@ multiply([1, 2], [3, 4])
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 @@ multiply([1, 2], [3, 4])
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 @@ def test():
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():
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 @@ def test():
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 test():
)
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 test():
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 test():
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 test():
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():
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 test():
)
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():
)
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 test_ancestor_looking_up_redefined_function():
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 502d34d2..04082469 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -37,6 +37,7 @@ import sys
import textwrap
import unittest
from functools import partial
+from typing import Any, List, Union
import pytest
@@ -65,7 +66,11 @@ except ImportError:
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 +80,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 +89,7 @@ class ModuleLoader(resources.SysPathSetup):
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 +110,10 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +135,14 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +187,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +197,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
# 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 +221,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +234,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
)
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 +247,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +260,27 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +291,7 @@ class ModuleNodeTest(ModuleLoader, unittest.TestCase):
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 +305,10 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +318,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
# 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 +336,13 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +350,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +364,12 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +380,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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
@@ -395,22 +400,32 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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_lambda_pytype(self):
+ # 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 = """
def f():
g = lambda: None
@@ -419,11 +434,11 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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.<lambda>" % __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 +464,12 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +484,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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,17 +496,18 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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()
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
- 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 +534,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +551,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +580,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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,13 +654,14 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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():
pass
"""
)
+ assert isinstance(func, nodes.FunctionDef)
func.instance_attrs["value"] = [nodes.Const(42)]
value = func.getattr("value")
self.assertEqual(len(value), 1)
@@ -654,7 +671,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +684,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +696,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +708,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +718,7 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +733,10 @@ class FunctionNodeTest(ModuleLoader, unittest.TestCase):
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 +765,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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
@@ -756,11 +773,12 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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())
- def test__bases__attribute(self):
+ def test__bases__attribute(self) -> None:
node = builder.extract_node(
"""
class A(object): pass
@@ -769,13 +787,14 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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)
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 +808,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +816,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +826,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +860,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +884,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +895,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +920,13 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# 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 +941,11 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +967,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
]
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 +979,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# 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 +992,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# 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 +1016,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1046,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1065,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1083,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1093,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1106,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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):
@@ -1097,11 +1116,12 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(klass, nodes.ClassDef)
self.assertEqual(
["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):
@@ -1120,12 +1140,13 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(klass, nodes.ClassDef)
self.assertFalse(_is_metaclass(klass))
ancestors = [base.name for base in klass.ancestors()]
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
@@ -1155,10 +1176,11 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(klass, nodes.ClassDef)
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
@@ -1167,6 +1189,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(klass, nodes.ClassDef)
inferred = next(klass.infer())
metaclass = inferred.metaclass()
self.assertIsInstance(metaclass, nodes.ClassDef)
@@ -1185,7 +1208,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1227,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# 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 +1274,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1288,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1298,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1315,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1330,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1345,12 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1369,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
)
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 +1461,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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):
@@ -1460,6 +1485,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
self.name = 'x'
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMro(
cls,
[
@@ -1475,7 +1501,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
],
)
- def test_mro_with_attribute_classes(self):
+ def test_mro_with_attribute_classes(self) -> None:
cls = builder.extract_node(
"""
class A:
@@ -1491,6 +1517,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMro(cls, ["C", "A", "B", "object"])
@test_utils.require_version(minver="3.7")
@@ -1504,6 +1531,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C(A[T], B): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".C", ".A", "typing.Generic", ".B", "builtins.object"]
)
@@ -1519,6 +1547,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C(Generic[T], A, B[T]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"]
)
@@ -1535,6 +1564,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class D(B[T], C[T], Generic[T]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".D", ".B", ".A", ".C", "typing.Generic", "builtins.object"]
)
@@ -1550,6 +1580,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C(A, Generic[T], B[T]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"]
)
@@ -1566,6 +1597,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C(A[T1], B[T2]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".C", ".A", ".B", "typing.Generic", "builtins.object"]
)
@@ -1582,6 +1614,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class C(A, B[T]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".C", ".A", ".Generic", ".B", "typing.Generic", "builtins.object"]
)
@@ -1599,6 +1632,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class E(C[str], D): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
self.assertEqualMroQName(
cls, [".E", ".C", ".A", ".B", "typing.Generic", ".D", "builtins.object"]
)
@@ -1613,6 +1647,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class A(Generic[T1], Generic[T2]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
with self.assertRaises(DuplicateBasesError):
cls.mro()
@@ -1626,10 +1661,11 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
class B(A[T], A[T]): ...
"""
)
+ assert isinstance(cls, nodes.ClassDef)
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
@@ -1639,16 +1675,18 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
yield
"""
)
+ assert isinstance(func, nodes.FunctionDef)
result = next(func.infer_call_result())
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}) #@
"""
)
+ assert isinstance(classes, nodes.Call)
first = next(classes.infer())
self.assertIsInstance(first, nodes.ClassDef)
self.assertEqual(first.name, "A")
@@ -1660,38 +1698,41 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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):
pass
"""
)
+ assert isinstance(cls, nodes.ClassDef)
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):
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):
- # Check that we don't have recursive attribute access for metaclass
+ def test_metaclass_lookup_using_same_class(self) -> None:
+ """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):
+ def test_metaclass_lookup_inference_errors(self) -> None:
module = builder.parse(
"""
class Metaclass(type):
@@ -1703,7 +1744,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1794,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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
@@ -1764,12 +1805,13 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
pass
"""
)
+ assert isinstance(cls, nodes.ClassDef)
local = cls.local_attr("test")[0]
inferred = next(local.infer())
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 +1836,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1852,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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): #@
@@ -1819,6 +1861,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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)
@@ -1829,7 +1872,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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)
@@ -1845,6 +1888,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
MyClass() #@
"""
)
+ assert isinstance(ast_nodes, list)
cls = next(ast_nodes[0].infer())
self.assertIsInstance(next(cls.igetattr("f2")), nodes.Lambda)
@@ -1852,7 +1896,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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():
@@ -1860,9 +1904,10 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
func = 42
"""
)
+ assert isinstance(ast_node, nodes.FunctionDef)
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 +1918,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
)
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 +1931,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
)
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 +1943,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1960,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +1985,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +2002,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +2020,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
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 +2039,7 @@ def test_issue940_metaclass_subclass_property():
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 +2058,7 @@ def test_issue940_property_grandchild():
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 +2075,7 @@ def test_issue940_metaclass_property():
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 +2094,7 @@ def test_issue940_with_metaclass_class_context_property():
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 +2110,7 @@ def test_issue940_metaclass_values_funcdef():
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 +2128,7 @@ def test_issue940_metaclass_derived_funcdef():
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 +2151,7 @@ def test_issue940_metaclass_funcdef_is_not_datadescriptor():
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 +2167,7 @@ def test_issue940_enums_as_a_real_world_usecase():
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 +2236,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 +2252,7 @@ def test_posonlyargs_default_value():
@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 +2277,7 @@ def test_ancestor_with_generic():
]
-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 e1a91a19..63ac10dd 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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
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 @@ class TestTransforms(unittest.TestCase):
# 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 ea5d0362..fd2026fd 100644
--- a/tests/unittest_utils.py
+++ b/tests/unittest_utils.py
@@ -18,7 +18,7 @@ from astroid.exceptions import InferenceError
class InferenceUtil(unittest.TestCase):
- def test_not_exclusive(self):
+ def test_not_exclusive(self) -> None:
module = builder.parse(
"""
x = 10
@@ -39,7 +39,7 @@ class InferenceUtil(unittest.TestCase):
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 @@ class InferenceUtil(unittest.TestCase):
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 @@ class InferenceUtil(unittest.TestCase):
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 @@ class InferenceUtil(unittest.TestCase):
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(
"""
()