How to use astroid - 10 common examples

To help you get started, we’ve selected a few astroid examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github life4 / deal / tests / test_linter / test_rules.py View on Github external
def test_check_raises_without_allowed():
    checker = CheckRaises()
    text = """
    @deal.raises()
    def test(a):
        raise ValueError
    """
    text = dedent(text).strip()
    funcs1 = Func.from_ast(ast.parse(text))
    funcs2 = Func.from_astroid(astroid.parse(text))
    for func in (funcs1[0], funcs2[0]):
        actual = [tuple(err) for err in checker(func)]
        expected = [(3, 10, 'DEAL021 raises contract error (ValueError)')]
        assert actual == expected
github PyCQA / pylint / tests / unittest_checker_python3.py View on Github external
def as_iterable_in_listcomp_test(self, fxn):
        code = "x = [x for x in {}(None, [1])]".format(fxn)
        module = astroid.parse(code)
        with self.assertNoMessages():
            self.walk(module)
github nelfin / pylint-protobuf / tests / test_checker.py View on Github external
def test_issue5_inferenceerror_should_not_propagate(self):
        node = astroid.extract_node("""
        foo = 'bar/baz'.split('/')[-1]
        """)
        try:
            self.walk(node.root())
        except astroid.exceptions.InferenceError:
            pytest.fail("InferenceError should not propagate")
github PyCQA / astroid / tests / unittest_nodes.py View on Github external
def test_async_await_keywords(self):
        async_def, async_for, async_with, await_node = builder.extract_node(
            """
        async def func(): #@
            async for i in range(10): #@
                f = __(await i)
            async with test(): #@
                pass
        """
        )
        self.assertIsInstance(async_def, nodes.AsyncFunctionDef)
        self.assertIsInstance(async_for, nodes.AsyncFor)
        self.assertIsInstance(async_with, nodes.AsyncWith)
        self.assertIsInstance(await_node, nodes.Await)
        self.assertIsInstance(await_node.value, nodes.Name)
github PyCQA / astroid / tests / unittest_scoped_nodes.py View on Github external
def test_no_infinite_metaclass_loop(self):
        klass = builder.extract_node(
            """
            class SSS(object):

                class JJJ(object):
                    pass

                @classmethod
                def Init(cls):
                    cls.JJJ = type('JJJ', (cls.JJJ,), {})

            class AAA(SSS):
                pass

            class BBB(AAA.JJJ):
                pass
        """
github PyCQA / astroid / tests / unittest_scoped_nodes.py View on Github external
def test_igetattr(self):
        func = builder.extract_node(
            """
        def test():
            pass
        """
        )
        func.instance_attrs["value"] = [nodes.Const(42)]
        value = func.getattr("value")
        self.assertEqual(len(value), 1)
        self.assertIsInstance(value[0], nodes.Const)
        self.assertEqual(value[0].value, 42)
        inferred = next(func.igetattr("value"))
        self.assertIsInstance(inferred, nodes.Const)
        self.assertEqual(inferred.value, 42)
github PyCQA / astroid / test / unittest_inference.py View on Github external
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)
        '''
        astroid = builder.string_build(code, __name__, __file__)
        infered = list(Instance(astroid['DataManager']).igetattr('app'))
        self.assertEqual(len(infered), 2, infered) # None / Instance(Application)
        infered = list(get_name_node(astroid['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)
github PyCQA / pylint / tests / extensions / test_check_docs.py View on Github external
def test_wrong_name_of_func_params_in_google_docstring(self):
        """Example of functions with inconsistent parameter names in the
        signature and in the Google style documentation
        """
        node = astroid.extract_node(
            """
        def function_foo(xarg, yarg, zarg):
            '''function foo ...

            Args:
                xarg1 (int): bla xarg
                yarg (float): bla yarg

                zarg1 (str): bla zarg
            '''
            return xarg + yarg
        """
        )
        with self.assertAddsMessages(
            Message(msg_id="missing-param-doc", node=node, args=("xarg, zarg",)),
            Message(msg_id="missing-type-doc", node=node, args=("xarg, zarg",)),
github PyCQA / pylint / tests / extensions / test_check_docs.py View on Github external
def test_finds_multiple_types_sphinx(self, complex_type):
        node = astroid.extract_node(
            '''
        def my_func(named_arg):
            """The docstring

            :param named_arg: Returned
            :type named_arg: {0}

            :returns: named_arg
            :rtype: {0}
            """
            return named_arg
        '''.format(
                complex_type
            )
        )
        with self.assertNoMessages():
github PyCQA / pylint / tests / extensions / test_check_docs.py View on Github external
def test_ignores_optional_specifier_google(self):
        node = astroid.extract_node(
            '''
        def do_something(param1, param2, param3=(), param4=[], param5=[], param6=True):
            """Do something.

            Args:
                param1 (str): Description.
                param2 (dict(str, int)): Description.
                param3 (tuple(str), optional): Defaults to empty. Description.
                param4 (List[str], optional): Defaults to empty. Description.
                param5 (list[tuple(str)], optional): Defaults to empty. Description.
                param6 (bool, optional): Defaults to True. Description.

            Returns:
                int: Description.
            """
            return param1, param2, param3, param4, param5, param6