Exemplo n.º 1
0
    def test_if(self):
        astng = builder.string_build('''

if 1:
    a = 1
    a = 2
elif 2:
    a = 12
    a = 13
else:
    a = 3
    a = 4
        ''')
        a1 = astng.locals['a'][0]
        a2 = astng.locals['a'][1]
        a3 = astng.locals['a'][2]
        a4 = astng.locals['a'][3]
        a5 = astng.locals['a'][4]
        a6 = astng.locals['a'][5]
        self.assertEquals(are_exclusive(a1, a2), False)
        self.assertEquals(are_exclusive(a1, a3), True)
        self.assertEquals(are_exclusive(a1, a5), True)
        self.assertEquals(are_exclusive(a3, a5), True)
        self.assertEquals(are_exclusive(a3, a4), False)
        self.assertEquals(are_exclusive(a5, a6), False)
Exemplo n.º 2
0
    def test_try_except(self):
        astng = builder.string_build('''
try:
    def exclusive_func2():
        "docstring"
except TypeError:
    def exclusive_func2():
        "docstring"
except:
    def exclusive_func2():
        "docstring"
else:
    def exclusive_func2():
        "this one redefine the one defined line 42"

        ''')
        f1 = astng.locals['exclusive_func2'][0]
        f2 = astng.locals['exclusive_func2'][1]
        f3 = astng.locals['exclusive_func2'][2]
        f4 = astng.locals['exclusive_func2'][3]
        self.assertEquals(are_exclusive(f1, f2), True)
        self.assertEquals(are_exclusive(f1, f3), True)
        self.assertEquals(are_exclusive(f1, f4), False)
        self.assertEquals(are_exclusive(f2, f4), True)
        self.assertEquals(are_exclusive(f3, f4), True)
        self.assertEquals(are_exclusive(f3, f2), True)
        
        self.assertEquals(are_exclusive(f2, f1), True)
        self.assertEquals(are_exclusive(f4, f1), False)
        self.assertEquals(are_exclusive(f4, f2), True)
Exemplo n.º 3
0
    def test_import_as(self):
        code = '''
import os.path as osp
print (osp.dirname(__file__))

from os.path import exists as e
assert e(__file__)

from new import code as make_code
print (make_code)
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng.igetattr('osp'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Module)
        self.failUnlessEqual(infered[0].name, 'os.path')
        infered = list(astng.igetattr('e'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Function)
        self.failUnlessEqual(infered[0].name, 'exists')
        if sys.version_info >= (3, 0):
            self.skipTest('<new> module has been removed')
        infered = list(astng.igetattr('make_code'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], Instance)
        self.failUnlessEqual(str(infered[0]),
                             'Instance of %s.type' % BUILTINS_NAME)
Exemplo n.º 4
0
    def test_set_comp_closure(self):
        astng = builder.string_build("""
ten = { var for var in range(10) }
var
        """)
        var = astng.body[1].value
        self.assertRaises(UnresolvableName, var.infered)
Exemplo n.º 5
0
    def test_limit(self):
        code = '''
l = [a
     for a,b in list]

a = 1
b = a
a = None

def func():
    c = 1
        '''
        astng = builder.string_build(code, __name__, __file__)
        # a & b
        a = astng.nodes_of_class(nodes.Name).next()
        self.assertEqual(a.lineno, 2)
        if sys.version_info < (3, 0):
            self.assertEqual(len(astng.lookup('b')[1]), 2)
            self.assertEqual(len(astng.lookup('a')[1]), 3)
            b = astng.locals['b'][1]
        else:
            self.assertEqual(len(astng.lookup('b')[1]), 1)
            self.assertEqual(len(astng.lookup('a')[1]), 2)
            b = astng.locals['b'][0]
        stmts = a.lookup('a')[1]
        self.assertEqual(len(stmts), 1)
        self.assertEqual(b.lineno, 6)
        b_infer = b.infer()
        b_value = b_infer.next()
        self.assertEqual(b_value.value, 1)
        # c
        self.assertRaises(StopIteration, b_infer.next)
        func = astng.locals['func'][0]
        self.assertEqual(len(func.lookup('c')[1]), 1)
Exemplo n.º 6
0
    def test_nonregr_func_global(self):
        code = '''
active_application = None

def get_active_application():
  global active_application
  return active_application

class Application(object):
  def __init__(self):
     global active_application
     active_application = self

class DataManager(object):
  def __init__(self, app=None):
     self.app = get_active_application()
  def test(self):
     p = self.app
     print (p)
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(Instance(astng['DataManager']).igetattr('app'))
        self.assertEqual(len(infered), 2, infered) # None / Instance(Application)
        infered = list(get_name_node(astng['DataManager']['test'], 'p').infer())
        self.assertEqual(len(infered), 2, infered)
        for node in infered:
            if isinstance(node, Instance) and node.name == 'Application':
                break
        else:
            self.fail('expected to find an instance of Application in %s' % infered)
