Exemplo n.º 1
0
def test_testing():
    """ """
    from mini_lambda import s, Len
    from valid8 import assert_valid, Validator
    from valid8.validation_lib import instance_of

    name = 'sweet_home'

    assert_valid('name',
                 name,
                 instance_of(str),
                 Len(s) > 0,
                 help_msg='name should be a non-empty string')

    v = Validator(instance_of(str),
                  Len(s) > 0,
                  help_msg='name should be a non-empty string')
    v.assert_valid('name', name)
Exemplo n.º 2
0
def test_instance_of():
    """ tests that the instance_of() function works """

    # Basic function
    assert instance_of('r', str)
    assert instance_of(True, int)

    with pytest.raises(HasWrongType):
        instance_of(1, str)

    with pytest.raises(HasWrongType):
        instance_of('r', int)

    # Function generator
    assert instance_of(str)('r')
    assert instance_of(int)(True)

    with pytest.raises(HasWrongType):
        instance_of(str)(1)

    with pytest.raises(HasWrongType):
        instance_of(int)('r')

    assert_valid('instance', 'r', instance_of(str))
Exemplo n.º 3
0
def test_readme_index_usage_basic():
    """ Tests that the examples provided in the index page under Usage examples/Basic are correct """

    from valid8 import assert_valid
    from valid8.validation_lib import instance_of, is_multiple_of

    surf = -1

    # (1) simplest: one named variable to validate, one validation function
    assert_valid('surface', surf, instance_of(int))
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface', surf, is_multiple_of(100))
    e = exc_info.value
    assert str(e) == 'Error validating [surface=-1]. ' \
                     'IsNotMultipleOf: Value should be a multiple of 100. Wrong value: -1.'

    # (2) native mini_lambda support to define validation functions
    from mini_lambda import x
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface', surf, x > 0)
    e = exc_info.value
    assert str(
        e
    ) == 'Error validating [surface=-1]. InvalidValue: Function [x > 0] returned [False] for value -1.'
Exemplo n.º 4
0
def test_readme_index_usage_composition():
    """ Tests that the examples provided in the index page under Usage examples/Composition are correct """

    from valid8 import assert_valid
    from valid8.validation_lib import is_multiple_of
    from mini_lambda import x

    surf = -1

    # (7) composition of several base validation functions
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface', surf, (x >= 0) & (x < 10000),
                     is_multiple_of(100))
    e = exc_info.value
    assert str(e) == "Error validating [surface=-1]. " \
                     "At least one validation function failed for value -1. " \
                     "Successes: [] / Failures: {'(x >= 0) & (x < 10000)': 'Returned False.', " \
                     "'is_multiple_of_100': 'IsNotMultipleOf: Value should be a multiple of 100.'}."

    # (8) ... with a global custom error type. Oh by the way this supports templating
    class InvalidSurface(ValidationError):
        help_msg = 'Surface should be between {min_s} and {max_s} and be a multiple of {mul_s}, found {var_value}'

    min_surface, mul_surface, max_surface = 0, 100, 10000
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface',
                     surf, (x >= min_surface) & (x < max_surface),
                     is_multiple_of(mul_surface),
                     error_type=InvalidSurface,
                     min_s=min_surface,
                     mul_s=mul_surface,
                     max_s=max_surface)
    e = exc_info.value
    assert str(e) == "Surface should be between 0 and 10000 and be a multiple of 100, found -1. " \
                     "Error validating [surface=-1]. " \
                     "At least one validation function failed for value -1. " \
                     "Successes: [] / Failures: {" \
                     "'(x >= 0) & (x < 10000)': 'Returned False.', " \
                     "'is_multiple_of_100': 'IsNotMultipleOf: Value should be a multiple of 100.'}."

    # (9) ... and possible user-friendly intermediate failure messages
    with pytest.raises(ValidationError) as exc_info:
        assert_valid(
            'surface', surf,
            ((x >= 0) & (x < 10000), 'Surface should be between 0 and 10000'),
            (is_multiple_of(100), 'Surface should be a multiple of 100'))
    e = exc_info.value
    assert str(e) == "Error validating [surface=-1]. " \
                     "At least one validation function failed for value -1. " \
                     "Successes: [] / Failures: {" \
                     "'(x >= 0) & (x < 10000)': 'InvalidValue: Surface should be between 0 and 10000. " \
                     "Returned False.', " \
                     "'is_multiple_of_100': 'InvalidValue: Surface should be a multiple of 100. " \
                     "IsNotMultipleOf: Value should be a multiple of 100.'}."

    # *********** other even more complex tests ***********

    # + unique applicative error type
    with pytest.raises(ValidationError) as exc_info:
        assert_valid(
            'surface',
            surf,
            failure_raiser(
                (x >= min_surface) & (x < max_surface),
                help_msg='Surface should be between {min_val} and {max_val}',
                min_val=min_surface,
                max_val=max_surface),
            (is_multiple_of(100),
             'Surface should be a multiple of 100, found {wrong_value}'),
            error_type=InvalidSurface,
            min_s=min_surface,
            mul_s=mul_surface,
            max_s=max_surface)
    e = exc_info.value
    assert str(e) == "Surface should be between 0 and 10000 and be a multiple of 100, found -1. " \
                     "Error validating [surface=-1]. " \
                     "At least one validation function failed for value -1. " \
                     "Successes: [] / Failures: {" \
                     "'(x >= 0) & (x < 10000)': 'InvalidValue: Surface should be between 0 and 10000. " \
                     "Returned False.', " \
                     "'is_multiple_of_100': 'InvalidValue: Surface should be a multiple of 100, found -1. " \
                     "IsNotMultipleOf: Value should be a multiple of 100.'}."
