1

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

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)
4

1 回答 1

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)
于 2009-07-24T17:58:11.650 回答