示例#1
0
    def create_transaction(self, sow, to_location, initiator=None, date=None):
        if isinstance(to_location.get_location,
                      SowAndPigletsCell) and not to_location.is_sow_empty:
            raise DjangoValidationError(message='Клетка №{} не пустая'. \
                format(to_location.sowAndPigletsCell.number))

        if not date:
            date = timezone.now()

        transaction = self.create(date=date,
                                  initiator=initiator,
                                  from_location=sow.location,
                                  to_location=to_location,
                                  sow=sow,
                                  tour=sow.tour,
                                  sow_status=sow.status,
                                  sow_group=sow.sow_group)

        if sow.status and (sow.status.title == 'Опоросилась'
                           or sow.status.title
                           == 'Отъем') and to_location.workshop:
            if to_location.workshop.number == 1 and sow.location.sowAndPigletsCell:
                sow.tour = None
                sow.change_status_to('Ожидает осеменения')

        if sow.status and sow.status.title != 'Супорос 35' and to_location.workshop:
            if to_location.workshop.number == 3 and sow.location.workshop and \
                sow.location.workshop.number in [1, 2]:
                raise DjangoValidationError(
                    message=f'Свиноматка №{sow.farm_id} не супорос')

        sow.change_sow_current_location(to_location)

        return transaction
示例#2
0
def get_week_interval(value):
    """
    Validate weekly interval parameters.

    Note: Raises Django ValidationError on incorrect data - this function is
    used both for validation and deriving the relevant interval.
    """
    # Data type, and presence checks
    try:
        isoweek = int(value['isoweek'])
        isoyear = int(value['isoyear'])
    except (ValueError, TypeError):
        msg = '"isoweek" and/or "isoyear" parameters are invalid.'
        raise DjangoValidationError(msg)
    except KeyError:
        raise DjangoValidationError('Missing parameter(s) for weekly interval.')

    # Value checks
    monday = f'{isoyear} {isoweek} 1'
    try:
        begin_date = datetime.datetime.strptime(monday, '%G %V %u').date()
    except ValueError:
        msg = f'isoweek={isoweek} and/or isoyear={isoyear} parameters are invalid.'
        raise DjangoValidationError(msg)

    t_begin = datetime.datetime.combine(begin_date, datetime.datetime.min.time())
    t_end = t_begin + relativedelta(days=7)

    return t_begin, t_end
示例#3
0
def get_month_interval(value):
    """
    Validate monthly interval parameters.

    Note: Raises Django ValidationError on incorrect data - this function is
    used both for validation and deriving the relevant interval.
    """
    # Data type, and presence checks
    try:
        month = int(value['month'])
        year = int(value['year'])
    except (ValueError, TypeError):
        msg = '"month" and/or "year" parameters are invalid.'
        raise DjangoValidationError(msg)
    except KeyError:
        raise DjangoValidationError('Missing parameter(s) for weekly interval.')

    # Value checks
    try:
        first_of_month = datetime.date(year, month, 1)
    except ValueError:
        msg = f'month={month} and/or year={year} parameters are invalid.'
        raise DjangoValidationError(msg)
    first_of_next_month = first_of_month + relativedelta(months=1)

    t_begin = datetime.datetime.combine(first_of_month, datetime.datetime.min.time())
    t_end = datetime.datetime.combine(first_of_next_month, datetime.datetime.min.time())

    return t_begin, t_end
示例#4
0
    def to_python(self, value):
        if value in self.empty_values:
            return None

        try:
            obj = json.loads(value)
        except JSONDecodeError:
            raise DjangoValidationError(
                self.default_error_messages["invalid_json"],
                code="invalid_json")

        if set(obj) != {"max_distance", "coordinates"}:
            raise DjangoValidationError(
                self.default_error_messages["invalid_fields"],
                code="invalid_fields")

        max_distance = obj["max_distance"]
        coordinates = obj["coordinates"]

        try:
            max_distance = float(max_distance)
        except ValueError:
            raise DjangoValidationError(
                self.default_error_messages["invalid_max_distance"],
                code="invalid_max_distance",
            )

        if not check_coordinates(coordinates):
            raise DjangoValidationError(
                self.default_error_messages["invalid_coordinates"],
                code="invalid_coordinates",
            )

        return Point(*coordinates), Distance(m=max_distance)
