예제 #1
0
    def test_decimal_number_invalid(self):
        validator = DecimalPlaces(2)

        mock_form = Mock()
        mock_field = Mock()
        mock_field.raw_data = ['1.234']

        with self.assertRaises(ValidationError) as ite:
            validator(mock_form, mock_field)

        error_message = error_messages['INVALID_DECIMAL'] % dict(max=2)
        self.assertEqual(error_message, str(ite.exception))
예제 #2
0
def get_number_field(answer, label, guidance, error_messages, answer_store):
    answer_errors = error_messages.copy()

    if 'validation' in answer and 'messages' in answer['validation']:
        for error_key, error_message in answer['validation']['messages'].items():
            answer_errors[error_key] = error_message

    mandatory_or_optional = get_mandatory_validator(answer, answer_errors, 'MANDATORY_NUMBER')

    max_decimals = answer.get('decimal_places', 0)
    if max_decimals > MAX_DECIMAL_PLACES:
        raise Exception('decimal_places: {} > system maximum: {} for answer id: {}'
                        .format(max_decimals, MAX_DECIMAL_PLACES, answer['id']))

    min_value, minimum_exclusive = get_schema_defined_limit(answer['id'], answer.get('min_value'), answer_store)
    if min_value is None:
        min_value = 0
    if min_value < MIN_NUMBER:
        raise Exception('min_value: {} < system minimum: {} for answer id: {}'
                        .format(min_value, MIN_NUMBER, answer['id']))

    max_value, maximum_exclusive = get_schema_defined_limit(answer['id'], answer.get('max_value'), answer_store)
    if max_value is None:
        max_value = MAX_NUMBER

    if max_value > MAX_NUMBER:
        raise Exception('max_value: {} > system maximum: {} for answer id: {}'
                        .format(max_value, MAX_NUMBER, answer['id']))

    if min_value > max_value:
        raise Exception('min_value: {} > max_value: {} for answer id: {}'.format(min_value, max_value, answer['id']))

    validate_with = mandatory_or_optional + [
        NumberCheck(answer_errors['INVALID_NUMBER']),
        NumberRange(minimum=min_value, minimum_exclusive=minimum_exclusive,
                    maximum=max_value, maximum_exclusive=maximum_exclusive,
                    messages=answer_errors, currency=answer.get('currency')),
        DecimalPlaces(max_decimals=max_decimals, messages=answer_errors),
    ]

    if max_decimals > 0:
        return CustomDecimalField(
            label=label,
            validators=validate_with,
            description=guidance,
        )
    return CustomIntegerField(
        label=label,
        validators=validate_with,
        description=guidance,
    )