Exemplo n.º 7
0
    def test_list_inference(self):
        """#20464"""
        code = '''
import optparse

A = []
B = []

def test():
  xyz = [
    "foobar=%s" % options.ca,
  ] + A + B

  if options.bind is not None:
    xyz.append("bind=%s" % options.bind)
  return xyz

def main():
  global options

  parser = optparse.OptionParser()
  (options, args) = parser.parse_args()

Z = test()
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng['Z'].infer())
        self.assertEqual(len(infered), 1, infered)
        self.assertIsInstance(infered[0], Instance)
        self.assertIsInstance(infered[0]._proxied, nodes.Class)
        self.assertEqual(infered[0]._proxied.name, 'list')
Exemplo n.º 8
0
    def test_except_inference(self):
        code = '''
try:
    print (hop)
except NameError, ex:
    ex1 = ex
except Exception, ex:
    ex2 = ex
    raise
        '''
        if sys.version_info >= (3, 0):
            code = code.replace(', ex:', ' as ex:')
        astng = builder.string_build(code, __name__, __file__)
        ex1 = astng['ex1']
        ex1_infer = ex1.infer()
        ex1 = ex1_infer.next()
        self.assertIsInstance(ex1, Instance)
        self.failUnlessEqual(ex1.name, 'NameError')
        self.failUnlessRaises(StopIteration, ex1_infer.next)
        ex2 = astng['ex2']
        ex2_infer = ex2.infer()
        ex2 = ex2_infer.next()
        self.assertIsInstance(ex2, Instance)
        self.failUnlessEqual(ex2.name, 'Exception')
        self.failUnlessRaises(StopIteration, ex2_infer.next)
Exemplo n.º 9
0
    def test_property(self):
        code = '''
from smtplib import SMTP
class SendMailController(object):

    @property
    def smtp(self):
        return SMTP(mailhost, port)

    @property
    def me(self):
        return self

my_smtp = SendMailController().smtp
my_me = SendMailController().me
'''
        decorators = set(['%s.property' % BUILTINS_NAME])
        astng = builder.string_build(code, __name__, __file__)
        self.assertEqual(astng['SendMailController']['smtp'].decoratornames(),
                          decorators)
        propinfered = list(astng.body[2].value.infer())
        self.assertEqual(len(propinfered), 1)
        propinfered = propinfered[0]
        self.assertIsInstance(propinfered, Instance)
        self.assertEqual(propinfered.name, 'SMTP')
        self.assertEqual(propinfered.root().name, 'smtplib')
        self.assertEqual(astng['SendMailController']['me'].decoratornames(),
                          decorators)
        propinfered = list(astng.body[3].value.infer())
        self.assertEqual(len(propinfered), 1)
        propinfered = propinfered[0]
        self.assertIsInstance(propinfered, Instance)
        self.assertEqual(propinfered.name, 'SendMailController')
        self.assertEqual(propinfered.root().name, __name__)
Exemplo n.º 10
0
    def test_method_argument(self):
        code = '''
class ErudiEntitySchema:
    """a entity has a type, a set of subject and or object relations"""
    def __init__(self, e_type, **kwargs):
        kwargs['e_type'] = e_type.capitalize().encode()

    def meth(self, e_type, *args, **kwargs):
        kwargs['e_type'] = e_type.capitalize().encode()
        print(args)
        '''
        astng = builder.string_build(code, __name__, __file__)
        arg = get_name_node(astng['ErudiEntitySchema']['__init__'], 'e_type')
        self.failUnlessEqual([n.__class__ for n in arg.infer()],
                             [YES.__class__])
        arg = get_name_node(astng['ErudiEntitySchema']['__init__'], 'kwargs')
        self.failUnlessEqual([n.__class__ for n in arg.infer()],
                             [nodes.Dict])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'e_type')
        self.failUnlessEqual([n.__class__ for n in arg.infer()],
                             [YES.__class__])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'args')
        self.failUnlessEqual([n.__class__ for n in arg.infer()],
                             [nodes.Tuple])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'kwargs')
        self.failUnlessEqual([n.__class__ for n in arg.infer()],
                             [nodes.Dict])
Exemplo n.º 11
0
    def test_del2(self):
        code = '''
a = 1
b = a
del a
c = a
a = 2
d = a
        '''
        astng = builder.string_build(code, __name__, __file__)
        n = astng['b']
        n_infer = n.infer()
        infered = n_infer.next()
        self.assertIsInstance(infered, nodes.Const)
        self.failUnlessEqual(infered.value, 1)
        self.failUnlessRaises(StopIteration, n_infer.next)
        n = astng['c']
        n_infer = n.infer()
        self.failUnlessRaises(InferenceError, n_infer.next)
        n = astng['d']
        n_infer = n.infer()
        infered = n_infer.next()
        self.assertIsInstance(infered, nodes.Const)
        self.failUnlessEqual(infered.value, 2)
        self.failUnlessRaises(StopIteration, n_infer.next)
Exemplo n.º 12
0
    def test_limit(self):
        code = '''
