def test_tuple(self):
        with pytest.raises(TypeError):
            Tuple(UnicodeString(),
                  Integer(),
                  Boolean(),
                  additional_validator='Not a validator')  # type: ignore

        field = Tuple(UnicodeString(), Integer(), Boolean())

        assert field.errors(['foo', 'bar',
                             'baz']) == [Error(message='Not a tuple')]
        assert field.errors({'foo': 'bar'}) == [Error(message='Not a tuple')]
        assert field.errors({'foo', 'bar',
                             'baz'}) == [Error(message='Not a tuple')]
        assert field.errors(
            ('foo', 'bar',
             True)) == [Error(message='Not an integer', pointer='1')]
        assert field.errors(('foo', 12, False)) == []
        assert field.errors(('foo', 12, True)) == []

        class V(AdditionalCollectionValidator[TupleType[AnyType]]):
            def errors(self, value):
                if value[2] is not True:
                    return [Error('The third value must be True', pointer='2')]
                return []

        field = Tuple(UnicodeString(),
                      Integer(),
                      Boolean(),
                      additional_validator=V())

        assert field.errors(('foo', 12, False)) == [
            Error(message='The third value must be True', pointer='2')
        ]
        assert field.errors(('foo', 12, True)) == []
Esempio n. 2
0
    def test_tuple(self):
        schema = Tuple(Integer(gt=0), UnicodeString(),
                       Constant('I love tuples'))

        self.assertEqual(schema.errors((1, 'test', 'I love tuples')), [])

        # too short
        self.assertEqual(
            schema.errors((1, 'test')),
            [Error('Number of elements 2 does not match expected 3')])

        # too long
        self.assertEqual(
            schema.errors((1, 'test', 'I love tuples', '... and coffee')),
            [Error('Number of elements 4 does not match expected 3')])

        self.assertEqual(schema.errors((
            -1,
            None,
            'I hate tuples',
        )), [
            Error('Value not > 0', pointer='0'),
            Error('Not a unicode string', pointer='1'),
            Error(
                'Value is not "I love tuples"',
                code=ERROR_CODE_UNKNOWN,
                pointer='2',
            ),
        ])

        self.assertEqual(
            schema.introspect(), {
                'type':
                'tuple',
                'contents': [
                    {
                        'type': 'integer',
                        'gt': 0
                    },
                    {
                        'type': 'unicode'
                    },
                    {
                        'type': 'constant',
                        'values': ['I love tuples']
                    },
                ]
            })
        class Helper(object):
            @classmethod
            @validate_method(schema, UnicodeString())
            def greeter(cls, name, greeting='Hello'):
                # Special case to check return value stuff
                if name == 'error':
                    return 5
                return '{}, {}!'.format(greeting, name)

            @staticmethod
            @validate_call(args=Tuple(Integer(), Integer()), kwargs=None, returns=Integer())
            def args_method(one, two):
                return one + two

            # noinspection PyMethodMayBeStatic
            @validate_method(
                args=List(UnicodeString()),
                kwargs=SchemalessDictionary(value_type=UnicodeString()),
                returns=List(UnicodeString()),
            )
            def args_and_kwargs_method(self, *args, **kwargs):
                return [s.format(**kwargs) for s in args]
Esempio n. 4
0
    def test_tuple(self):  # type: () -> None
        schema = Tuple(Integer(gt=0), UnicodeString(),
                       Constant('I love tuples'))

        self.assertEqual(schema.errors((1, 'test', 'I love tuples')), [])

        # too short
        self.assertEqual(
            schema.errors((1, 'test')),
            [Error('Number of elements 2 does not match expected 3')])

        # too long
        self.assertEqual(
            schema.errors((1, 'test', 'I love tuples', '... and coffee')),
            [Error('Number of elements 4 does not match expected 3')])

        self.assertEqual(schema.errors((
            -1,
            None,
            'I hate tuples',
        )), [
            Error('Value not > 0', pointer='0'),
            Error('Not a unicode string', pointer='1'),
            Error(
                'Value is not "I love tuples"',
                code=ERROR_CODE_UNKNOWN,
                pointer='2',
            ),
        ])

        self.assertEqual(
            schema.introspect(), {
                'type':
                'tuple',
                'contents': [
                    {
                        'type': 'integer',
                        'gt': 0
                    },
                    {
                        'type': 'unicode'
                    },
                    {
                        'type': 'constant',
                        'values': ['I love tuples']
                    },
                ]
            })

        with pytest.raises(TypeError):
            # noinspection PyTypeChecker
            Tuple('not a field')  # type: ignore

        with pytest.raises(TypeError):
            Tuple(Integer(gt=0),
                  UnicodeString(),
                  Constant('I love tuples'),
                  description=b'Not a unicode string')

        with pytest.raises(TypeError):
            Tuple(Integer(gt=0),
                  UnicodeString(),
                  Constant('I love tuples'),
                  unsupported='argument')
