Beispiel #1
0
def test_location_synchronizer_create_or_update_locations(logger_mock, mock_cartodb_locations,
                                                          cartodbtable, carto_response):
    LocationFactory(p_code='RW', is_active=True)
    cartodbtable.parent_code_col = 'parent_code_col'
    cartodbtable.save(update_fields=['parent_code_col'])
    synchronizer = LocationSynchronizer(pk=cartodbtable.pk)
    mock_cartodb_locations.return_value = carto_response

    # test new location
    new, updated, skipped, error = synchronizer.create_or_update_locations()
    assert new == 1
    assert skipped == updated == error == 0

    # test updated location
    new, updated, skipped, error = synchronizer.create_or_update_locations()
    assert updated == 1
    assert new == skipped == error == 0

    # test error: multiple location exception
    LocationFactory(p_code='RW01', is_active=True)
    with pytest.raises(CartoException):
        new, updated, skipped, error = synchronizer.create_or_update_locations()
        assert new == updated == skipped == 0
        logger_mock.assert_called_with(
            f"Multiple locations found for: {cartodbtable.admin_level}, "
            f"{carto_response[0][cartodbtable.name_col]} ({carto_response[0][cartodbtable.pcode_col]})")

    # test skipped location
    mock_cartodb_locations.return_value[0][cartodbtable.pcode_col] = ''
    new, updated, skipped, error = synchronizer.create_or_update_locations()
    assert skipped == 1
    assert new == updated == error == 0
Beispiel #2
0
    def test_location(self):
        # Test with nonascii gateway name
        location = LocationFactory.build(admin_level_name='xyz', name='R\xe4dda Barnen', p_code='abc')
        self.assertEqual(str(location), 'R\xe4dda Barnen (xyz: abc)')

        # Test with str gateway name
        location = LocationFactory.build(admin_level_name='xyz', name='R\xe4dda Barnen', p_code='abc')
        self.assertEqual(str(location), 'R\xe4dda Barnen (xyz: abc)')
Beispiel #3
0
def test_location_synchronizer_clean_upper_level(logger_mock, cartodbtable):
    synchronizer = LocationSynchronizer(pk=cartodbtable.pk)
    location_1 = LocationFactory(p_code='RW', is_active=True)
    location_2 = LocationFactory(
        parent=location_1, p_code='RW01', is_active=False, admin_level=cartodbtable.admin_level - 1)

    synchronizer.clean_upper_level()
    location_1.refresh_from_db()
    assert location_1.is_active
    expected_calls = [
        call(f"Deleting parent {location_2}")]
    logger_mock.assert_has_calls(expected_calls)
Beispiel #4
0
    def setUp(self):
        self.unicef_staff = UserFactory(is_superuser=True)
        group = GroupFactory()
        self.unicef_staff.groups.add(group)
        # The tested endpoints require the country id in the query string
        self.country = CountryFactory()
        self.unicef_staff.profile.country = self.country
        self.unicef_staff.save()

        self.location_no_geom = LocationFactory(name="Test no geom")
        self.location_with_geom = LocationFactory(
            name="Test with geom",
            geom="MultiPolygon(((10 10, 10 20, 20 20, 20 15, 10 10)), ((10 10, 10 20, 20 20, 20 15, 10 10)))"
        )
Beispiel #5
0
 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', 'gateway', 'parent', 'geo_point')
     )
Beispiel #6
0
 def test_prp_api_performance(self):
     EXPECTED_QUERIES = 24
     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')
Beispiel #7
0
    def test_travel_creation(self):
        dsaregion = DSARegion.objects.first()
        currency = PublicsCurrencyFactory()
        location = LocationFactory()

        data = {
            '0': {},
            '1': {
                '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'
            }],
            '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'
        }

        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)
Beispiel #8
0
    def test_activity_results(self):
        location = LocationFactory()
        location_2 = LocationFactory()

        data = {
            'activities': [{
                'is_primary_traveler': True,
                'locations': [location.id, location_2.id],
                'partner': PartnerFactory(partner_type=PartnerType.GOVERNMENT).id,
                'travel_type': TravelType.PROGRAMME_MONITORING
            }],
            'traveler': self.traveler.id
        }
        response = self.forced_auth_req('post', reverse('t2f:travels:list:index'), data=data,
                                        user=self.traveler)

        self.assertEqual(response.status_code, 400)
        response_json = json.loads(response.rendered_content)
        self.assertEqual(response_json, {'activities': [{'result': ['This field is required.']}]})
