How to use the schematics.exceptions.DataError function in schematics

To help you get started, we’ve selected a few schematics examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github schematics / schematics / tests / test_validation.py View on Github external
'id': 'ENG203', 'attending': [
                    {'name': u'Danny'},
                    {'name': u'Sandy'},
                ],
            },
        }
    }

    school = School(valid_data)
    school.validate()

    invalid_data = school.serialize()
    invalid_data['courses']["ENG103"]['attending'][0]['name'] = None

    school = School(invalid_data)
    with pytest.raises(DataError) as exception:
        school.validate()

    messages = exception.value.messages

    assert messages == {
        'courses': {
            "ENG103": {
                'attending': {
                    0: {
                        'name': [u'This field is required.']
                    }
github hotosm / tasking-manager / tests / server / unit / models / dtos / test_mapping_dto.py View on Github external
def test_mapped_task_with_validated_status_is_invalid(self):

        mapped_task = MappedTaskDTO()
        mapped_task.task_id = 1
        mapped_task.project_id = 1
        mapped_task.status = TaskStatus.VALIDATED.name

        # Act / Assert
        with self.assertRaises(DataError):
            mapped_task.validate()
github pylipp / financeager / test / test_period.py View on Github external
def test_invalid_base_entry_name(self):
        with self.assertRaises(DataError) as context:
            model = BaseValidationModel({"name": "", "value": 123})
            model.validate()
        self.assertListEqual(["name"], list(context.exception.errors.keys()))
github brianz / serverless-design-patterns / tests / test_cupping_model.py View on Github external
def test_cupping_invalid_cupping_score():
    with pytest.raises(DataError) as e:
        CuppingModel({
            'name': 'Tester',
            'session_id': 10,
            'scores': {
                'Aroma': 'abc',
                'Flavor': '5',
            },
            'overall_score': 88.5,
        })

    errors = prettify_schematics_errors(e)
    assert errors == {
           'scores': {
               'Aroma': "Number 'abc' failed to convert to a decimal."
            }
github hotosm / tasking-manager / server / api / users / user_apis.py View on Github external
responses:
            200:
                description: Users found
            500:
                description: Internal Server Error
        """
        try:
            query = UserSearchQuery()
            query.page = (
                int(request.args.get("page")) if request.args.get("page") else 1
            )
            query.username = request.args.get("username")
            query.mapping_level = request.args.get("level")
            query.role = request.args.get("role")
            query.validate()
        except DataError as e:
            current_app.logger.error(f"Error validating request: {str(e)}")
            return str(e), 400

        try:
            users_dto = UserService.get_all_users(query)
            return users_dto.to_primitive(), 200
        except Exception as e:
            error_msg = f"User GET - unhandled error: {str(e)}"
            current_app.logger.critical(error_msg)
            return {"error": error_msg}, 500
github Ermlab / python-ddd / application / queries.py View on Github external
def is_valid(self):
        try:
            self.validate()
        except DataError:
            return False
        return True
github hotosm / tasking-manager / server / api / organisations / resources.py View on Github external
description: Unauthorized - Invalid credentials
            402:
                description: Duplicate Name - Organisation name already exists
            500:
                description: Internal Server Error
        """
        request_user = User().get_by_id(tm.authenticated_user_id)
        if request_user.role != 1:
            return {"Error": "Only admin users can create organisations."}, 401

        try:
            organisation_dto = NewOrganisationDTO(request.get_json())
            if request_user.username not in organisation_dto.managers:
                organisation_dto.managers.append(request_user.username)
            organisation_dto.validate()
        except DataError as e:
            current_app.logger.error(f"error validating request: {str(e)}")
            return str(e), 400

        try:
            org_id = OrganisationService.create_organisation(organisation_dto)
            return {"organisationId": org_id}, 201
        except OrganisationServiceError as e:
            return str(e), 400
        except Exception as e:
            error_msg = f"Organisation PUT - unhandled error: {str(e)}"
            current_app.logger.critical(error_msg)
            return {"Error": error_msg}, 500
github hotosm / tasking-manager / server / api / project_admin_api.py View on Github external
200:
                description: Project updated
            400:
                description: Client Error - Invalid Request
            401:
                description: Unauthorized - Invalid credentials
            404:
                description: Project not found
            500:
                description: Internal Server Error
        """
        try:
            project_dto = ProjectDTO(request.get_json())
            project_dto.project_id = project_id
            project_dto.validate()
        except DataError as e:
            current_app.logger.error(f"Error validating request: {str(e)}")
            return str(e), 400

        try:
            ProjectAdminService.update_project(project_dto)
            return {"Status": "Updated"}, 200
        except InvalidGeoJson as e:
            return {"Invalid GeoJson": str(e)}, 400
        except NotFound:
            return {"Error": "Project Not Found"}, 404
        except ProjectAdminServiceError as e:
            return {"error": str(e)}, 400
        except Exception as e:
            error_msg = f"Project GET - unhandled error: {str(e)}"
            current_app.logger.critical(error_msg)
            return {"error": error_msg}, 500
github hotosm / ml-enabler / ml_enabler / api / ml.py View on Github external
version_dto.version_minor = version_array[1]
                version_dto.version_patch = version_array[2]
                version_id = MLModelVersionService.create_version(version_dto)

                prediction_id = PredictionService.create(model_id, version_id, payload)
                return {"prediction_id": prediction_id}, 200
            except DataError as e:
                current_app.logger.error(f'Error validating request: {str(e)}')
                return str(e), 400
            except Exception as e:
                error_msg = f'Unhandled error: {str(e)}'
                current_app.logger.error(error_msg)
                return {"error": error_msg}, 500
        except NotFound:
            return {"error": "model not found"}, 404
        except DataError as e:
            current_app.logger.error(f'Error validating request: {str(e)}')
            return str(e), 400
        except Exception as e:
            error_msg = f'Unhandled error: {str(e)}'
            current_app.logger.error(error_msg)
            return {"error": error_msg}, 500
github brianz / serverless-design-patterns / ch2 / serverless / cupping / handlers / helpers.py View on Github external
def create_session_from_json_payload(json_payload):
    cuppings = [CuppingModel(c) for c in json_payload.get('cuppings', ())]
    json_payload['cuppings'] = cuppings

    try:
        session_model = SessionModel(json_payload)
        session_model.validate()
        return Session.from_model(session_model)
    except DataError as e:
        errors = prettify_schematics_errors(e)
        raise InvalidInputData(errors)