python断言函数的建议

时间:2009-07-24 17:42:33

标签: python assert

我在多个脚本中多次使用断言,我想知道是否有人对更好的方法有任何建议,而不是我在下面创建的函数。

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)

1 个答案:

答案 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)