Esempio n. 5
0
    def test_dictionary_ordering(self):  # type: () -> None
        schema1 = Dictionary(
            OrderedDict((
                ('foo', UnicodeString()),
                ('bar', Boolean()),
                ('baz', List(Integer())),
            )),
            optional_keys=('foo', ),
            description='Hello, world',
        )

        assert schema1.introspect()['contents'] == {
            'baz': List(Integer()).introspect(),
            'foo': UnicodeString().introspect(),
            'bar': Boolean().introspect(),
        }

        assert schema1.introspect()['display_order'] == ['foo', 'bar', 'baz']

        schema2 = schema1.extend(
            OrderedDict((
                ('bar', Integer()),
                ('qux', Set(UnicodeString())),
                ('moon', Tuple(Decimal(), UnicodeString())),
            )))

        assert schema2.introspect()['contents'] == {
            'baz': List(Integer()).introspect(),
            'foo': UnicodeString().introspect(),
            'moon': Tuple(Decimal(), UnicodeString()).introspect(),
            'bar': Integer().introspect(),
            'qux': Set(UnicodeString()).introspect(),
        }

        assert schema2.introspect()['display_order'] == [
            'foo', 'bar', 'baz', 'qux', 'moon'
        ]

        assert not schema1.errors({'bar': True, 'foo': 'Hello', 'baz': [15]})

        errors = schema1.errors({
            'baz': 'Nope',
            'foo': False,
            'bar': ['Heck nope']
        })

        assert errors == [
            Error(code='INVALID',
                  pointer='foo',
                  message='Not a unicode string'),
            Error(code='INVALID', pointer='bar', message='Not a boolean'),
            Error(code='INVALID', pointer='baz', message='Not a list'),
        ]

        assert not schema2.errors(
            {
                'bar': 91,
                'foo': 'Hello',
                'qux': {'Yes'},
                'baz': [15],
                'moon': (decimal.Decimal('15.25'), 'USD')
            }, )

        errors = schema2.errors({
            'baz': 'Nope',
            'foo': False,
            'bar': ['Heck nope'],
            'qux': 'Denied',
            'moon': 72
        })

        assert errors == [
            Error(code='INVALID',
                  pointer='foo',
                  message='Not a unicode string'),
            Error(code='INVALID', pointer='bar', message='Not an integer'),
            Error(code='INVALID', pointer='baz', message='Not a list'),
            Error(code='INVALID',
                  pointer='qux',
                  message='Not a set or frozenset'),
            Error(code='INVALID', pointer='moon', message='Not a tuple'),
        ]
    def test_validate_call(self):  # type: () -> None
        schema = Dictionary({
            'name': UnicodeString(max_length=20),
            'greeting': UnicodeString(),
        }, optional_keys=('greeting', ))

        @validate_call(schema, UnicodeString())
        def greeter(name, greeting='Hello'):
            # Special case to check return value stuff
            if name == 'error':
                return 5
            return '{}, {}!'.format(greeting, name)

        assert getattr(greeter, '__validated__') is True
        assert getattr(greeter, '__validated_schema_args__') is None
        assert getattr(greeter, '__validated_schema_kwargs__') is schema
        assert getattr(greeter, '__validated_schema_returns__') == UnicodeString()

        self.assertEqual(greeter(name='Andrew'), 'Hello, Andrew!')
        self.assertEqual(greeter(name='Andrew', greeting='Ahoy'), 'Ahoy, Andrew!')

        with self.assertRaises(ValidationError):
            greeter(name='Andrewverylongnameperson')

        with self.assertRaises(ValidationError):
            greeter(name='Andrew', greeeeeeting='Boo')

        with self.assertRaises(ValidationError):
            greeter(name='error')

        with self.assertRaises(PositionalError):
            greeter('Andrew')

        @validate_call(
            args=Tuple(Integer(), UnicodeString()),
            kwargs=None,
            returns=Null(),
        )
        def args_function(foo, bar):
            if foo:
                return bar.format(bar)

        assert getattr(args_function, '__validated__') is True
        assert getattr(args_function, '__validated_schema_args__') == Tuple(Integer(), UnicodeString())
        assert getattr(args_function, '__validated_schema_kwargs__') is None
        assert getattr(args_function, '__validated_schema_returns__') == Null()

        assert args_function(0, 'John {}') is None
        with pytest.raises(ValidationError):
            args_function(1, 'Jeff {}')
        with pytest.raises(ValidationError):
            args_function(0, b'Nope {}')
        with pytest.raises(ValidationError):
            args_function(0, bar='John {}')
        with pytest.raises(KeywordError):
            args_function(0, 'John {}', extra='Unsupported')

        @validate_call(
            args=Tuple(Integer(), UnicodeString()),
            kwargs=Dictionary({'extra': UnicodeString()}, optional_keys=('extra', )),
            returns=UnicodeString(),
        )
        def args_and_kwargs_function(foo, bar, extra='baz'):
            return bar.format(foo, extra)

        assert getattr(args_and_kwargs_function, '__validated__') is True
        assert getattr(args_and_kwargs_function, '__validated_schema_args__') == Tuple(Integer(), UnicodeString())
        assert (
            getattr(args_and_kwargs_function, '__validated_schema_kwargs__') ==
            Dictionary({'extra': UnicodeString()}, optional_keys=('extra', ))
        )
        assert getattr(args_and_kwargs_function, '__validated_schema_returns__') == UnicodeString()

        assert args_and_kwargs_function(0, 'John {}: {}') == 'John 0: baz'
        assert args_and_kwargs_function(1, 'Jeff {}: {}', extra='cool') == 'Jeff 1: cool'
        with pytest.raises(ValidationError):
            args_and_kwargs_function(1, 'Jeff {}: {}', 'cool')
        with pytest.raises(ValidationError):
            args_and_kwargs_function('nope', 'Jeff {}: {}')
        with pytest.raises(ValidationError):
            args_and_kwargs_function(1, b'nope')
        with pytest.raises(ValidationError):
            args_and_kwargs_function(0, bar='John {}: {}')
    def test_validate_method(self):  # type: () -> None
        schema = Dictionary({
            'name': UnicodeString(max_length=20),
            'greeting': UnicodeString(),
        }, optional_keys=('greeting', ))

        class Helper(object):
            @classmethod
            @validate_method(schema, UnicodeString())
            def greeter(cls, name, greeting='Hello'):
                # Special case to check return value stuff
                if name == 'error':
                    return 5
                return '{}, {}!'.format(greeting, name)

            @staticmethod
            @validate_call(args=Tuple(Integer(), Integer()), kwargs=None, returns=Integer())
            def args_method(one, two):
                return one + two

            # noinspection PyMethodMayBeStatic
            @validate_method(
                args=List(UnicodeString()),
                kwargs=SchemalessDictionary(value_type=UnicodeString()),
                returns=List(UnicodeString()),
            )
            def args_and_kwargs_method(self, *args, **kwargs):
                return [s.format(**kwargs) for s in args]

        assert getattr(Helper.greeter, '__validated__') is True
        assert getattr(Helper.greeter, '__validated_schema_args__') is None
        assert getattr(Helper.greeter, '__validated_schema_kwargs__') is schema
        assert getattr(Helper.greeter, '__validated_schema_returns__') == UnicodeString()

        assert getattr(Helper.args_method, '__validated__') is True
        assert getattr(Helper.args_method, '__validated_schema_args__') == Tuple(Integer(), Integer())
        assert getattr(Helper.args_method, '__validated_schema_kwargs__') is None
        assert getattr(Helper.args_method, '__validated_schema_returns__') == Integer()

        assert getattr(Helper.args_and_kwargs_method, '__validated__') is True
        assert getattr(Helper.args_and_kwargs_method, '__validated_schema_args__') == List(UnicodeString())
        assert (
            getattr(Helper.args_and_kwargs_method, '__validated_schema_kwargs__') ==
            SchemalessDictionary(value_type=UnicodeString())
        )
        assert getattr(Helper.args_and_kwargs_method, '__validated_schema_returns__') == List(UnicodeString())

        self.assertEqual(Helper.greeter(name='Andrew'), 'Hello, Andrew!')
        self.assertEqual(Helper.greeter(name='Andrew', greeting='Ahoy'), 'Ahoy, Andrew!')

        with self.assertRaises(ValidationError):
            Helper.greeter(name='Andrewverylongnameperson')

        with self.assertRaises(ValidationError):
            Helper.greeter(name='Andrew', greeeeeeting='Boo')

        with self.assertRaises(ValidationError):
            Helper.greeter(name='error')

        with self.assertRaises(PositionalError):
            Helper.greeter('Andrew')

        assert Helper.args_method(1, 2) == 3
        assert Helper.args_method(75, 23) == 98
        with pytest.raises(ValidationError):
            Helper.args_method(1.0, 2)
        with pytest.raises(ValidationError):
            Helper.args_method(1, 2.0)
        with pytest.raises(KeywordError):
            Helper.args_method(1, 2, extra='Forbidden')

        assert Helper().args_and_kwargs_method('hello', 'cool {planet}', 'hot {star}', planet='Earth', star='Sun') == [
            'hello',
            'cool Earth',
            'hot Sun',
        ]
        with pytest.raises(ValidationError):
            Helper().args_and_kwargs_method(1, 'sweet', planet='Earth', star='Sun')
        with pytest.raises(ValidationError):
            Helper().args_and_kwargs_method('hello', 'cool {planet}', 'hot {star}', planet=1, star=2)