Example #1
0
def test_fields_equal():
    values = ("pong", "pong")
    v = V.fields_equal('hog')
    assert v.__name__ == "fields_equal"
    assert values == v(values)
    values = ('tim', 'worthy')
    assert_invalid(lambda: v(values), {None: 'hog'})
    s = V.Schema({
        'foo': V.to_integer(),
        ('foo', 'bar'): V.fields_equal(u"foo and bar don't match")
    })
    d = dict(foo='1', bar=1)
    expected = dict(foo=1, bar=1)
    assert s(d) == expected
    # Check field=None
    s = V.Schema({
        'foo':
        V.to_integer(),
        ('foo', 'bar'):
        V.fields_equal(u"foo and bar don't match", field=None)
    })
    d = dict(foo='1', bar=2)
    with py.test.raises(V.Invalid) as e:
        s(d)
    errors = e.value.unpack_errors()
    assert errors == {None: u"foo and bar don't match"}
Example #2
0
def test_nested_schema():
    nested_validators = dict(foo=V.to_unicode(),
                             bar=V.nested(flim=V.to_unicode(),
                                          flam=V.to_unicode()))
    schema = V.Schema(nested_validators)
    data = dict(foo="Foo", bar=dict(flim="Flim", flam="Flam"))
    assert schema(data) == data
Example #3
0
def test_Schema_errors():
    schema = V.Schema(dict(foo=V.is_integer(msg="number, not word, idiot!")))
    data = dict(foo="one")
    expected = {
        'foo': "number, not word, idiot!",
        None: "Problems were found in the submitted data."
    }
    with py.test.raises(V.Invalid) as e:
        schema(data)
    result = e.value.errors
    assert expected == result
Example #4
0
def test_schema_4():
    s = V.Schema(
        {
            'foo': V.is_integer(),
            'bar': V.is_integer(),
            ('foo', 'bar'): V.fields_equal(msg='flam', field=None)
        },
        msg="flibble")
    d = dict(foo=1, bar=2)
    with py.test.raises(V.Invalid) as e:
        s(d)
    errors = e.value.unpack_errors()
    assert errors == {None: 'flam'}
Example #5
0
def test_nested_many_fail_nested_errors():
    schema = V.Schema(dict(foo=V.nested_many(V.is_integer())))
    data = dict(foo=dict(a=1, b="two", c=3))
    with py.test.raises(V.Invalid) as e:
        result = schema(data)
    errors = e.value.unpack_errors()
    expected = {
        'foo': {
            'b': "not an integer"
        },
        None: "Problems were found in the submitted data."
    }
    assert expected == errors
def test_ContextValidator():
    def _is_in_database(msg="it's not in the database"):
        "Checks if something is in the database"

        def f(value, context):
            if not value in context['database']:
                raise V.Invalid(msg)
            return True

        return f

    is_in_database = _is_in_database

    assert is_in_database.__name__ == _is_in_database.__name__
    assert is_in_database.__doc__ == _is_in_database.__doc__
    v = is_in_database()

    context = dict(database=['foo', 'bar', 'bum'])
    assert is_in_database()('foo', context)

    with py.test.raises(V.Invalid) as e:
        assert is_in_database()('flooble', context)
    errors = e.value.unpack_errors()
    assert errors == {None: "it's not in the database"}

    with py.test.raises(V.Invalid) as e:
        assert is_in_database("ting nah in db")('flooble', context)
    errors = e.value.unpack_errors()
    assert errors == {None: "ting nah in db"}

    foo_schema = V.Schema(dict(flibble=is_in_database()))
    data = dict(flibble='foo')
    context = dict(database=['foo', 'bar', 'bum'])
    result = foo_schema(data, context)
    assert result == dict(flibble=True)

    with py.test.raises(V.Invalid) as e:
        data = dict(flibble='flansit')
        context = dict(database=['foo', 'bar', 'bum'])
        result = foo_schema(data, context)
    errors = e.value.unpack_errors()
    assert errors == {
        None: "Problems were found in the submitted data.",
        'flibble': "it's not in the database"
    }

    validator = V.nested(flim=is_in_database('doodah'))
    data = dict(flim='foo')
    context = dict(database=['foo', 'bar', 'bum'])
    result = validator(data, context)
    assert result == dict(flim=True)
Example #7
0
def test_credit_card_3():
    cc = '4000000000998'
    invalid_cc = str(int(cc) - 1)
    validators = dict(
        cc_card=(V.strip, V.not_empty("Please enter a credit card number")),
        cc_type=V.belongs(('Visa', 'Discover'), msg="belongs"))
    v = V.credit_card(require_type=True,
                      cc_field='cc_card',
                      cc_type_field='cc_type')
    validators[('cc_card', 'cc_type')] = v
    s = V.Schema(validators)
    data = dict(cc_card=invalid_cc, cc_type='')
    try:
        s(data)
    except V.Invalid, e:
        errors = e.unpack_errors()
        assert set(errors) == set(('cc_card', 'cc_type', None))
