def brainless_manager(self):
     manager = AstroidManager()
     # avoid caching into the AstroidManager borg since we get problems
     # with other tests :
     manager.__dict__ = {}
     manager.astroid_cache = {}
     manager._mod_file_cache = {}
     manager.transforms = {}
     manager.clear_cache() # trigger proper bootstraping
     return manager
 def brainless_manager(self):
     manager = AstroidManager()
     # avoid caching into the AstroidManager borg since we get problems
     # with other tests :
     manager.__dict__ = {}
     manager.astroid_cache = {}
     manager._mod_file_cache = {}
     manager.transforms = {}
     manager.clear_cache()  # trigger proper bootstraping
     return manager
 def brainless_manager(self):
     manager = AstroidManager()
     # avoid caching into the AstroidManager borg since we get problems
     # with other tests :
     manager.__dict__ = {}
     manager._failed_import_hooks = []
     manager.astroid_cache = {}
     manager._mod_file_cache = {}
     manager._transform = transforms.TransformVisitor()
     manager.clear_cache() # trigger proper bootstraping
     return manager
 def brainless_manager(self):
     manager = AstroidManager()
     # avoid caching into the AstroidManager borg since we get problems
     # with other tests :
     manager.__dict__ = {}
     manager._failed_import_hooks = []
     manager.astroid_cache = {}
     manager._mod_file_cache = {}
     manager._transform = transforms.TransformVisitor()
     manager.clear_cache()  # trigger proper bootstraping
     return manager
Beispiel #5
0
def builtin_lookup(name: str) -> tuple[nodes.Module, Sequence[nodes.NodeNG]]:
    """Lookup a name in the builtin module.

    Return the list of matching statements and the ast for the builtin module
    """
    manager = AstroidManager()
    try:
        _builtin_astroid = manager.builtins_module
    except KeyError:
        # User manipulated the astroid cache directly! Rebuild everything.
        manager.clear_cache()
        _builtin_astroid = manager.builtins_module
    if name == "__dict__":
        return _builtin_astroid, ()
    try:
        stmts: Sequence[nodes.NodeNG] = _builtin_astroid.locals[name]
    except KeyError:
        stmts = ()
    return _builtin_astroid, stmts
