Пример #1
0
    def test_error_is_added_given_nonempty_dict(self):
        validation_error_builder = ValidationErrorBuilder()
        field_validator_1 = FieldValidator('dummy value', TEST_FIELD_NAME,
                                           TEST_DISPLAY_NAME,
                                           validation_error_builder)
        field_validator_2 = FieldValidator('dummy value', TEST_FIELD_NAME_2,
                                           TEST_DISPLAY_NAME,
                                           validation_error_builder)

        default_message = '{} {}'.format(TEST_DISPLAY_NAME, TEST_MESSAGE)
        validation_error_builder.add_error(field_validator_1, default_message)
        validation_error_builder.add_error(field_validator_2, default_message)

        validation_errors = validation_error_builder.get().errors
        self.assertEqual(len(validation_errors), 2)
        self.assertTrue(TEST_FIELD_NAME in validation_errors)
        self.assertEqual(validation_errors[TEST_FIELD_NAME].summary_message,
                         default_message)

        self.assertEqual(validation_errors[TEST_FIELD_NAME].inline_message,
                         default_message)

        self.assertTrue(TEST_FIELD_NAME_2 in validation_errors)
        self.assertEqual(validation_errors[TEST_FIELD_NAME_2].summary_message,
                         default_message)

        self.assertEqual(validation_errors[TEST_FIELD_NAME_2].inline_message,
                         default_message)