Exemplo n.º 5
0
def test_readme_index_usage_customization():
    """ Tests that the examples provided in the index page under Usage examples/Customization are correct """

    from valid8 import assert_valid, ValidationError
    from valid8.validation_lib import is_multiple_of
    from mini_lambda import x

    from valid8 import NonePolicy

    surf = -1

    # (3) explicit validation policy for None
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface', None, x > 0, none_policy=NonePolicy.FAIL)
    e = exc_info.value
    assert str(
        e
    ) == 'Error validating [surface=None]. ValueIsNone: The value must be non-None. Wrong value: None.'

    # *** (4) TEST: custom ValidationFailure (not ValidationError) message. Does it have any interest ? ***
    with pytest.raises(ValidationError) as exc_info:
        assert_valid(
            'surface', surf,
            (is_multiple_of(100), 'Surface should be a multiple of 100'))
    e = exc_info.value
    assert str(e) == 'Error validating [surface=-1]. ' \
                     'InvalidValue: Surface should be a multiple of 100. ' \
                     'Function [is_multiple_of_100] raised ' \
                     'IsNotMultipleOf: Value should be a multiple of 100. Wrong value: -1.'

    # (4) custom error message (exception is still a ValidationError)
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface',
                     surf,
                     x > 0,
                     help_msg='Surface should be positive')
    e = exc_info.value
    assert str(e) == "Surface should be positive. " \
                     "Error validating [surface=-1]. InvalidValue: Function [x > 0] returned [False] for value -1."

    # (5) custom error types (recommended to provide unique applicative errors)
    class InvalidSurface(ValidationError):
        help_msg = 'Surface should be a positive number'

    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface',
                     surf,
                     is_multiple_of(100),
                     error_type=InvalidSurface)
    e = exc_info.value
    assert isinstance(e, InvalidSurface)
    assert str(e) == 'Surface should be a positive number. ' \
                     'Error validating [surface=-1]. ' \
                     'IsNotMultipleOf: Value should be a multiple of 100. Wrong value: -1.'

    # (6) custom error types with templating
    class InvalidSurface(ValidationError):
        help_msg = 'Surface should be > {minimum}, found {var_value}'

    min_value = 0
    with pytest.raises(ValidationError) as exc_info:
        assert_valid('surface',
                     surf,
                     x > min_value,
                     error_type=InvalidSurface,
                     minimum=min_value)
    e = exc_info.value
    assert str(e) == "Surface should be > 0, found -1. " \
                     "Error validating [surface=-1]. InvalidValue: Function [x > 0] returned [False] for value -1."
Exemplo n.º 6
0
def test_usage_ensure_valid():
    """ Tests that the examples in the usage section of the documentation work """

    is_multiple_of, is_multiple_of_3 = create_base_functions()

    from mini_lambda import s

    # (1) Existing function
    assert_valid('nb', 0, isfinite)
    with pytest.raises(ValidationError):
        assert_valid('nb', inf, isfinite)
    # (2) Functools partial
    assert_valid('typ', int, partial(issubclass, bool))
    with pytest.raises(ValidationError):
        assert_valid('typ', str, partial(issubclass, bool))
    # (3) User-defined, standard
    assert_valid('nb', 3, is_multiple_of_3)
    with pytest.raises(ValidationError):
        assert_valid('nb', 1, is_multiple_of_3)
    # (4) User-defined, lambda
    assert_valid('txt', 'abc', lambda s: s.islower())
    with pytest.raises(ValidationError):
        assert_valid('txt', 'aBc', lambda s: s.islower())
    # (5) User-defined, mini-lambda
    assert_valid('txt', 'Abc', s.lower().startswith('a'))
    with pytest.raises(ValidationError):
        assert_valid('txt', 'Bbc', s.lower().startswith('a'))
    # (6) User-defined, factory
    assert_valid('nb', 15, is_multiple_of(5))
    with pytest.raises(ValidationError):
        assert_valid('nb', 1, is_multiple_of(5))

    gt_0, gt_1, gt_2, gt_3 = create_base_functions_2()
    assert_valid('nb', 1, gt_0)
    with pytest.raises(ValidationError):
        assert_valid('nb', -0.2, gt_0)
    assert_valid('nb', 1, gt_1)
    with pytest.raises(ValidationError):
        assert_valid('nb', 0.2, gt_1)
    assert_valid('nb', 2, gt_2)
    with pytest.raises(ValidationError):
        assert_valid('nb', 0.2, gt_2)
    assert_valid('nb', 3, gt_3)
    with pytest.raises(ValidationError):
        assert_valid('nb', 0.2, gt_3)
Exemplo n.º 7
0
 def hello(age):
     assert_valid('age', age, [isfinite, between(0, 150), Int(x) == x])
     print('Hello, %s-years-old fella !' % age)