Ejemplo n.º 1
0
 class CosmicEntity(field.SchemaField):
     fields = (
         field.StrField('value'),
         field.StrField('_value'),
         field.StrField('__value'),
         field.IntField('errors'),
         field.IntField('_errors'),
         field.IntField('__errors'),
     )
Ejemplo n.º 2
0
def test_field_loads_data():
    """Load data to IntField, check if we can access it. Try with different
    types on input (normalisation should kick in).
    """
    schema = field.IntField('meaning_of_everything', allow_none=True)

    class AnObject:
        def __str__(self):
            return '6'

    values_to_check = [
        ('12', 12),
        (-1, -1),
        ('0', 0),
        (42, 42),
        (0, 0),
        (AnObject(), 6),
        (None, None),
    ]

    for value_before, value_after in values_to_check:
        schema.loads(value_before)

        assert schema.name == 'meaning_of_everything'
        assert schema == value_after
        assert schema.errors == []
        assert schema.as_python() == value_after
        assert schema.as_json() == value_after
Ejemplo n.º 3
0
def test_inline_schema_works():
    """Inline schema is created on the fly.
    """
    schema = field.SchemaField('user',
                               fields=[
                                   field.StrField('name'),
                                   field.StrField('last_name'),
                                   field.IntField('age'),
                               ])

    schema.loads({
        'name': 'Frank',
        'last_name': 'Castle',
        'age': '35',
    })

    assert schema['name'] == 'Frank'
    assert schema['last_name'] == 'Castle'
    assert schema['age'] == 35

    assert schema == {
        'name': 'Frank',
        'last_name': 'Castle',
        'age': 35,
    }
Ejemplo n.º 4
0
def test_cases_when_normalisation_fails():
    """Test checks if normalisation is not overcommitting itself.
    """
    schema = field.IntField('meaning_of_everything', allow_none=False)

    values_to_check = [
        'True',
        True,
        False,
        'hello',
        '12.3.4.5',
        13.4,
        '12.8',
    ]

    for value in values_to_check:
        with pytest.raises(exception.NormalisationError):
            schema.loads(value)

        assert schema.errors == \
            [f'IntField cannot be populated with value: {value}']

        try:
            schema.loads(value)
        except exception.NormalisationError as err:
            assert schema.errors == \
                [f'IntField cannot be populated with value: {value}']
            assert str(err) == \
                f'IntField cannot be populated with value: {value}'
Ejemplo n.º 5
0
def test_cases_when_we_do_not_allow_nones():
    schema = field.IntField('meaning_of_everything', allow_none=False)

    with pytest.raises(exception.NormalisationError):
        schema.loads(None)

    try:
        schema.loads(None)
    except exception.NormalisationError as err:
        assert schema.errors == ['None is not allowed value']
        assert str(err) == 'None is not allowed value'
def test_collection_of_same_collection_works():
    even_numbers_collection = field.CollectionField(
        'even_numbers',
        type_=field.IntField('individual_number',
                             validators=[
                                 lambda val: (f"Number is not even, got {val}"
                                              if val % 2 else True)
                             ]),
        validators=[
            lambda val:
            (True if len(val) > 1 else
             f"List has to be at least 2 elements long, got {len(val)}")
        ],
    )

    master_collection = field.CollectionField('series_of_even_numbers',
                                              type_=even_numbers_collection)

    master_collection.loads([[2, 4, 6], [12, 18, 22]])

    assert master_collection.dumps() == [[2, 4, 6], [12, 18, 22]]

    # check if validation is working as expected

    with pytest.raises(exception.ValidationError):
        master_collection.loads([
            [2, 4],
            [2, 5, 6],
            [6, 12],
        ])

    with pytest.raises(exception.ValidationError):
        master_collection.loads([
            [
                2,
            ],
        ])
def test_error_handling_works_on_content_of_collection_part_2():
    """Collection is the first field that may have a validation error on itself
    (for example only 5 elements max) and on the value that collection has (for
    example only even numbers). Tests are split same way.

    This verifies validation on individual elements works.
    """
    schema = field.CollectionField(
        'list_of_even_numbers',
        type_=field.IntField('individual_number',
                             validators=[
                                 lambda val: (f"Number is not even, got {val}"
                                              if val % 2 else True)
                             ]))

    try:
        schema.loads([4, 5, 8])
    except exception.ValidationError as err:
        assert str(err) == 'Validation error'
        assert schema.errors == [{
            1: [
                'Number is not even, got 5',
            ]
        }]

    try:
        schema.loads([2, 3, 4, 5, 6])
    except exception.ValidationError as err:
        assert str(err) == 'Validation error'
        assert schema.errors == [{
            1: [
                'Number is not even, got 3',
            ],
            3: [
                'Number is not even, got 5',
            ],
        }]
Ejemplo n.º 8
0
 class Newspaper(field.SchemaField):
     fields = [
         field.IntField('issue'),
         field.StrField('title'),
         field.CollectionField('articles', Article),
     ]
Ejemplo n.º 9
0
 class User(field.SchemaField):
     fields = [
         field.StrField('name'),
         field.StrField('last_name'),
         field.IntField('age'),
     ]
def test_error_handling_works_on_content_of_collection_part_3():
    """Collection is the first field that may have a validation error on itself
    (for example only 5 elements max) and on the value that collection has (for
    example only even numbers). Tests are split same way.

    This tests verifies that validation is done in phases, only when phase one
    (validation of main collection) is success we progress to phase 2. This
    assumption is driven by the fact that while we may collection of max 5
    elements we definitely do not want to validate collection of 10k elements.
    """
    schema = field.CollectionField(
        'short_list_of_even_numbers',
        type_=field.IntField('individual_number',
                             validators=[
                                 lambda val: (f"Number is not even, got {val}"
                                              if val % 2 else True)
                             ]),
        validators=[
            lambda val:
            (True if 1 < len(val) < 6 else
             f"List has to be between 2 and 5 elements, got {len(val)}")
        ])

    # this is warm up and sanity check
    schema.loads([2, 4, 6])

    assert schema.errors == []

    # this is too short, we should not care about number being even
    try:
        schema.loads([
            3,
        ])
    except exception.ValidationError as err:
        assert str(err) == 'Validation error'
        assert schema.errors == [
            'List has to be between 2 and 5 elements, got 1'
        ]

    # this is too long, we should not care about number being even
    try:
        schema.loads([2, 3, 5, 7, 9, 10, 12, 14])
    except exception.ValidationError as err:
        assert str(err) == 'Validation error'
        assert schema.errors == [
            'List has to be between 2 and 5 elements, got 8'
        ]

    # this is right on length, but one number is not even
    try:
        schema.loads([2, 5, 10])
    except exception.ValidationError as err:
        assert str(err) == "Validation error"
        assert schema.errors == [{
            1: ['Number is not even, got 5'],
        }]

    # this one is right on spot
    schema.loads([2, 6, 12])

    assert schema.errors == []