我在多个脚本中多次使用断言,我想知道是否有人对更好的方法有任何建议,而不是我在下面创建的函数。
def assert_validation(expected, actual, type='', message=''):
if type == '==':
assert expected == actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '!=':
assert expected != actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '<=':
assert expected <= actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '>=':
assert expected >= actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
def assert_str_validation(expected, actual, type='', message=''):
if type == '==':
assert str(expected) == str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '!=':
assert str(expected) != str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '<=':
assert str(expected) <= str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
elif type == '>=':
assert str(expected) >= str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message)
答案 0 :(得分:11)
嗯,这当然更短......你真的不能只在脚本本身使用assert expected == actual
或其他什么吗?
def assert_validation(expected, actual, type='', message='', trans=(lambda x: x)):
m = { '==': (lambda e, a: e == a),
'!=': (lambda e, a: e != a),
'<=': (lambda e, a: e <= a),
'>=': (lambda e, a: e >= a), }
assert m[type](trans(expected), trans(actual)), 'Expected: %s, Actual: %s, %s' % (expected, actual, message)
def assert_str_validation(expected, actual, type='', message=''):
assert_validation(expected, actual, type, message, trans=str)