python利用with语句实现断言多个表达式,最后抛出所有的断言失败的信息

# 注意点:1. with 语句中可以执行正常的代码, 异常会被捕获抛出
#        2. lis里面的语句会在程序执行完过后才执行
#        3. AssertStructException语句 我重写了 想要好看的格式可以自己加
#        4. 不建议整段代码全部加with,因为你有可能在代码中写覆盖变量原有值得写法,这时locals()会覆盖掉原有的变量值,在需要断言的多个断言处加即可。例如:a=0,断言a=0,后面你又写a=1,此时a=0断言不通过。
# 联系方式: QQ 892431872
# 用途 用于断言多个值得时候,可以拿到所有失败的断言
#      断言不影响程序执行,在程序执行完才执行断言的操作

# 断言结构异常,重写__str__()方法
class AssertStructException(Exception): def __str__(self): str_dict = '\n' for arg in self.args: if type(arg) == dict: for key, value in arg.items(): str_dict = str_dict + ('其他错误: ' if '内部程序错误' in key else '错误断言:') + str(key) + ', ' + '失败原因: ' + str(value) + '\n' else: str_dict = str_dict + '其他错误:' + str(arg) + '\n' return str_dict if str_dict != '\n' else super().__str__() # 上下文管理器 from contextlib import contextmanager @contextmanager def assert_struct(vars): lis = [] error = {} try: yield lis except Exception as e: error['内部程序错误'] = e locals().update(vars) for ls in lis: try: if 'assert' in ls: exec (ls) else: assert eval(ls) except Exception as e2: error[ls] = e2 if len(error) > 0: raise AssertStructException(error)

# 测试代码 类
class TestAssertStruct(object): def setup_class(self): self.d = 0 def test_assert_struct(self): a = 0 c = 1 self.b = 0 d = A() print(locals())
     # 使用上下文管理器 with assert_struct(locals()) as lis: i
= 1 / 0 lis.append('a == 0') lis.append('int(abs(1-2)) == 1') lis.append('1 > 2') lis.append('self.b > 0') lis.append('self.d == 0') a = 1 print(locals())
     with assert_struct(locals()) as lis:
print(111111) lis.append('assert a == 1') lis.append('assert int(abs(1-2)) == 1') lis.append('assert 1 < 2') lis.append('assert self.b == 0') # 测试代码 函数 def test_assert_struct(): a = 0 c = 1 b = 0 print(locals()) with assert_struct(locals()) as lis: lis.append('a == 0') lis.append('int(abs(1-2)) == 1') lis.append('1 < 2') lis.append('b == 0') a = 1 print(locals()) with assert_struct(locals()) as lis: print(111111) lis.append('a == 1') lis.append('int(abs(1-2)) == 1') lis.append('1 < 2') lis.append('b == 0') # print(locals())

 

posted @ 2020-04-30 17:35  小tong  阅读(781)  评论(0)    收藏  举报