Suggestions for python assert function

2019-06-07 21:32发布

问题:

I'm using assert multiple times throughout multiple scripts, I was wondering if anyone has any suggestions on a better way to achieve this instead of the functions I have created below.

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:

Well this is certainly shorter... can you really not just use assert expected == actual or whatever in the scripts themselves?

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)


标签: python assert