l = [a
     for a,b in list]

a = 1
b = a
a = None

def func():
    c = 1
        '''
        astng = builder.string_build(code, __name__, __file__)
        names = astng.nodes_of_class(nodes.Name)
        a = names.next()
        stmts = a.lookup('a')[1]
        self.failUnlessEqual(len(stmts), 1)
        b = astng.locals['b'][1]
        #self.failUnlessEqual(len(b.lookup('b')[1]), 1)
        self.failUnlessEqual(len(astng.lookup('b')[1]), 2)
        b_infer = b.infer()
        b_value = b_infer.next()
        self.failUnlessEqual(b_value.value, 1)
        self.failUnlessRaises(StopIteration, b_infer.next)
        func = astng.locals['func'][0]
        self.failUnlessEqual(len(func.lookup('c')[1]), 1)
Exemplo n.º 13
0
    def test_binary_op_custom_class(self):
        code = '''
class myarray:
    def __init__(self, array):
        self.array = array
    def __mul__(self, x):
        return myarray([2,4,6])
    def astype(self):
        return "ASTYPE"

def randint(maximum):
    if maximum is not None:
        return myarray([1,2,3]) * 2
    else:
        return int(5)

x = randint(1)
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng.igetattr('x'))
        self.failUnlessEqual(len(infered), 2)
        value = [str(v) for v in infered]
        # The __name__ trick here makes it work when invoked directly
        # (__name__ == '__main__') and through pytest (__name__ ==
        # 'unittest_inference')
        self.assertEqual(value, ['Instance of %s.myarray' % __name__,
                                 'Instance of %s.int' % BUILTINS_NAME])
Exemplo n.º 14
0
    def test_property(self):
        code = '''
from smtplib import SMTP
class SendMailController(object):

    @property
    def smtp(self):
        return SMTP(mailhost, port)

    @property
    def me(self):
        return self

print SendMailController().smtp
print SendMailController().me
'''
        astng = builder.string_build(code, __name__, __file__)
        self.assertEquals(astng['SendMailController']['smtp'].decoratornames(),
                          set(('__builtin__.property',)))
        propinfered = list(astng.body[2].values[0].infer())
        self.assertEquals(len(propinfered), 1)
        propinfered = propinfered[0]
        self.assertIsInstance(propinfered, Instance)
        self.assertEquals(propinfered.name, 'SMTP')
        self.assertEquals(propinfered.root().name, 'smtplib')
        self.assertEquals(astng['SendMailController']['me'].decoratornames(),
                          set(('__builtin__.property',)))
        propinfered = list(astng.body[3].values[0].infer())
        self.assertEquals(len(propinfered), 1)
        propinfered = propinfered[0]
        self.assertIsInstance(propinfered, Instance)
        self.assertEquals(propinfered.name, 'SendMailController')
        self.assertEquals(propinfered.root().name, __name__)
Exemplo n.º 15
0
 def test_python25_relative_import(self):
     data = "from ...common import date; print (date)"
     # !! FIXME also this relative import would not work 'in real' (no __init__.py in test/)
     # the test works since we pretend we have a package by passing the full modname
     astng = builder.string_build(data, 'logilab.astng.test.unittest_inference', __file__)
     infered = get_name_node(astng, 'date').infer().next()
     self.assertIsInstance(infered, nodes.Module)
     self.assertEqual(infered.name, 'logilab.common.date')
Exemplo n.º 16
0
    def test_function_module_special(self):
        astng = builder.string_build('''
def initialize(linter):
    """initialize linter with checkers in this package """
    package_load(linter, __path__[0])
        ''', 'data.__init__', 'data/__init__.py')
        path = [n for n in astng.nodes_of_class(nodes.Name) if n.name == '__path__'][0]
        self.assertEqual(len(path.lookup('__path__')[1]), 1)
Exemplo n.º 17
0
 def test_python25_relative_import(self):
     if sys.version_info < (2, 5):
         self.skip('require py >= 2.5')
     data = "from ...common import date; print date"
     astng = builder.string_build(data, 'logilab.astng.test.unittest_inference', __file__)
     infered = get_name_node(astng, 'date').infer().next()
     self.assertIsInstance(infered, nodes.Module)
     self.assertEquals(infered.name, 'logilab.common.date')
Exemplo n.º 18
0
 def test_binary_op_tuple_add(self):
     astng = builder.string_build('a = (1,) + (2,)', __name__, __file__)
     infered = list(astng['a'].infer())
     self.failUnlessEqual(len(infered), 1)
     self.assertIsInstance(infered[0], nodes.Tuple)
     self.failUnlessEqual(len(infered[0].elts), 2)
     self.failUnlessEqual(infered[0].elts[0].value, 1)
     self.failUnlessEqual(infered[0].elts[1].value, 2)
