Python mongoengine.errors.ValidationError() Examples

The following are 16 code examples of mongoengine.errors.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mongoengine.errors , or try the search function .
Example #1
Source File: datastore.py    From flask-security with MIT License 6 votes vote down vote up
def find_user(self, case_insensitive=False, **kwargs):
        from mongoengine.queryset.visitor import Q, QCombination
        from mongoengine.errors import ValidationError

        try:
            if case_insensitive:
                # While it is of course possible to pass in multiple keys to filter on
                # that isn't the normal use case. If caller asks for case_insensitive
                # AND gives multiple keys - throw an error.
                if len(kwargs) > 1:
                    raise ValueError("Case insensitive option only supports single key")
                attr, identifier = kwargs.popitem()
                query = {f"{attr}__iexact": identifier}
                return self.user_model.objects(**query).first()
            else:
                queries = map(lambda i: Q(**{i[0]: i[1]}), kwargs.items())
                query = QCombination(QCombination.AND, queries)
                return self.user_model.objects(query).first()
        except ValidationError:  # pragma: no cover
            return None 
Example #2
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_validate_registered_type_embedded_document(self):
        class Tester(db.Document):
            extras = db.ExtrasField()

        @Tester.extras('test')
        class EmbeddedExtra(db.EmbeddedDocument):
            name = db.StringField(required=True)

        tester = Tester(extras={'test': {}})
        with pytest.raises(ValidationError):
            tester.validate()

        tester.extras['test'] = {'name': 'test'}
        tester.validate()

        tester.extras['test'] = EmbeddedExtra(name='test')
        tester.validate() 
Example #3
Source File: test_objectid.py    From mongoengine-goodjson with MIT License 5 votes vote down vote up
def test_encode(self):
        """Serialization should be failed."""
        with self.assertRaises(ValidationError) as e:
            self.doc.to_json()
        self.assertEqual(e.exception.field_name, "uid") 
Example #4
Source File: test_objectid.py    From mongoengine-goodjson with MIT License 5 votes vote down vote up
def test_encode(self):
        """Serialization should be failed."""
        with self.assertRaises(ValidationError) as e:
            self.doc.to_json()
        self.assertEqual(e.exception.field_name, "uid") 
Example #5
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_valid(self):
        obj = DateTester(a_date='invalid')
        with pytest.raises(ValidationError):
            obj.save() 
Example #6
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_valid(self):
        obj = DateRangeTester(temporal={'start': 'wrong'})
        with pytest.raises(ValidationError):
            obj.save() 
Example #7
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_empty_but_required(self):
        obj = RequiredDateRangeTester()
        assert obj.temporal is None
        with pytest.raises(ValidationError):
            obj.save() 
Example #8
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_valid(self):
        obj = URLTester(url='invalid')
        with pytest.raises(ValidationError):
            obj.save() 
Example #9
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_public_private(self):
        url = 'http://10.10.0.2/path/'
        PrivateURLTester(url=url).save()
        with pytest.raises(ValidationError):
            URLTester(url=url).save() 
Example #10
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fail_to_validate_wrong_type(self, dbtype, value):
        class Tester(db.Document):
            extras = db.ExtrasField()

        Tester.extras.register('test', dbtype)

        with pytest.raises(db.ValidationError):
            Tester(extras={'test': value}).validate() 
Example #11
Source File: test_model.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_validate_custom_type(self):
        class Tester(db.Document):
            extras = db.ExtrasField()

        @Tester.extras('test')
        class Custom(BaseField):
            def validate(self, value):
                if not isinstance(value, dict):
                    raise db.ValidationError('Should be a dict instance')

        tester = Tester(extras={'test': {}})
        tester.validate() 
Example #12
Source File: commands.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_zones(col, path):
    with open(path, 'rb') as fp:
        unpacker = msgpack.Unpacker(fp, raw=False)
        next(unpacker)  # Skip headers.
        for i, geozone in enumerate(unpacker):
            params = {
                'slug': slugify.slugify(geozone['name'], separator='-'),
                'level': geozone['level'],
                'code': geozone['code'],
                'name': geozone['name'],
                'keys': geozone.get('keys'),
                'parents': geozone.get('parents', []),
                'ancestors': geozone.get('ancestors', []),
                'successors': geozone.get('successors', []),
                'validity': geozone.get('validity'),
                'population': geozone.get('population'),
                'dbpedia': geozone.get('dbpedia'),
                'flag': geozone.get('flag'),
                'blazon': geozone.get('blazon'),
                'wikidata': geozone.get('wikidata'),
                'wikipedia': geozone.get('wikipedia'),
                'area': geozone.get('area'),
            }
            if geozone.get('geom') and (
                geozone['geom']['type'] != 'GeometryCollection' or
                    geozone['geom']['geometries']):
                params['geom'] = geozone['geom']
            try:
                col.objects(id=geozone['_id']).modify(upsert=True, **{
                    'set__{0}'.format(k): v for k, v in params.items()
                })
            except errors.ValidationError as e:
                log.warning('Validation error (%s) for %s with %s',
                            e, geozone['_id'], params)
                continue
    return i 
Example #13
Source File: test_task.py    From fastlane with MIT License 5 votes vote down vote up
def test_task_create2(client):
    """Test creating a new task fails when no task_id provided"""
    msg = "ValidationError (Task:None) (Field is required: ['task_id'])"
    with expect.error_to_happen(ValidationError, message=msg):
        Task.create_task(None)

    with expect.error_to_happen(ValidationError, message=msg):
        Task.create_task("") 
Example #14
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def run_validators(self, value):
        """ validate value.

        Uses document field's ``validate()``
        """
        try:
            self.model_field.validate(value)
        except MongoValidationError as e:
            raise ValidationError(e.message)
        super(DocumentField, self).run_validators(value) 
Example #15
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def run_validators(self, value):
        try:
            self.mongo_field().validate(value)
        except MongoValidationError as e:
            raise ValidationError(e.message)
        super(MongoValidatingField, self).run_validators(value) 
Example #16
Source File: serializers.py    From django-rest-framework-mongoengine with MIT License 4 votes vote down vote up
def create(self, validated_data):
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model
        try:
            # recursively create EmbeddedDocuments from their validated data
            # before creating the document instance itself
            instance = self.recursive_save(validated_data)
        except TypeError as exc:
            msg = (
                'Got a `TypeError` when calling `%s.objects.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.objects.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception text was: %s.' %
                (
                    ModelClass.__name__,
                    ModelClass.__name__,
                    type(self).__name__,
                    exc
                )
            )
            raise TypeError(msg)
        except me_ValidationError as exc:
            msg = (
                'Got a `ValidationError` when calling `%s.objects.create()`. '
                'This may be because request data satisfies serializer validations '
                'but not Mongoengine`s. You may need to check consistency between '
                '%s and %s.\nIf that is not the case, please open a ticket '
                'regarding this issue on https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues'
                '\nOriginal exception was: %s' %
                (
                    ModelClass.__name__,
                    ModelClass.__name__,
                    type(self).__name__,
                    exc
                )
            )
            raise me_ValidationError(msg)

        return instance