Exemplo n.º 1
0
    def test_get_draft_with_cancelled_quote(self):
        """Test getting a cancelled quote with order in draft is allowed."""
        order = OrderFactory(
            quote=QuoteFactory(cancelled_on=now()),
            status=OrderStatus.DRAFT,
        )

        url = reverse(
            'api-v3:omis-public:quote:detail',
            kwargs={'public_token': order.public_token},
        )
        client = self.create_api_client(
            scope=Scope.public_omis_front_end,
            grant_type=Application.GRANT_CLIENT_CREDENTIALS,
        )
        response = client.get(url)

        quote = order.quote
        assert response.status_code == status.HTTP_200_OK
        assert response.json() == {
            'created_on': format_date_or_datetime(quote.created_on),
            'cancelled_on': format_date_or_datetime(quote.cancelled_on),
            'accepted_on': None,
            'expires_on': quote.expires_on.isoformat(),
            'content': quote.content,
            'terms_and_conditions': TermsAndConditions.objects.first().content,
        }
Exemplo n.º 2
0
    def test_basic_search_no_permissions(self, setup_es):
        """Tests model permissions enforcement in basic search for a user with no permissions."""
        user = create_test_user(permission_codenames=[], dit_team=TeamFactory())
        api_client = self.create_api_client(user=user)

        InvestmentProjectFactory(created_by=user)
        CompanyFactory()
        ContactFactory()
        EventFactory()
        CompanyInteractionFactory()
        OrderFactory()

        setup_es.indices.refresh()

        url = reverse('api-v3:search:basic')
        response = api_client.get(
            url,
            data={
                'term': '',
                'entity': 'company',
            },
        )

        assert response.status_code == status.HTTP_200_OK
        response_data = response.json()
        assert response_data['count'] == 0

        assert len(response_data['aggregations']) == 0
Exemplo n.º 3
0
    def test_permissions(self, es_with_collector, permission, permission_entity, entity):
        """
        Tests model permissions enforcement in basic search.

        TODO: we should test permissions relevant to a specific search app in the tests for that
            search app, and remove this test.
        """
        user = create_test_user(permission_codenames=[permission], dit_team=TeamFactory())
        api_client = self.create_api_client(user=user)

        InvestmentProjectFactory(created_by=user)
        CompanyFactory()
        ContactFactory()
        EventFactory()
        CompanyInteractionFactory()
        OrderFactory()

        es_with_collector.flush_and_refresh()

        url = reverse('api-v3:search:basic')
        response = api_client.get(
            url,
            data={
                'term': '',
                'entity': entity,
            },
        )

        assert response.status_code == status.HTTP_200_OK
        response_data = response.json()
        assert (response_data['count'] == 0) == (permission_entity != entity)

        assert len(response_data['aggregations']) == 1
        assert response_data['aggregations'][0]['entity'] == permission_entity
Exemplo n.º 4
0
    def test_409_if_order_in_disallowed_status(self, disallowed_status, quote_fields):
        """
        Test that if the order is not in one of the allowed statuses, the endpoint
        returns 409.
        """
        quote = QuoteFactory(**quote_fields)
        order = OrderFactory(
            status=disallowed_status,
            quote=quote,
        )

        url = reverse(
            f'api-v3:omis-public:quote:accept',
            kwargs={'public_token': order.public_token},
        )
        client = self.create_api_client(
            scope=Scope.public_omis_front_end,
            grant_type=Application.GRANT_CLIENT_CREDENTIALS,
        )
        response = client.post(url)

        assert response.status_code == status.HTTP_409_CONFLICT
        assert response.json() == {
            'detail': (
                'The action cannot be performed '
                f'in the current status {disallowed_status.label}.'
            ),
        }
    def test_validation_errors_appended(self):
        """
        Test that if a field gets more than one error during the validation,
        the errors are appended to the same list and not overridden by other validators.
        """
        order = OrderFactory()

        with mock.patch.object(
                OrderDetailsFilledInValidator,
                'get_extra_validators',
        ) as get_extra_validators:

            # trigger a second validation error on the same field
            get_extra_validators.return_value = [
                mock.Mock(side_effect=ValidationError({
                    'description': ['A different error...'],
                }), ),
            ]

            validator = OrderDetailsFilledInValidator()
            validator.set_instance(order)

            with pytest.raises(ValidationError) as exc:
                validator({
                    'description': '',
                })

            assert exc.value.detail == {
                'description': [
                    'This field is required.',
                    'A different error...',
                ],
            }
