Exemple #1
0
 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",
             "max": 1,
             "count": 1,
         }]
     }
     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())
Exemple #2
0
    def test_update_parent(self):
        """If location does exist then update it
        and if parent instance provided, set parent value as well
        """
        carto = CartoDBTableFactory()
        parent1 = LocationFactory(p_code="p1")
        location = LocationFactory(p_code="123", parent=parent1)

        parent2 = LocationFactory(p_code="p2")
        name = "Test"

        self.assertEqual(location.parent, parent1)
        success, not_added, created, updated = tasks.create_location(
            "123",
            carto,
            True,
            parent2,
            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 = Location.objects.get(p_code="123")
        self.assertIsNotNone(location.point)
        self.assertIsNone(location.geom)
        self.assertEqual(location.name, name)
        self.assertEqual(location.parent, parent2)
Exemple #3
0
    def test_location(self):
        # Test with nonascii 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(str(location), u'R\xe4dda Barnen (xyz PCode: abc)')

        # Test with str gateway name
        gateway_type = GatewayTypeFactory.build(name='xyz')
        location = LocationFactory.build(gateway=gateway_type,
                                         name=u'R\xe4dda Barnen',
                                         p_code='abc')
        self.assertEqual(str(location), u'R\xe4dda Barnen (xyz PCode: abc)')
Exemple #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)))"
        )
Exemple #5
0
    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)
Exemple #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')
Exemple #7
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', 'location_type',
          'location_type_admin_level', 'parent', 'geo_point'))
Exemple #8
0
    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)
Exemple #9
0
 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",
             "max": 1,
             "count": 1,
         }]
     }
     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)
Exemple #10
0
 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()
Exemple #11
0
    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)
Exemple #12
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)
Exemple #13
0
    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(self):
     super(TestInterventionSectorLocationLinkModelExport, self).setUp()
     self.location = LocationFactory(name="Name", )
     self.link = InterventionSectorLocationLinkFactory(
         intervention=self.intervention, )
     self.link.locations.add(self.location)
Exemple #15
0
    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 test_intervention_location_export(self):
        # First intervention was already created for us in setUpTestData
        partner_name = self.intervention.agreement.partner.name

        # 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 = SectorFactory(name='Sector 0')
        sec1 = SectorFactory(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')))
        # Sections
        sec2 = SectorFactory(name='Sector 2')
        sec3 = SectorFactory(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')))
        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 = datetime.date.today()
        self.assertEqual(
            f'attachment;filename={today.year}_{today.month}_{today.day}_TST_Interventions.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,PD Ref Number,Partnership,Status,Location,Section,CP output,Start Date,End Date,Name of UNICEF Focal Point,Hyperlink\r\n'
            f'{partner_name},{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},{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},{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},{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,{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,{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,{self.intervention3.number},{agreement_number_3},draft,Location 2,,Result Fred,,,,https://testserver/pmp/interventions/{self.intervention3.id}/details/\r\n',
            result,
        )
Exemple #17
0
    def test_activity_export(self):
        tz = timezone.get_default_timezone()
        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(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,
                                 sector=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',
                          '',
                          ''])
Exemple #18
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')
Exemple #19
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)
Exemple #20
0
 def populate_locations(self, create, extracted, **kwargs):
     location = LocationFactory()
     self.locations.add(location)