Exemplo n.º 19
0
 def test_binary_op_list_mul_none(self):
     'test correct handling on list multiplied by None'
     astng = builder.string_build( 'a = [1] * None\nb = [1] * "r"')
     infered = astng['a'].infered()
     self.assertEqual(len(infered), 1)
     self.assertEqual(infered[0], YES)
     infered = astng['b'].infered()
     self.assertEqual(len(infered), 1)
     self.assertEqual(infered[0], YES)
Exemplo n.º 20
0
    def test_simple_for_genexpr(self):
        code = '''
print ((d,e) for e,d in ([1,2], [3,4]))
        '''
        astng = builder.string_build(code, __name__, __file__)
        self.failUnlessEqual([i.value for i in
                            get_name_node(astng, 'd', -1).infer()], [2, 4])
        self.failUnlessEqual([i.value for i in
                            get_name_node(astng, 'e', -1).infer()], [1, 3])
Exemplo n.º 21
0
 def test_binary_op_list_mul(self):
     for code in ('a = [[]] * 2', 'a = 2 * [[]]'):
         astng = builder.string_build(code, __name__, __file__)
         infered = list(astng['a'].infer())
         self.failUnlessEqual(len(infered), 1)
         self.assertIsInstance(infered[0], nodes.List)
         self.failUnlessEqual(len(infered[0].elts), 2)
         self.assertIsInstance(infered[0].elts[0], nodes.List)
         self.assertIsInstance(infered[0].elts[1], nodes.List)
Exemplo n.º 22
0
    def test_qqch(self):
        code = '''
from logilab.common.modutils import load_module_from_name
xxx = load_module_from_name('__pkginfo__')
        '''
        astng = builder.string_build(code, __name__, __file__)
        xxx = astng['xxx']
        self.assertSetEqual(set(n.__class__ for n in xxx.infered()),
                            set([nodes.Const, YES.__class__]))
    def test_two_parents_from_same_module(self):
        code = '''
from data import nonregr
class Xxx(nonregr.Aaa, nonregr.Ccc):
    "doc"
        '''
        astng = builder.string_build(code, __name__, __file__)
        parents = list(astng['Xxx'].ancestors())
        self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object
 def test_builtin_types_py27(self):
     code = 's = {1}'
     astng = builder.string_build(code, __name__, __file__)
     n = astng['s']
     infered = n.infer().next()
     self.assertIsInstance(infered, nodes.Set)
     self.assertIsInstance(infered, Instance)
     self.assertEqual(infered.name, 'set')
     self.assertIn('remove', infered._proxied.locals)
Exemplo n.º 25
0
    def test_set_comp_closure(self):
        if sys.version_info < (2, 7):
            self.skipTest('this test require python >= 2.7')
        astng = builder.string_build("""
ten = { var for var in range(10) }
var
        """)
        var = astng.body[1].value
        self.assertRaises(UnresolvableName, var.infered)
Exemplo n.º 26
0
 def test_python25_generator_exit(self):
     sys.stderr = StringIO()
     data = "b = {}[str(0)+''].a"
     astng = builder.string_build(data, __name__, __file__)
     list(astng['b'].infer())
     output = sys.stderr.getvalue()
     # I have no idea how to test for this in another way...
     self.failIf("RuntimeError" in output, "Exception exceptions.RuntimeError: 'generator ignored GeneratorExit' in <generator object> ignored")
     sys.stderr = sys.__stderr__
Exemplo n.º 27
0
    def test_nonregr_getitem_empty_tuple(self):
        code = '''
def f(x):
        a = ()[x]
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng['f'].ilookup('a'))
        self.failUnlessEqual(len(infered), 1)
        self.failUnlessEqual(infered[0], YES)
Exemplo n.º 28
0
    def test_qqch(self):
        code = '''
from logilab.common.modutils import load_module_from_name
xxx = load_module_from_name('__pkginfo__')
        '''
        astng = builder.string_build(code, __name__, __file__)
        xxx = astng['xxx']
        infered = list(xxx.infer())
        self.failUnlessEqual(sorted([n.__class__ for n in infered]),
                             sorted([nodes.Const, YES.__class__]))
Exemplo n.º 29
0
    def test_builtin_open(self):
        code = '''
open("toto.txt")
        '''
        astng = builder.string_build(code, __name__, __file__)
        node = get_name_node(astng, 'open', -1)
        infered = list(node.infer())
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Function)
        self.failUnlessEqual(infered[0].name, 'open')
Exemplo n.º 30
0
    def test_set_comps(self):
        astng = builder.string_build("""
print ({ i for i in range(10) })
print ({ i for i in range(10) })
        """, __name__, __file__)
        xnames = [n for n in astng.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)
Exemplo n.º 31
0
    def test__new__(self):
        code = '''
