在python文件中搜索所有if条件,并在下一个lin中添加print语句

2024-04-26 10:37:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编辑一个python文件,这样在每个if条件之后,我需要添加一行

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

数字8.4(通常是y.x)指的是这个if条件在函数8(y)中(函数只是序列号,8没有什么特别之处),x是yth函数中的第x个if条件。你知道吗

当然,要添加的行必须添加适当的缩进。条件检查是正在检查的条件。你知道吗

例如:

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

变成:

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()

我如何做到这一点?你知道吗

额外背景: 我有大约1200行python代码,其中包含大约180个if条件—我需要查看在执行47个测试用例期间是否命中了每个if条件。 换句话说,我需要做代码覆盖。复杂的是-我正在使用cocotb刺激进行RTL验证。因此,没有直接的方法来驱动刺激,所以我看不到一个简单的方法来使用标准覆盖率.py测试覆盖率的方法。 有没有别的办法检查保险范围?我觉得我错过了什么。你知道吗


Tags: 方法函数indebugselfifcheckcoverage
2条回答

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.

Cocotbhas support for coverage built indocs

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

如果你真的不能用覆盖率.py,然后我将编写一个使用检查堆栈找到调用者,然后linecache读取源代码行,并以这种方式记录。然后只需在整个文件中将if something:更改为if condition(something):,这应该相当简单。你知道吗

以下是概念证明:

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!")

这张照片:

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

相关问题 更多 >