tags:

views:

408

answers:

1

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)
+6  A: 

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)
Steve Losh
Should be +1 for the first sentence. +1 for actually solving the problem and +1 for minimizing the performance hit. Unfortuneatly I can upvote it only once :)
wuub
assert_str_validation should be assert_validation(str(expected), str(actual), ...) and the str parameter is unused and can be removed.
Glenn Maynard
In fact it should be `assert m[type](str(expected), str(actual))...`, and str in `assert_validation` could be better named, but that's just nitpicking.
wuub
Yep, fixed both of those. str was renamed to trans (for transform) and is now actually used.
Steve Losh