def testModuleLevelNames(self): assign = test_utils.extract_node(""" import collections Class = collections.namedtuple("a", ("b", "c")) #@ """) with self.assertNoMessages(): self.checker.visit_assname(assign.targets[0]) assign = test_utils.extract_node(""" class ClassA(object): pass ClassB = ClassA """) with self.assertNoMessages(): self.checker.visit_assname(assign.targets[0]) module = test_utils.build_module(""" def A(): return 1, 2, 3 CONSTA, CONSTB, CONSTC = A() CONSTD = A()""") with self.assertNoMessages(): self.checker.visit_assname(module.body[1].targets[0].elts[0]) self.checker.visit_assname(module.body[2].targets[0]) assign = test_utils.extract_node(""" CONST = "12 34 ".rstrip().split()""") with self.assertNoMessages(): self.checker.visit_assname(assign.targets[0])
def test_not_next_method(self): arg_node = test_utils.extract_node('x.next(x) #@') stararg_node = test_utils.extract_node('x.next(*x) #@') kwarg_node = test_utils.extract_node('x.next(y=x) #@') with self.assertNoMessages(): for node in (arg_node, stararg_node, kwarg_node): self.checker.visit_call(node)
def test_annotation_support(self): func = test_utils.extract_node(""" def test(a: int, b: str, c: None, d, e, *args: float, **kwargs: int)->int: pass """) self.assertIsInstance(func.args.vararg.annotation, Name) self.assertEqual(func.args.vararg.annotation.name, 'float') self.assertIsInstance(func.args.kwarg.annotation, Name) self.assertEqual(func.args.kwarg.annotation.name, 'int') self.assertIsInstance(func.returns, Name) self.assertEqual(func.returns.name, 'int') arguments = func.args self.assertIsInstance(arguments.args[0].annotation, Name) self.assertEqual(arguments.args[0].annotation.name, 'int') self.assertIsInstance(arguments.args[1].annotation, Name) self.assertEqual(arguments.args[1].annotation.name, 'str') self.assertIsInstance(arguments.args[2].annotation, Const) self.assertIsNone(arguments.args[2].annotation.value) self.assertIs(arguments.args[3].annotation, nodes.Empty) self.assertIs(arguments.args[4].annotation, nodes.Empty) func = test_utils.extract_node(""" def test(a: int=1, b: str=2): #@ pass """) self.assertIsInstance(func.args.args[0].annotation, Name) self.assertEqual(func.args.args[0].annotation.name, 'int') self.assertIsInstance(func.args.args[1].annotation, Name) self.assertEqual(func.args.args[1].annotation.name, 'str') self.assertIs(func.returns, nodes.Empty)
def test_dict_not_iter_method(self): arg_node = test_utils.extract_node("x.iterkeys(x) #@") stararg_node = test_utils.extract_node("x.iterkeys(*x) #@") kwarg_node = test_utils.extract_node("x.iterkeys(y=x) #@") non_dict_node = test_utils.extract_node("x=[]\nx.iterkeys() #@") with self.assertNoMessages(): for node in (arg_node, stararg_node, kwarg_node, non_dict_node): self.checker.visit_call(node)
def test_dict_not_view_method(self): arg_node = test_utils.extract_node('x.viewkeys(x) #@') stararg_node = test_utils.extract_node('x.viewkeys(*x) #@') kwarg_node = test_utils.extract_node('x.viewkeys(y=x) #@') non_dict_node = test_utils.extract_node('x=[]\nx.viewkeys() #@') with self.assertNoMessages(): for node in (arg_node, stararg_node, kwarg_node, non_dict_node): self.checker.visit_call(node)
def test_wrong_name_of_func_params_in_numpy_docstring(self): """Example of functions with inconsistent parameter names in the signature and in the Numpy style documentation """ node = test_utils.extract_node(""" def function_foo(xarg, yarg, zarg): '''function foo ... Parameters ---------- xarg1: int bla xarg yarg: float bla yarg zarg1: str bla zarg ''' return xarg + yarg """) with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=node, args=('xarg, xarg1, zarg, zarg1',)), Message( msg_id='missing-type-doc', node=node, args=('xarg, xarg1, zarg, zarg1',)), ): self.checker.visit_functiondef(node) node = test_utils.extract_node(""" def function_foo(xarg, yarg): '''function foo ... Parameters ---------- yarg1: float bla yarg For the other parameters, see bla. ''' return xarg + yarg """) with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=node, args=('yarg1',)), Message( msg_id='missing-type-doc', node=node, args=('yarg1',)) ): self.checker.visit_functiondef(node)
def test_custom_callback_string(self): """ Test the --calbacks option works. """ def cleanup(): self.checker._to_consume = _to_consume _to_consume = self.checker._to_consume self.checker._to_consume = [] self.addCleanup(cleanup) node = test_utils.extract_node( """ def callback_one(abc): ''' should not emit unused-argument. ''' """ ) with self.assertNoMessages(): self.checker.visit_functiondef(node) self.checker.leave_functiondef(node) node = test_utils.extract_node( """ def two_callback(abc, defg): ''' should not emit unused-argument. ''' """ ) with self.assertNoMessages(): self.checker.visit_functiondef(node) self.checker.leave_functiondef(node) node = test_utils.extract_node( """ def normal_func(abc): ''' should emit unused-argument. ''' """ ) with self.assertAddsMessages(Message("unused-argument", node=node["abc"], args="abc")): self.checker.visit_functiondef(node) self.checker.leave_functiondef(node) node = test_utils.extract_node( """ def cb_func(abc): ''' Previous callbacks are overriden. ''' """ ) with self.assertAddsMessages(Message("unused-argument", node=node["abc"], args="abc")): self.checker.visit_functiondef(node) self.checker.leave_functiondef(node)
def test_scope_of_dict_comprehension(self): ast_nodes = test_utils.extract_node(''' {i: __(j) for (i, j) in DATA} {i:j for (i, j) in __(DATA)} ''') elt_scope = ast_nodes[0].scope() self.assertIsInstance(elt_scope, nodes.DictComp) iter_scope = ast_nodes[1].scope() self.assertIsInstance(iter_scope, nodes.Module) ast_node = test_utils.extract_node(''' {i:1 for i in DATA}''') target = ast_node.down().down().down() target_scope = target.scope() self.assertIsInstance(target_scope, nodes.DictComp)
def test_metaclass_assignment(self): node = test_utils.extract_node(""" class Foo(object): #@ __metaclass__ = type""") message = testutils.Message('metaclass-assignment', node=node) with self.assertAddsMessages(message): self.checker.visit_classdef(node)
def testPropertyNames(self): # If a method is annotated with @property, it's name should # match the attr regex. Since by default the attribute regex is the same # as the method regex, we override it here. self.checker.config.attr_rgx = re.compile('[A-Z]+') methods = test_utils.extract_node(""" import abc class FooClass(object): @property def FOO(self): #@ pass @property def bar(self): #@ pass @abc.abstractproperty def BAZ(self): #@ pass """) with self.assertNoMessages(): self.checker.visit_function(methods[0]) self.checker.visit_function(methods[2]) with self.assertAddsMessages(Message('invalid-name', node=methods[1], args=('attribute', 'bar'))): self.checker.visit_function(methods[1])
def test_invalid_docstring_characters(self): stmt = test_utils.extract_node( 'def fff():\n """test\\x00"""\n pass') with self.assertAddsMessages( Message('invalid-characters-in-docstring', line=2, args=('test\x00',))): self.checker.visit_functiondef(stmt)
def test_builtin_fromlineno_missing(self): cls = test_utils.extract_node(''' class Foo(Exception): #@ pass ''') new = cls.getattr('__new__')[-1] self.assertEqual(new.args.fromlineno, 0)
def test_unpacking_in_dicts(self): code = "{'x': 1, **{'y': 2}}" node = extract_node(code) self.assertEqual(node.as_string(), code) keys = [key for (key, _) in node.items] self.assertIsInstance(keys[0], nodes.Const) self.assertIsInstance(keys[1], nodes.DictUnpack)
def test_numpy(self): node = test_utils.extract_node(''' import numpy numpy.ones #@ ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.FunctionDef)
def test_constr_params_in_class_numpy(self): """Example of a class with missing constructor parameter documentation (Numpy style) Everything is completely analogous to functions. """ node = test_utils.extract_node(""" class ClassFoo(object): '''docstring foo Parameters ---------- y: bla missing constructor parameter documentation ''' def __init__(self, x, y): pass """) with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=node, args=('x',)), Message( msg_id='missing-type-doc', node=node, args=('x, y',)) ): self._visit_methods_of_class(node)
def test_missing_func_params_in_numpy_docstring(self): """Example of a function with missing NumPy style parameter documentation in the docstring """ node = test_utils.extract_node(""" def function_foo(x, y, z): '''docstring ... Parameters ---------- x: bla z: int bar some other stuff ''' pass """) with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=node, args=('y',)), Message( msg_id='missing-type-doc', node=node, args=('x, y',)) ): self.checker.visit_functiondef(node)
def test_all_elements_without_parent(self): node = test_utils.extract_node('__all__ = []') node.value.elts.append(astroid.Const('test')) root = node.root() with self.assertNoMessages(): self.checker.visit_module(root) self.checker.leave_module(root)
def test_super_mro(self): ast_nodes = test_utils.extract_node(''' class A(object): pass class B(A): pass class C(A): pass class E(C, B): def __init__(self): super(E, self) #@ super(C, self) #@ super(B, self) #@ super(B, 1) #@ super(1, B) #@ ''') first = next(ast_nodes[0].infer()) self.assertEqualMro(first, ['C', 'B', 'A', 'object']) second = next(ast_nodes[1].infer()) self.assertEqualMro(second, ['B', 'A', 'object']) third = next(ast_nodes[2].infer()) self.assertEqualMro(third, ['A', 'object']) fourth = next(ast_nodes[3].infer()) with self.assertRaises(exceptions.SuperError): fourth.super_mro() fifth = next(ast_nodes[4].infer()) with self.assertRaises(exceptions.SuperError): fifth.super_mro()
def test_existing_func_params_in_numpy_docstring(self): """Example of a function with correctly documented parameters and return values (Numpy style) """ node = test_utils.extract_node(""" def function_foo(xarg, yarg, zarg): '''function foo ... Parameters ---------- xarg: int bla xarg yarg: float bla yarg zarg: int bla zarg Returns ------- float sum ''' return xarg + yarg """) with self.assertNoMessages(): self.checker.visit_functiondef(node)
def testFunctionNoDocstringByName(self): self.checker.config.docstring_min_length = 2 func = test_utils.extract_node(""" def __fun__(tion): pass""") with self.assertNoMessages(): self.checker.visit_function(func)
def test_not_implemented(self): node = test_utils.extract_node(''' NotImplemented #@ ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, NotImplemented)
def test_super_complex_mro(self): ast_nodes = test_utils.extract_node(''' class A(object): def spam(self): return "A" def foo(self): return "A" @staticmethod def static(self): pass class B(A): def boo(self): return "B" def spam(self): return "B" class C(A): def boo(self): return "C" class E(C, B): def __init__(self): super(E, self).boo #@ super(C, self).boo #@ super(E, self).spam #@ super(E, self).foo #@ super(E, self).static #@ ''') first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.BoundMethod) self.assertEqual(first.bound.name, 'C') second = next(ast_nodes[1].infer()) self.assertIsInstance(second, bases.BoundMethod) self.assertEqual(second.bound.name, 'B') third = next(ast_nodes[2].infer()) self.assertIsInstance(third, bases.BoundMethod) self.assertEqual(third.bound.name, 'B') fourth = next(ast_nodes[3].infer()) self.assertEqual(fourth.bound.name, 'A') static = next(ast_nodes[4].infer()) self.assertIsInstance(static, nodes.FunctionDef) self.assertEqual(static.parent.scope().name, 'A')
def test_missing_func_params_in_sphinx_docstring(self): """Example of a function with missing Sphinx parameter documentation in the docstring """ node = test_utils.extract_node(""" def function_foo(x, y, z): '''docstring ... :param x: bla :param int z: bar ''' pass """) with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=node, args=('y',)), Message( msg_id='missing-type-doc', node=node, args=('x, y',)) ): self.checker.visit_functiondef(node)
def test_inferring_invalid_supers(self): ast_nodes = test_utils.extract_node(''' class Super(object): def __init__(self): # MRO pointer is not a type super(1, self) #@ # MRO type is not a subtype super(Super, 1) #@ # self is not a subtype of Bupper super(Bupper, self) #@ class Bupper(Super): pass ''') first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) with self.assertRaises(exceptions.SuperError) as cm: first.super_mro() self.assertIsInstance(cm.exception.super_.mro_pointer, nodes.Const) self.assertEqual(cm.exception.super_.mro_pointer.value, 1) for node, invalid_type in zip(ast_nodes[1:], (nodes.Const, bases.Instance)): inferred = next(node.infer()) self.assertIsInstance(inferred, objects.Super, node) with self.assertRaises(exceptions.SuperError) as cm: inferred.super_mro() self.assertIsInstance(cm.exception.super_.type, invalid_type)
def test_missing_method_params_in_numpy_docstring(self): """Example of a class method with missing parameter documentation in the Numpy style docstring """ node = test_utils.extract_node(""" class Foo(object): def method_foo(self, x, y): '''docstring ... missing parameter documentation Parameters ---------- x: bla ''' pass """) method_node = node.body[0] with self.assertAddsMessages( Message( msg_id='missing-param-doc', node=method_node, args=('y',)), Message( msg_id='missing-type-doc', node=method_node, args=('x, y',)) ): self._visit_methods_of_class(node)
def test_inferring_super_outside_methods(self): ast_nodes = test_utils.extract_node(''' class Module(object): pass class StaticMethod(object): @staticmethod def static(): # valid, but we don't bother with it. return super(StaticMethod, StaticMethod) #@ # super outside methods aren't inferred super(Module, Module) #@ # no argument super is not recognised outside methods as well. super() #@ ''') in_static = next(ast_nodes[0].value.infer()) self.assertIsInstance(in_static, bases.Instance) self.assertEqual(in_static.qname(), "%s.super" % bases.BUILTINS) module_level = next(ast_nodes[1].infer()) self.assertIsInstance(module_level, bases.Instance) self.assertEqual(in_static.qname(), "%s.super" % bases.BUILTINS) no_arguments = next(ast_nodes[2].infer()) self.assertIsInstance(no_arguments, bases.Instance) self.assertEqual(no_arguments.qname(), "%s.super" % bases.BUILTINS)
def test_ssl_protocol(self): node = extract_node(''' import ssl ssl.PROTOCOL_TLSv1 ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const)
def test_ignored_modules_patterns(self): node = test_utils.extract_node(''' import xml xml.etree.portocola #@ ''') with self.assertNoMessages(): self.checker.visit_attribute(node)
def test_ignores_no_docstring(self): return_node = test_utils.extract_node(''' def my_func(self): return False #@ ''') with self.assertNoMessages(): self.checker.visit_return(return_node)
def test_super_data_model(self): ast_nodes = test_utils.extract_node(''' class X(object): pass class A(X): def __init__(self): super(A, self) #@ super(A, A) #@ super(X, A) #@ ''') first = next(ast_nodes[0].infer()) thisclass = first.getattr('__thisclass__')[0] self.assertIsInstance(thisclass, nodes.ClassDef) self.assertEqual(thisclass.name, 'A') selfclass = first.getattr('__self_class__')[0] self.assertIsInstance(selfclass, nodes.ClassDef) self.assertEqual(selfclass.name, 'A') self_ = first.getattr('__self__')[0] self.assertIsInstance(self_, bases.Instance) self.assertEqual(self_.name, 'A') cls = first.getattr('__class__')[0] self.assertEqual(cls, first._proxied) second = next(ast_nodes[1].infer()) thisclass = second.getattr('__thisclass__')[0] self.assertEqual(thisclass.name, 'A') self_ = second.getattr('__self__')[0] self.assertIsInstance(self_, nodes.ClassDef) self.assertEqual(self_.name, 'A') third = next(ast_nodes[2].infer()) thisclass = third.getattr('__thisclass__')[0] self.assertEqual(thisclass.name, 'X') selfclass = third.getattr('__self_class__')[0] self.assertEqual(selfclass.name, 'A')
def test_object_type_too_many_types(self): node = test_utils.extract_node(''' from unknown import Unknown def test(x): if x: return lambda: None else: return 1 test(Unknown) #@ ''') self.assertEqual(helpers.object_type(node), util.Uninferable)
def test_super_infer(self): node = test_utils.extract_node(''' class Super(object): def __init__(self): super(Super, self) #@ ''') inferred = next(node.infer()) self.assertIsInstance(inferred, objects.Super) reinferred = next(inferred.infer()) self.assertIsInstance(reinferred, objects.Super) self.assertIs(inferred, reinferred)
def test_unpack_infer_uninferable_nodes(self): node = test_utils.extract_node(''' x = [A] * 1 f = [x, [A] * 2] f ''') inferred = next(node.infer()) unpacked = list(node_classes.unpack_infer(inferred)) self.assertEqual(len(unpacked), 3) self.assertTrue(all(elt is astroid_util.Uninferable for elt in unpacked))
def test_pytest(self): ast_node = test_utils.extract_node(''' import pytest pytest #@ ''') module = next(ast_node.infer()) self.assertIn('deprecated_call', module) self.assertIn('exit', module) self.assertIn('fail', module) self.assertIn('fixture', module) self.assertIn('mark', module)
def testTryExceptFinallyNoMultipleStatement(self): tree = test_utils.extract_node(""" try: #@ pass except: pass finally: pass""") with self.assertNoMessages(): self.checker.process_tokens([]) self.checker.visit_default(tree.body[0])
def test_super_invalid_mro(self): node = test_utils.extract_node(''' class A(object): test = 42 class Super(A, A): def __init__(self): super(Super, self) #@ ''') inferred = next(node.infer()) with self.assertRaises(exceptions.NotFoundError): next(inferred.getattr('test'))
def test_namedtuple_base(self): klass = test_utils.extract_node(""" from collections import namedtuple class X(namedtuple("X", ["a", "b", "c"])): pass """) 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_reassignment_in_except_handler(self): node = extract_node(''' import exceptions try: {}["a"] except KeyError, exceptions.IndexError: pass IndexError #@ ''') self.assertEqual(len(node.inferred()), 1)
def test_no_member_in_getattr_ignored(self): """Make sure that a module attribute access check is omitted with a module that is configured to be ignored. """ node = test_utils.extract_node(""" import argparse argparse.THIS_does_not_EXIST """) with self.assertNoMessages(): self.checker.visit_attribute(node)
def test_rethrow(self): raise_node = test_utils.extract_node(''' def my_func(): try: fake_func() except RuntimeError: raise #@ ''') found = utils.possible_exc_types(raise_node) expected = set(["RuntimeError"]) self.assertEqual(found, expected)
def test_bitbucket_issue_164(self): """Issue 164 report a false negative for access-member-before-definition""" n1, n2 = test_utils.extract_node(""" class MyClass1(object): def __init__(self): self.first += 5 #@ self.first = 0 #@ """) with self.assertAddsMessages(Message('access-member-before-definition', node=n1.target, args=('first', n2.lineno))): self.walk(n1.root())
def test_is_subtype_supertype_old_style_classes(self): cls_a, cls_b = test_utils.extract_node(''' class A: #@ pass class B(A): #@ pass ''') self.assertFalse(helpers.is_subtype(cls_a, cls_b)) self.assertFalse(helpers.is_subtype(cls_b, cls_a)) self.assertFalse(helpers.is_supertype(cls_a, cls_b)) self.assertFalse(helpers.is_supertype(cls_b, cls_a))
def test_no_name_in_module_skipped(self): """Make sure that 'from ... import ...' does not emit a 'no-name-in-module' with a module that is configured to be ignored. """ node = test_utils.extract_node(""" from argparse import THIS_does_not_EXIST """) with self.assertNoMessages(): self.checker.visit_from(node)
def as_used_by_iterable_in_for_loop_test(self, fxn): checker = '{}-builtin-not-iterating'.format(fxn) node = test_utils.extract_node(""" for x in (whatever( {}() #@ )): pass """.format(fxn)) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node)
def test_namedtuple_inference(self): klass = test_utils.extract_node(""" from collections import namedtuple name = "X" fields = ["a", "b", "c"] class X(namedtuple(name, fields)): pass """) base = next(base for base in klass.ancestors() if base.name == 'X') self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs))
def as_used_in_variant_in_genexp_test(self, fxn): checker = '{}-builtin-not-iterating'.format(fxn) node = test_utils.extract_node(""" list( __({}(x)) for x in [1] ) """.format(fxn)) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node)
def test_warns_no_docstring(self): node = test_utils.extract_node(''' def my_func(self): return False ''') return_node = node.body[0] with self.assertAddsMessages( Message( msg_id='missing-returns-doc', node=node)): self.checker.visit_return(return_node)
def test_enum_func_form_is_class_not_instance(self): cls, instance = test_utils.extract_node(''' from enum import Enum f = Enum('Audience', ['a', 'b', 'c']) f #@ f() #@ ''') inferred_cls = next(cls.infer()) self.assertIsInstance(inferred_cls, nodes.ClassDef) inferred_instance = next(instance.infer()) self.assertIsInstance(inferred_instance, bases.Instance)
def test_custom_callback_string(self): """ Test the --calbacks option works. """ def cleanup(): self.checker._to_consume = _to_consume _to_consume = self.checker._to_consume self.checker._to_consume = [] self.addCleanup(cleanup) node = test_utils.extract_node(""" def callback_one(abc): ''' should not emit unused-argument. ''' """) with self.assertNoMessages(): self.checker.visit_function(node) self.checker.leave_function(node) node = test_utils.extract_node(""" def two_callback(abc, defg): ''' should not emit unused-argument. ''' """) with self.assertNoMessages(): self.checker.visit_function(node) self.checker.leave_function(node) node = test_utils.extract_node(""" def normal_func(abc): ''' should emit unused-argument. ''' """) with self.assertAddsMessages( Message('unused-argument', node=node['abc'], args='abc')): self.checker.visit_function(node) self.checker.leave_function(node) node = test_utils.extract_node(""" def cb_func(abc): ''' Previous callbacks are overriden. ''' """) with self.assertAddsMessages( Message('unused-argument', node=node['abc'], args='abc')): self.checker.visit_function(node) self.checker.leave_function(node)
def test_using_cmp_argument(self): nodes = test_utils.extract_node(""" [].sort(cmp=lambda x: x) #@ a = list(range(x)) a.sort(cmp=lambda x: x) #@ sorted([], cmp=lambda x: x) #@ """) for node in nodes: message = testutils.Message('using-cmp-argument', node=node) with self.assertAddsMessages(message): self.checker.visit_callfunc(node)
def test_ignores_uninferable_type(self): raise_node = test_utils.extract_node(''' import not_a_module def my_func(): try: fake_func() except not_a_module.Error: raise #@ ''') found = utils.possible_exc_types(raise_node) expected = set() self.assertEqual(found, expected)
def test_regression_non_parent_init_called_tracemalloc(self): # This used to raise a non-parent-init-called on Pylint 1.3 # See issue https://bitbucket.org/logilab/pylint/issue/308/ # for reference. node = test_utils.extract_node(""" from tracemalloc import Sequence class _Traces(Sequence): def __init__(self, traces): #@ Sequence.__init__(self) """) with self.assertNoMessages(): self.checker.visit_functiondef(node)
def test_finds_google_return_list_of_custom_class(self): return_node = test_utils.extract_node(''' def my_func(self): """This is a docstring. Returns: list(:class:`mymodule.Class`): An object """ return [mymodule.Class()] #@ ''') with self.assertNoMessages(): self.checker.visit_return(return_node)
def test_lgc_classproperty(self): '''test expected values of constants after rebuilding''' code = ''' from logilab.common.decorators import classproperty class A(object): @classproperty def hop(cls): #@ return None ''' method = test_utils.extract_node(code) self.assertEqual('classmethod', method.type)
def test_warns_unknown_style(self): node = test_utils.extract_node(''' def my_func(self): """This is a docstring.""" raise RuntimeError('hi') ''') raise_node = node.body[0] with self.assertAddsMessages( Message(msg_id='missing-raises-doc', node=node, args=('RuntimeError', ))): self.checker.visit_raise(raise_node)
def test_super_yes_objects(self): ast_nodes = test_utils.extract_node(''' from collections import Missing class A(object): def __init__(self): super(Missing, self) #@ super(A, Missing) #@ ''') 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): node = test_utils.extract_node(''' import collections class A(object): def __init__(self): super(A, collections) #@ ''') inferred = next(node.infer()) with self.assertRaises(exceptions.SuperError): inferred.super_mro() with self.assertRaises(exceptions.SuperArgumentTypeError): inferred.super_mro()
def test_property_setters(self): method = test_utils.extract_node(""" class FooClass(object): @property def foo(self): pass @foo.setter def FOOSETTER(self): #@ pass """) with self.assertNoMessages(): self.checker.visit_function(method)
def test_from_imports(self): ast_node = test_utils.extract_node(''' from six.moves import http_client http_client.HTTPSConnection #@ ''') inferred = next(ast_node.infer()) self.assertIsInstance(inferred, nodes.Class) if six.PY3: qname = 'http.client.HTTPSConnection' else: qname = 'httplib.HTTPSConnection' self.assertEqual(inferred.qname(), qname)
def test_threading(self): module = test_utils.extract_node(""" import threading threading.Lock() """) inferred = next(module.infer()) self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.root().name, 'threading') self.assertIsInstance( inferred.getattr('acquire')[0], astroid.FunctionDef) self.assertIsInstance( inferred.getattr('release')[0], astroid.FunctionDef)