Python 故障注入

Tha*_*nos 5 python testing

有没有一种巧妙的方法可以在 Python 脚本中注入失败?我想避免在源代码中添加以下内容:

failure_ABC = True
failure_XYZ = True
def inject_failure_ABC():
    raise Exception('ha! a fake error')
def inject_failure_XYZ():
    # delete some critical file
    pass

# some real code
if failure_ABC:
    inject_failure_ABC()
# some more real code
if failure_XYZ:
    inject_failure_XYZ()
# even more real code
Run Code Online (Sandbox Code Playgroud)

编辑: 我有以下想法:插入“失败点”作为特制的评论。编写一个简单的解析器,该解析器将在 Python 解释器之前调用,并将生成带有实际故障代码的实际检测 Python 脚本。例如:

#!/usr/bin/parser_script_producing_actual_code_and_calls python
# some real code
# FAIL_123
if foo():
    # FAIL_ABC
    execute_some_real_code()
else:
    # FAIL_XYZ
    execute_some_other_real_code()
Run Code Online (Sandbox Code Playgroud)

以 开头的任何内容FAIL_都被脚本视为故障点,并根据配置文件启用/禁用故障。你怎么认为?

Tho*_*anz 2

如果您只想在某个时刻停止代码并回退到交互式解释器,可以使用:

assert 1==0
Run Code Online (Sandbox Code Playgroud)

但这仅在您不使用 -O 运行 python 时才有效

编辑 实际上,我的第一个答案是快速,没有真正理解你想做什么,抱歉。

如果您通过参数而不是通过变量/函数进行参数化,也许您的代码已经变得更具可读性。就像是

failure = {"ABC": False, "XYZ":False}

#Do something, maybe set failure

def inject_failure(failure):
    if not any(failure.values()):
        return
    if failure["ABC"]:
        raise Exception('ha! a fake error')
    elif failure["XYZ"]:
        # delete some critical file
        pass

inject_failure(failure)
Run Code Online (Sandbox Code Playgroud)