示例#5
0
    def to_python(self, value):
        if value in self.empty_values:
            return None

        try:
            obj = json.loads(value)
        except JSONDecodeError:
            raise DjangoValidationError(self.default_error_messages['invalid_json'], code='invalid_json')

        if set(obj) != {'max_distance', 'coordinates'}:
            raise DjangoValidationError(self.default_error_messages['invalid_fields'], code='invalid_fields')

        max_distance = obj['max_distance']
        coordinates = obj['coordinates']

        try:
            max_distance = float(max_distance)
        except ValueError:
            raise DjangoValidationError(self.default_error_messages['invalid_max_distance'], code='invalid_max_distance')


        if not check_coordinates(coordinates):
            raise DjangoValidationError(self.default_error_messages['invalid_coordinates'], code='invalid_coordinates')

        return Point(*coordinates), Distance(m=max_distance)
示例#6
0
    def test_django_exception_with_multiple_messages(self):
        error = DjangoValidationError([
            DjangoValidationError("Some invalid data"),
            DjangoValidationError("Another invalid field"),
        ])
        response = exception_handler(error, Mock())

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.data['non_field_errors'] == [
            "Some invalid data",
            "Another invalid field",
        ]
示例#7
0
def test_reraise_django_validation_error():
    with pytest.raises(ValidationError) as excinfo:
        with reraise_django_validation_errors():
            raise DjangoValidationError('derp')

    assert excinfo.value.args[0] == 'derp'
    assert excinfo.value.message == 'derp'

    with pytest.raises(ValidationError) as excinfo:
        with reraise_django_validation_errors():
            raise DjangoValidationError({'foo': ['derp']})

    assert excinfo.value.message_dict == {'foo': ['derp']}
示例#8
0
    def full_clean(self, *args, **kwargs):
        """ Добавлена логика проверки размеров
        изображения при добавлении через админку
        """
        super().full_clean(*args, **kwargs)

        if not self.check_size_image():
            raise DjangoValidationError(
                f'Размер изображения должен быть не менее {self.image_min_h}'
                f'x{self.image_min_w} пикселей')
        if not self.check_size_thumb():
            raise DjangoValidationError(
                f'Размер миниатюры должен быть не менее {self.thumb_min_h}'
                f'x{self.thumb_min_w} пикселей')
    def clean(self):
        # Rule 1. If return date is in past
        if not self.returned_date.date() > datetime.today().date():
            raise DjangoValidationError({
                'returned_date':
                _('Return cannot be borrowed from past date')
            })

        # Rule 2. If return date smaller than date borrowed
        if self.returned_date < self.book_borrowed.date_borrowed:
            raise DjangoValidationError({
                'returned_date':
                _('Returned date must be not be ahead of borrowed')
            })
示例#10
0
    def claim_service(self, request, *args, **kwargs):
        try:
            with atomic():
                if request.user.groups.filter(name='Providers').exists():
                    user = request.user
                else:
                    try:
                        user = get_user_model().objects.create_user(
                            email=request.data['email'],
                            password=get_user_model(
                            ).objects.make_random_password(),
                            is_active=False)
                    except DjangoValidationError:
                        raise DjangoValidationError(
                            'User with this email exists')
                    provider_group, _ = Group.objects.get_or_create(
                        name='Providers')
                    user.groups.add(provider_group)

                # Create or update Provider
                data = dict(request.data, user=user.get_api_url())
                if hasattr(user, 'provider'):
                    serializer = ProviderSerializer(
                        user.provider, data=data, context={'request': request})
                else:
                    serializer = ProviderSerializer(
                        data=data, context={'request': request})
                try:
                    serializer.is_valid(raise_exception=True)
                except DRFValidationError:
                    raise DjangoValidationError(
                        'All fields needs to be filled.')
                serializer.save()
                headers = self.get_success_headers(serializer.data)
                service = Service.objects.get(id=request.data['service_id'])
                user.send_activation_email_to_staff(request, service,
                                                    serializer.instance)
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED,
                                headers=headers)
        except DjangoValidationError as ex:
            return Response('; '.join(ex.messages),
                            status=status.HTTP_400_BAD_REQUEST)
        except Exception as ex:
            logger.error(
                'There was an error during claim',
                exc_info=True,
            )
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)
    def clean(self):
        # Rule 1. If books are not available raise error
        if not self.book.available_books > 0:
            raise DjangoValidationError(
                {'book': _('There are no books available at the moment')})

        # Rule 2. If book borrowed date is in past
        if self.date_borrowed.day > datetime.today().day:
            raise DjangoValidationError(
                {'date_borrowed': _('Book cannot be borrowed from past date')})

        # Rule 3. If return date is smaller that borrowed date
        if self.return_date < self.date_borrowed:
            raise DjangoValidationError(
                {'return_date': _('Return date must be not be in past')})
