Ananay Garg
Ananay Garg

Reputation: 27

Search for all the if conditions in a python file and adding a print statement in the next line

I have to edit a python file such that after every if condition, i need to add a line which says

if condition_check:
    if self.debug == 1: print "COVERAGE CONDITION #8.3 True (condition_check)"
    #some other code
else:
    if self.debug == 1: print "COVERAGE CONDITION #8.4 False (condition_check)"
    #some other code

The number 8.4(generally y.x) refer to the fact that this if condition is in function number 8(y) (the functions are just sequentially numbers, nothing special about 8) and x is xth if condition in yth function.

and of course, the line that will be added will have to be added with proper indentation. The condition_check is the condition being checked.

For example:

if (self.order_in_cb):
         self.ccu_process_crossing_buffer_order()

becomes:

if (self.order_in_cb):
         if self.debug == 1: print "COVERAGE CONDITION #8.2 TRUE (self.order_in_cb)"
         self.ccu_process_crossing_buffer_order()

How do i achieve this?

EXTRA BACKGROUND: I have about 1200 lines of python code with about 180 if conditions - i need to see if every if condition is hit during the execution of 47 test cases. In other words i need to do code coverage. The complication is - i am working with cocotb stimulus for RTL verification. As a result, there is no direct way to drive the stimulus, so i dont see an easy way to use the standard coverage.py way to test coverage. Is there a way to check the coverage so other way? I feel i am missing something.

Upvotes: 1

Views: 586

Answers (2)

Eric
Eric

Reputation: 97691

I have about 1200 lines of python code with about 180 if conditions - i need to see if every if condition is hit during the execution of 47 test cases. In other words i need to do code coverage. The complication is - i am working with cocotb stimulus for RTL verification.

Cocotb has support for coverage built in (docs)

export COVERAGE=1
# run cocotb however you currently invoke it

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 376072

If you truly can't use coverage.py, then I would write a helper function that used inspect.stack to find the caller, then linecache to read the line of source, and log that way. Then you only have to change if something: to if condition(something): throughout your file, which should be fairly easy.

Here's a proof of concept:

import inspect
import linecache
import re

debug = True

def condition(label, cond):
    if debug:
        caller = inspect.stack()[1]
        line = linecache.getline(caller.filename, caller.lineno)
        condcode = re.search(r"if condition\(.*?,(.*)\):", line).group(1)
        print("CONDITION {}: {}".format(label, condcode))
    return cond


x = 1
y = 1
if condition(1.1, x + y == 2):
    print("it's two!")

This prints:

CONDITION 1.1:  x + y == 2
it's two!

Upvotes: 1

Related Questions