Exemplo n.º 6
0
    def test_with_minimal_address(self):
        """
        Test that if the company address doesn't have line2, county and country
        it's formatted correctly.
        """
        company = CompanyFactory(
            address_1='line 1',
            address_2='',
            address_town='London',
            address_county='',
            address_postcode='SW1A 1AA',
            address_country_id=None,
            registered_address_1='',
            registered_address_2='',
            registered_address_town='',
            registered_address_county='',
            registered_address_postcode='',
            registered_address_country_id=None,
        )
        order = OrderFactory(
            company=company,
            contact=ContactFactory(company=company),
        )
        content = generate_quote_content(
            order=order,
            expires_on=dateutil_parse('2017-05-18').date(),
        )

        assert 'line 1, London, SW1A 1AA' in content
Exemplo n.º 7
0
    def test_non_empty(self):
        """
        Test that calling GET returns the list of advisers assigned to the order.
        """
        advisers = AdviserFactory.create_batch(3)
        order = OrderFactory(assignees=[])
        for i, adviser in enumerate(advisers[:2]):
            OrderAssigneeFactory(
                order=order,
                adviser=adviser,
                estimated_time=(120 * i),
            )

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.get(url)

        assert response.status_code == status.HTTP_200_OK
        assert response.json() == [{
            'adviser': {
                'id': str(adviser.id),
                'first_name': adviser.first_name,
                'last_name': adviser.last_name,
                'name': adviser.name,
            },
            'estimated_time': (120 * i),
            'actual_time': None,
            'is_lead': False,
        } for i, adviser in enumerate(advisers[:2])]
Exemplo n.º 8
0
    def test_409_if_order_not_in_allowed_status(self, disallowed_status):
        """
        Test that if the order is not in one of the allowed statuses, the endpoint
        returns 409.
        """
        order = OrderFactory(status=disallowed_status)

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [{
                'adviser': {
                    'id': AdviserFactory().id
                },
            }],
        )

        assert response.status_code == status.HTTP_409_CONFLICT
        assert response.json() == {
            'detail':
            ('The action cannot be performed '
             f'in the current status {OrderStatus[disallowed_status]}.'),
        }
Exemplo n.º 9
0
    def test_400_if_readonly_fields_changed(self):
        """
        Test that the `actual_time` field cannot be set when the order is in draft.
        """
        order = OrderFactory(assignees=[])
        OrderAssigneeFactory(order=order, estimated_time=100, is_lead=True)
        assignee2 = OrderAssigneeFactory(order=order,
                                         estimated_time=250,
                                         is_lead=False)

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [
                {
                    'adviser': {
                        'id': assignee2.adviser.id
                    },
                    'actual_time': 200,
                },
            ],
        )

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.json() == [
            {
                'actual_time': [
                    'This field cannot be changed at this stage.',
                ],
            },
        ]
Exemplo n.º 10
0
    def test_400_if_assignee_added_with_extra_field(self, order_status, data):
        """
        Test that estimated_time, actual_time and is_lead cannot be set
        at this stage even when adding a new adviser.
        """
        order = OrderFactory(status=order_status)
        new_adviser = AdviserFactory()

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [
                {
                    'adviser': {
                        'id': new_adviser.id
                    },
                    **data,
                },
            ],
        )

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.json() == [
            {
                list(data)[0]: [
                    'This field cannot be changed at this stage.',
                ],
            },
        ]
Exemplo n.º 11
0
    def test_400_if_readonly_fields_changed(self, order_status, data):
        """
        Test that estimated_time, actual_time and is_lead cannot be set
        at this stage.
        """
        order = OrderFactory(status=order_status, assignees=[])
        assignee = OrderAssigneeFactory(order=order)

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [
                {
                    'adviser': {
                        'id': assignee.adviser.id
                    },
                    **data,
                },
            ],
        )

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.json() == [
            {
                list(data)[0]: [
                    'This field cannot be changed at this stage.',
                ],
            },
        ]