Beispiel #9
0
def test_api_location_list_modified(django_app, admin_user, locations3):
    url = reverse('locations:locations-list')
    response = django_app.get(url, user=admin_user)
    assert len(response.json) == len(locations3)
    etag = response["ETag"]
    LocationFactory()

    response = django_app.get(url,
                              user=admin_user,
                              headers=dict(IF_NONE_MATCH=etag))
    assert len(response.json) == len(locations3) + 1
Beispiel #10
0
    def setUp(self):
        super().setUp()

        self.unicef_staff = UserFactory(is_superuser=True)
        group = GroupFactory()
        self.unicef_staff.groups.add(group)
        self.country = CountryFactory()
        self.unicef_staff.profile.country = self.country
        self.unicef_staff.save()
        self.partner = PartnerFactory()
        self.agreement = AgreementFactory(partner=self.partner)
        self.intervention = InterventionFactory(agreement=self.agreement)
        self.location_no_geom = LocationFactory(name="Test no geom")
        self.location_with_geom = LocationFactory(
            name="Test with geom",
            geom=
            "MultiPolygon(((10 10, 10 20, 20 20, 20 15, 10 10)), ((10 10, 10 20, 20 20, 20 15, 10 10)))"
        )
        self.inactive_location = LocationFactory(is_active=False)
        self.locations = [self.location_no_geom, self.location_with_geom]
Beispiel #11
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)
Beispiel #12
0
def test_location_synchronizer_sync(logger_mock, mock_cartodb_locations,
                                    cartodbtable, carto_response):
    synchronizer = LocationSynchronizer(pk=cartodbtable.pk)
    location_1 = LocationFactory(p_code='RW', is_active=True)
    location_2 = LocationFactory(
        parent=location_1, p_code='RW01', is_active=False, admin_level=cartodbtable.admin_level - 1)
    mock_cartodb_locations.return_value = carto_response

    # test new and deleted-leaf location
    new, updated, skipped, error = synchronizer.sync()
    assert new == 1
    assert skipped == updated == error == 0
    location_1.refresh_from_db()
    assert location_1.is_active
    expected_calls = [
        call(f"Deleting parent {location_2}")]
    logger_mock.assert_has_calls(expected_calls)

    # test updated location
    new, updated, skipped, error = synchronizer.sync()
    assert updated == 1
    assert new == skipped == error == 0
Beispiel #13
0
    def test_activity_location(self):
        location = LocationFactory()
        location_2 = LocationFactory()
        location_3 = LocationFactory()

        data = {'activities': [{'is_primary_traveler': True,
                                'locations': [location.id, location_2.id]}],
                'traveler': self.traveler.id}
        response = self.forced_auth_req('post', reverse('t2f:travels:list:index'), data=data,
                                        user=self.traveler)
        response_json = json.loads(response.rendered_content)

        data = response_json
        data['activities'].append({'locations': [location_3.id],
                                   'is_primary_traveler': True})
        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.assertCountEqual(response_json['activities'][0]['locations'], [location.id, location_2.id])
        self.assertEqual(response_json['activities'][1]['locations'], [location_3.id])
Beispiel #14
0
 def setUpTestData(cls):
     cls.section = SectionFactory()
     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()
Beispiel #15
0
    def setUp(self):
        self.unicef_staff = UserFactory(is_staff=True)
        self.carto_table = CartoDBTableFactory(remap_table_name="test_rmp")
        self.locations = [
            LocationFactory(gateway=self.carto_table.location_type)
            for x in range(5)
        ]
        self.remapped_location = self.locations[0]
        self.new_location = self.locations[1]
        self.obsolete_locations = self.locations[2:]

        self.mock_sql = Mock()
        self.mock_remap_data = Mock()
        self.mock_carto_data = Mock()
        self.geom = "MultiPolygon(((10 10, 10 20, 20 20, 20 15, 10 10)), ((10 10, 10 20, 20 20, 20 15, 10 10)))"
Beispiel #16
0
def test_api_location_queries(
    django_app,
    admin_user,
    location,
    django_assert_num_queries,
):
    url = reverse('locations:locations-list')

    with django_assert_num_queries(10):
        django_app.get(url, user=admin_user)

    query_count = 3
    with django_assert_num_queries(query_count):
        django_app.get(url, user=admin_user)

    # add another location with reference to parent
    # and ensure no extra queries
    LocationFactory(parent=location)
    with django_assert_num_queries(query_count):
        django_app.get(url, user=admin_user)