class NewTest(object):
    "doc"
    def __new__(cls, arg):
        self = object.__new__(cls)
        self.arg = arg
        return self

n = NewTest()
        '''
        astng = builder.string_build(code, __name__, __file__)
        self.assertRaises(InferenceError, list,
                          astng['NewTest'].igetattr('arg'))
        n = astng['n'].infer().next()
        infered = list(n.igetattr('arg'))
        self.assertEqual(len(infered), 1, infered)
Exemplo n.º 32
0
    def test_inner_decorator_member_lookup(self):
        if sys.version_info < (2, 4):
            self.skipTest('this test require python >= 2.4')
        code = '''
class FileA:
    def decorator(bla):
        return bla
    
    @decorator
    def funcA():
        return 4
        '''
        astng = builder.string_build(code, __name__, __file__)
        decname = get_name_node(astng['FileA'], 'decorator')
        it = decname.infer()
        obj = it.next()
        self.assertIsInstance(obj, nodes.Function)
        self.assertRaises(StopIteration, it.next)
Exemplo n.º 33
0
    def test_exc_ancestors(self):
        code = '''
def f():
    raise NotImplementedError
        '''
        astng = builder.string_build(code, __name__, __file__)
        names = astng.nodes_of_class(nodes.Name)
        nie = names.next().infer().next()
        self.assertIsInstance(nie, nodes.Class)
        nie_ancestors = [c.name for c in nie.ancestors()]
        if sys.version_info < (2, 5):
            self.failUnlessEqual(
                nie_ancestors, ['RuntimeError', 'StandardError', 'Exception'])
        else:
            self.failUnlessEqual(nie_ancestors, [
                'RuntimeError', 'StandardError', 'Exception', 'BaseException',
                'object'
            ])
Exemplo n.º 34
0
    def test_float_complex_ambiguity(self):
        code = '''
def test_anu(lst):
    """
    prambanan:type lst l(t(i(int), i(str)))
    """
    for a,b in lst:
        print a
        '''
        astng = builder.string_build(code, __name__, __file__)
        sgen = ScopeGenerator("test", astng)
        sgen.visit(astng)
        a = astng["test_anu"]["a"]
        for inferred in a.infer():
            print inferred
        b = astng["test_anu"]["b"]
        for inferred in b.infer():
            print inferred
Exemplo n.º 35
0
    def test_factory_method(self):
        code = '''
class Super(object):
      @classmethod
      def instance(cls):
              return cls()

class Sub(Super):
      def method(self):
              print ('method called')

sub = Sub.instance()
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng.igetattr('sub'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], Instance)
        self.failUnlessEqual(infered[0]._proxied.name, 'Sub')
Exemplo n.º 36
0
    def test_mulassign_inference(self):
        code = '''

def first_word(line):
    """Return the first word of a line"""

    return line.split()[0]

def last_word(line):
    """Return last word of a line"""

    return line.split()[-1]

def process_line(word_pos):
    """Silly function: returns (ok, callable) based on argument.

       For test purpose only.
    """

    if word_pos > 0:
        return (True, first_word)
    elif word_pos < 0:
        return  (True, last_word)
    else:
        return (False, None)

if __name__ == '__main__':

    line_number = 0
    for a_line in file('test_callable.py'):
        tupletest  = process_line(line_number)
        (ok, fct)  = process_line(line_number)
        if ok:
            fct(a_line)
'''
        astng = builder.string_build(code, __name__, __file__)
        self.failUnlessEqual(
            len(list(astng['process_line'].infer_call_result(None))), 3)
        self.failUnlessEqual(len(list(astng['tupletest'].infer())), 3)
        values = [
            'Function(first_word)', 'Function(last_word)', 'Const(NoneType)'
        ]
        self.failUnlessEqual(
            [str(infered) for infered in astng['fct'].infer()], values)
Exemplo n.º 37
0
    def test_dict_comps(self):
        if sys.version_info < (2, 7):
            self.skipTest('this test require python >= 2.7')
        astng = builder.string_build(
            """
print ({ i: j for i in range(10) for j in range(10) })
print ({ i: j for i in range(10) for j in range(10) })
        """, __name__, __file__)
        xnames = [n for n in astng.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)

        xnames = [n for n in astng.nodes_of_class(nodes.Name) if n.name == 'j']
        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)
Exemplo n.º 38
0
    def test_global_delete(self):
        code = '''
def run2():
    f = Frobble()

class Frobble:
    pass
Frobble.mumble = True

del Frobble

def run1():
    f = Frobble()
'''
        astng = builder.string_build(code, __name__, __file__)
        stmts = astng['run2'].lookup('Frobbel')[1]
        self.assertEqual(len(stmts), 0)
        stmts = astng['run1'].lookup('Frobbel')[1]
        self.assertEqual(len(stmts), 0)