示例#12
0
    def prepare_for_double_semenation(self):
        if self.location.get_workshop.number != 1:
            raise DjangoValidationError(message='Свиноматка не в Цехе 1.')

        if self.tour or not self.alive:
            self.tour = None
            self.change_status_to('Ожидает осеменения')
示例#13
0
 def create_or_return_then_assing_farm_id(self,
                                          farm_id,
                                          birth_id=None,
                                          initiator=None):
     sow = self.get_queryset_with_not_alive().filter(
         farm_id=farm_id).first()
     if not sow:
         sow = self.filter(farm_id__isnull=True,
                           location__workshop__number__in=[1]).first()
         if sow:
             sow.assing_farm_id(farm_id=farm_id, birth_id=birth_id)
             AssingFarmIdEvent.objects.create_event(sow=sow,
                                                    assing_type='gilt',
                                                    farm_id=farm_id,
                                                    birth_id=sow.birth_id)
         else:
             raise DjangoValidationError(
                 message=
                 f'Больше нет ремонтных свинок в Цехе 1. Переведите из Цеха 2'
             )
             # sow = self.create_new_and_put_in_workshop_one(farm_id=farm_id, birth_id=birth_id)
             # AssingFarmIdEvent.objects.create_event(sow=sow, assing_type='nowhere',
             #     farm_id=farm_id, birth_id=birth_id)
     else:
         if not sow.birth_id:
             sow.birth_id = birth_id
             sow.save()
     return sow
示例#14
0
def uuid_validator(value):
    try:
        uuid.UUID(value)
    except ValueError:
        raise DjangoValidationError('%(value)s is not a valid UUID.',
                                    code='invalid',
                                    params={'value': value})
示例#15
0
    def filter_date_with_accuracy(self, qs, value):
        match = re.fullmatch(r'\d{4}', value)
        if match:
            return self.get_method(qs)(**{
                f'{self.field_name}__year': int(value)
            })

        match = re.fullmatch(r'(\d{4})-(\d{1,2})', value)
        if match:
            year = int(match[1])
            month = int(match[2])
            if not 1 <= month <= 12:
                raise DjangoValidationError(
                    {self.field_name: _('Wrong month: %s') % month})
            params = {
                f'{self.field_name}__year': year,
                f'{self.field_name}__month': month,
            }
            if self.accuracy_choices:
                params[f'{self.field_name}_accuracy__in'] = (
                    self.accuracy_choices.EXACT.value,
                    self.accuracy_choices.MONTH.value,
                )
            return self.get_method(qs)(**params)
        try:
            params = {self.field_name: value}
            if self.accuracy_choices:
                params[
                    f'{self.field_name}_accuracy'] = self.accuracy_choices.EXACT.value
            return self.get_method(qs)(**params)
        except DjangoValidationError as e:
            e.error_dict = {self.field_name: e.message % {'value': value}}
            raise
示例#16
0
 def validate(self, password, user=None):
     # pylint: disable=unused-argument
     if not len(re.findall(r"\d", password)) >= self.min:
         raise DjangoValidationError(
             _(f"This password must contain at least {self.min} digit(s), 0-9."
               ),
             code="password_no_number",
         )
示例#17
0
    def clean(self, value):
        # check string format (only numbers and the '.' character

        if not re.match(r'^([0-9]\.?)+$', value):
            msg = "Versions must be of the format 'major.minor.patch'"
            raise DjangoValidationError(msg)

        return value
示例#18
0
    def test_error_with_messages(self):
        error = DjangoValidationError([
            DjangoValidationError('First message'),
            DjangoValidationError('Second message')
        ])

        self.assertFalse(hasattr(error, 'message'))
        self.assertTrue(hasattr(error, 'messages'))
        self.assertEqual(len(error.messages), 2)
        self.assertEqual(error.messages[0], 'First message')
        self.assertEqual(error.messages[1], 'Second message')

        converted_error = convert_validation_error(error)

        self.assertEqual(len(converted_error.detail), 2)
        self.assertEqual(converted_error.detail[0], 'First message')
        self.assertEqual(converted_error.detail[1], 'Second message')