class AstroidManagerTest(resources.SysPathSetup,
                         resources.AstroidCacheSetupMixin, unittest.TestCase):
    def setUp(self):
        super(AstroidManagerTest, self).setUp()
        self.manager = AstroidManager()
        self.manager.clear_cache(self._builtins)  # take care of borg

    def test_ast_from_file(self):
        """check if the method return a good astroid object"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_cache(self):
        """check if the cache works"""
        import unittest
        filepath = unittest.__file__
        self.manager.ast_from_file(filepath)
        astroid = self.manager.ast_from_file('unhandledName', 'unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_astro_builder(self):
        """check if the source is at True, AstroidBuilder build a good astroid"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath, None, True, True)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_name_astro_builder_exception(self):
        """check if an exception is thrown if we give a wrong filepath"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_file,
                          'unhandledName')

    def test_do_not_expose_main(self):
        obj = self.manager.ast_from_module_name('__main__')
        self.assertEqual(obj.name, '__main__')
        self.assertEqual(obj.items(), [])

    def test_ast_from_module_name(self):
        """check if the ast_from_module_name method return a good astroid"""
        astroid = self.manager.ast_from_module_name('unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_module_name_not_python_source(self):
        """check if the ast_from_module_name method return a good astroid with a no python source module"""
        astroid = self.manager.ast_from_module_name('time')
        self.assertEqual(astroid.name, 'time')
        self.assertIn('time', self.manager.astroid_cache)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_name_astro_builder_exception(self):
        """check if the method raise an exception if we give a wrong module"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.ast_from_module_name, 'unhandledModule')

    def _test_ast_from_zip(self, archive):
        origpath = sys.path[:]
        sys.modules.pop('mypypa', None)
        archive_path = resources.find(archive)
        sys.path.insert(0, archive_path)
        try:
            module = self.manager.ast_from_module_name('mypypa')
            self.assertEqual(module.name, 'mypypa')
            end = os.path.join(archive, 'mypypa')
            self.assertTrue(module.file.endswith(end),
                            "%s doesn't endswith %s" % (module.file, end))
        finally:
            # remove the module, else after importing egg, we don't get the zip
            if 'mypypa' in self.manager.astroid_cache:
                del self.manager.astroid_cache['mypypa']
                del self.manager._mod_file_cache[('mypypa', None)]
            if archive_path in sys.path_importer_cache:
                del sys.path_importer_cache[archive_path]
            sys.path = origpath

    def test_ast_from_module_name_egg(self):
        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):
        self._test_ast_from_zip(
            os.path.sep.join(
                ['data', os.path.normcase('MyPyPa-0.1.0-py2.5.zip')]))

    def test_zip_import_data(self):
        """check if zip_import_data works"""
        filepath = resources.find('data/MyPyPa-0.1.0-py2.5.zip/mypypa')
        astroid = self.manager.zip_import_data(filepath)
        self.assertEqual(astroid.name, 'mypypa')

    def test_zip_import_data_without_zipimport(self):
        """check if zip_import_data return None without zipimport"""
        self.assertEqual(self.manager.zip_import_data('path'), None)

    def test_file_from_module(self):
        """check if the unittest filepath is equals to the result of the method"""
        if sys.version_info > (3, 0):
            unittest_file = unittest.__file__
        else:
            unittest_file = unittest.__file__[:-1]
        self.assertEqual(
            unittest_file,
            self.manager.file_from_module_name('unittest', None)[0])

    def test_file_from_module_name_astro_building_exception(self):
        """check if the method launch a exception with a wrong module name"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.file_from_module_name,
                          'unhandledModule', None)

    def test_ast_from_module(self):
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.pure_python, True)
        import time
        astroid = self.manager.ast_from_module(time)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_cache(self):
        """check if the module is in the cache manager"""
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_class(self):
        astroid = self.manager.ast_from_class(int)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_with_module(self):
        """check if the method works with the module name"""
        astroid = self.manager.ast_from_class(int, int.__module__)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object, object.__module__)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_attr_error(self):
        """give a wrong class at the ast_from_class method"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.ast_from_class, None)

    def test_from_directory(self):
        obj = self.manager.project_from_files([resources.find('data')],
                                              _silent_no_wrap, 'data')
        self.assertEqual(obj.name, 'data')
        self.assertEqual(obj.path,
                         os.path.abspath(resources.find('data/__init__.py')))

    def test_project_node(self):
        obj = self.manager.project_from_files([resources.find('data')],
                                              _silent_no_wrap, 'data')
        expected = [
            'data', 'data.SSL1', 'data.SSL1.Connection1', 'data.absimp',
            'data.absimp.sidepackage', 'data.absimp.string', 'data.absimport',
            'data.all', 'data.appl', 'data.appl.myConnection',
            'data.clientmodule_test', 'data.descriptor_crash', 'data.email',
            'data.find_test', 'data.find_test.module',
            'data.find_test.module2', 'data.find_test.noendingnewline',
            'data.find_test.nonregr', 'data.format', 'data.lmfp',
            'data.lmfp.foo', 'data.module', 'data.module1abs',
            'data.module1abs.core', 'data.module2', 'data.noendingnewline',
            'data.nonregr', 'data.notall', 'data.package',
            'data.package.absimport', 'data.package.hello',
            'data.package.import_package_subpackage_module',
            'data.package.subpackage', 'data.package.subpackage.module',
            'data.recursion', 'data.suppliermodule_test',
            'data.unicode_package', 'data.unicode_package.core'
        ]
        self.assertListEqual(sorted(obj.keys()), expected)

    def testFailedImportHooks(self):
        def hook(modname):
            if modname == 'foo.bar':
                return unittest
            else:
                raise AstroidBuildingException()

        with self.assertRaises(AstroidBuildingException):
            self.manager.ast_from_module_name('foo.bar')
        self.manager.register_failed_import_hook(hook)
        self.assertEqual(unittest,
                         self.manager.ast_from_module_name('foo.bar'))
        with self.assertRaises(AstroidBuildingException):
            self.manager.ast_from_module_name('foo.bar.baz')
        del self.manager._failed_import_hooks[0]