Exemplo n.º 39
0
    def test_builtin_types(self):
        code = '''
l = [1]
t = (2,)
d = {}
s = ''
u = u''
        '''
        astng = builder.string_build(code, __name__, __file__)
        n = astng['l']
        infered = n.infer().next()
        self.assertIsInstance(infered, nodes.List)
        self.assertIsInstance(infered, Instance)
        self.failUnlessEqual(infered.getitem(0).value, 1)
        self.assertIsInstance(infered._proxied, nodes.Class)
        self.failUnlessEqual(infered._proxied.name, 'list')
        self.failUnless('append' in infered._proxied.locals)
        n = astng['t']
        infered = n.infer().next()
        self.assertIsInstance(infered, nodes.Tuple)
        self.assertIsInstance(infered, Instance)
        self.failUnlessEqual(infered.getitem(0).value, 2)
        self.assertIsInstance(infered._proxied, nodes.Class)
        self.failUnlessEqual(infered._proxied.name, 'tuple')
        n = astng['d']
        infered = n.infer().next()
        self.assertIsInstance(infered, nodes.Dict)
        self.assertIsInstance(infered, Instance)
        self.assertIsInstance(infered._proxied, nodes.Class)
        self.failUnlessEqual(infered._proxied.name, 'dict')
        self.failUnless('get' in infered._proxied.locals)
        n = astng['s']
        infered = n.infer().next()
        self.assertIsInstance(infered, nodes.Const)
        self.assertIsInstance(infered, Instance)
        self.failUnlessEqual(infered.name, 'str')
        self.failUnless('lower' in infered._proxied.locals)
        n = astng['u']
        infered = n.infer().next()
        self.assertIsInstance(infered, nodes.Const)
        self.assertIsInstance(infered, Instance)
        self.failUnlessEqual(infered.name, 'unicode')
        self.failUnless('lower' in infered._proxied.locals)
Exemplo n.º 40
0
    def test_float_complex_ambiguity(self):
        code = '''
def no_conjugate_member(magic_flag):
    """should not raise E1101 on something.conjugate"""
    if magic_flag:
        something = 1.0
    else:
        something = 1.0j
    if isinstance(something, float):
        return something
    return something.conjugate()
        '''
        astng = builder.string_build(code, __name__, __file__)
        self.failUnlessEqual([
            i.value for i in astng['no_conjugate_member'].ilookup('something')
        ], [1.0, 1.0j])
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'something', -1).infer()],
            [1.0, 1.0j])
Exemplo n.º 41
0
    def test_static_method_lookup(self):
        code = '''
class FileA:
    @staticmethod
    def funcA():
        return 4


class Test:
    FileA = [1,2,3]

    def __init__(self):
        print (FileA.funcA())
        '''
        astng = builder.string_build(code, __name__, __file__)
        it = astng['Test']['__init__'].ilookup('FileA')
        obj = it.next()
        self.assertIsInstance(obj, nodes.Class)
        self.assertRaises(StopIteration, it.next)
Exemplo n.º 42
0
    def test_factory_method(self):
        if sys.version_info < (2, 4):
            self.skip('this test require python >= 2.4')
        code = '''
class Super(object):
      @classmethod
      def instance(cls):
              return cls()

class Sub(Super):
      def method(self):
              print 'method called'

sub = Sub.instance()
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng.igetattr('sub'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], Instance)
        self.failUnlessEqual(infered[0]._proxied.name, 'Sub')
Exemplo n.º 43
0
    def test_explicit___name__(self):
        code = '''
class Pouet:
    __name__ = "pouet"
p1 = Pouet()

class PouetPouet(Pouet): pass
p2 = Pouet()

class NoName: pass
p3 = NoName()
'''
        astng = builder.string_build(code, __name__, __file__)
        p1 = astng['p1'].infer().next()
        self.assertTrue(p1.getattr('__name__'))
        p2 = astng['p2'].infer().next()
        self.assertTrue(p2.getattr('__name__'))
        self.assertTrue(astng['NoName'].getattr('__name__'))
        p3 = astng['p3'].infer().next()
        self.assertRaises(NotFoundError, p3.getattr, '__name__')
Exemplo n.º 44
0
    def test_decorator_arguments_lookup(self):
        code = '''
def decorator(value):
    def wrapper(function):
        return function
    return wrapper

class foo:
    member = 10

    @decorator(member) #This will cause pylint to complain
    def test(self):
        pass
        '''
        astng = builder.string_build(code, __name__, __file__)
        member = get_name_node(astng['foo'], 'member')
        it = member.infer()
        obj = it.next()
        self.assertIsInstance(obj, nodes.Const)
        self.assertEqual(obj.value, 10)
        self.assertRaises(StopIteration, it.next)
Exemplo n.º 45
0
    def test_bt_ancestor_crash(self):
        code = '''