Example #8
0
def test_errors():
    schema = V.Schema(dict(foo=(V.to_unicode(msg="foo can't be converted"),
                                V.not_empty(msg="foo is empty")),
                           bar=(V.is_integer(msg="bar isn't an integer"),
                                V.not_empty(msg="bar is empty"))),
                      msg="Check the errors and try again.  Moron.")

    with py.test.raises(V.Invalid) as e:
        data = schema(dict(foo=None, bar=None))

    expected = {
        None: 'Check the errors and try again.  Moron.',
        'bar': "bar isn't an integer",
        'foo': 'foo is empty'
    }

    result = e.value.unpack_errors()
    assert result == expected
Example #9
0
def test_schema_3():
    v = V.Schema(
        dict(x=(V.is_integer('intx'), V.clamp(min=5, max=100, msg='clampx')),
             y=(V.is_integer('inty'), V.clamp(min=5, max=100, msg='clampy')),
             text=V.strip), {
                 'schema.error': 'schema',
                 'schema.extra': 'extra',
                 'schema.missing': 'missing'
             }, False, False)

    d1 = dict(x=40, y=20, text='hi there')
    assert v(d1) == d1
    d2 = dict(x=1, y=20, text='hi there')
    assert_invalid(lambda: v(d2), {None: 'schema', 'x': 'clampx'})
    d3 = dict(x=10, y=10)
    assert_invalid(lambda: v(d3), {None: 'missing'})
    d4 = dict(x=10, y=10, text='ho', pingpong='lather')
    assert_invalid(lambda: v(d4), {None: 'extra'})
Example #10
0
def test_schema_1():
    s = V.Schema(
        dict(
            username=(
                V.strip,
                V.regex('[a-z][a-z0-9]+', 'invalid username'),
                V.clamp_length(max=16, msg='username is too long'),
            ),
            user_id=V.either(
                V.empty(),
                V.all_of(V.to_integer('not an integer'),
                         V.clamp(min=1, max=9999, msg='out of range'))),
            department=(V.strip,
                        V.belongs(['interactive', 'programming'],
                                  'department not recognized')),
        ), "there were errors with your submission")
    data = dict(username='******', user_id='1', department='interactive')
    newdata = s(data)
    assert data['username'] == newdata['username']
    assert int(data['user_id']) == newdata['user_id']
    assert data['department'] == newdata['department']
Example #11
0
def test_schema_2():
    s = V.Schema(
        dict(x=(V.is_integer('intx'), V.clamp(min=5, max=100, msg='clampx')),
             y=(V.is_integer('inty'), V.clamp(min=5, max=100, msg='clampy')),
             text=V.strip), "schema")

    def check_keys(data, context=None):
        allkeys = set(('x', 'y', 'text'))
        found = set(data.keys())
        if allkeys.difference(found):
            raise V.Invalid("incomplete data")
        if found.difference(allkeys):
            raise V.Invalid("extra data")

    v = V.all_of(V.check(check_keys), s)
    d1 = dict(x=40, y=20, text='hi there')
    assert v(d1) == d1
    d2 = dict(x=1, y=20, text='hi there')
    assert_invalid(lambda: v(d2), {None: 'schema', 'x': 'clampx'})
    d3 = dict(x=10, y=10)
    assert_invalid(lambda: v(d3), {None: 'incomplete data'})
    d4 = dict(x=10, y=10, text='ho', pingpong='lather')
    assert_invalid(lambda: v(d4), {None: 'extra data'})
Example #12
0
def test_only_one_of():
    v = V.only_one_of(msg="Please only choose one value")
    assert v.__name__ == "only_one_of"
    assert v((0, 1)) == (0, 1)
    assert v((1, False, None, [])) == (1, False, None, [])
    with py.test.raises(V.Invalid) as e:
        v((1, False, None, True))
    assert e.value.unpack_errors() == {None: "Please only choose one value"}
    schema = V.Schema({
        'field1': (V.to_integer()),
        'field2': (V.to_integer()),
        ('field1', 'field2'):
        V.only_one_of(msg="Please only choose one value", field='field1')
    })
    assert schema(dict(field1="0", field2="1")) == dict(field1=0, field2=1)
    with py.test.raises(V.Invalid) as e:
        schema(dict(field1=True, field2=1))

    errors = e.value.unpack_errors()
    expected = {
        None: "Problems were found in the submitted data.",
        "field1": "Please only choose one value"
    }
    assert expected == errors
Example #13
0
def test_filter_missing():
    s = V.Schema(dict(x=V.to_integer(), y=V.to_integer()), filter_extra=False)

    d1 = dict(x="1", y="2", foo="bar")
    expected = dict(x=1, y=2, foo="bar")
    assert s(d1) == expected