class NonAssertMethodAtTestFunctionFixture:
    definition_is_none = None
    definitions_is_not_a_function = _ast.Pass()
    definitions_is_not_a_test_function = _ast.FunctionDef(name='not_a_test')
    definitions_with_only_assert = _ast.FunctionDef(name='test',
                                                    body=[_ast.Assert()])
    definitions_with_code = _ast.FunctionDef(
        name='test', body=[_ast.Pass(lineno=1),
                           _ast.Assert()])
Пример #2
0
 def test_issue793(self):
     import _ast as ast
     body = ast.Module([
         ast.Try([ast.Pass(lineno=2, col_offset=4)],
             [ast.ExceptHandler(ast.Name('Exception', ast.Load(),
                                         lineno=3, col_offset=0),
                                None, [ast.Pass(lineno=4, col_offset=0)],
                                lineno=4, col_offset=0)],
             [], [], lineno=1, col_offset=0)
     ])
     exec(compile(body, '<string>', 'exec'))
Пример #3
0
class SetterOrGetterDefNamesLineNumbersFixture:
    definition_is_none = None
    definition_is_pass = _ast.Pass()
    name_is_none = _ast.FunctionDef(name=None)
    without_setget_keywords = _ast.FunctionDef(name='test')
    with_set_keywords = _ast.FunctionDef(name='set_test', lineno=1)
    with_get_keywords = _ast.FunctionDef(name='get_test', lineno=2)
Пример #4
0
class ConstructorFixture:

    constructor_without_params = _ast.ClassDef(
        name='Test',
        body=[
            _ast.FunctionDef(
                name='__init__',
                body=[_ast.Pass()],
            ),
        ],
        bases=None,
    )
    empty_class = _ast.ClassDef(
        name='Test',
        body=[],
        bases=None,
    )
    class_without_constructor = _ast.ClassDef(
        name='Test',
        body=[
            _ast.FunctionDef(
                name='some_function',
                body=[_ast.Pass()],
            ),
        ],
        bases=None,
    )
    class_with_constructor_and_additional_method = _ast.ClassDef(
        name='Test',
        body=[
            _ast.FunctionDef(
                name='some_function',
                body=[_ast.Pass()],
            ),
            _ast.FunctionDef(
                name='__init__',
                body=[_ast.Pass()],
            ),
        ],
        bases=None,
    )
    class_with_inheritance = _ast.ClassDef(
        name='Test',
        body=[],
        bases=[_ast.ClassDef(name='TestParent')],
    )
Пример #5
0
class SetEncapsulatedAttribsLineNumbersFixture:
    definition_is_none = None
    definition_is_pass = _ast.Pass()
    is_constructor = _ast.FunctionDef(name='__init__')
    without_assign = _ast.FunctionDef(name='test', body=[_ast.Pass()])
    with_assign_without_self = _ast.FunctionDef(
        name='test', body=[
            _ast.Pass(),
            _ast.Assign(targets=[_ast.Attribute(value=(_ast.Name(id='test')), lineno=1)]),
        ],
    )
    with_assign_with_self = _ast.FunctionDef(
        name='test', body=[
            _ast.Pass(),
            _ast.Assign(targets=[_ast.Attribute(value=(_ast.Name(id='self')), lineno=1)]),
        ],
    )
Пример #6
0
class ReturnedValueFixture:
    node_is_none = None
    assign_expression_as_input = _ast.Assign(lineno=1)
    pass_expression_as_input = _ast.Pass(lineno=1)
    plain_expression_as_input = _ast.Expr(lineno=1)
    function_body_is_empty = _ast.FunctionDef(lineno=1, body=[])
    function_body_without_return_expression = _ast.FunctionDef(
        lineno=1,
        body=[_ast.Pass(), _ast.Expr(), _ast.Assign],
    )
    function_body_with_return_expression = _ast.FunctionDef(
        lineno=1,
        body=[
            _ast.Pass(),
            _ast.Expr(),
            _ast.Assign(),
            _ast.Return(lineno=1, value=None)
        ],
    )
Пример #7
0
class StaticOrPrivateFixture:
    definition_is_assign = _ast.Assign()
    definition_is_pass = _ast.Pass()
    definition_is_expr = _ast.Expr()
    empty_decorator_list_and_name = _ast.FunctionDef()
    empty_decorator_list = _ast.FunctionDef(name='test')
    is_private = _ast.FunctionDef(name='_test')
    is_protected = _ast.FunctionDef(name='__test')
    is_magic = _ast.FunctionDef(name='__test__')
    decorated = _ast.FunctionDef(name='test', decorator_list=['any_decorator'])
    is_static = _ast.FunctionDef(
        name='test',
        decorator_list=[_ast.FunctionDef(id='staticmethod')],
    )
Пример #8
0
    def visitFor(self, node):
        target = self.visit(node.target)
        for_iter = self.visit(node.iter)
        self.reduce(node.body)

        len_body = len(node.body)
        if len_body == 0:
            node.body.append(
                _ast.Pass(lineno=node.lineno, col_offset=node.col_offset))

        self.reduce(node.orelse)

        len_orelse = len(node.orelse)

        return (len_body == 0) and (len_orelse == 0) and target and for_iter