class Warning(Warning):
    pass
        '''
        astng = builder.string_build(code, __name__, __file__)
        w = astng['Warning']
        ancestors = w.ancestors()
        ancestor = next(ancestors)
        self.failUnlessEqual(ancestor.name, 'Warning')
        self.failUnlessEqual(ancestor.root().name, EXC_MODULE)
        ancestor = next(ancestors)
        self.failUnlessEqual(ancestor.name, 'Exception')
        self.failUnlessEqual(ancestor.root().name, EXC_MODULE)
        ancestor = next(ancestors)
        self.failUnlessEqual(ancestor.name, 'BaseException')
        self.failUnlessEqual(ancestor.root().name, EXC_MODULE)
        ancestor = next(ancestors)
        self.failUnlessEqual(ancestor.name, 'object')
        self.failUnlessEqual(ancestor.root().name, BUILTINS_NAME)
        self.failUnlessRaises(StopIteration, ancestors.__next__)
Exemplo n.º 46
0
    def test_static_method_lookup(self):
        if sys.version_info < (2, 4):
            self.skipTest('this test require python >= 2.4')
        code = '''
class FileA:
    @staticmethod
    def funcA():
        return 4


class Test:
    FileA = [1,2,3]
    
    def __init__(self):
        print FileA.funcA()
        '''
        astng = builder.string_build(code, __name__, __file__)
        it = astng['Test']['__init__'].ilookup('FileA')
        obj = it.next()
        self.assertIsInstance(obj, nodes.Class)
        self.assertRaises(StopIteration, it.next)
Exemplo n.º 47
0
    def test_simple_for(self):
        code = '''
for a in [1, 2, 3]:
    print a
for b,c in [(1,2), (3,4)]:
    print b
    print c

print [(d,e) for e,d in ([1,2], [3,4])]
        '''
        astng = builder.string_build(code, __name__, __file__)
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'a', -1).infer()],
            [1, 2, 3])
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'b', -1).infer()], [1, 3])
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'c', -1).infer()], [2, 4])
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'd', -1).infer()], [2, 4])
        self.failUnlessEqual(
            [i.value for i in get_name_node(astng, 'e', -1).infer()], [1, 3])
Exemplo n.º 48
0
    def test_bt_ancestor_crash(self):
        code = '''
class Warning(Warning):
    pass
        '''
        astng = builder.string_build(code, __name__, __file__)
        w = astng['Warning']
        ancestors = w.ancestors()
        ancestor = ancestors.next()
        self.failUnlessEqual(ancestor.name, 'Warning')
        self.failUnlessEqual(ancestor.root().name, 'exceptions')
        ancestor = ancestors.next()
        self.failUnlessEqual(ancestor.name, 'Exception')
        self.failUnlessEqual(ancestor.root().name, 'exceptions')
        if sys.version_info >= (2, 5):
            ancestor = ancestors.next()
            self.failUnlessEqual(ancestor.name, 'BaseException')
            self.failUnlessEqual(ancestor.root().name, 'exceptions')
            ancestor = ancestors.next()
            self.failUnlessEqual(ancestor.name, 'object')
            self.failUnlessEqual(ancestor.root().name, '__builtin__')
        self.failUnlessRaises(StopIteration, ancestors.next)
Exemplo n.º 49
0
    def test_method_argument(self):
        code = '''
class ErudiEntitySchema:
    """a entity has a type, a set of subject and or object relations"""
    def __init__(self, e_type, **kwargs):
        kwargs['e_type'] = e_type.capitalize().encode()

    def meth(self, e_type, *args, **kwargs):
        kwargs['e_type'] = e_type.capitalize().encode()
        print(args)
        '''
        astng = builder.string_build(code, __name__, __file__)
        arg = get_name_node(astng['ErudiEntitySchema']['__init__'], 'e_type')
        self.assertEqual([n.__class__ for n in arg.infer()], [YES.__class__])
        arg = get_name_node(astng['ErudiEntitySchema']['__init__'], 'kwargs')
        self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'e_type')
        self.assertEqual([n.__class__ for n in arg.infer()], [YES.__class__])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'args')
        self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Tuple])
        arg = get_name_node(astng['ErudiEntitySchema']['meth'], 'kwargs')
        self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
Exemplo n.º 50
0
    def test_im_func_unwrap(self):
        code = '''
class EnvBasedTC:
    def pactions(self):
        print "hop"
pactions = EnvBasedTC.pactions.im_func
print pactions

class EnvBasedTC2:
    pactions = EnvBasedTC.pactions.im_func
    print pactions

