def test_add_parent_multiple(self): """Check that if parent is provided but multiple locations match parent that location record is NOT created """ carto_parent = CartoDBTableFactory() LocationFactory(p_code="456") LocationFactory(p_code="456") self.mock_sql.return_value = { "rows": [{ "the_geom": "Point(20 20)", "name": "New Location", "pcode": "123", "parent": "456" }] } carto = CartoDBTableFactory( parent=carto_parent, parent_code_col="parent", ) self.assertFalse( Location.objects.filter(name="New Location", p_code="123").exists()) response = self._run_update(carto.pk) self._assert_response(response, carto.table_name, 0, 0, 1) self.assertFalse( Location.objects.filter(name="New Location", p_code="123").exists())
def test_get_filter(self): LocationFactory(name="Test") LocationFactory(name="Other") self.client.force_login(self.unicef_staff) response = self.client.get("{}?q=te".format( reverse("locations-autocomplete-light"))) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(len(data["results"]), 1)
def test_location(self): # Test with unicode gateway name gateway_type = GatewayTypeFactory.build(name=u'xyz') location = LocationFactory.build(gateway=gateway_type, name=u'R\xe4dda Barnen', p_code='abc') self.assertEqual(six.text_type(location), u'R\xe4dda Barnen (xyz PCode: abc)') # Test with str gateway name gateway_type = GatewayTypeFactory.build(name=b'xyz') location = LocationFactory.build(gateway=gateway_type, name=u'R\xe4dda Barnen', p_code='abc') self.assertEqual(six.text_type(location), u'R\xe4dda Barnen (xyz PCode: abc)')
def test_exists_point(self): """If single object exists and 'the_geom' value is Point then update point value Name is also updated """ carto = CartoDBTableFactory() location = LocationFactory(p_code="123", point=None) site_name = "test" self.assertIsNone(location.point) self.assertNotEqual(location.name, site_name) success, not_added, created, updated = tasks.create_location( "123", carto, None, None, site_name, {"the_geom": "Point(20 20)"}, 0, 0, 0, ) self.assertTrue(success) self.assertEqual(not_added, 0) self.assertEqual(created, 0) self.assertEqual(updated, 1) location_updated = Location.objects.get(pk=location.pk) self.assertIsNotNone(location_updated.point) self.assertEqual(location_updated.name, site_name)
def test_prp_api_performance(self): EXPECTED_QUERIES = 23 with self.assertNumQueries(EXPECTED_QUERIES): self.run_prp_v1( user=self.unicef_staff, method='get' ) # make a bunch more stuff, make sure queries don't go up. intervention = InterventionFactory(agreement=self.agreement, title='New Intervention') result = ResultFactory(name='Another Result') result_link = InterventionResultLink.objects.create( intervention=intervention, cp_output=result) lower_result = LowerResult.objects.create(result_link=result_link, name='Lower Result 1') indicator_blueprint = IndicatorBlueprint.objects.create( title='The Blueprint' ) applied_indicator = AppliedIndicator.objects.create( indicator=indicator_blueprint, lower_result=lower_result, ) applied_indicator.locations.add(LocationFactory(name='A Location', gateway=GatewayTypeFactory(name='Another Gateway'), p_code='a-p-code')) applied_indicator.disaggregation.create(name='Another Disaggregation') with self.assertNumQueries(EXPECTED_QUERIES): self.run_prp_v1( user=self.unicef_staff, method='get' )
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) cls.locations = [LocationFactory() for x in range(5)] # heavy_detail_expected_keys are the keys that should be in response.data.keys() cls.heavy_detail_expected_keys = sorted( ('id', 'name', 'p_code', 'location_type', 'location_type_admin_level', 'parent', 'geo_point'))
def test_add_with_parent(self): """Check that if parent is provided that record is created with parent """ carto_parent = CartoDBTableFactory() parent = LocationFactory(p_code="456") self.mock_sql.return_value = { "rows": [{ "the_geom": "Point(20 20)", "name": "New Location", "pcode": "123", "parent": "456" }] } carto = CartoDBTableFactory( parent=carto_parent, parent_code_col="parent", ) self.assertFalse( Location.objects.filter(name="New Location", p_code="123").exists()) response = self._run_update(carto.pk) self._assert_response(response, carto.table_name, 1, 0, 0) self.assertTrue( Location.objects.filter(name="New Location", p_code="123").exists()) location = Location.objects.get(name="New Location", p_code="123") self.assertEqual(location.parent, parent)
def test_exists_geom(self): """If single object exists and 'the_geom' value is NOT Point then update geom value Name is also updated """ carto = CartoDBTableFactory() location = LocationFactory(p_code="123", geom=None) site_name = "test" self.assertIsNone(location.geom) self.assertNotEqual(location.name, site_name) success, not_added, created, updated = tasks.create_location( "123", carto, None, None, "test", { "the_geom": "MultiPolygon(((10 10, 10 20, 20 20, 20 15, 10 10)), ((10 10, 10 20, 20 20, 20 15, 10 10)))" }, 0, 0, 0, ) self.assertTrue(success) self.assertEqual(not_added, 0) self.assertEqual(created, 0) self.assertEqual(updated, 1) location_updated = Location.objects.get(pk=location.pk) self.assertIsNotNone(location_updated.geom) self.assertEqual(location_updated.name, site_name)
def test_new_parent(self): """If location does NOT exist then create it and if parent instance provided, set parent value as well """ carto = CartoDBTableFactory() parent = LocationFactory(p_code="321") self.assertFalse(Location.objects.filter(p_code="123").exists()) name = "Test" success, not_added, created, updated = tasks.create_location( "123", carto, True, parent, name, {"the_geom": "Point(20 20)"}, 0, 0, 0, ) self.assertTrue(success) self.assertEqual(not_added, 0) self.assertEqual(created, 1) self.assertEqual(updated, 0) location = Location.objects.get(p_code="123") self.assertIsNotNone(location.point) self.assertIsNone(location.geom) self.assertEqual(location.name, name) self.assertEqual(location.parent, parent)
def setUp(self): super(TestInterventionSectorLocationLinkModelExport, self).setUp() self.location = LocationFactory( name="Name", ) self.link = InterventionSectorLocationLinkFactory( intervention=self.intervention, ) self.link.locations.add(self.location)
def setUpTestData(cls): cls.section = SectorFactory() cls.intervention = InterventionFactory() cls.result_link = InterventionResultLinkFactory( intervention=cls.intervention, ) cls.lower_result = LowerResultFactory( result_link=cls.result_link, ) cls.applied_indicator = AppliedIndicatorFactory( lower_result=cls.lower_result, ) cls.location = LocationFactory() cls.indicator = IndicatorBlueprintFactory()
def test_multiple_objects(self): """Multiple objects match the pcode, just 'no added' should increment by 1 """ carto = CartoDBTableFactory() LocationFactory(p_code="123") LocationFactory(p_code="123") success, not_added, created, updated = tasks.create_location( "123", carto, None, None, "test", {}, 0, 0, 0, ) self.assertFalse(success) self.assertEqual(not_added, 1) self.assertEqual(created, 0) self.assertEqual(updated, 0)
def test_api_location_list_modified(self): response = self.forced_auth_req('get', reverse('locations-list'), user=self.unicef_staff) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 5) etag = response["ETag"] LocationFactory() response = self.forced_auth_req('get', reverse('locations-list'), user=self.unicef_staff, HTTP_IF_NONE_MATCH=etag) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 6)
def test_exists_no_geom(self): """If single object exists but 'the_geom' value is False then nothing happens """ carto = CartoDBTableFactory() LocationFactory(p_code="123") success, not_added, created, updated = tasks.create_location( "123", carto, None, None, "test", {"the_geom": False}, 0, 0, 0, ) self.assertFalse(success) self.assertEqual(not_added, 0) self.assertEqual(created, 0) self.assertEqual(updated, 0)
def setup_intervention_test_data(test_case, include_results_and_indicators=False): today = datetime.date.today() test_case.unicef_staff = UserFactory(is_staff=True) test_case.partnership_manager_user = UserFactory(is_staff=True) test_case.partnership_manager_user.groups.add(GroupFactory()) test_case.partner = PartnerFactory(name='Partner 1', vendor_number="VP1") test_case.partner1 = PartnerFactory(name='Partner 2') test_case.agreement = AgreementFactory( partner=test_case.partner, signed_by_unicef_date=datetime.date.today()) test_case.active_agreement = AgreementFactory( partner=test_case.partner1, status='active', signed_by_unicef_date=datetime.date.today(), signed_by_partner_date=datetime.date.today()) test_case.intervention = InterventionFactory(agreement=test_case.agreement, title='Intervention 1') test_case.intervention_2 = InterventionFactory( agreement=test_case.agreement, title='Intervention 2', document_type=Intervention.PD, ) test_case.active_intervention = InterventionFactory( agreement=test_case.active_agreement, title='Active Intervention', document_type=Intervention.PD, start=today - datetime.timedelta(days=1), end=today + datetime.timedelta(days=90), status='active', signed_by_unicef_date=today - datetime.timedelta(days=1), signed_by_partner_date=today - datetime.timedelta(days=1), unicef_signatory=test_case.unicef_staff, partner_authorized_officer_signatory=test_case.partner1.staff_members. all().first()) test_case.result_type = ResultType.objects.get_or_create( name=ResultType.OUTPUT)[0] test_case.result = ResultFactory(result_type=test_case.result_type) test_case.partnership_budget = InterventionBudget.objects.create( intervention=test_case.intervention, unicef_cash=10, unicef_cash_local=100, partner_contribution=20, partner_contribution_local=200, in_kind_amount_local=10, ) # set up two frs not connected to any interventions test_case.fr_1 = FundsReservationHeaderFactory(intervention=None, currency='USD') test_case.fr_2 = FundsReservationHeaderFactory(intervention=None, currency='USD') if include_results_and_indicators: # setup additional inicator/results test_case.result = ResultFactory(name='A Result') test_case.result_link = InterventionResultLink.objects.create( intervention=test_case.active_intervention, cp_output=test_case.result) test_case.lower_result = LowerResult.objects.create( result_link=test_case.result_link, name='Lower Result 1') test_case.indicator_blueprint = IndicatorBlueprint.objects.create( title='The Blueprint') test_case.applied_indicator = AppliedIndicator.objects.create( indicator=test_case.indicator_blueprint, lower_result=test_case.lower_result, ) test_case.applied_indicator.locations.add( LocationFactory(name='A Location', gateway=GatewayTypeFactory(name='A Gateway'), p_code='a-p-code')) test_case.disaggregation = test_case.applied_indicator.disaggregation.create( name='A Disaggregation')
def fake(): """ Generates fake test data into database :return: None """ locationas = LocationFactory.create_batch(3)
def test_travel_creation(self): dsaregion = DSARegion.objects.first() currency = PublicsCurrencyFactory() wbs = PublicsWBSFactory() grant = wbs.grants.first() fund = grant.funds.first() location = LocationFactory() data = {'0': {}, '1': {'date': '2016-12-16', 'breakfast': False, 'lunch': False, 'dinner': False, 'accomodation': False, 'no_dsa': False}, 'deductions': [{'date': '2016-12-15', 'breakfast': False, 'lunch': False, 'dinner': False, 'accomodation': False, 'no_dsa': False}, {'date': '2016-12-16', 'breakfast': False, 'lunch': False, 'dinner': False, 'accomodation': False, 'no_dsa': False}], 'itinerary': [{'airlines': [], 'overnight_travel': False, 'origin': 'a', 'destination': 'b', 'dsa_region': dsaregion.id, 'departure_date': '2016-12-15T15:02:13+01:00', 'arrival_date': '2016-12-16T15:02:13+01:00', 'mode_of_travel': ModeOfTravel.BOAT}], 'activities': [{'is_primary_traveler': True, 'locations': [location.id], 'travel_type': TravelType.ADVOCACY, 'date': '2016-12-15T15:02:13+01:00'}], 'cost_assignments': [{'wbs': wbs.id, 'grant': grant.id, 'fund': fund.id, 'share': '100'}], 'clearances': {'medical_clearance': 'requested', 'security_clearance': 'requested', 'security_course': 'requested'}, 'ta_required': True, 'international_travel': False, 'mode_of_travel': [ModeOfTravel.BOAT], 'traveler': self.traveler.id, 'supervisor': self.unicef_staff.id, 'start_date': '2016-12-15T15:02:13+01:00', 'end_date': '2016-12-16T15:02:13+01:00', 'estimated_travel_cost': '123', 'currency': currency.id, 'purpose': 'Purpose', 'additional_note': 'Notes', 'medical_clearance': 'requested', 'security_clearance': 'requested', 'security_course': 'requested'} response = self.forced_auth_req('post', reverse('t2f:travels:list:index'), data=data, user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(len(response_json['itinerary']), 1)
def locations(self, created, extracted, **kwargs): if created: self.locations.add(*[LocationFactory() for i in range(3)]) if extracted: self.locations.add(*extracted)
def test_non_auth(self): LocationFactory() response = self.client.get(reverse("locations-autocomplete-light")) self.assertEqual(response.status_code, status.HTTP_302_FOUND)
def populate_locations(self, create, extracted, **kwargs): location = LocationFactory() self.locations.add(location)
def test_activity_export(self): office = OfficeFactory(name='Budapest') section_health = SectorFactory(name='Health') section_education = SectorFactory(name='Education') location_ABC = LocationFactory(name='Location ABC') location_345 = LocationFactory(name='Location 345') location_111 = LocationFactory(name='Location 111') partnership_A1 = InterventionFactory(title='Partnership A1') partner = partnership_A1.agreement.partner partner.name = 'Partner A' partner.save() partnership_A2 = InterventionFactory(title='Partnership A2') agreement = partnership_A2.agreement agreement.partner = partner agreement.save() partnership_B3 = InterventionFactory(title='Partnership B3') partner = partnership_B3.agreement.partner partner.name = 'Partner B' partner.save() partnership_C1 = InterventionFactory(title='Partnership C1') partner = partnership_C1.agreement.partner partner.name = 'Partner C' partner.save() # Some results result_A11 = ResultFactory(name='Result A11') result_A21 = ResultFactory(name='Result A21') # set up travels user_joe_smith = UserFactory(first_name='Joe', last_name='Smith') user_alice_carter = UserFactory(first_name='Alice', last_name='Carter') user_lenox_lewis = UserFactory(first_name='Lenox', last_name='Lewis') travel_1 = TravelFactory( reference_number='2016/1000', traveler=user_joe_smith, office=office, sector=section_health, start_date=datetime.strptime('08-Nov-2017', '%d-%b-%Y'), end_date=datetime.strptime('14-Nov-2017', '%d-%b-%Y')) travel_2 = TravelFactory( reference_number='2016/1211', traveler=user_alice_carter, office=office, sector=section_education, start_date=datetime.strptime('08-Nov-2017', '%d-%b-%Y'), end_date=datetime.strptime('14-Nov-2017', '%d-%b-%Y')) # Do some cleanup TravelActivity.objects.all().delete() # Create the activities finally activity_1 = TravelActivityFactory( travel_type=TravelType.PROGRAMME_MONITORING, date=datetime(2016, 12, 3, tzinfo=UTC), result=result_A11, primary_traveler=user_joe_smith) activity_1.travels.add(travel_1) activity_1.locations.set([location_ABC, location_345]) activity_1.partner = partnership_A1.agreement.partner activity_1.partnership = partnership_A1 activity_1.save() activity_2 = TravelActivityFactory( travel_type=TravelType.PROGRAMME_MONITORING, date=datetime(2016, 12, 4, tzinfo=UTC), result=result_A21, primary_traveler=user_lenox_lewis) activity_2.travels.add(travel_1) activity_2.locations.set([location_111]) activity_2.partner = partnership_A2.agreement.partner activity_2.partnership = partnership_A2 activity_2.save() activity_3 = TravelActivityFactory(travel_type=TravelType.MEETING, date=datetime(2016, 12, 3, tzinfo=UTC), result=None, primary_traveler=user_joe_smith) activity_3.travels.add(travel_1) activity_3.locations.set([location_ABC]) activity_3.partner = partnership_B3.agreement.partner activity_3.partnership = partnership_B3 activity_3.save() activity_4 = TravelActivityFactory(travel_type=TravelType.SPOT_CHECK, date=datetime(2016, 12, 6, tzinfo=UTC), result=None, primary_traveler=user_alice_carter) activity_4.travels.add(travel_2) activity_4.locations.set([location_111, location_345]) activity_4.partner = partnership_C1.agreement.partner activity_4.partnership = partnership_C1 activity_4.save() with self.assertNumQueries(6): response = self.forced_auth_req( 'get', reverse('t2f:travels:list:activity_export'), user=self.unicef_staff) export_csv = csv.reader(StringIO(response.content.decode('utf-8'))) rows = [r for r in export_csv] self.assertEqual(len(rows), 5) # check header self.assertEqual(rows[0], [ 'reference_number', 'traveler', 'office', 'section', 'status', 'trip_type', 'partner', 'partnership', 'results', 'locations', 'start_date', 'end_date', 'is_secondary_traveler', 'primary_traveler_name' ]) self.assertEqual(rows[1], [ '2016/1000', 'Joe Smith', 'Budapest', 'Health', 'planned', 'Programmatic Visit', 'Partner A', 'Partnership A1', 'Result A11', 'Location 345, Location ABC', '08-Nov-2017', '14-Nov-2017', '', '' ]) self.assertEqual(rows[2], [ '2016/1000', 'Joe Smith', 'Budapest', 'Health', 'planned', 'Programmatic Visit', 'Partner A', 'Partnership A2', 'Result A21', 'Location 111', '08-Nov-2017', '14-Nov-2017', 'YES', 'Lenox Lewis' ]) self.assertEqual(rows[3], [ '2016/1000', 'Joe Smith', 'Budapest', 'Health', 'planned', 'Meeting', 'Partner B', 'Partnership B3', '', 'Location ABC', '08-Nov-2017', '14-Nov-2017', '', '' ]) self.assertEqual(rows[4], [ '2016/1211', 'Alice Carter', 'Budapest', 'Education', 'planned', 'Spot Check', 'Partner C', 'Partnership C1', '', 'Location 111, Location 345', '08-Nov-2017', '14-Nov-2017', '', '' ])
def test_travel_creation(self): dsa_region = PublicsDSARegionFactory() currency = PublicsCurrencyFactory() wbs = PublicsWBSFactory() grant = wbs.grants.first() fund = grant.funds.first() location = LocationFactory() purpose = 'Some purpose to check later' data = { 'deductions': [{ 'date': '2016-12-15', 'breakfast': False, 'lunch': False, 'dinner': False, 'accomodation': False, 'no_dsa': False }, { 'date': '2016-12-16', 'breakfast': False, 'lunch': False, 'dinner': False, 'accomodation': False, 'no_dsa': False }], 'itinerary': [{ 'origin': 'Berlin', 'destination': 'Budapest', 'departure_date': '2017-04-14T17:06:55.821490', 'arrival_date': '2017-04-15T17:06:55.821490', 'dsa_region': dsa_region.id, 'overnight_travel': False, 'mode_of_travel': ModeOfTravel.RAIL, 'airlines': [] }, { 'origin': 'Budapest', 'destination': 'Berlin', 'departure_date': '2017-05-20T12:06:55.821490', 'arrival_date': '2017-05-21T12:06:55.821490', 'dsa_region': dsa_region.id, 'overnight_travel': False, 'mode_of_travel': ModeOfTravel.RAIL, 'airlines': [] }], 'activities': [{ 'is_primary_traveler': True, 'locations': [location.id], 'travel_type': TravelType.ADVOCACY, 'date': '2016-12-15T15:02:13+01:00' }], 'cost_assignments': [{ 'wbs': wbs.id, 'grant': grant.id, 'fund': fund.id, 'share': '100' }], 'clearances': { 'medical_clearance': 'requested', 'security_clearance': 'requested', 'security_course': 'requested' }, 'ta_required': True, 'international_travel': False, 'mode_of_travel': [ModeOfTravel.BOAT], 'traveler': self.traveler.id, 'supervisor': self.unicef_staff.id, 'start_date': '2016-12-15T15:02:13+01:00', 'end_date': '2016-12-16T15:02:13+01:00', 'estimated_travel_cost': '123', 'currency': currency.id, 'purpose': purpose, 'additional_note': 'Notes', 'medical_clearance': 'requested', 'security_clearance': 'requested', 'security_course': 'requested' } response = self.forced_auth_req( 'post', reverse('t2f:travels:list:state_change', kwargs={'transition_name': 'save_and_submit'}), data=data, user=self.traveler) response_json = json.loads(response.rendered_content) self.assertEqual(response_json['purpose'], purpose) self.assertEqual(response_json['status'], Travel.SUBMITTED) travel_id = response_json['id'] response = self.forced_auth_req('post', reverse( 't2f:travels:details:state_change', kwargs={ 'travel_pk': travel_id, 'transition_name': 'approve' }), user=self.unicef_staff) response_json = json.loads(response.rendered_content) self.assertEqual(response_json['status'], Travel.APPROVED) data = {'purpose': 'Some totally different purpose than before'} response = self.forced_auth_req( 'patch', reverse('t2f:travels:details:index', kwargs={'travel_pk': response_json['id']}), data=data, user=self.traveler) response_json = json.loads(response.rendered_content) self.assertEqual(response_json['purpose'], purpose)