def test_augassign_attr(self): test_utils.build_module(""" class Counter: v = 0 def inc(self): self.v += 1 """, __name__)
def test_absolute_import(self): module_import = test_utils.build_module( 'from __future__ import absolute_import; import os') module_from = test_utils.build_module( 'from __future__ import absolute_import; from os import path') with self.assertNoMessages(): for module in (module_import, module_from): self.walk(module)
def test_asstuple(self): code = 'a, b = range(2)' astroid = test_utils.build_module(code) self.assertIn('b', astroid.locals) code = ''' def visit_if(self, node): node.test, body = node.tests[0] ''' astroid = test_utils.build_module(code) self.assertIn('body', astroid['visit_if'].locals)
def test_infered_dont_pollute(self): code = ''' def func(a=None): a.custom_attr = 0 def func2(a={}): a.custom_attr = 0 ''' test_utils.build_module(code) nonetype = nodes.const_factory(None) self.assertNotIn('custom_attr', nonetype.locals) self.assertNotIn('custom_attr', nonetype.instance_attrs) nonetype = nodes.const_factory({}) self.assertNotIn('custom_attr', nonetype.locals) self.assertNotIn('custom_attr', nonetype.instance_attrs)
def test_bad_import_inference(self): # 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. inference.infer_from will try to import this module, which will fail and raise a InferenceException (by mixins.do_import_module). The infer_name will catch this exception and yield and YES instead. ''' code = ''' try: from pickle import PickleError except ImportError: from nonexistent import PickleError try: pass except PickleError: pass ''' astroid = test_utils.build_module(code) handler_type = astroid.body[1].handlers[0].type excs = list(unpack_infer(handler_type)) # The number of returned object can differ on Python 2 # and Python 3. In one version, an additional item will # be returned, from the _pickle module, which is not # present in the other version. self.assertIsInstance(excs[0], nodes.Class) self.assertEqual(excs[0].name, 'PickleError') self.assertIs(excs[-1], bases.YES)
def astroid(self): try: return self.__class__.__dict__['CODE_Astroid'] except KeyError: astroid = test_utils.build_module(self.CODE) self.__class__.CODE_Astroid = astroid return astroid
def test_decorator_builtin_descriptors(self): astroid = test_utils.build_module(""" def static_decorator(platform=None, order=50): def wrapper(f): f.cgm_module = True f.cgm_module_order = order f.cgm_module_platform = platform return staticmethod(f) return wrapper def classmethod_decorator(platform=None): def wrapper(f): f.platform = platform return classmethod(f) return wrapper class SomeClass(object): @static_decorator() def static(node, cfg): pass @classmethod_decorator() def classmethod(cls): pass @static_decorator def not_so_static(node): pass @classmethod_decorator def not_so_classmethod(node): pass """) node = astroid.locals['SomeClass'][0] self.assertEqual(node.locals['static'][0].type, 'staticmethod') self.assertEqual(node.locals['classmethod'][0].type, 'classmethod') self.assertEqual(node.locals['not_so_static'][0].type, 'method') self.assertEqual(node.locals['not_so_classmethod'][0].type, 'method')
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_set_comp_closure(self): astroid = test_utils.build_module(""" ten = { var for var in range(10) } var """) var = astroid.body[1].value self.assertRaises(UnresolvableName, var.infered)
def test_newstyle_detection(self): data = ''' class A: "old style" class B(A): "old style" class C(object): "new style" class D(C): "new style" __metaclass__ = type class E(A): "old style" class F: "new style" ''' mod_ast = test_utils.build_module(data, __name__) if IS_PY3: self.assertTrue(mod_ast['A'].newstyle) self.assertTrue(mod_ast['B'].newstyle) self.assertTrue(mod_ast['E'].newstyle) else: self.assertFalse(mod_ast['A'].newstyle) self.assertFalse(mod_ast['B'].newstyle) self.assertFalse(mod_ast['E'].newstyle) self.assertTrue(mod_ast['C'].newstyle) self.assertTrue(mod_ast['D'].newstyle) self.assertTrue(mod_ast['F'].newstyle)
def test_limit(self): code = """ l = [a for a,b in list] a = 1 b = a a = None def func(): c = 1 """ astroid = test_utils.build_module(code, __name__) # a & b a = next(astroid.nodes_of_class(nodes.Name)) self.assertEqual(a.lineno, 2) if sys.version_info < (3, 0): self.assertEqual(len(astroid.lookup("b")[1]), 2) self.assertEqual(len(astroid.lookup("a")[1]), 3) b = astroid.locals["b"][1] else: self.assertEqual(len(astroid.lookup("b")[1]), 1) self.assertEqual(len(astroid.lookup("a")[1]), 2) b = astroid.locals["b"][0] stmts = a.lookup("a")[1] self.assertEqual(len(stmts), 1) self.assertEqual(b.lineno, 6) b_infer = b.infer() b_value = next(b_infer) self.assertEqual(b_value.value, 1) # c self.assertRaises(StopIteration, partial(next, b_infer)) func = astroid.locals["func"][0] self.assertEqual(len(func.lookup("c")[1]), 1)
def test_metaclass_error(self): astroid = test_utils.build_module(""" class Test(object): __metaclass__ = typ """) klass = astroid['Test'] self.assertFalse(klass.metaclass())
def test_metaclass_ancestors(self): astroid = test_utils.build_module(""" from abc import ABCMeta class FirstMeta(object): __metaclass__ = ABCMeta class SecondMeta(object): __metaclass__ = type class Simple(object): pass class FirstImpl(FirstMeta): pass class SecondImpl(FirstImpl): pass class ThirdImpl(Simple, SecondMeta): pass """) classes = { 'ABCMeta': ('FirstImpl', 'SecondImpl'), 'type': ('ThirdImpl', ) } for metaclass, names in classes.items(): for name in names: impl = astroid[name] meta = impl.metaclass() self.assertIsInstance(meta, nodes.Class) self.assertEqual(meta.name, metaclass)
def test_module_level_names(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_getattr_method_transform(self): data = ''' class Clazz(object): def m1(self, value): self.value = value m2 = m1 def func(arg1, arg2): "function that will be used as a method" return arg1.value + arg2 Clazz.m3 = func inst = Clazz() inst.m4 = func ''' astroid = test_utils.build_module(data) cls = astroid['Clazz'] # test del statement not returned by getattr for method in ('m1', 'm2', 'm3'): inferred = list(cls.igetattr(method)) self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], UnboundMethod) inferred = list(Instance(cls).igetattr(method)) self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], BoundMethod) inferred = list(Instance(cls).igetattr('m4')) self.assertEqual(len(inferred), 1) self.assertIsInstance(inferred[0], nodes.Function)
def test_is_method(self): data = ''' class A: def meth1(self): return 1 @classmethod def meth2(cls): return 2 @staticmethod def meth3(): return 3 def function(): return 0 @staticmethod def sfunction(): return -1 ''' astroid = test_utils.build_module(data) self.assertTrue(astroid['A']['meth1'].is_method()) self.assertTrue(astroid['A']['meth2'].is_method()) self.assertTrue(astroid['A']['meth3'].is_method()) self.assertFalse(astroid['function'].is_method()) self.assertFalse(astroid['sfunction'].is_method())
def test_type_builtin_descriptor_subclasses(self): astroid = test_utils.build_module(""" class classonlymethod(classmethod): pass class staticonlymethod(staticmethod): pass class Node: @classonlymethod def clsmethod_subclass(cls): pass @classmethod def clsmethod(cls): pass @staticonlymethod def staticmethod_subclass(cls): pass @staticmethod def stcmethod(cls): pass """) node = astroid.locals['Node'][0] self.assertEqual(node.locals['clsmethod_subclass'][0].type, 'classmethod') self.assertEqual(node.locals['clsmethod'][0].type, 'classmethod') self.assertEqual(node.locals['staticmethod_subclass'][0].type, 'staticmethod') self.assertEqual(node.locals['stcmethod'][0].type, 'staticmethod')
def test_limit(self): code = ''' l = [a for a,b in list] a = 1 b = a a = None def func(): c = 1 ''' astroid = test_utils.build_module(code, __name__) # a & b a = next(astroid.nodes_of_class(nodes.Name)) self.assertEqual(a.lineno, 2) if sys.version_info < (3, 0): self.assertEqual(len(astroid.lookup('b')[1]), 2) self.assertEqual(len(astroid.lookup('a')[1]), 3) b = astroid.locals['b'][1] else: self.assertEqual(len(astroid.lookup('b')[1]), 1) self.assertEqual(len(astroid.lookup('a')[1]), 2) b = astroid.locals['b'][0] stmts = a.lookup('a')[1] self.assertEqual(len(stmts), 1) self.assertEqual(b.lineno, 6) b_infer = b.infer() b_value = next(b_infer) self.assertEqual(b_value.value, 1) # c self.assertRaises(StopIteration, partial(next, b_infer)) func = astroid.locals['func'][0] self.assertEqual(len(func.lookup('c')[1]), 1)
def test_argnames(self): if sys.version_info < (3, 0): code = 'def f(a, (b, c), *args, **kwargs): pass' else: code = 'def f(a, b, c, *args, **kwargs): pass' astroid = test_utils.build_module(code, __name__) self.assertEqual(astroid['f'].argnames(), ['a', 'b', 'c', 'args', 'kwargs'])
def test_two_future_imports(self): mod = test_utils.build_module(""" from __future__ import print_function from __future__ import absolute_import """) self.assertEqual(set(['print_function', 'absolute_import']), mod.future_imports)
def test_augassign_attr(self): astroid = test_utils.build_module( """ class Counter: v = 0 def inc(self): self.v += 1 """, __name__)
def testFuturePrintStatementWithoutParensWarning(self): code = """from __future__ import print_function print('Hello world!') """ tree = test_utils.build_module(code) with self.assertNoMessages(): self.checker.process_module(tree) self.checker.process_tokens(tokenize_str(code))
def test_lambda_pytype(self): data = ''' def f(): g = lambda: None ''' astroid = test_utils.build_module(data) g = list(astroid['f'].ilookup('g'))[0] self.assertEqual(g.pytype(), '%s.function' % BUILTINS)
def test_function_module_special(self): astroid = test_utils.build_module(''' def initialize(linter): """initialize linter with checkers in this package """ package_load(linter, __path__[0]) ''', 'data.__init__') path = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == '__path__'][0] self.assertEqual(len(path.lookup('__path__')[1]), 1)
def test_slots(self): astroid = test_utils.build_module(""" from collections import deque from textwrap import dedent class First(object): __slots__ = ("a", "b", 1) class Second(object): __slots__ = "a" class Third(object): __slots__ = deque(["a", "b", "c"]) class Fourth(object): __slots__ = {"a": "a", "b": "b"} class Fifth(object): __slots__ = list class Sixth(object): __slots__ = "" class Seventh(object): __slots__ = dedent.__name__ class Eight(object): __slots__ = ("parens") """) first = astroid['First'] first_slots = first.slots() self.assertEqual(len(first_slots), 2) self.assertIsInstance(first_slots[0], nodes.Const) self.assertIsInstance(first_slots[1], nodes.Const) self.assertEqual(first_slots[0].value, "a") self.assertEqual(first_slots[1].value, "b") second_slots = astroid['Second'].slots() self.assertEqual(len(second_slots), 1) self.assertIsInstance(second_slots[0], nodes.Const) self.assertEqual(second_slots[0].value, "a") third_slots = astroid['Third'].slots() self.assertEqual(third_slots, []) fourth_slots = astroid['Fourth'].slots() self.assertEqual(len(fourth_slots), 2) self.assertIsInstance(fourth_slots[0], nodes.Const) self.assertIsInstance(fourth_slots[1], nodes.Const) self.assertEqual(fourth_slots[0].value, "a") self.assertEqual(fourth_slots[1].value, "b") fifth_slots = astroid['Fifth'].slots() self.assertEqual(fifth_slots, []) sixth_slots = astroid['Sixth'].slots() self.assertEqual(sixth_slots, []) seventh_slots = astroid['Seventh'].slots() self.assertEqual(len(seventh_slots), 0) eight_slots = astroid['Eight'].slots() self.assertEqual(len(eight_slots), 1) self.assertIsInstance(eight_slots[0], nodes.Const) self.assertEqual(eight_slots[0].value, "parens")
def test_simple_metaclass(self): astroid = test_utils.build_module(""" class Test(object): __metaclass__ = type """) klass = astroid['Test'] metaclass = klass.metaclass() self.assertIsInstance(metaclass, scoped_nodes.Class) self.assertEqual(metaclass.name, 'type')
def test_checker_disabled_by_default(self): node = test_utils.build_module(textwrap.dedent(""" abc = 1l raise Exception, "test" raise "test" `abc` """)) with self.assertNoMessages(): self.walk(node)
def test_slots_py2_not_implemented(self): module = test_utils.build_module(""" class OldStyle: __slots__ = ("a", "b") """) msg = "The concept of slots is undefined for old-style classes." with self.assertRaises(NotImplementedError) as cm: module['OldStyle'].slots() self.assertEqual(str(cm.exception), msg)
def test_newstyle_and_metaclass_good(self): astroid = test_utils.build_module(""" from abc import ABCMeta class Test: __metaclass__ = ABCMeta """) klass = astroid['Test'] self.assertTrue(klass.newstyle) self.assertEqual(klass.metaclass().name, 'ABCMeta') astroid = test_utils.build_module(""" from abc import ABCMeta __metaclass__ = ABCMeta class Test: pass """) klass = astroid['Test'] self.assertTrue(klass.newstyle) self.assertEqual(klass.metaclass().name, 'ABCMeta')
def testCheckMessages(self): linter = self.MockLinter({'first-message': True, 'second-message': False, 'third-message': True}) walker = utils.PyLintASTWalker(linter) checker = self.Checker() walker.add_checker(checker) walker.walk(test_utils.build_module("x = func()")) self.assertEqual(set(['module', 'assname']), checker.called)
def test_gen_expr_var_scope(self): data = 'l = list(n for n in range(10))\n' astroid = test_utils.build_module(data, __name__) # n unavailable outside gen expr scope self.assertNotIn('n', astroid) # test n is inferable anyway n = test_utils.get_name_node(astroid, 'n') self.assertIsNot(n.scope(), astroid) self.assertEqual([i.__class__ for i in n.infer()], [YES.__class__])
def test_assign_to_True(self): """test that True and False assignements don't crash""" code = """ True = False def hello(False): pass del True """ if sys.version_info >= (3, 0): with self.assertRaises(SyntaxError): test_utils.build_module(code) else: ast = test_utils.build_module(code) ass_true = ast['True'] self.assertIsInstance(ass_true, nodes.AssName) self.assertEqual(ass_true.name, "True") del_true = ast.body[2].targets[0] self.assertIsInstance(del_true, nodes.DelName) self.assertEqual(del_true.name, "True")
def test_metaclass_yes_leak(self): astroid = test_utils.build_module(""" # notice `ab` instead of `abc` from ab import ABCMeta class Meta(object): __metaclass__ = ABCMeta """) klass = astroid['Meta'] self.assertIsNone(klass.metaclass())
def create_file_backed_module(self, code): tmp = tempfile.NamedTemporaryFile() tmp.write(code) tmp.flush() module = test_utils.build_module(code) module.file = tmp.name # Just make sure to keep a reference to the file # so it isn't deleted. module._tmpfile = tmp return module
def test_with_lineno(self): astroid = test_utils.build_module(''' from __future__ import with_statement with file("/tmp/pouet") as f: print (f) ''', __name__) with_ = astroid.body[1] self.assertEqual(with_.fromlineno, 3) self.assertEqual(with_.tolineno, 4) self.assertEqual(with_.blockstart_tolineno, 3)
def test_slots_py2(self): module = test_utils.build_module(""" class UnicodeSlots(object): __slots__ = (u"a", u"b", "c") """) slots = module['UnicodeSlots'].slots() self.assertEqual(len(slots), 3) self.assertEqual(slots[0].value, "a") self.assertEqual(slots[1].value, "b") self.assertEqual(slots[2].value, "c")
def test_module_getattr(self): data = ''' appli = application appli += 2 del appli ''' astroid = test_utils.build_module(data, __name__) # test del statement not returned by getattr self.assertEqual(len(astroid.getattr('appli')), 2, astroid.getattr('appli'))
def test_set_comps(self): astroid = test_utils.build_module(""" print ({ i for i in range(10) }) print ({ i for i in range(10) }) """, __name__) xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i'] self.assertEqual(len(xnames[0].lookup('i')[1]), 1) self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2) self.assertEqual(len(xnames[1].lookup('i')[1]), 1) self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3)