'''
        astng = builder.string_build(code, __name__, __file__)
        pactions = get_name_node(astng, 'pactions')
        infered = list(pactions.infer())
        self.assertEquals(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Function)
        pactions = get_name_node(astng['EnvBasedTC2'], 'pactions')
        infered = list(pactions.infer())
        self.assertEquals(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Function)
Exemplo n.º 51
0
    def test_except_inference(self):
        code = '''
try:
    print hop
except NameError, ex:
    ex1 = ex
except Exception, ex:
    ex2 = ex
    raise
        '''
        astng = builder.string_build(code, __name__, __file__)
        ex1 = astng['ex1']
        ex1_infer = ex1.infer()
        ex1 = ex1_infer.next()
        self.assertIsInstance(ex1, Instance)
        self.failUnlessEqual(ex1.name, 'NameError')
        self.failUnlessRaises(StopIteration, ex1_infer.next)
        ex2 = astng['ex2']
        ex2_infer = ex2.infer()
        ex2 = ex2_infer.next()
        self.assertIsInstance(ex2, Instance)
        self.failUnlessEqual(ex2.name, 'Exception')
        self.failUnlessRaises(StopIteration, ex2_infer.next)
Exemplo n.º 52
0
    def test_mechanize_open(self):
        try:
            import mechanize
        except ImportError:
            self.skipTest('require mechanize installed')
        data = '''from mechanize import Browser
print (Browser)
b = Browser()
'''
        astng = builder.string_build(data, __name__, __file__)
        browser = next(get_name_node(astng, 'Browser').infer())
        self.assertIsInstance(browser, nodes.Class)
        bopen = list(browser.igetattr('open'))
        self.skipTest('the commit said: "huum, see that later"')
        self.assertEqual(len(bopen), 1)
        self.assertIsInstance(bopen[0], nodes.Function)
        self.failUnless(bopen[0].callable())
        b = next(get_name_node(astng, 'b').infer())
        self.assertIsInstance(b, Instance)
        bopen = list(b.igetattr('open'))
        self.assertEqual(len(bopen), 1)
        self.assertIsInstance(bopen[0], BoundMethod)
        self.failUnless(bopen[0].callable())
Exemplo n.º 53
0
    def test_simple_subscript(self):
        code = '''
a = [1, 2, 3][0]
b = (1, 2, 3)[1]
c = (1, 2, 3)[-1]
d = a + b + c
print (d)
e = {'key': 'value'}
f = e['key']
print (f)
        '''
        astng = builder.string_build(code, __name__, __file__)
        self.assertEqual(
            [i.value for i in get_name_node(astng, 'a', -1).infer()], [1])
        self.assertEqual(
            [i.value for i in get_name_node(astng, 'b', -1).infer()], [2])
        self.assertEqual(
            [i.value for i in get_name_node(astng, 'c', -1).infer()], [3])
        self.assertEqual(
            [i.value for i in get_name_node(astng, 'd', -1).infer()], [6])
        self.assertEqual(
            [i.value for i in get_name_node(astng, 'f', -1).infer()],
            ['value'])
Exemplo n.º 54
0
    def test_import_as(self):
        code = '''
import os.path as osp
print osp.dirname(__file__)

from os.path import exists as e
assert e(__file__)

from new import code as make_code
print make_code
        '''
        astng = builder.string_build(code, __name__, __file__)
        infered = list(astng.igetattr('osp'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Module)
        self.failUnlessEqual(infered[0].name, 'os.path')
        infered = list(astng.igetattr('e'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], nodes.Function)
        self.failUnlessEqual(infered[0].name, 'exists')
        infered = list(astng.igetattr('make_code'))
        self.failUnlessEqual(len(infered), 1)
        self.assertIsInstance(infered[0], Instance)
        self.failUnlessEqual(str(infered[0]), 'Instance of __builtin__.type')
Exemplo n.º 55
0
 def setUp(self):
     self.astng = builder.string_build(self.CODE, __name__, __file__)
Exemplo n.º 56
0
 def test_binary_op_shiftleft(self):
     astng = builder.string_build('a = 23 <<1', __name__, __file__)
     self._test_const_infered(astng['a'], 23 << 1)
Exemplo n.º 57
0
 def test_binary_op_bitxor(self):
     astng = builder.string_build('a = 23^9', __name__, __file__)
     self._test_const_infered(astng['a'], 23 ^ 9)
Exemplo n.º 58
0
 def test_binary_op_str_mul(self):
     astng = builder.string_build('a = "*" * 40', __name__, __file__)
     self._test_const_infered(astng['a'], "*" * 40)
Exemplo n.º 59
0
 def test_binary_op_float_div(self):
     astng = builder.string_build('a = 1 / 2.', __name__, __file__)
     self._test_const_infered(astng['a'], 1 / 2.)
Exemplo n.º 60
0
 def test_binary_op_int_sub(self):
     astng = builder.string_build('a = 1 - 2', __name__, __file__)
     self._test_const_infered(astng['a'], -1)