Beispiel #17
0
def test_location_synchronizer_handle_obsolete_locations(logger_mock, cartodbtable):
    synchronizer = LocationSynchronizer(pk=cartodbtable.pk)
    location_1 = LocationFactory(p_code='RW', is_active=True)
    LocationFactory(parent=location_1, p_code='RW01', is_active=True)
    location_2 = LocationFactory(p_code='PER', is_active=True)
    assert location_1.is_active
    assert location_2.is_active

    synchronizer.handle_obsolete_locations(['RW', 'PER'])
    location_1.refresh_from_db()
    assert not location_1.is_active
    expected_calls = [
        call(f"Deactivating {location_1}"),
        call(f"Deleting {location_2}")]
    logger_mock.assert_has_calls(expected_calls)
Beispiel #18
0
 def setUp(self):
     super(TestInterventionSectionLocationLinkModelExport, self).setUp()
     self.location = LocationFactory(name="Name", )
     self.link = InterventionSectionLocationLinkFactory(
         intervention=self.intervention, )
     self.link.locations.add(self.location)
Beispiel #19
0
def location(db):
    return LocationFactory()
Beispiel #20
0
def location2(db, request):
    from unicef_locations.tests.factories import LocationFactory
    return LocationFactory(parent=None)
Beispiel #21
0
 def populate_locations(self, create, extracted, **kwargs):
     location = LocationFactory()
     self.locations.add(location)
Beispiel #22
0
def locations3(db):
    return [LocationFactory() for _ in range(3)]
Beispiel #23
0
    def locations(self, created, extracted, **kwargs):
        if created:
            self.locations.add(*[LocationFactory() for i in range(3)])

        if extracted:
            self.locations.add(*extracted)
Beispiel #24
0
 def setUpTestData(cls):
     cls.section = SectionFactory()
     cls.location = LocationFactory()
Beispiel #25
0
    def test_activity_export(self):
        tz = timezone.get_default_timezone()
        office = OfficeFactory(name='Budapest')
        section_health = SectionFactory(name='Health')
        section_education = SectionFactory(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,
                                 section=section_health,
                                 start_date=datetime(2017, 11, 8, tzinfo=tz),
                                 end_date=datetime(2017, 11, 14, tzinfo=tz),
                                 )
        supervisor = UserFactory()
        travel_2 = TravelFactory(reference_number='2016/1211',
                                 supervisor=supervisor,
                                 traveler=user_alice_carter,
                                 office=office,
                                 section=section_education,
                                 start_date=datetime(2017, 11, 8, tzinfo=tz),
                                 end_date=datetime(2017, 11, 14, tzinfo=tz),
                                 )

        # 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',
                          '',
                          ''])
Beispiel #26
0
 def get_fixtures(cls):
     return {
         'location': LocationFactory(id=101, p_code='abc'),
         'locationtype': GatewayTypeFactory(),
     }
Beispiel #27
0
    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)