Пример #2
0
    def test_error_is_added_with_inline_message(self):
        validation_error_builder = ValidationErrorBuilder()
        field_validator_1 = FieldValidator('dummy value',
                                           TEST_FIELD_NAME,
                                           None,
                                           validation_error_builder,
                                           inline_message=TEST_INLINE)
        field_validator_2 = FieldValidator('dummy value',
                                           TEST_FIELD_NAME_2,
                                           None,
                                           validation_error_builder,
                                           inline_message=TEST_INLINE)

        validation_error_builder.add_error(field_validator_1, TEST_MESSAGE)
        validation_error_builder.add_error(field_validator_2, TEST_MESSAGE)
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 2)
        self.assertTrue(TEST_FIELD_NAME in validation_errors)
        self.assertEqual(validation_errors[TEST_FIELD_NAME].summary_message,
                         TEST_MESSAGE)

        self.assertEqual(validation_errors[TEST_FIELD_NAME].inline_message,
                         TEST_INLINE)
        self.assertTrue(TEST_FIELD_NAME_2 in validation_errors)
        self.assertEqual(validation_errors[TEST_FIELD_NAME_2].summary_message,
                         TEST_MESSAGE)
        self.assertEqual(validation_errors[TEST_FIELD_NAME_2].inline_message,
                         TEST_INLINE)
    def test_two_factor_authentication_post_check_your_email_incorrect_code_invalid_attempts_increases(
            self, mock_datetime, mock_validator, mock_audit_api_service):
        self.mock_session.return_value.user.permissions = [
            Permissions.manage_source_information,
            Permissions.account_management
        ]
        self.mock_session.return_value.two_factor_authentication_invalid_attempts = 1
        self.mock_session.return_value.two_factor_authentication_code = 12345
        self.mock_session.return_value.two_factor_authentication_redirect_url = 'redirect-url'
        self.mock_session.return_value.\
            two_factor_authentication_generation_time = 15  # 15 minutes since epoch
        mock_datetime.now.return_value.\
            timestamp.return_value = 1200                   # 20 minutes since epoch
        mock_validator.validate.return_value = ValidationErrorBuilder()
        mock_validator.generate_invalid_code_error_message.return_value = ValidationErrorBuilder(
        )

        self.client.post(
            url_for('two_factor_authentication.post_check_your_email'),
            data={'code': '123'})

        mock_audit_api_service.audit_event.assert_called_with(
            'Invalid entry of 2FA code')
        self.assertEqual(
            self.mock_session.return_value.
            two_factor_authentication_invalid_attempts, 2)
    def validate(day, month, year):
        """Specifies which validation methods should be called for each input field.


        parameters:
            - day: The day the charge was added. This is an optional field on the form.
            - month: The month the charge was added. This is an optional field on the form.
            - year: The year the charge was added. This is an optional field on the form.

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        validation_error_builder = ValidationErrorBuilder()

        if day or month or year:
            FieldsetValidator([day, month, year], 'date', 'Date', validation_error_builder) \
                .is_valid_date()

            FieldValidator(year, "date", 'Date', validation_error_builder,
                           summary_message="Date is invalid", inline_message="Year must be in the format YYYY")\
                .is_year_format()

            FieldsetValidator([day, month, year], 'date', 'Date', validation_error_builder,
                              summary_message="Date is invalid", inline_message="Date cannot be a future date") \
                .is_past_date()

        return validation_error_builder.get()
    def validate(form):
        """Extracts value from common fields from applicant info and address_fields_partial for validation.


        parameters:
            - form: The form which includes the payment methods

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        payment_method = form.get('payment_method', '')
        payment_ref = form.get('payment_ref', '')
        no_payment_notes = form.get('no_payment_notes', '')

        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(payment_method, 'payment_method', 'Payment method', validation_error_builder,
                       inline_message='Choose one option') \
            .is_required()

        if payment_method == "govuk":
            FieldValidator(payment_ref, 'payment_ref', 'Payment reference', validation_error_builder) \
                .is_required()

        if payment_method == "none":
            FieldValidator(no_payment_notes, 'no_payment_notes', 'Explanation', validation_error_builder) \
                .is_required()

        return validation_error_builder.get()
    def test_two_factor_authentication_post_check_your_email_code_expired(
            self, mock_datetime, mock_validator, mock_audit_api_service):
        self.mock_session.return_value.user.permissions = [
            Permissions.manage_source_information,
            Permissions.account_management
        ]
        self.mock_session.return_value.two_factor_authentication_invalid_attempts = None
        self.mock_session.return_value.two_factor_authentication_code = 12345
        self.mock_session.return_value.two_factor_authentication_redirect_url = 'redirect-url'
        self.mock_session.return_value.\
            two_factor_authentication_generation_time = 5  # 5 minutes since epoch
        mock_datetime.now.return_value.\
            timestamp.return_value = 1200                  # 20 minutes since epoch
        mock_validator.validate.return_value = ValidationErrorBuilder()
        invalid_code_error = ['invalid code error']
        errors = ValidationErrorBuilder()
        errors.errors['code'] = invalid_code_error
        mock_validator.generate_invalid_code_error_message.return_value = errors

        response = self.client.post(
            url_for('two_factor_authentication.post_check_your_email'),
            data={'code': '12345'})

        mock_audit_api_service.audit_event.assert_called_with(
            'Invalid entry of 2FA code')
        self.assertTrue(
            mock_validator.generate_invalid_code_error_message.called)
        self.assertEqual(
            self.mock_session.return_value.
            two_factor_authentication_invalid_attempts, 1)
        self.assertTrue(self.mock_session.return_value.commit_2fa_state.called)
        self.assert_context('validation_errors', errors.errors)
        self.assertTemplateUsed('check_your_email.html')
        self.assertStatus(response, 400)
    def generate_invalid_code_error_message():
        validation_error_builder = ValidationErrorBuilder()
        validation_error_builder.add_error(TwoFactorAuthenticationValidator,
                                           'Invalid security code')
        validation_errors = validation_error_builder.get()

        return validation_errors