Пример #9
0
def remove_unused_assign(root, symbol):
    '''
    Remove redundant statements.

    The statement `a = 1` will be removed::

        a = 1
        a = 2

    The statement `a = 1` will not be removed because `b` depends on it::

        a = 1
        b = a + 2
        a = 2

    :param root: ast node
    '''

    gen = GatherAssignments()
    gen.visit(root)

    to_remove = []

    if symbol not in gen.assign_id_map:
        return

    assignments = gen.assign_id_map[symbol]

    if len(assignments) < 2:
        return

    for j in range(len(assignments) - 1):
        i1 = root.body.index(assignments[j].root)
        i2 = root.body.index(assignments[j + 1].root)

        body = root.body[i1 + 1:i2]
        grapher = GraphGen()
        for stmnt in body:
            grapher.visit(stmnt)

        if symbol not in grapher.used:
            to_remove.extend(assignments[j].assignments)

    Pass = lambda node: _ast.Pass(lineno=node.lineno,
                                  col_offset=node.col_offset)

    for old in to_remove:
        replace_nodes(root, old, Pass(old))
Пример #10
0
    node is removable only if all of its children are as well.
    '''
    throw_away = []
    for child in self.children(node):
        throw_away.append(self.visit(child))

    if self.mode == 'exclusive':
        return all(throw_away)
    elif self.mode == 'inclusive':
        return any(throw_away)
    else:
        raise TypeError("mode must be one of 'exclusive' or 'inclusive'")


# Helper function to create a pass node with a line number and col_offset
Pass = lambda node: _ast.Pass(lineno=node.lineno, col_offset=node.col_offset)


class PruneVisitor(Visitor):
    '''
    Visitor to remove ast nodes
    
    :param symbols: set of symbol that are removable.
    
    '''
    def __init__(self, symbols, mode='exclusive'):
        self.remove_symbols = symbols

        if mode not in ['exclusive', 'inclusive']:
            raise TypeError("mode must be one of 'exclusive' or 'inclusive'")
Пример #11
0
def pass_stmt() -> _ast.Pass:
    return _ast.Pass()
Пример #12
0
def Pass():
    """Creates an _ast.Pass node."""
    return _ast.Pass()
    def split_handlers(self, handlers_blocks):
        handlers = []
        except_instrs = []

        ends = []
        while len(handlers_blocks):

            instr = handlers_blocks.pop(0)
            except_instrs.append(instr)

            if (instr.opname == 'COMPARE_OP') and (instr.arg == 'exception match'):

                jump = handlers_blocks.pop(0)
                assert jump.opname == 'POP_JUMP_IF_FALSE'

                next_handler = jump.oparg

                instr = handlers_blocks.pop(0)
                except_instrs.append(instr)
                instr = handlers_blocks.pop(0)
                except_instrs.append(instr)
                instr = handlers_blocks.pop(0)
                except_instrs.append(instr)

                assert except_instrs[0].opname == 'DUP_TOP'
                assert except_instrs[-3].opname == 'POP_TOP'
                assert except_instrs[-1].opname == 'POP_TOP'

                exec_stmnt = self.decompile_block(except_instrs[1:-4]).stmnt()

                assert len(exec_stmnt) == 1

                exc_type = exec_stmnt[0]


                if except_instrs[-2].opname == 'STORE_NAME':
                    exc_name = _ast.Name(id=except_instrs[-2].arg, ctx=_ast.Store(), lineno=except_instrs[-2].lineno, col_offset=0)
                else:
                    assert except_instrs[-2].opname == 'POP_TOP'
                    exc_name = None

                handler_body = []
                while len(handlers_blocks):
                    instr = handlers_blocks.pop(0)
                    if instr.i == next_handler:
                        handlers_blocks.insert(0, instr)
                        break

                    handler_body.append(instr)

                assert handler_body[-1].opname == 'JUMP_FORWARD'
                ends.append(handler_body[-1].arg)

                exc_body = self.decompile_block(handler_body[:-1]).stmnt()
                if not exc_body:
                    exc_body.append(_ast.Pass(lineno=except_instrs[-2].lineno, col_offset=0))
                # is this for python 3?
                if py3 and exc_name is not None:
                    exc_name = exc_name.id
                    
                handlers.append(_ast.ExceptHandler(type=exc_type, name=exc_name, body=exc_body, lineno=instr.lineno, col_offset=0))

                except_instrs = []

        assert except_instrs[-1].opname == 'END_FINALLY'

        if len(except_instrs) == 1:
            pass
        else:

            assert except_instrs[0].opname == 'POP_TOP'
            assert except_instrs[1].opname == 'POP_TOP'
            assert except_instrs[2].opname == 'POP_TOP'
            assert except_instrs[-2].opname in ['JUMP_FORWARD', 'JUMP_ABSOLUTE'], except_instrs[-2]
            ends.append(except_instrs[-2].arg)
            exc_body = self.decompile_block(except_instrs[3:-2]).stmnt()
            if not exc_body:
                exc_body.append(_ast.Pass(lineno=except_instrs[-2].lineno, col_offset=0))

            handlers.append(_ast.ExceptHandler(type=None, name=None, body=exc_body, lineno=except_instrs[0].lineno, col_offset=0))

            assert all(e == ends[0] for e in ends)

        end = ends[0]

        return end, handlers
Пример #14
0
def build_pass():
    add_ast_node(_ast.Pass())
Пример #15
0
class ConstructorNonAttribsValueLineNumberFixture:
    definition_is_none = None
    definition__is_not_a_function = _ast.Pass
    definitions_is_not_a_constructor = _ast.FunctionDef(name='test', body=[_ast.Expr(lineno=1)])
    definitions_consist_of_assign_with_attribute = _ast.FunctionDef(
        name='__init__', body=[_ast.Assign(targets=[_ast.Attribute(lineno=2)], lineno=1)],
    )
    definitions_consist_of_assign_without_attribute = _ast.FunctionDef(
        name='__init__', body=[_ast.Assign(targets=[_ast.Expr(lineno=2)], lineno=1)],
    )
    definitions_consist_of_any_but_not_a_assign = _ast.FunctionDef(name='__init__', body=[_ast.Pass(lineno=3)])