示例#19
0
 def validate(self, password, user=None):
     # pylint: disable=unused-argument
     if not len(
             re.findall(r"[()[\]{}|\\`~!@#$%^&*_\-+=;:'\",<>./?]",
                        password)) >= self.min:
         raise DjangoValidationError(
             _(f"This password must contain at least {self.min} symbol: {self.symbols}"
               ), )
示例#20
0
 def validate(self, password, user=None):
     # pylint: disable=unused-argument
     if not len(re.findall(r"[a-z]", password)) >= self.min:
         raise DjangoValidationError(
             _(f"This password must contain at least {self.min} lowercase letter, a-z."
               ),
             code="password_no_lower",
         )
示例#21
0
 def test_django_validation_error(self):
     error = "This is an error."
     response = custom_exception_handler(
         exc=DjangoValidationError(error),
         context={},
     )
     self.assertEqual(response.data,
                      {"non_field_errors": ["This is an error."]})
示例#22
0
def validate_group_hptuning_config(config, raise_for_rest=False):
    try:
        HPTuningConfig.from_dict(config)
    except MarshmallowValidationError as e:
        if raise_for_rest:
            raise ValidationError(e)
        else:
            raise DjangoValidationError(e)
示例#23
0
    def test_function_returns_dict_for_django_validation_error(self):
        message = '@ must be in email address'
        exc = DjangoValidationError(message)
        detail = get_validation_error_detail(exc)

        self.assertIsInstance(detail, dict)
        self.assertIn('non_field_errors', detail.keys())
        self.assertEqual(detail['non_field_errors'][0], message)
示例#24
0
def validate_group_params_config(config, raise_for_rest=False):
    try:
        SettingsConfig.from_dict(config)
    except MarshmallowValidationError as e:
        if raise_for_rest:
            raise ValidationError(e)
        else:
            raise DjangoValidationError(e)
示例#25
0
 def validate_data(self, input_email):
     if CtrlfUser.objects.filter(email=input_email).exists():
         raise ValidationError("이미 존재하는 이메일 입니다.", code=status.HTTP_404_NOT_FOUND)
     try:
         validate_email(input_email)
     except DjangoValidationError:
         raise DjangoValidationError("이메일 형식이 유효하지 않습니다.", code=status.HTTP_400_BAD_REQUEST)
     return input_email
示例#26
0
def is_there_single_tour_in_file(rows):
    tour = rows[0][3]

    for row in rows:
        if row[3] != tour:
            raise DjangoValidationError(message='В файле несколько туров.')

    return True
示例#27
0
    def test_error_with_message(self):
        error = DjangoValidationError('A message')

        self.assertTrue(hasattr(error, 'message'))
        self.assertTrue(hasattr(error, 'messages'))
        self.assertEqual(error.message, 'A message')
        self.assertEqual(error.messages[0], 'A message')

        converted_error = convert_validation_error(error)
        self.assertEqual(converted_error.detail[0], 'A message')
示例#28
0
 def verify_pass(self, data):
     pass1 = data.get('password1')
     pass2 = data.get('password2')
     if pass1 or pass2:
         if pass1 != pass2:
             raise DjangoValidationError('Transport authentication passwords do not match')
         data['password'] = base64.b64decode(pass1).decode('utf-8') if re.match(r'^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$', pass1) else pass1
         del data['password1']
         del data['password2']
     return data
示例#29
0
    def validate_body(self, body):
        """
        Do some basic picture checks on request body and files.
        Obviously these values can be spoofed, so checks on
        file extension and MIME type etc are just to "fail fast".
        We will check the files _properly_ in the lambda hook.
        """
        try:
            UploadRequestSchema().load(body)
        except MarshmallowValidationError as e:
            # for now, log the error and body to sentry
            # so we've got visibility on errors
            logger.error(f"{e}\n{body}")

            raise DjangoValidationError("Request body did not match schema")

        files = body["files"]
        if len(files) == 2 and files[0]["name"] == files[1]["name"]:
            raise DjangoValidationError("Files must have different names")
示例#30
0
def validate_outputs_config(config, raise_for_rest=False):
    if not config:
        return None
    try:
        OutputsConfig.from_dict(config)
    except MarshmallowValidationError as e:
        if raise_for_rest:
            raise ValidationError(e)
        else:
            raise DjangoValidationError(e)