dimanche 14 février 2021

how to get identifiers of specific rules in python ast

I want to analyze the source code of logical coverage and I have to get all predicates for next steps. below is the SUT

def testfunc_1(x, y):
    if x > y:
        if x < 300 and y < 700:
            return "answer"

I am trying to get predicates by python's AST module below is what I have tried so far

def get_sut_predicates(func_name):
    print('get sut predicates')
    func = getattr(sut, func_name)
    source = inspect.getsource(func)
    p = ast.parse(source, func_name, mode='exec')
    v = AnalysisNodeVisitor()
    v.visit(p)


class AnalysisNodeVisitor(ast.NodeVisitor):

    def visit_If(self, node: If):
        print('if', node.test._fields[0] + ' ' + node.test._fields[1] + ' ' + node.test._fields[2])
        ast.NodeVisitor.generic_visit(self, node)

when I run this piece of code I get bellow result:

>> if left ops comparators

But something I would like to achieve is below result:

>> if x > y

actually I don't know how to get identifiers ?

Aucun commentaire:

Enregistrer un commentaire