def test_success(self): """Test that a quote can be generated.""" company = CompanyFactory( registered_address_1='Reg address 1', registered_address_2='Reg address 2', registered_address_town='Reg address town', registered_address_county='Reg address county', registered_address_postcode='Reg address postcode', registered_address_country_id=constants.Country.japan.value.id, ) order = OrderFactory( company=company, billing_company_name='', billing_contact_name='', billing_email='', billing_phone='', billing_address_1='', billing_address_2='', billing_address_town='', billing_address_county='', billing_address_postcode='', billing_address_country_id=None, ) adviser = AdviserFactory() order.generate_quote(by=adviser) # quote created and populated assert order.quote.pk assert order.quote.reference assert order.quote.content assert order.quote.created_by == adviser # status changed assert order.status == OrderStatus.quote_awaiting_acceptance assert not order.billing_contact_name assert not order.billing_email assert not order.billing_phone # billing fields populated assert order.billing_company_name == company.name assert order.billing_address_1 == company.registered_address_1 assert order.billing_address_2 == company.registered_address_2 assert order.billing_address_county == company.registered_address_county assert order.billing_address_town == company.registered_address_town assert order.billing_address_postcode == company.registered_address_postcode assert order.billing_address_country == company.registered_address_country
def test_without_committing(self): """ Test that if udpate_order_pricing is called without committing, the order model is changed but not the db. """ order = OrderFactory(vat_status=VATStatus.UK) orig_total_cost = order.total_cost # change order and recalculate pricing without saving order.vat_status = VATStatus.OUTSIDE_EU update_order_pricing(order, commit=False) assert order.total_cost != orig_total_cost # refresh and check that it hasn't changed order.refresh_from_db() assert order.total_cost == orig_total_cost
def test_with_commit(self): """ Test that if udpate_order_pricing is called with commit = True, the order model is changed and the db as well. """ order = OrderFactory(vat_status=VATStatus.uk) orig_total_cost = order.total_cost # change order and recalculate pricing without saving order.vat_status = VATStatus.outside_eu update_order_pricing(order, commit=True) assert order.total_cost != orig_total_cost # refresh and check that it changed order.refresh_from_db() assert order.total_cost != orig_total_cost
def test_create(self, order_status): """Test a successful call to create a list of payments.""" order = OrderFactory(status=order_status) url = reverse('api-v3:omis:payment:collection', kwargs={'order_pk': order.pk}) response = self.api_client.post( url, [ { 'transaction_reference': 'some ref1', 'amount': 1, 'received_on': '2017-04-20', }, { 'transaction_reference': 'some ref2', 'amount': order.total_cost - 1, 'method': PaymentMethod.MANUAL, 'received_on': '2017-04-21', }, ], ) assert response.status_code == status.HTTP_201_CREATED response_items = sorted(response.json(), key=itemgetter('transaction_reference')) assert response_items == [ { 'created_on': '2017-04-25T13:00:00Z', 'reference': '201704250001', 'transaction_reference': 'some ref1', 'additional_reference': '', 'amount': 1, 'method': PaymentMethod.BACS, # bacs is the default one 'received_on': '2017-04-20', }, { 'created_on': '2017-04-25T13:00:00Z', 'reference': '201704250002', 'transaction_reference': 'some ref2', 'additional_reference': '', 'amount': order.total_cost - 1, 'method': PaymentMethod.MANUAL, 'received_on': '2017-04-21', }, ] order.refresh_from_db() assert order.status == OrderStatus.PAID assert order.paid_on == dateutil_parse('2017-04-21T00:00:00Z')
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)
def test_orders_to_es_documents(): """Test converting 2 orders to Elasticsearch documents.""" orders = OrderFactory.create_batch(2) result = ESOrder.db_objects_to_es_documents(orders) assert {item['_id'] for item in result} == {str(item.pk) for item in orders}
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']
def test_pricing_unchanged_if_update_unrelated(self): """ Test that if an assignee is changed in an unrelated way, the pricing on the order doesn't change. """ order = OrderFactory(discount_value=0) assert order.total_cost > 0 pre_update_total_cost = order.total_cost assignee = order.assignees.first() assignee.is_lead = not assignee.is_lead assignee.save() order.refresh_from_db() assert order.total_cost > 0 post_update_total_cost = order.total_cost assert pre_update_total_cost == post_update_total_cost
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, )
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
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)
def test_create_as_atomic_operation(self): """ Test that if there's a problem when saving the order, the quote is not saved either so that we keep db integrity. """ order = OrderFactory() url = reverse('api-v3:omis:quote:detail', kwargs={'order_pk': order.pk}) with mock.patch.object(Order, 'save') as mocked_save: mocked_save.side_effect = Exception() with pytest.raises(Exception): self.api_client.post(url) order.refresh_from_db() assert not order.quote assert not Quote.objects.count()
def test_without_any_active_quote(self): """Test that if there isn't any active quote, the validation passes.""" order = OrderFactory() validator = NoOtherActiveQuoteExistsSubValidator() try: validator(order=order) except Exception: pytest.fail('Should not raise a validator error.')
def test_order_info(self, settings): """ Test the order info template. If the template variables have been changed in GOV.UK notifications this is going to raise HTTPError (400 - Bad Request). """ settings.OMIS_NOTIFICATION_API_KEY = settings.OMIS_NOTIFICATION_TEST_API_KEY notify = Notify() notify.order_info(OrderFactory(), what_happened='', why='')
def test_create_from_order( self, mocked_generate_datetime_based_reference, mocked_calculate_payment_due_date, ): """Test that Invoice.objects.create_from_order creates an invoice.""" payment_due_date = dateutil_parse('2030-01-01').date() mocked_generate_datetime_based_reference.return_value = '201702010004' mocked_calculate_payment_due_date.return_value = payment_due_date order = OrderFactory() invoice = Invoice.objects.create_from_order(order) invoice.refresh_from_db() assert invoice.order_reference == order.reference assert invoice.invoice_number == '201702010004' assert invoice.payment_due_date == payment_due_date assert invoice.billing_company_name == order.billing_company_name assert invoice.billing_address_1 == order.billing_address_1 assert invoice.billing_address_2 == order.billing_address_2 assert invoice.billing_address_town == order.billing_address_town assert invoice.billing_address_county == order.billing_address_county assert invoice.billing_address_postcode == order.billing_address_postcode assert invoice.billing_address_country == order.billing_address_country assert invoice.po_number == order.po_number assert invoice.invoice_company_name == constants.DIT_COMPANY_NAME assert invoice.invoice_address_1 == constants.DIT_ADDRESS_1 assert invoice.invoice_address_2 == constants.DIT_ADDRESS_2 assert invoice.invoice_address_town == constants.DIT_ADDRESS_TOWN assert invoice.invoice_address_county == constants.DIT_ADDRESS_COUNTY assert invoice.invoice_address_postcode == constants.DIT_ADDRESS_POSTCODE assert str(invoice.invoice_address_country.pk ) == constants.DIT_ADDRESS_COUNTRY_ID assert invoice.invoice_vat_number == constants.DIT_VAT_NUMBER assert invoice.contact_email == order.get_current_contact_email() assert invoice.vat_status == order.vat_status assert invoice.vat_number == order.vat_number assert invoice.vat_verified == order.vat_verified assert invoice.net_cost == order.net_cost assert invoice.subtotal_cost == order.subtotal_cost assert invoice.vat_cost == order.vat_cost assert invoice.total_cost == order.total_cost
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:payment-gateway-session:collection', kwargs={'public_token': order.public_token}, ) response = api_client.post(url, data={}) assert response.status_code == status.HTTP_401_UNAUTHORIZED
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
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
def test_creating_order_syncs_to_es(setup_es): """Test that when I create an order, it gets synced to ES.""" order = OrderFactory() setup_es.indices.refresh() assert setup_es.get( index=OrderSearchApp.es_model.get_write_index(), doc_type=OrderSearchApp.name, id=order.pk, )
def test_audit_log(s3_stubber): """Test that reversion revisions are created.""" sectors = SectorFactory.create_batch( 3, segment=factory.Iterator(['sector_1', 'sector_2', 'sector_3']), ) order_without_change = OrderFactory( reference='order_1', sector_id=sectors[0].pk, ) order_with_change = OrderFactory( reference='order_2', sector_id=sectors[1].pk, ) bucket = 'test_bucket' object_key = 'test_key' csv_content = f"""id,old_sector_id,new_sector_id {order_without_change.pk},{sectors[0].pk},{sectors[0].pk} {order_with_change.pk},{sectors[1].pk},{sectors[2].pk} """ s3_stubber.add_response( 'get_object', { 'Body': BytesIO(csv_content.encode(encoding='utf-8')), }, expected_params={ 'Bucket': bucket, 'Key': object_key, }, ) call_command('update_order_sector', bucket, object_key) versions = Version.objects.get_for_object(order_without_change) assert versions.count() == 0 versions = Version.objects.get_for_object(order_with_change) assert versions.count() == 1 assert versions[0].revision.get_comment() == 'Order sector correction.'
def test_404_if_in_disallowed_status(self, order_status, public_omis_api_client): """Test that if the order is not in an allowed state, the endpoint returns 404.""" order = OrderFactory(status=order_status) 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_404_NOT_FOUND
def test_zero_with_no_estimated_time(self): """ Test that if an order doesn't have any assignees, the pricing is zero. """ order = OrderFactory(assignees=[]) assert not order.assignees.count() order = Order(vat_status=None) pricing = calculate_order_pricing(order) assert pricing == ZERO_PRICING
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={}, follow=True) assert response.status_code == 200 assert len(response.redirect_chain) == 1 assert response.redirect_chain[0][0] == self.login_url_with_redirect( url)
def test_without_quote(self): """Test that if the order doesn't have any quote, the endpoint returns 404.""" order = OrderFactory() url = reverse( f'api-v3:omis:quote:cancel', kwargs={'order_pk': order.pk}, ) response = self.api_client.post(url) assert response.status_code == status.HTTP_404_NOT_FOUND
def test_customer_notified(self): """ Test that calling `quote_cancelled` sends an email notifying the customer that the quote has been cancelled. """ order = OrderFactory() notify.client.reset_mock() notify.quote_cancelled(order, by=AdviserFactory()) assert notify.client.send_email_notification.called call_args = notify.client.send_email_notification.call_args_list[0][1] assert call_args['email_address'] == order.get_current_contact_email() assert call_args[ 'template_id'] == Template.quote_cancelled_for_customer.value assert call_args['personalisation'][ 'recipient name'] == order.contact.name assert call_args['personalisation'][ 'embedded link'] == order.get_public_facing_url()
def _company_factory( num_interactions=0, num_contacts=0, num_orders=0, num_referrals=0, num_company_list_items=0, num_pipeline_items=0, ): """Factory for a company that has companies, interactions and OMIS orders.""" company = CompanyFactory() ContactFactory.create_batch(num_contacts, company=company) CompanyInteractionFactory.create_batch(num_interactions, company=company) CompanyReferralFactory.create_batch(num_referrals, company=company, contact=None) OrderFactory.create_batch(num_orders, company=company) CompanyListItemFactory.create_batch(num_company_list_items, company=company) PipelineItemFactory.create_batch(num_pipeline_items, company=company) return company
def test_empty(self): """Test that calling GET returns [] if no-one is assigned.""" order = OrderFactory(assignees=[]) 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() == []
def test_access_allowed_if_with_view_permission(self): """Test that a 200 is returned if the user has the view permission.""" order = OrderFactory() user = create_test_user(permission_codenames=['view_orderassignee']) api_client = self.create_api_client(user=user) url = reverse( 'api-v3:omis:order:assignee', kwargs={'order_pk': order.id}, ) response = api_client.get(url) assert response.status_code == status.HTTP_200_OK
def test_access_is_denied_if_without_permissions(self): """Test that a 403 is returned if the user has no permissions.""" order = OrderFactory() user = create_test_user() api_client = self.create_api_client(user=user) url = reverse( 'api-v3:omis:order:assignee', kwargs={'order_pk': order.id}, ) response = api_client.get(url) assert response.status_code == status.HTTP_403_FORBIDDEN
def test_without_whitelisted_ip(self, public_omis_api_client): """Test that making a request without the whitelisted client IP returns an error.""" order = OrderFactory() url = reverse( 'api-v3:public-omis:quote:detail', kwargs={'public_token': order.public_token}, ) public_omis_api_client.set_http_x_forwarded_for('1.1.1.1') response = public_omis_api_client.get(url) assert response.status_code == status.HTTP_401_UNAUTHORIZED