测开之路五十六:实现类似unittest的断言

 

import inspect


class Case(object):
""" 实现断言 """

def __init__(self):
self.result = {} # 存断言的结果

def _assert(self, expression, message):
""" 真正执行断言的函数 """
"""
[2][1]二维数组,以a调b时b调c为例
第一个下标
如果是0,则代表当前函数(c),
如果是1,代表谁调的函数(b)
如果是2,代表谁调的函数(a)
···
第二个下标
如果是1,代表当前文件
如果是2,代表文件执行到多少行了
如果是3,代表当前执行的函数名
如果是4,代表当前执行的这块代码
···
"""
file = inspect.stack()[2][1]
line = inspect.stack()[2][2]
func = inspect.stack()[2][3]
code = inspect.stack()[2][4]
self.result.setdefault(func, {
'file': file,
'line': line,
'func': func,
'code': code,
'result': {
'status': expression,
'message': message
}
})
if not expression:
print(message) # 断言失败打印失败信息
# raise AssertionError(message) # 断言失败抛异常

def assertEqual(self, first, second, message=''):
self._assert(first == second, message)

def assertNotEqual(self, first, second, message=''):
self._assert(first != second, message)

def assertIn(self, first, second, message=''):
self._assert(first in second, message)

def assertNotIn(self, first, second, message=''):
self._assert(first not in second, message)

def assertIs(self, first, second, message=''):
self._assert(first is second, message)

def assertNotIs(self, first, second, message=''):
self._assert(first is not second, message)

def assertNone(self, first, message=''):
self._assert(first is None, message)

def assertNotNone(self, first, message=''):
self._assert(first is not None, message)

def assertTrue(self, first, message=''):
self._assert(bool(first) == True, message)

def assertFalse(self, first, message=''):
self._assert(bool(first) == False, message)
posted @ 2019-06-25 23:10  向前走。  阅读(201)  评论(0编辑  收藏  举报