Exemplo n.º 12
0
    def test_400_popup_not_allowed(self):
        """Test popup not allowed."""
        order = OrderFactory()
        url = reverse('admin:order_order_cancel', args=(order.pk, ))

        response = self.client.get(f'{url}?{IS_POPUP_VAR}=1')
        assert response.status_code == 400
Exemplo n.º 13
0
    def test_get(self, order_status, public_omis_api_client):
        """Test a successful call to get a list of payments."""
        order = OrderFactory(status=order_status)
        PaymentFactory.create_batch(2, order=order)
        PaymentFactory.create_batch(5)  # create some extra ones not linked to `order`

        url = reverse(
            'api-v3:public-omis:payment:collection',
            kwargs={'public_token': order.public_token},
        )
        response = public_omis_api_client.get(url)

        assert response.status_code == status.HTTP_200_OK
        assert response.json() == [
            {
                'created_on': format_date_or_datetime(payment.created_on),
                'reference': payment.reference,
                'transaction_reference': payment.transaction_reference,
                'additional_reference': payment.additional_reference,
                'amount': payment.amount,
                'method': payment.method,
                'received_on': payment.received_on.isoformat(),
            }
            for payment in order.payments.all()
        ]
Exemplo n.º 14
0
 def test_order_info(self, end_to_end_notify, notify_task_return_value_tracker):
     """
     Test the order info template.
     If the template variables have been changed in GOV.UK notifications the
     celery task will be unsuccessful.
     """
     end_to_end_notify.order_info(OrderFactory(), what_happened='', why='')
     self._assert_tasks_successful(1, notify_task_return_value_tracker)
Exemplo n.º 15
0
    def test_fails_with_incomplete_fields(self, validators):
        """Test raises ValidationError if the order is incomplete."""
        validators.OrderDetailsFilledInValidator.side_effect = ValidationError(
            'error')

        order = OrderFactory()
        with pytest.raises(ValidationError):
            order.generate_quote(by=None)
Exemplo n.º 16
0
    def test_fails_if_theres_already_an_active_quote(self, validators):
        """Test raises APIConflictException if there's already an active quote."""
        validators.NoOtherActiveQuoteExistsValidator.side_effect = APIConflictException(
            'error')

        order = OrderFactory()
        with pytest.raises(APIConflictException):
            order.generate_quote(by=None)
Exemplo n.º 17
0
 def test_without_lead_assignee(self):
     """
     Test that get_lead_assignee() returns None if there are assignees
     but none of them is a lead.
     """
     order = OrderFactory(assignees=[])
     OrderAssigneeFactory(order=order, is_lead=False)
     assert not order.get_lead_assignee()
Exemplo n.º 18
0
 def test_with_lead_assignee(self):
     """
     Test that get_lead_assignee() returns the lead assignee if present.
     """
     order = OrderFactory(assignees=[])
     lead_assignee = OrderAssigneeFactory(order=order, is_lead=True)
     OrderAssigneeFactory(order=order, is_lead=False)
     assert order.get_lead_assignee() == lead_assignee
Exemplo n.º 19
0
    def test_fails_if_order_not_in_allowed_status(self, disallowed_status):
        """
        Test that if the order is in a disallowed status, the invoice details cannot be updated.
        """
        order = OrderFactory(status=disallowed_status)
        with pytest.raises(APIConflictException):
            order.update_invoice_details()

        assert order.status == disallowed_status
Exemplo n.º 20
0
    def test_ok_if_order_in_allowed_status(self, allowed_status):
        """
        Test that an order can be reopened if it's in one of the allowed statuses.
        """
        order = OrderFactory(status=allowed_status)

        order.reopen(by=AdviserFactory())

        assert order.status == OrderStatus.draft
