【问题标题】:Search for all the if conditions in a python file and adding a print statement in the next line在 python 文件中搜索所有 if 条件并在下一行添加 print 语句
【发布时间】:2019-06-26 06:51:37
【问题描述】:

我必须编辑一个 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)是指 this if 条件在函数编号 8(y) 中(函数只是顺序数字,8 没什么特别之处)并且 x 是第 y 个函数中的第 x 个 if 条件。

当然,要添加的行必须带有适当的缩进。 condition_check 是被检查的条件。

例如:

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 验证。结果,没有直接的方法来驱动刺激,所以我看不到使用标准 coverage.py 测试覆盖率的简单方法。 有没有办法以其他方式检查覆盖范围?我觉得我错过了什么。

【问题讨论】:

  • 如果你能做到……我会笑你来这里并要求我们为你编码。去阅读如何导入文件并执行迭代和读取...
  • 我相信你有调试包装器。查一下
  • 其他可能性是解析你的python文件。并找到所有带有正则表达式的 if 语句
  • Python 标准库包括解析器和 AST。哦,是的,我也非常全面的日志库,所以你甚至不必到处添加丑陋的 if self.DEBUG 测试......
  • 看起来你应该在编写这么多 Python 代码之前学会使用 logging 模块。

标签: python automation code-coverage cocotb


【解决方案1】:

如果你真的不能使用coverage.py,那么我会编写一个辅助函数,使用inspect.stack 来查找调用者,然后使用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!

【讨论】:

    【解决方案2】:

    我有大约 1200 行 python 代码和大约 180 个 if 条件 - 我需要查看在执行 47 个测试用例期间是否满足每个 if 条件。换句话说,我需要进行代码覆盖。复杂的是 - 我正在使用 cocotb 刺激进行 RTL 验证。

    Cocotb has support for coverage built in (docs)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多