def test_enquiry_list_filtered_unassigned_html(self): """Test retrieving enquiry list and ensure we get expected count""" EnquirerFactory() enquiries = [ EnquiryFactory( enquiry_stage=ref_data.EnquiryStage.ADDED_TO_DATAHUB), EnquiryFactory( enquiry_stage=ref_data.EnquiryStage.AWAITING_RESPONSE), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.NEW), ] owner = enquiries[1].owner enquiries[0].owner = None enquiries[0].save() # owner assigned response = self.client.get(reverse("index"), {"owner__id": owner.id}, **headers) soup = BeautifulSoup(response.content, "html.parser") enquiry_els = soup.select(".entity__list-item") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(enquiry_els), 1) # owner unassigned response = self.client.get(reverse("index"), {"owner__id": "UNASSIGNED"}, **headers) soup = BeautifulSoup(response.content, "html.parser") enquiry_els = soup.select(".entity__list-item") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(enquiry_els), 1)
def test_enquiry_list_filtered_enquiry_stage_html(self): """Test retrieving enquiry list and ensure we get expected count""" EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.ADDED_TO_DATAHUB), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.AWAITING_RESPONSE), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.NEW) # enquiry stage - ADDED_TO_DATAHUB response = self.client.get( reverse("index"), {"enquiry_stage": ref_data.EnquiryStage.ADDED_TO_DATAHUB}, **headers, ) soup = BeautifulSoup(response.content, "html.parser") enquiry_els = soup.select(".entity__list-item") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(enquiry_els), 1) # enquiry stage - NON_FDI response = self.client.get( reverse("index"), {"enquiry_stage": ref_data.EnquiryStage.NON_FDI}, **headers, ) soup = BeautifulSoup(response.content, "html.parser") enquiry_els = soup.select(".entity__list-item") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(enquiry_els), 0)
def test_enquiry_list_filtered(self): """Test retrieving enquiry list and ensure we get expected count""" EnquiryFactory(company_name="Foo Bar") EnquiryFactory(company_name="Bar Inc") EnquiryFactory(company_name="Baz") response = self.client.get( reverse("index"), {"company_name__icontains": "Bar"}, **headers, ) data = response.data self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(data["count"], 2)
def get_an_enquiry_detail(self): """Helper function to get a single enquiry and retrieve details""" enquiry = EnquiryFactory() response = self.client.get( reverse("enquiry-detail", kwargs={"pk": enquiry.id})) self.assertEqual(response.status_code, status.HTTP_200_OK) return response.context["enquiry"]
def test_enquiry_successful_update(self, _): """ Test a successful update Creates an enquiry first, updates few fields and ensures the data is updated after submitting the form """ # POST request to a form expects all the fields but sending optional # fields whose value is None causing form_invalid errors. # Setting content-type as json also not helping, ignore blank fields data = self.set_enquiry_for_update(enquiry=EnquiryFactory()) response = self.client.post( reverse("enquiry-edit", kwargs={"pk": data["id"]}), data) # POST request response to a form is 302 self.assertEqual(response.status_code, status.HTTP_302_FOUND) # retrieve updated record response = self.client.get( reverse("enquiry-detail", kwargs={"pk": data["id"]})) self.assertEqual(response.status_code, status.HTTP_200_OK) updated = response.context["enquiry"] self.assertEqual(updated.company_name, data["company_name"]) self.assertEqual(updated.enquiry_stage, data["enquiry_stage"]) self.assertEqual(updated.notes, data["notes"]) self.assertEqual(updated.country, data["country"]) self.assertEqual(updated.enquirer.first_name, "updated first name")
def test_enquiry_consent_update(self, mock_task): enquiry = EnquiryFactory() data = self.set_enquiry_for_update(enquiry=enquiry) assert mock_task.call_count == 0 self.client.post(reverse("enquiry-edit", kwargs={"pk": enquiry.pk}), data) assert mock_task.call_count == 2
def test_enquiry_failed_update(self, _): """ Test an unsuccessful update Creates an enquiry first, submits invalid data to a mandatory field and ensures the data is not updated after submitting the form """ enquiry = self.get_an_enquiry_detail() enquiry = model_to_dict(enquiry) response = self.client.post( reverse("enquiry-edit", kwargs={"pk": enquiry["id"]}), {"enquiry_stage": ""}, ) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) updated_enquiry = model_to_dict(response.context["enquiry"]) self.assertEqual(updated_enquiry["enquiry_stage"], enquiry["enquiry_stage"]) self.assertNotEqual(updated_enquiry["enquiry_stage"], "") """Test the template is using the right variables to show enquiry data in the simple case when data is a string""" enquiry = EnquiryFactory() response = self.client.get( reverse("enquiry-detail", kwargs={"pk": enquiry.id})) self.assertContains(response, enquiry.company_name) self.assertContains(response, enquiry.notes)
def test_enquiry_list(self): """Test retrieving enquiry list and ensure we get expected count""" enquiries = [EnquiryFactory() for i in range(2)] response = self.client.get(reverse("index")) self.assertEqual(response.status_code, status.HTTP_200_OK) response = response.json() results = response["results"] self.assertEqual(len(results), len(enquiries))
def test_dh_request_payload(self, fetch_metadata): enquiry = EnquiryFactory( primary_sector='Aerospace', investment_type='Joint venture', ) fdi_id = uuid4() stage_id = uuid4() investment_type_id = uuid4() sector_id = uuid4() website_id = uuid4() invest_id = uuid4() fetch_metadata.side_effect = lambda _: [ {'id': investment_type_id, 'name': 'FDI'}, {'id': fdi_id, 'name': 'Joint venture'}, {'id': stage_id, 'name': 'Prospect'}, {'id': sector_id, 'name': 'Aerospace'}, {'id': website_id, 'name': 'Website'}, {'id': invest_id, 'name': 'Invest in GREAT Britain'}, ] company_id = uuid4() contact_id = uuid4() referral_adviser = uuid4() client_relationship_manager_id = uuid4() payload, error_key = dh_prepare_payload( enquiry, company_id, contact_id, referral_adviser, client_relationship_manager_id, ) expected_dh_payload = { 'name': enquiry.project_name, 'investor_company': company_id, 'description': enquiry.project_description, 'anonymous_description': enquiry.anonymised_project_description, 'investment_type': investment_type_id, 'fdi_type': fdi_id, 'stage': stage_id, 'investor_type': None, 'level_of_involvement': None, 'specific_programme': None, 'client_contacts': [contact_id], 'client_relationship_manager': client_relationship_manager_id, 'sector': sector_id, 'estimated_land_date': None, 'business_activities': [ref_data.DATA_HUB_BUSINESS_ACTIVITIES_SERVICES], 'referral_source_adviser': referral_adviser, 'referral_source_activity': website_id, 'referral_source_activity_website': invest_id, } assert payload == expected_dh_payload assert error_key is None
def test_enquiry_list_html(self): """Test retrieving enquiry list and ensure we get expected count""" enquiries = EnquiryFactory.create_batch(2) response = self.client.get(reverse("index"), **headers) soup = BeautifulSoup(response.content, "html.parser") enquiry_els = soup.select(".entity__list-item") self.assertEqual(response.status_code, status.HTTP_200_OK) count = len(enquiry_els) self.assertEqual(count, len(enquiries))
def test_enquiry_list_filtered_unassigned(self): """Test retrieving enquiry list and ensure we get expected count""" EnquirerFactory() enquiries = [ EnquiryFactory( enquiry_stage=ref_data.EnquiryStage.ADDED_TO_DATAHUB), EnquiryFactory( enquiry_stage=ref_data.EnquiryStage.AWAITING_RESPONSE), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.NEW), ] owner = enquiries[1].owner enquiries[0].owner = None enquiries[0].save() enquiry_unassigned = enquiries[0] enquiry_assigned = enquiries[1] # owner assigned response = self.client.get(reverse("index"), {"owner__id": owner.id}, **headers) data = response.data enquiry_data = data["results"][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(data["count"], 1) self.assert_factory_enquiry_equals_enquiry_response( enquiry_assigned, enquiry_data) # owner unassigned response = self.client.get(reverse("index"), {"owner__id": "UNASSIGNED"}) data = response.data enquiry_data_unassigned = data["results"][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(data["count"], 1) self.assert_factory_enquiry_equals_enquiry_response( enquiry_unassigned, enquiry_data_unassigned)
def test_enquiry_detail_template_ref_data(self, _): """Test the template is using the right variables to show enquiry data in the case when data is a ref_data choice and has a verbose name""" enquiry = EnquiryFactory() response = self.client.get( reverse("enquiry-detail", kwargs={"pk": enquiry.id})) enquiry_stage_display_name = get_display_name(ref_data.EnquiryStage, enquiry.enquiry_stage) country_display_name = get_display_name(ref_data.Country, enquiry.country) self.assertContains(response, enquiry_stage_display_name) self.assertContains(response, country_display_name)
def test_enquiry_list_filtered_enquiry_stage(self): """Test retrieving enquiry list and ensure we get expected count""" EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.ADDED_TO_DATAHUB), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.AWAITING_RESPONSE), EnquiryFactory(enquiry_stage=ref_data.EnquiryStage.NEW) # enquiry stage - ADDED_TO_DATAHUB response = self.client.get( reverse("index"), {"enquiry_stage": ref_data.EnquiryStage.ADDED_TO_DATAHUB}, ) data = response.data self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(data["count"], 1) # enquiry stage - NON_FDI response = self.client.get( reverse("index"), {"enquiry_stage": ref_data.EnquiryStage.NON_FDI}, ) data = response.data self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(data["count"], 0)
def test_investment_creation_fails_company_not_in_dh(self): """ Test that we cannot create investment if company doesn't exist in Data Hub """ enquiry = EnquiryFactory() req = RequestFactory() post_req = req.post("/investment/", {"name": "test"}) post_req.session = {settings.AUTHBROKER_TOKEN_SESSION_KEY: {"access_token": "mock_token"}} with requests_mock.Mocker() as m: url = settings.DATA_HUB_WHOAMI_URL m.get(url, json={"user": "******"}) response = dh_investment_create(post_req, enquiry) self.assertEqual( response["errors"][0]["company"], f"{enquiry.company_name} doesn't exist in Data Hub", )
def test_investment_enquiry_cannot_submit_twice(self): """ If an enquiry is already submitted ensure it cannot be sent again """ enquiry = EnquiryFactory() req = RequestFactory() post_req = req.post("/investment/", {"name": "test"}) post_req.session = {settings.AUTHBROKER_TOKEN_SESSION_KEY: {"access_token": "mock_token"}} enquiry.dh_company_id = "1234-2468" enquiry.date_added_to_datahub = date.today() enquiry.save() with requests_mock.Mocker() as m: url = settings.DATA_HUB_WHOAMI_URL m.get(url, json={"user": "******"}) response = dh_investment_create(post_req, enquiry) prev_date = enquiry.date_added_to_datahub.strftime("%d %B %Y") stage = enquiry.get_datahub_project_status_display() self.assertEqual( response["errors"][0]["enquiry"], f"Enquiry can only be submitted once, previously submitted on {prev_date}, stage\ {stage}", )
def test_enquiry_serializer(self): """ Test serialization of Enquiry object Ensures the format of date fields is as expected and choice field values match with their display value """ enquiry = EnquiryFactory() sr_data = serializers.EnquiryDetailSerializer(enquiry).data self.assertEqual(enquiry.created.strftime("%d %B %Y"), sr_data["created"]) self.assertEqual(enquiry.modified.strftime("%d %B %Y"), sr_data["modified"]) self.assertEqual(enquiry.date_added_to_datahub.strftime("%d %B %Y"), sr_data["date_added_to_datahub"]) self.assertEqual(enquiry.project_success_date.strftime("%d %B %Y"), sr_data["project_success_date"]) self.assertEqual( get_display_value(ref_data.EnquiryStage, enquiry.enquiry_stage), sr_data["enquiry_stage"]) self.assertEqual( get_display_value(ref_data.InvestmentReadiness, enquiry.investment_readiness), sr_data["investment_readiness"]) self.assertEqual( get_display_value( ref_data.InvestmentProgramme, enquiry.specific_investment_programme, ), sr_data["specific_investment_programme"]) self.assertEqual(get_display_value(ref_data.Country, enquiry.country), sr_data["country"]) self.assertEqual( get_display_value(ref_data.PrimarySector, enquiry.primary_sector), sr_data["primary_sector"]) self.assertEqual( get_display_value(ref_data.InvestmentType, enquiry.investment_type), sr_data["investment_type"])
def test_enquiries_list_pagination(self): """ Tests pagination of enquiries list view. Creates enquiries and retrieves single page of results each time and ensures we get the expected number of results for that page. It will be same for all pages except for the last page if num_enquiries is not a multiple of page_size """ num_enquiries = 123 enquiries = EnquiryFactory.create_batch(num_enquiries) # sort enquiries to match the default sort enquiries.sort(key=lambda x: x.date_received, reverse=True) ids = [e.id for e in enquiries] page_size = settings.REST_FRAMEWORK["PAGE_SIZE"] total_pages = (num_enquiries + page_size - 1) // page_size for page in range(total_pages): start = page * page_size end = start + page_size response = self.client.get(reverse("index"), {"page": page + 1}, **headers) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual([enq["id"] for enq in response.data["results"]], ids[start:end]) self.assertEqual(response.data["current_page"], page + 1) response = self.client.get(reverse("index"), **headers) pages = response.context["pages"] assert response.context["total_pages"] == 13 assert pages[0]["page_number"] == 1 assert pages[0]["link"] == ("/?page=1") page_labels = [page["page_number"] for page in pages] assert page_labels == [1, 2, 3, 4, "...", 13] # Ensure accesing the page after the last page should return 404 response = self.client.get(reverse("index"), {"page": total_pages + 1}) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_enquiry_consent_get(self, mock_consent_check): enquiry = EnquiryFactory() assert mock_consent_check.call_count == 0 self.client.get(reverse("enquiry-detail", kwargs={"pk": enquiry.id})) assert mock_consent_check.call_count == 2
def test_enquiries_pagination(self, api_client, settings): """Should return pages""" settings.HAWK_CREDENTIALS = { 'test': { 'key': 'test-key', 'scopes': ("enquiries", ), }, } enquiries = [EnquiryFactory() for _ in range(30)] # test return 10 results url = f"http://testserver{reverse('api-v1-enquiries')}" sender = _auth_sender("test", "test-key", url, "GET") response = api_client.get(url, content_type="", HTTP_AUTHORIZATION=sender.request_header) data = response.json() assert response.status_code == status.HTTP_200_OK assert data["count"] == len(enquiries) assert data["next"] is not None assert data["previous"] is None assert len(data["results"]) == 10 # test return 20 results url = f"http://testserver{reverse('api-v1-enquiries')}?page_size=20" sender = _auth_sender("test", "test-key", url, "GET") response = api_client.get(url, content_type="", HTTP_AUTHORIZATION=sender.request_header) data = response.json() assert response.status_code == status.HTTP_200_OK assert data["count"] == len(enquiries) assert data["next"] is not None assert data["previous"] is None assert len(data["results"]) == 20 # test return all results url = f"http://testserver{reverse('api-v1-enquiries')}?page_size=100" sender = _auth_sender("test", "test-key", url, "GET") response = api_client.get(url, content_type="", HTTP_AUTHORIZATION=sender.request_header) data = response.json() assert response.status_code == status.HTTP_200_OK assert data["count"] == len(enquiries) assert data["next"] is None assert data["previous"] is None assert len(data["results"]) == len(enquiries) # test return 2nd page url = f"http://testserver{reverse('api-v1-enquiries')}?page_size=5&page=2" sender = _auth_sender("test", "test-key", url, "GET") response = api_client.get(url, content_type="", HTTP_AUTHORIZATION=sender.request_header) data = response.json() assert response.status_code == status.HTTP_200_OK assert data["count"] == len(enquiries) assert data["next"] is not None assert data["previous"] is not None assert len(data["results"]) == 5
def test_enquiry_detail(self, _): """Test retrieving a valid enquiry returns 200""" enquiry = EnquiryFactory() response = self.client.get( reverse("enquiry-detail", kwargs={"pk": enquiry.id})) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_new_enquiry_removed_by_method(settings): settings.ALLOW_TEST_FIXTURE_SETUP = True new_enquiry_pk = EnquiryFactory().pk Client().post(RESET_URL, SEED_USER_DATA, content_type="application/json") with pytest.raises(Enquiry.DoesNotExist): Enquiry.objects.get(pk=new_enquiry_pk)
def test_enquiry_model_creation(self): enquiry = EnquiryFactory() self.assertTrue(isinstance(enquiry.enquirer, Enquirer)) self.assertTrue(isinstance(enquiry, Enquiry)) self.assertEqual(Enquiry.objects.count(), 1)