class Python3TC(unittest.TestCase):
    def setUp(self):
        self.manager = AstroidManager()
        self.manager.clear_cache() # take care of borg
        self.builder = AstroidBuilder(self.manager)

    @require_version('3.0')
    def test_starred_notation(self):
        astroid = self.builder.string_build("*a, b = [1, 2, 3]", 'test', 'test')

        # Get the star node
        node = next(next(next(astroid.get_children()).get_children()).get_children())

        self.assertTrue(isinstance(node.ass_type(), Assign))

    @require_version('3.3')
    def test_yield_from(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertIsInstance(func, Function)
        yieldfrom_stmt = func.body[0]

        self.assertIsInstance(yieldfrom_stmt, Discard)
        self.assertIsInstance(yieldfrom_stmt.value, YieldFrom)
        self.assertEqual(yieldfrom_stmt.as_string(),
                         'yield from iter([1, 2])')

    @require_version('3.3')
    def test_yield_from_is_generator(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertIsInstance(func, Function)
        self.assertTrue(func.is_generator())

    @require_version('3.3')
    def test_yield_from_as_string(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
            value = yield from other()
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertEqual(func.as_string().strip(), body.strip())

    # metaclass tests

    @require_version('3.0')
    def test_simple_metaclass(self):
        astroid = self.builder.string_build("class Test(metaclass=type): pass")
        klass = astroid.body[0]

        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'type')

    @require_version('3.0')
    def test_metaclass_error(self):
        astroid = self.builder.string_build("class Test(metaclass=typ): pass")
        klass = astroid.body[0]
        self.assertFalse(klass.metaclass())

    @require_version('3.0')
    def test_metaclass_imported(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta 
        class Test(metaclass=ABCMeta): pass"""))
        klass = astroid.body[1]

        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'ABCMeta')

    @require_version('3.0')
    def test_as_string(self):
        body = dedent("""
        from abc import ABCMeta 
        class Test(metaclass=ABCMeta): pass""")
        astroid = self.builder.string_build(body)
        klass = astroid.body[1]

        self.assertEqual(klass.as_string(),
                         '\n\nclass Test(metaclass=ABCMeta):\n    pass\n')

    @require_version('3.0')
    def test_old_syntax_works(self):
        astroid = self.builder.string_build(dedent("""
        class Test:
            __metaclass__ = type
        class SubTest(Test): pass
        """))
        klass = astroid['SubTest']
        metaclass = klass.metaclass()
        self.assertIsNone(metaclass)

    @require_version('3.0')
    def test_metaclass_yes_leak(self):
        astroid = self.builder.string_build(dedent("""
        # notice `ab` instead of `abc`
        from ab import ABCMeta

        class Meta(metaclass=ABCMeta): pass
        """))
        klass = astroid['Meta']
        self.assertIsNone(klass.metaclass())

    @require_version('3.0')
    def test_parent_metaclass(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta
        class Test(metaclass=ABCMeta): pass
        class SubTest(Test): pass
        """))
        klass = astroid['SubTest']
        self.assertTrue(klass.newstyle)
        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'ABCMeta')

    @require_version('3.0')
    def test_metaclass_ancestors(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta

        class FirstMeta(metaclass=ABCMeta): pass
        class SecondMeta(metaclass=type):
            pass

        class Simple:
            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, Class)
                self.assertEqual(meta.name, metaclass)

    @require_version('3.0')
    def test_annotation_support(self):
        astroid = self.builder.string_build(dedent("""
        def test(a: int, b: str, c: None, d, e,
                 *args: float, **kwargs: int)->int:
            pass
        """))
        func = astroid['test']
        self.assertIsInstance(func.args.varargannotation, Name)
        self.assertEqual(func.args.varargannotation.name, 'float')
        self.assertIsInstance(func.args.kwargannotation, Name)
        self.assertEqual(func.args.kwargannotation.name, 'int')
        self.assertIsInstance(func.returns, Name)
        self.assertEqual(func.returns.name, 'int')
        arguments = func.args
        self.assertIsInstance(arguments.annotations[0], Name)
        self.assertEqual(arguments.annotations[0].name, 'int')
        self.assertIsInstance(arguments.annotations[1], Name)
        self.assertEqual(arguments.annotations[1].name, 'str')
        self.assertIsInstance(arguments.annotations[2], Const)
        self.assertIsNone(arguments.annotations[2].value)
        self.assertIsNone(arguments.annotations[3])
        self.assertIsNone(arguments.annotations[4])

        astroid = self.builder.string_build(dedent("""
        def test(a: int=1, b: str=2):
            pass
        """))
        func = astroid['test']
        self.assertIsInstance(func.args.annotations[0], Name)
        self.assertEqual(func.args.annotations[0].name, 'int')
        self.assertIsInstance(func.args.annotations[1], Name)
        self.assertEqual(func.args.annotations[1].name, 'str')
        self.assertIsNone(func.returns)