Exemplo n.º 21
0
    def test_atomicity(self):
        """Test that if there's a problem with saving the order, the quote is not saved either."""
        order = OrderFactory()
        with mock.patch.object(order, 'save') as mocked_save:
            mocked_save.side_effect = Exception()

            with pytest.raises(Exception):
                order.generate_quote(by=None)
            assert not Quote.objects.count()
    def test_404_if_quote_doesnt_exist(self):
        """Test that if the quote doesn't exist, the endpoint returns 404."""
        order = OrderFactory()
        assert not order.quote

        url = reverse('api-v3:omis:quote:detail', kwargs={'order_pk': order.pk})
        response = self.api_client.get(url)

        assert response.status_code == status.HTTP_404_NOT_FOUND
Exemplo n.º 23
0
    def test_fails_if_order_not_in_allowed_status(self, disallowed_status):
        """
        Test that if the order is in a disallowed status, the order cannot be marked as paid.
        """
        order = OrderFactory(status=disallowed_status)
        with pytest.raises(APIConflictException):
            order.mark_as_paid(by=None, payments_data=[])

        assert order.status == disallowed_status
Exemplo n.º 24
0
    def test_403_if_not_logged_in(self):
        """Test redirect to login if the user isn't authenticated."""
        url = reverse('admin:order_order_cancel', args=(OrderFactory().pk, ))

        client = Client()
        response = client.post(url, data={})

        assert response.status_code == 302
        assert response['Location'] == self.login_url_with_redirect(url)
Exemplo n.º 25
0
    def test_with_multiple_orders(self, data_flow_api_client):
        """Test that endpoint returns correct number of record in expected order"""
        with freeze_time('2019-01-01 12:30:00'):
            order_1 = OrderFactory()
        with freeze_time('2019-01-03 12:00:00'):
            order_2 = OrderFactory()
        with freeze_time('2019-01-01 12:00:00'):
            order_3 = OrderFactory()
            order_4 = OrderFactory()

        response = data_flow_api_client.get(self.view_url)
        assert response.status_code == status.HTTP_200_OK
        response_results = response.json()['results']
        assert len(response_results) == 4
        expected_order_list = sorted([order_3, order_4],
                                     key=lambda item: item.pk) + [order_1, order_2]
        for index, order in enumerate(expected_order_list):
            assert order.reference == response_results[index]['reference']
Exemplo n.º 26
0
def test_creating_order_syncs_to_opensearch(opensearch_with_signals):
    """Test that when I create an order, it gets synced to ES."""
    order = OrderFactory()
    opensearch_with_signals.indices.refresh()

    assert opensearch_with_signals.get(
        index=OrderSearchApp.search_model.get_write_index(),
        id=order.pk,
    )
Exemplo n.º 27
0
    def test_fails_if_order_not_in_allowed_status(self, disallowed_status):
        """
        Test that if the order is in a disallowed status, the order cannot be marked as complete.
        """
        order = OrderFactory(status=disallowed_status)
        with pytest.raises(APIConflictException):
            order.complete(by=None)

        assert order.status == disallowed_status
Exemplo n.º 28
0
    def test_409_if_order_in_disallowed_status(self, disallowed_status):
        """
        Test that if the order is not in one of the allowed statuses, the endpoint
        returns 409.
        """
        order = OrderFactory(status=disallowed_status)

        url = reverse('api-v3:omis:payment:collection', kwargs={'order_pk': order.pk})
        response = self.api_client.post(url, [])
        assert response.status_code == status.HTTP_409_CONFLICT
Exemplo n.º 29
0
    def test_without_credentials(self, api_client):
        """Test that making a request without credentials returns an error."""
        order = OrderFactory()

        url = reverse(
            'api-v3:public-omis:quote:accept',
            kwargs={'public_token': order.public_token},
        )
        response = api_client.post(url, json_={})
        assert response.status_code == status.HTTP_401_UNAUTHORIZED
Exemplo n.º 30
0
    def test_no_notification_on_order_updated(self):
        """Test that no notification is triggered when saving an order."""
        order = OrderFactory()

        notify.client.reset_mock()

        order.description = 'new description'
        order.save()

        assert not notify.client.send_email_notification.called