Пример #8
0
    def validate(confirmation, action):
        """Specifies which validation methods should be called for each input FieldValidator.


        parameters:
            - confirmation: Whether the user acknowledges they are permitted to add the charge.

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        validation_error_builder = ValidationErrorBuilder()

        if action == 'update':
            summary_message_text = 'Confirm that you have the authority to update this charge'
        elif action == 'cancel':
            summary_message_text = 'Confirm that you have the authority to cancel this charge'

        FieldValidator(confirmation, 'location-confirmation', None, validation_error_builder,
                       summary_message=summary_message_text,
                       inline_message='If the charge is in your authority, tick and continue. '
                                      'If the charge is in another authority, get permission from that authority.') \
            .is_required()

        return validation_error_builder.get()
Пример #9
0
    def validate(form):
        """Extracts postcode and land description for validation.


        parameters:
            - form: The form which includes Yes/No radio buttons, postcode, and land description

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        have_address = form.get('have_address', '')
        charge_geographic_description = form.get(
            'charge_geographic_description', '')

        validation_error_builder = ValidationErrorBuilder()

        if have_address == 'No':
            FieldValidator(charge_geographic_description, 'charge_geographic_description', None,
                           validation_error_builder,
                           summary_message='Location is required',
                           inline_message='Location is required') \
                .is_required()

        return validation_error_builder.get()
    def validate(location_info, has_address):
        validation_error_builder = ValidationErrorBuilder()

        if has_address == 'ProvideAddress':
            FieldValidator(location_info, 'search_term', 'Charge Address', validation_error_builder,
                           summary_message='Choose an address',
                           inline_message='Search for a different postcode if the address you need is not listed.') \
                .is_required()

        elif has_address == 'No':
            FieldValidator(location_info, 'charge-geographic-description',
                           'Charge Geographic Description', validation_error_builder,
                           summary_message='Describe the search area',
                           inline_message='Explain where you want to search without an address. '
                                          'For example, use a nearby landmark as a reference point. ') \
                .is_required()

            FieldValidator(location_info, 'charge-geographic-description',
                           'Charge Geographic Description', validation_error_builder,
                           summary_message='Answer is too long',
                           inline_message='Reduce your answer to 1000 characters or less') \
                .is_length_less_than_or_equal_to(1000)

        else:
            FieldValidator(has_address, 'address-from-group', 'Choose one option',
                           validation_error_builder,
                           summary_message='Choose one option') \
                .is_required()

        validation_errors = validation_error_builder.get()

        return validation_errors
    def test_is_required_with_invalid_input(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator(INVALID_FIELD_SET, VALID_FIELD_NAME, VALID_DISPLAY_NAME, validation_error_builder) \
            .is_required()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 1)
        self.assertTrue(VALID_FIELD_NAME in validation_errors)
    def validate(land_compensation_paid, amount_of_compensation, vary_action):
        """Specifies which validation methods should be called for each input field.


        parameters:
            - land_compensation_paid: Part of the compensation (paid in advance)
            - amount_of_compensation: The total amount of compensation payable
            to the landowner from which the land was acquired.

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(land_compensation_paid, 'land-compensation-paid', 'Advance payment amount',
                       validation_error_builder, summary_message='Enter the advance payment',
                       inline_message='This is part of the compensation (paid in advance)') \
            .is_required()

        if not vary_action:
            FieldValidator(amount_of_compensation, 'amount-of-compensation', 'Total compensation amount',
                           validation_error_builder, summary_message='Enter the total compensation',
                           inline_message='This is the total compensation') \
                .is_required()

            FieldValidator(amount_of_compensation, 'amount-of-compensation', 'Total compensation amount',
                           validation_error_builder,
                           summary_message='Compensation must be a positive number',
                           inline_message='Compensation must be a positive number')\
                .is_positive_number()

            FieldValidator(land_compensation_paid, 'land-compensation-paid', 'Advance payment amount',
                           validation_error_builder,
                           summary_message='Advance payment cannot be more than total compensation',
                           inline_message='Advance payment cannot be more than total compensation')\
                .is_less_than_or_equal_to(amount_of_compensation)

            FieldValidator(amount_of_compensation, 'amount-of-compensation', 'Total compensation amount',
                           validation_error_builder,
                           summary_message='Compensation payment can only have 2 numbers after the decimal place',
                           inline_message='Compensation payment can only have 2 numbers after the decimal place')\
                .is_number_with_zero_or_x_decimal_places(2)

        FieldValidator(land_compensation_paid, 'land-compensation-paid', 'Advance payment amount',
                       validation_error_builder,
                       summary_message='Advance payment must be a positive number',
                       inline_message='Advance payment must be a positive number')\
            .is_positive_number()

        FieldValidator(land_compensation_paid, 'land-compensation-paid', 'Advance payment amount',
                       validation_error_builder,
                       summary_message='Advance payment can only have 2 numbers after the decimal place',
                       inline_message='Advance payment can only have 2 numbers after the decimal place')\
            .is_number_with_zero_or_x_decimal_places(2)

        return validation_error_builder.get()
    def validate(shapefile, existing_geometries, already_uploaded):
        """Specifies which validation methods should be called for each input field.


        parameters:
            - shapefile: The contents of the file the user has uploaded
            - existing_geometries: A collection of features already drawn/uploaded by the user
            - already_uploaded: True if user has clicked upload button multiple times and session has been updated

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(shapefile, 'shapefile-input', 'shapefile-input', validation_error_builder,
                       summary_message="Upload a file",
                       inline_message="Upload a file") \
            .is_required()

        FieldValidator(shapefile, 'shapefile-input', 'shapefile-input', validation_error_builder,
                       summary_message="File is bigger than 1MB",
                       inline_message="Upload a smaller file") \
            .is_uploaded_filesize_less_than_bytes(1000000)

        if already_uploaded:
            all_extents = existing_geometries['features'] \
                if existing_geometries and 'features' in existing_geometries \
                else []
        else:
            shapefile_contents = []

            try:
                with fiona.drivers():
                    with fiona.BytesCollection(shapefile.read()) as shpfile:
                        for shape in shpfile:
                            shapefile_contents.append(shape)
                shapefile.seek(0)
            except Exception:
                pass

            FieldValidator(shapefile_contents, 'shapefile-input', 'shapefile-input', validation_error_builder,
                           summary_message="File not uploaded",
                           inline_message="Upload a different file") \
                .is_required()

            if existing_geometries and 'features' in existing_geometries:
                all_extents = shapefile_contents + existing_geometries[
                    'features']
            else:
                all_extents = shapefile_contents

        FieldValidator(all_extents, 'shapefile-input', 'shapefile-input', validation_error_builder,
                       inline_message="Too many extents",
                       summary_message="Number of extents must be 500 (or fewer)") \
            .is_length_less_than_or_equal_to(500)

        return validation_error_builder.get()
    def test_is_past_date_with_future_date(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator([VALID_DAY, VALID_MONTH, VALID_FUTURE_YEAR], VALID_FIELD_NAME, VALID_DISPLAY_NAME,
                          validation_error_builder) \
            .is_past_date()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 1)
        self.assertTrue(VALID_FIELD_NAME in validation_errors)
    def test_is_phone_number_doesnt_add_error_when_phone_valid(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(VALID_PHONE, 'phoneNumber', 'Phone number',
                       validation_error_builder) \
            .is_phone_number()
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('phoneNumber' not in validation_errors)
    def test_is_valid_date_adds_error_when_date_invalid(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator([VALID_DAY, VALID_MONTH], VALID_FIELD_NAME, VALID_DISPLAY_NAME,
                          validation_error_builder) \
            .is_valid_date()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 1)
        self.assertTrue(VALID_FIELD_NAME in validation_errors)
    def test_is_valid_date_does_not_add_error_when_date_valid(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator([VALID_DAY, VALID_MONTH, VALID_PAST_YEAR], VALID_FIELD_NAME, VALID_DISPLAY_NAME,
                          validation_error_builder) \
            .is_valid_date()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 0)
        self.assertTrue(VALID_FIELD_NAME not in validation_errors)
    def test_is_less_than_length_same_value(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(TEN_CHARS, 'username', 'Username',
                       validation_error_builder) \
            .is_length_less_than_or_equal_to(10)
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('username' not in validation_errors)
    def test_has_enough_fields_populated_equal(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator([VALID_DATA, VALID_DATA, EMPTY_STRING, EMPTY_STRING], VALID_FIELD_NAME, VALID_DISPLAY_NAME,
                          validation_error_builder) \
            .has_enough_fields_populated(2)
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 0)
        self.assertTrue(VALID_FIELD_NAME not in validation_errors)
    def test_is_future_date_with_current_date(self):
        validation_error_builder = ValidationErrorBuilder()
        FieldsetValidator([CURRENT_DAY, CURRENT_DAY, CURRENT_DAY], VALID_FIELD_NAME, VALID_DISPLAY_NAME,
                          validation_error_builder) \
            .is_future_date()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 1)
        self.assertTrue(VALID_FIELD_NAME in validation_errors)
    def test_is_length_equal_to_false(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(TEN_CHARS, 'username', 'Username',
                       validation_error_builder) \
            .is_length_equal_to(9)
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('username' in validation_errors)
    def test_is_int_does_add_error_when_invalid(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator("123.5", 'testfield', 'Test Field',
                       validation_error_builder) \
            .is_int()
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('testfield' in validation_errors)
    def test_is_positive_or_zero_does_add_error_when_invalid(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator("-12345", 'testfield', 'Test Field',
                       validation_error_builder) \
            .is_positive_number_or_zero()
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('testfield' in validation_errors)
    def test_is_item_not_in_list_does_add_error_when_invalid(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator("def", 'testfield', 'Test Field',
                       validation_error_builder) \
            .is_item_not_in_list(["def"])
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('testfield' in validation_errors)
    def test_is_item_count_equal_to(self):
        list_set = [1, 2]
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(list_set, 'a', 'b',
                       validation_error_builder) \
            .is_item_count_equal_to(2)
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(len(validation_errors), 0)
    def test_is_email_adds_error_when_email_invalid(self):
        validation_error_builder = ValidationErrorBuilder()
        email = 'invalid email'

        FieldValidator(email, 'email', email, validation_error_builder) \
            .is_email()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(validation_errors['email'].summary_message,
                         'invalid email is not a valid email address')
    def test_is_required_doesnt_add_error_when_input_provided(self):
        validation_error_builder = ValidationErrorBuilder()
        username = '******'

        FieldValidator(username, 'username', 'Username',
                       validation_error_builder) \
            .is_required()
        validation_errors = validation_error_builder.get().errors

        self.assertTrue('username' not in validation_errors)
    def test_is_phone_number_adds_error_when_phone_invalid_non_numeric(self):
        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(INVALID_PHONE_NON_NUMERIC, 'phoneNumber', 'Phone number',
                       validation_error_builder) \
            .is_phone_number()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(validation_errors['phoneNumber'].summary_message,
                         'Phone number is not a valid phone number')
    def validate(amount_secured, interest_paid_indicator, interest_rate):
        """Specifies which validation methods should be called for each input field.


        parameters:
            - amount_secured: The amount secured
            - interest_paid_indicator: Indicates if interest will be paid on the amount.
            - interest_rate: The interest rate.

        returns:
            dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message.
        """

        validation_error_builder = ValidationErrorBuilder()

        FieldValidator(amount_secured,
                       'amount-secured',
                       'Amount originally secured',
                       validation_error_builder,
                       summary_message='Amount is required',
                       inline_message=
                       "If you don't know the amount, go back and choose 'No'"
                       ).is_required()

        FieldValidator(amount_secured, 'amount-secured', 'Amount originally secured', validation_error_builder,
                       summary_message='Amount must be a positive number with up to 2 decimal places',
                       inline_message='Amount must be a positive number with up to 2 decimal places, for example '
                                      '100 or 100.10')\
            .is_number_with_zero_or_x_decimal_places(2)

        FieldValidator(amount_secured, 'amount-secured', 'Amount originally secured', validation_error_builder,
                       summary_message='Amount cannot have more than 13 characters before the decimal point',
                       inline_message='Amount must be shorter than 13 characters') \
            .is_number_x_length_y_decimal_places(13, 2)

        FieldValidator(interest_paid_indicator,
                       'interest-paid-indicator',
                       'Interest paid',
                       validation_error_builder,
                       summary_message='Choose one option',
                       inline_message='Choose one option').is_required()

        if interest_paid_indicator == 'Yes':

            FieldValidator(interest_rate, 'interest-rate', 'Interest rate', validation_error_builder,
                           summary_message='Interest is required',
                           inline_message="Interest is the authority's borrowing rate or other agreed rate")\
                .is_required()

            FieldValidator(interest_rate, 'interest-rate', 'Interest rate', validation_error_builder,
                           summary_message='Interest rate cannot have more than 70 characters',
                           inline_message='Interest rate must be shorter than 70 characters') \
                .is_length_less_than_or_equal_to(70)

        return validation_error_builder.get()
    def test_is_required_adds_error_when_input_empty(self):
        validation_error_builder = ValidationErrorBuilder()
        username = ''

        FieldValidator(username, 'username', 'Username',
                       validation_error_builder) \
            .is_required()
        validation_errors = validation_error_builder.get().errors

        self.assertEqual(validation_errors['username'].summary_message,
                         'Username is required')