Beispiel #8
0
class Python3TC(TestCase):
    def setUp(self):
        self.manager = AstroidManager()
        self.manager.clear_cache() # take care of borg
        self.builder = AstroidBuilder(self.manager)

    @require_version('3.0')
    def test_starred_notation(self):
        astroid = self.builder.string_build("*a, b = [1, 2, 3]", 'test', 'test')

        # Get the star node
        node = next(next(next(astroid.get_children()).get_children()).get_children())

        self.assertTrue(isinstance(node.ass_type(), Assign))

    @require_version('3.3')
    def test_yield_from(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertIsInstance(func, Function)
        yieldfrom_stmt = func.body[0]

        self.assertIsInstance(yieldfrom_stmt, Discard)
        self.assertIsInstance(yieldfrom_stmt.value, YieldFrom)
        self.assertEqual(yieldfrom_stmt.as_string(),
                         'yield from iter([1, 2])')

    @require_version('3.3')
    def test_yield_from_is_generator(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertIsInstance(func, Function)
        self.assertTrue(func.is_generator())

    @require_version('3.3')
    def test_yield_from_as_string(self):
        body = dedent("""
        def func():
            yield from iter([1, 2])
            value = yield from other()
        """)
        astroid = self.builder.string_build(body)
        func = astroid.body[0]
        self.assertEqual(func.as_string().strip(), body.strip())

    # metaclass tests

    @require_version('3.0')
    def test_simple_metaclass(self):
        astroid = self.builder.string_build("class Test(metaclass=type): pass")
        klass = astroid.body[0]

        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'type')

    @require_version('3.0')
    def test_metaclass_error(self):
        astroid = self.builder.string_build("class Test(metaclass=typ): pass")
        klass = astroid.body[0]
        self.assertFalse(klass.metaclass())

    @require_version('3.0')
    def test_metaclass_imported(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta 
        class Test(metaclass=ABCMeta): pass"""))
        klass = astroid.body[1]

        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'ABCMeta')

    @require_version('3.0')
    def test_as_string(self):
        body = dedent("""
        from abc import ABCMeta 
        class Test(metaclass=ABCMeta): pass""")
        astroid = self.builder.string_build(body)
        klass = astroid.body[1]

        self.assertEqual(klass.as_string(),
                         '\n\nclass Test(metaclass=ABCMeta):\n    pass\n')

    @require_version('3.0')
    def test_old_syntax_works(self):
        astroid = self.builder.string_build(dedent("""
        class Test:
            __metaclass__ = type
        class SubTest(Test): pass
        """))
        klass = astroid['SubTest']
        metaclass = klass.metaclass()
        self.assertIsNone(metaclass)

    @require_version('3.0')
    def test_metaclass_yes_leak(self):
        astroid = self.builder.string_build(dedent("""
        # notice `ab` instead of `abc`
        from ab import ABCMeta

        class Meta(metaclass=ABCMeta): pass
        """))
        klass = astroid['Meta']
        self.assertIsNone(klass.metaclass())

    @require_version('3.0')
    def test_parent_metaclass(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta
        class Test(metaclass=ABCMeta): pass
        class SubTest(Test): pass
        """))
        klass = astroid['SubTest']
        self.assertTrue(klass.newstyle)
        metaclass = klass.metaclass()
        self.assertIsInstance(metaclass, Class)
        self.assertEqual(metaclass.name, 'ABCMeta')

    @require_version('3.0')
    def test_metaclass_ancestors(self):
        astroid = self.builder.string_build(dedent("""
        from abc import ABCMeta

        class FirstMeta(metaclass=ABCMeta): pass
        class SecondMeta(metaclass=type):
            pass

        class Simple:
            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, Class)
                self.assertEqual(meta.name, metaclass)

    @require_version('3.0')
    def test_annotation_support(self):
        astroid = self.builder.string_build(dedent("""
        def test(a: int, b: str, c: None, d, e,
                 *args: float, **kwargs: int)->int:
            pass
        """))
        func = astroid['test']
        self.assertIsInstance(func.args.varargannotation, Name)
        self.assertEqual(func.args.varargannotation.name, 'float')
        self.assertIsInstance(func.args.kwargannotation, Name)
        self.assertEqual(func.args.kwargannotation.name, 'int')
        self.assertIsInstance(func.returns, Name)
        self.assertEqual(func.returns.name, 'int')
        arguments = func.args
        self.assertIsInstance(arguments.annotations[0], Name)
        self.assertEqual(arguments.annotations[0].name, 'int')
        self.assertIsInstance(arguments.annotations[1], Name)
        self.assertEqual(arguments.annotations[1].name, 'str')
        self.assertIsInstance(arguments.annotations[2], Const)
        self.assertIsNone(arguments.annotations[2].value)
        self.assertIsNone(arguments.annotations[3])
        self.assertIsNone(arguments.annotations[4])

        astroid = self.builder.string_build(dedent("""
        def test(a: int=1, b: str=2):
            pass
        """))
        func = astroid['test']
        self.assertIsInstance(func.args.annotations[0], Name)
        self.assertEqual(func.args.annotations[0].name, 'int')
        self.assertIsInstance(func.args.annotations[1], Name)
        self.assertEqual(func.args.annotations[1].name, 'str')
        self.assertIsNone(func.returns)
Beispiel #9
0
class AstroidManagerTC(TestCase):
    def setUp(self):
        self.manager = AstroidManager()
        self.manager.clear_cache() # take care of borg

    def test_ast_from_file(self):
        """check if the method return a good astroid object"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_cache(self):
        """check if the cache works"""
        import unittest
        filepath = unittest.__file__
        self.manager.ast_from_file(filepath)
        astroid = self.manager.ast_from_file('unhandledName', 'unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_astro_builder(self):
        """check if the source is at True, AstroidBuilder build a good astroid"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath, None, True, True)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_name_astro_builder_exception(self):
        """check if an exception is thrown if we give a wrong filepath"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_file, 'unhandledName')

    def test_do_not_expose_main(self):
        obj = self.manager.ast_from_module_name('__main__')
        self.assertEqual(obj.name, '__main__')
        self.assertEqual(list(obj.items()), [])

    def test_ast_from_module_name(self):
        """check if the ast_from_module_name method return a good astroid"""
        astroid = self.manager.ast_from_module_name('unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_module_name_not_python_source(self):
        """check if the ast_from_module_name method return a good astroid with a no python source module"""
        astroid = self.manager.ast_from_module_name('time')
        self.assertEqual(astroid.name, 'time')
        self.assertIn('time', self.manager.astroid_cache)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_name_astro_builder_exception(self):
        """check if the method raise an exception if we give a wrong module"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_module_name, 'unhandledModule')

    def _test_ast_from_zip(self, archive):
        origpath = sys.path[:]
        sys.modules.pop('mypypa', None)
        archive_path = join(DATA, archive)
        sys.path.insert(0, archive_path)
        try:
            module = self.manager.ast_from_module_name('mypypa')
            self.assertEqual(module.name, 'mypypa')
            end = join(archive, 'mypypa')
            self.assertTrue(module.file.endswith(end),
                            "%s doesn't endswith %s" % (module.file, end))
        finally:
            # remove the module, else after importing egg, we don't get the zip
            if 'mypypa' in self.manager.astroid_cache:
                del self.manager.astroid_cache['mypypa']
                del self.manager._mod_file_cache[('mypypa', None)]
            if archive_path in sys.path_importer_cache:
                del sys.path_importer_cache[archive_path]
            sys.path = origpath

    def test_ast_from_module_name_egg(self):
        self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.egg')

    def test_ast_from_module_name_zip(self):
        self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.zip')

    def test_zip_import_data(self):
        """check if zip_import_data works"""
        filepath = self.datapath('MyPyPa-0.1.0-py2.5.zip/mypypa')
        astroid = self.manager.zip_import_data(filepath)
        self.assertEqual(astroid.name, 'mypypa')

    def test_zip_import_data_without_zipimport(self):
        """check if zip_import_data return None without zipimport"""
        self.assertEqual(self.manager.zip_import_data('path'), None)

    def test_file_from_module(self):
        """check if the unittest filepath is equals to the result of the method"""
        import unittest
        if PY3K:
            unittest_file = unittest.__file__
        else:
            unittest_file = unittest.__file__[:-1]
        self.assertEqual(unittest_file,
                        self.manager.file_from_module_name('unittest', None))

    def test_file_from_module_name_astro_building_exception(self):
        """check if the method launch a exception with a wrong module name"""
        self.assertRaises(AstroidBuildingException, self.manager.file_from_module_name, 'unhandledModule', None)

    def test_ast_from_module(self):
        import unittest
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.pure_python, True)
        import time
        astroid = self.manager.ast_from_module(time)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_cache(self):
        """check if the module is in the cache manager"""
        import unittest
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_class(self):
        astroid = self.manager.ast_from_class(int)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_with_module(self):
        """check if the method works with the module name"""
        astroid = self.manager.ast_from_class(int, int.__module__)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object, object.__module__)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_attr_error(self):
        """give a wrong class at the ast_from_class method"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_class, None)

    def test_from_directory(self):
        obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data')
        self.assertEqual(obj.name, 'data')
        self.assertEqual(obj.path, join(DATA, '__init__.py'))

    def test_project_node(self):
        obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data')
        expected = set(['SSL1', '__init__', 'all', 'appl', 'format', 'module',
                        'module2', 'noendingnewline', 'nonregr', 'notall'])
        expected = [
            'data', 'data.SSL1', 'data.SSL1.Connection1',
            'data.absimport', 'data.all',
            'data.appl', 'data.appl.myConnection', 'data.email',
            'data.find_test',
            'data.find_test.module',
            'data.find_test.module2',
            'data.find_test.noendingnewline',
            'data.find_test.nonregr',
            'data.format',
            'data.lmfp',
            'data.lmfp.foo',
            'data.module',
            'data.module1abs', 'data.module1abs.core',
            'data.module2', 'data.noendingnewline',
            'data.nonregr', 'data.notall']
        self.assertListEqual(sorted(k for k in list(obj.keys())), expected)
Beispiel #10
0
class AstroidManagerTest(resources.SysPathSetup,
                         resources.AstroidCacheSetupMixin,
                         unittest.TestCase):

    @property
    def project(self):
        return self.manager.project_from_files(
            [resources.find('data')],
            _silent_no_wrap, 'data',
            black_list=['joined_strings.py'])

    def setUp(self):
        super(AstroidManagerTest, self).setUp()
        self.manager = AstroidManager()
        self.manager.clear_cache(self._builtins) # take care of borg

    def test_ast_from_file(self):
        """check if the method return a good astroid object"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_cache(self):
        """check if the cache works"""
        import unittest
        filepath = unittest.__file__
        self.manager.ast_from_file(filepath)
        astroid = self.manager.ast_from_file('unhandledName', 'unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_astro_builder(self):
        """check if the source is at True, AstroidBuilder build a good astroid"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath, None, True, True)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_name_astro_builder_exception(self):
        """check if an exception is thrown if we give a wrong filepath"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_file, 'unhandledName')

    def test_do_not_expose_main(self):
        obj = self.manager.ast_from_module_name('__main__')
        self.assertEqual(obj.name, '__main__')
        self.assertEqual(obj.items(), [])

    def test_ast_from_module_name(self):
        """check if the ast_from_module_name method return a good astroid"""
        astroid = self.manager.ast_from_module_name('unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_module_name_not_python_source(self):
        """check if the ast_from_module_name method return a good astroid with a no python source module"""
        astroid = self.manager.ast_from_module_name('time')
        self.assertEqual(astroid.name, 'time')
        self.assertIn('time', self.manager.astroid_cache)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_name_astro_builder_exception(self):
        """check if the method raise an exception if we give a wrong module"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_module_name, 'unhandledModule')

    def _test_ast_from_zip(self, archive):
        origpath = sys.path[:]
        sys.modules.pop('mypypa', None)
        archive_path = resources.find(archive)
        sys.path.insert(0, archive_path)
        try:
            module = self.manager.ast_from_module_name('mypypa')
            self.assertEqual(module.name, 'mypypa')
            end = os.path.join(archive, 'mypypa')
            self.assertTrue(module.file.endswith(end),
                            "%s doesn't endswith %s" % (module.file, end))
        finally:
            # remove the module, else after importing egg, we don't get the zip
            if 'mypypa' in self.manager.astroid_cache:
                del self.manager.astroid_cache['mypypa']
                del self.manager._mod_file_cache[('mypypa', None)]
            if archive_path in sys.path_importer_cache:
                del sys.path_importer_cache[archive_path]
            sys.path = origpath

    def test_ast_from_module_name_egg(self):
        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):
        self._test_ast_from_zip(
            os.path.sep.join(['data', os.path.normcase('MyPyPa-0.1.0-py2.5.zip')])
        )

    def test_zip_import_data(self):
        """check if zip_import_data works"""
        filepath = resources.find('data/MyPyPa-0.1.0-py2.5.zip/mypypa')
        astroid = self.manager.zip_import_data(filepath)
        self.assertEqual(astroid.name, 'mypypa')

    def test_zip_import_data_without_zipimport(self):
        """check if zip_import_data return None without zipimport"""
        self.assertEqual(self.manager.zip_import_data('path'), None)

    def test_file_from_module(self):
        """check if the unittest filepath is equals to the result of the method"""
        if sys.version_info > (3, 0):
            unittest_file = unittest.__file__
        else:
            unittest_file = unittest.__file__[:-1]
        self.assertEqual(unittest_file,
                        self.manager.file_from_module_name('unittest', None)[0])

    def test_file_from_module_name_astro_building_exception(self):
        """check if the method launch a exception with a wrong module name"""
        self.assertRaises(AstroidBuildingException, self.manager.file_from_module_name, 'unhandledModule', None)

    def test_ast_from_module(self):
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.pure_python, True)
        import time
        astroid = self.manager.ast_from_module(time)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_cache(self):
        """check if the module is in the cache manager"""
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_class(self):
        astroid = self.manager.ast_from_class(int)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_with_module(self):
        """check if the method works with the module name"""
        astroid = self.manager.ast_from_class(int, int.__module__)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object, object.__module__)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_attr_error(self):
        """give a wrong class at the ast_from_class method"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_class, None)

    def test_from_directory(self):
        self.assertEqual(self.project.name, 'data')
        self.assertEqual(self.project.path,
                         os.path.abspath(resources.find('data/__init__.py')))

    def test_project_node(self):
        expected = [
            'data',
            'data.SSL1',
            'data.SSL1.Connection1',
            'data.absimp',
            'data.absimp.sidepackage',
            'data.absimp.string',
            'data.absimport',
            'data.all',
            'data.appl',
            'data.appl.myConnection',
            'data.clientmodule_test',
            'data.descriptor_crash',
            'data.email',
            'data.find_test',
            'data.find_test.module',
            'data.find_test.module2',
            'data.find_test.noendingnewline',
            'data.find_test.nonregr',
            'data.format',
            'data.lmfp',
            'data.lmfp.foo',
            'data.module',
            'data.module1abs',
            'data.module1abs.core',
            'data.module2',
            'data.noendingnewline',
            'data.nonregr',
            'data.notall',
            'data.package',
            'data.package.absimport',
            'data.package.hello',
            'data.package.import_package_subpackage_module',
            'data.package.subpackage',
            'data.package.subpackage.module',
            'data.recursion',
            'data.suppliermodule_test',
            'data.unicode_package',
            'data.unicode_package.core']
        self.assertListEqual(sorted(self.project.keys()), expected)

    def testFailedImportHooks(self):
        def hook(modname):
            if modname == 'foo.bar':
                return unittest
            else:
                raise AstroidBuildingException()

        with self.assertRaises(AstroidBuildingException):
            self.manager.ast_from_module_name('foo.bar')
        self.manager.register_failed_import_hook(hook)
        self.assertEqual(unittest, self.manager.ast_from_module_name('foo.bar'))
        with self.assertRaises(AstroidBuildingException):
            self.manager.ast_from_module_name('foo.bar.baz')
        del self.manager._failed_import_hooks[0]
Beispiel #11
0
class AstroidManagerTC(TestCase):
    def setUp(self):
        self.manager = AstroidManager()
        self.manager.clear_cache()  # take care of borg

    def test_ast_from_file(self):
        """check if the method return a good astroid object"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_cache(self):
        """check if the cache works"""
        import unittest
        filepath = unittest.__file__
        self.manager.ast_from_file(filepath)
        astroid = self.manager.ast_from_file('unhandledName', 'unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_astro_builder(self):
        """check if the source is at True, AstroidBuilder build a good astroid"""
        import unittest
        filepath = unittest.__file__
        astroid = self.manager.ast_from_file(filepath, None, True, True)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_file_name_astro_builder_exception(self):
        """check if an exception is thrown if we give a wrong filepath"""
        self.assertRaises(AstroidBuildingException, self.manager.ast_from_file,
                          'unhandledName')

    def test_do_not_expose_main(self):
        obj = self.manager.ast_from_module_name('__main__')
        self.assertEqual(obj.name, '__main__')
        self.assertEqual(obj.items(), [])

    def test_ast_from_module_name(self):
        """check if the ast_from_module_name method return a good astroid"""
        astroid = self.manager.ast_from_module_name('unittest')
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_module_name_not_python_source(self):
        """check if the ast_from_module_name method return a good astroid with a no python source module"""
        astroid = self.manager.ast_from_module_name('time')
        self.assertEqual(astroid.name, 'time')
        self.assertIn('time', self.manager.astroid_cache)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_name_astro_builder_exception(self):
        """check if the method raise an exception if we give a wrong module"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.ast_from_module_name, 'unhandledModule')

    def _test_ast_from_zip(self, archive):
        origpath = sys.path[:]
        sys.modules.pop('mypypa', None)
        archive_path = join(DATA, archive)
        sys.path.insert(0, archive_path)
        try:
            module = self.manager.ast_from_module_name('mypypa')
            self.assertEqual(module.name, 'mypypa')
            end = join(archive, 'mypypa')
            self.assertTrue(module.file.endswith(end),
                            "%s doesn't endswith %s" % (module.file, end))
        finally:
            # remove the module, else after importing egg, we don't get the zip
            if 'mypypa' in self.manager.astroid_cache:
                del self.manager.astroid_cache['mypypa']
                del self.manager._mod_file_cache[('mypypa', None)]
            if archive_path in sys.path_importer_cache:
                del sys.path_importer_cache[archive_path]
            sys.path = origpath

    def test_ast_from_module_name_egg(self):
        self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.egg')

    def test_ast_from_module_name_zip(self):
        self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.zip')

    def test_zip_import_data(self):
        """check if zip_import_data works"""
        filepath = self.datapath('MyPyPa-0.1.0-py2.5.zip/mypypa')
        astroid = self.manager.zip_import_data(filepath)
        self.assertEqual(astroid.name, 'mypypa')

    def test_zip_import_data_without_zipimport(self):
        """check if zip_import_data return None without zipimport"""
        self.assertEqual(self.manager.zip_import_data('path'), None)

    def test_file_from_module(self):
        """check if the unittest filepath is equals to the result of the method"""
        import unittest
        if PY3K:
            unittest_file = unittest.__file__
        else:
            unittest_file = unittest.__file__[:-1]
        self.assertEqual(unittest_file,
                         self.manager.file_from_module_name('unittest', None))

    def test_file_from_module_name_astro_building_exception(self):
        """check if the method launch a exception with a wrong module name"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.file_from_module_name,
                          'unhandledModule', None)

    def test_ast_from_module(self):
        import unittest
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.pure_python, True)
        import time
        astroid = self.manager.ast_from_module(time)
        self.assertEqual(astroid.pure_python, False)

    def test_ast_from_module_cache(self):
        """check if the module is in the cache manager"""
        import unittest
        astroid = self.manager.ast_from_module(unittest)
        self.assertEqual(astroid.name, 'unittest')
        self.assertIn('unittest', self.manager.astroid_cache)

    def test_ast_from_class(self):
        astroid = self.manager.ast_from_class(int)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_with_module(self):
        """check if the method works with the module name"""
        astroid = self.manager.ast_from_class(int, int.__module__)
        self.assertEqual(astroid.name, 'int')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)

        astroid = self.manager.ast_from_class(object, object.__module__)
        self.assertEqual(astroid.name, 'object')
        self.assertEqual(astroid.parent.frame().name, BUILTINS)
        self.assertIn('__setattr__', astroid)

    def test_ast_from_class_attr_error(self):
        """give a wrong class at the ast_from_class method"""
        self.assertRaises(AstroidBuildingException,
                          self.manager.ast_from_class, None)

    def test_from_directory(self):
        obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data')
        self.assertEqual(obj.name, 'data')
        self.assertEqual(obj.path, join(DATA, '__init__.py'))

    def test_project_node(self):
        obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data')
        expected = set([
            'SSL1', '__init__', 'all', 'appl', 'format', 'module', 'module2',
            'noendingnewline', 'nonregr', 'notall'
        ])
        expected = [
            'data', 'data.SSL1', 'data.SSL1.Connection1', 'data.absimport',
            'data.all', 'data.appl', 'data.appl.myConnection', 'data.email',
            'data.find_test', 'data.find_test.module',
            'data.find_test.module2', 'data.find_test.noendingnewline',
            'data.find_test.nonregr', 'data.format', 'data.lmfp',
            'data.lmfp.foo', 'data.module', 'data.module1abs',
            'data.module1abs.core', 'data.module2', 'data.noendingnewline',
            'data.nonregr', 'data.notall'
        ]
        self.assertListEqual(sorted(k for k in obj.keys()), expected)