Beispiel #28
0
    def test_intervention_location_export(self):
        # First intervention was already created for us in setUpTestData
        partner_name = self.intervention.agreement.partner.name
        partner_vendor_code = self.intervention.agreement.partner.vendor_number

        # Assign known dates that we can test for in the output later on
        self.intervention.start = datetime.date(2013, 1, 6)
        self.intervention.end = datetime.date(2013, 3, 20)
        self.intervention.save()

        # Some locations
        self.intervention.flat_locations.add(
            LocationFactory(name='Location 0'),
            LocationFactory(name='Location 1'))

        # Some sections
        sec = SectionFactory(name='Sector 0')
        sec1 = SectionFactory(name='Sector 1')
        self.intervention.sections.add(sec, sec1)

        # Some focal points
        self.intervention.unicef_focal_points.add(
            UserFactory(first_name='Jack', last_name='Bennie'),
            UserFactory(first_name='Phil', last_name='Silver'))

        # Some results
        InterventionResultLinkFactory(cp_output=ResultFactory(sector=sec1,
                                                              name='Result A'),
                                      intervention=self.intervention)
        InterventionResultLinkFactory(cp_output=ResultFactory(sector=sec1,
                                                              name='Result B'),
                                      intervention=self.intervention)

        # Another intervention, with no locations
        self.intervention2 = InterventionFactory(agreement=AgreementFactory(
            partner=PartnerFactory(name='Partner 2', vendor_number='123')))
        # Sections
        sec2 = SectionFactory(name='Sector 2')
        sec3 = SectionFactory(name='Sector 3')
        self.intervention2.sections.add(sec2, sec3)
        # Results
        InterventionResultLinkFactory(cp_output=ResultFactory(sector=sec2,
                                                              name='Result C'),
                                      intervention=self.intervention2)
        InterventionResultLinkFactory(cp_output=ResultFactory(sector=sec3,
                                                              name='Result D'),
                                      intervention=self.intervention2)

        # Intervention with no sectors
        self.intervention3 = InterventionFactory(agreement=AgreementFactory(
            partner=PartnerFactory(name='Partner 3', vendor_number='456')))
        self.intervention3.flat_locations.add(
            LocationFactory(name='Location 2'))
        InterventionResultLinkFactory(
            intervention=self.intervention3,
            cp_output=ResultFactory(name='Result Fred'))

        self.url = reverse('partners_api:intervention-locations-list', )

        response = self.forced_auth_req(
            'get',
            self.url,
            user=self.unicef_staff,
            data={"format": "csv"},
        )
        self.assertEqual(200,
                         response.status_code,
                         msg=response.content.decode('utf-8'))
        result = response.content.decode('utf-8')

        today = '{:%Y_%m_%d}'.format(datetime.date.today())
        self.assertEqual(
            f'attachment;filename=PD_locations_as_of_{today}_TST.csv',
            response['Content-Disposition'],
        )

        # Leave this here to easily uncomment for debugging.
        # print("RESULT:")
        # for line in result.split('\r\n'):
        #     print('f' + repr(line + '\r\n'))

        agreement_number_1 = self.intervention.agreement.agreement_number
        agreement_number_2 = self.intervention2.agreement.agreement_number
        agreement_number_3 = self.intervention3.agreement.agreement_number
        self.assertEqual(
            f'Partner,Vendor Number,PD Ref Number,Agreement,Status,Location,Section,CP output,Start Date,End Date,Name of UNICEF Focal Point,Hyperlink\r\n'
            f'{partner_name},{partner_vendor_code},{self.intervention.number},{agreement_number_1},draft,Location 0,Sector 0,"Result A, Result B",2013-01-06,2013-03-20,"Jack Bennie, Phil Silver",https://testserver/pmp/interventions/{self.intervention.id}/details/\r\n'
            f'{partner_name},{partner_vendor_code},{self.intervention.number},{agreement_number_1},draft,Location 1,Sector 0,"Result A, Result B",2013-01-06,2013-03-20,"Jack Bennie, Phil Silver",https://testserver/pmp/interventions/{self.intervention.id}/details/\r\n'
            f'{partner_name},{partner_vendor_code},{self.intervention.number},{agreement_number_1},draft,Location 0,Sector 1,"Result A, Result B",2013-01-06,2013-03-20,"Jack Bennie, Phil Silver",https://testserver/pmp/interventions/{self.intervention.id}/details/\r\n'
            f'{partner_name},{partner_vendor_code},{self.intervention.number},{agreement_number_1},draft,Location 1,Sector 1,"Result A, Result B",2013-01-06,2013-03-20,"Jack Bennie, Phil Silver",https://testserver/pmp/interventions/{self.intervention.id}/details/\r\n'
            f'Partner 2,123,{self.intervention2.number},{agreement_number_2},draft,,Sector 2,"Result C, Result D",,,,https://testserver/pmp/interventions/{self.intervention2.id}/details/\r\n'
            f'Partner 2,123,{self.intervention2.number},{agreement_number_2},draft,,Sector 3,"Result C, Result D",,,,https://testserver/pmp/interventions/{self.intervention2.id}/details/\r\n'
            f'Partner 3,456,{self.intervention3.number},{agreement_number_3},draft,Location 2,,Result Fred,,,,https://testserver/pmp/interventions/{self.intervention3.id}/details/\r\n',
            result,
        )
Beispiel #29
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')

    test_case.file_type_attachment = AttachmentFileTypeFactory(
        code="partners_intervention_attachment")
    test_case.file_type_prc = AttachmentFileTypeFactory(
        code="partners_intervention_prc_review")
    test_case.file_type_pd = AttachmentFileTypeFactory(
        code="partners_intervention_signed_pd")