def setUp(self):
        self.district = Location(
            **dict(name='Kampala', type='district', parent=None))
        self.district.save()

        self.disaster_type = DisasterType(
            **dict(name="Fire", description="Fire"))
        self.disaster_type.save()

        self.serialized_location = dict(created_at=self.district.created_at,
                                        type=self.district.type,
                                        name=self.district.name,
                                        id=str(self.district.id),
                                        latlong=[])

        self.serialized_disaster_type = dict(
            created_at=self.disaster_type.created_at,
            name=self.disaster_type.name,
            description=self.disaster_type.description,
            id=str(self.disaster_type.id))

        self.disaster = dict(name=self.disaster_type,
                             locations=[self.district],
                             description="Big Flood",
                             date=datetime.datetime(2014, 12, 1, 11, 3),
                             status="Assessment")

        self.serialized_disaster = dict(name=self.serialized_disaster_type,
                                        locations=[self.serialized_location],
                                        description="Big Flood",
                                        date="2014-12-01T11:03",
                                        status="Assessment")
示例#2
0
    def test_should_serialize_location_stats_service_integration(self):
        disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        disaster_type.save()

        disaster_attr = dict(name=disaster_type,
                             locations=[self.district],
                             description="Big Flood",
                             date="2014-12-01",
                             status="Assessment")

        Disaster(**disaster_attr).save()

        location_stats_service = LocationStatsService(location=self.district)
        queryset = location_stats_service.aggregate_stats()
        serialized_object = LocationStatsSerializer(queryset)
        serialized_data = {
            'messages': {
                'count': 1,
                'percentage': 50,
                'reporter_ratio': 0
            },
            'disasters': {
                'count': 1,
                'percentage': 100,
                'reporter_ratio': 0
            }
        }

        self.assertEqual(serialized_data, serialized_object.data)
示例#3
0
    def setUp(self):
        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.district = Location(
            **dict(name='Kampala', type='district', parent=None)).save()
示例#4
0
    def setUp(self):
        self.location_name = 'Kampala'
        text = "NECOC.%s. fire baba fire" % self.location_name
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        phone_number = "+256775019449"
        self.message = dict(phone_no=phone_number,
                            text=text,
                            received_at=self.date_time,
                            relayer_id=234,
                            run_id=23243)
        self.kampala = Location(**dict(
            name=self.location_name, parent=None, type='district')).save()
        self.bukoto_name = 'Bukoto'
        self.bukoto = Location(**dict(
            name=self.bukoto_name, parent=None, type='district')).save()
        text = "NECOC.%s. flood" % self.bukoto_name
        self.message_bukoto = dict(phone_no=phone_number,
                                   text=text,
                                   received_at=self.date_time,
                                   relayer_id=234,
                                   run_id=23243)

        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.disaster_attr = dict(name=self.disaster_type,
                                  locations=[self.kampala],
                                  description="Big Flood",
                                  date="2014-12-01",
                                  status="Assessment")

        self.disaster_attr_bukoto = self.disaster_attr.copy()
        self.disaster_attr_bukoto["locations"] = [self.bukoto]
    def test_should_serialize_summary_stats_service_integration(self):
        disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        disaster_type.save()

        disaster_attr = dict(name=disaster_type,
                             locations=[self.district],
                             description="Big Flood",
                             date="2014-12-01",
                             status="Assessment")

        Disaster(**disaster_attr).save()

        location_stats_service = StatsSummaryService(location=self.district)
        queryset = location_stats_service.aggregate_stats()
        serialized_object = SummaryStatsSerializer(queryset)
        serialized_data = {
            'disasters': {
                'count': 1,
                'affected': 1,
                'types': {
                    'Flood': 1
                }
            }
        }

        self.assertEqual(serialized_data, serialized_object.data)
class DisasterSerializerTest(MongoTestCase):
    def setUp(self):
        self.district = Location(**dict(name="Kampala", type="district", parent=None))
        self.district.save()

        self.disaster_type = DisasterType(**dict(name="Fire", description="Fire"))
        self.disaster_type.save()

        self.serialized_location = dict(
            created_at=self.district.created_at,
            type=self.district.type,
            name=self.district.name,
            id=str(self.district.id),
            latlong=[],
        )

        self.serialized_disaster_type = dict(
            created_at=self.disaster_type.created_at,
            name=self.disaster_type.name,
            description=self.disaster_type.description,
            id=str(self.disaster_type.id),
        )

        self.disaster = dict(
            name=self.disaster_type,
            locations=[self.district],
            description="Big Flood",
            date=datetime.datetime(2014, 12, 1, 11, 3),
            status="Assessment",
        )

        self.serialized_disaster = dict(
            name=self.serialized_disaster_type,
            locations=[self.serialized_location],
            description="Big Flood",
            date="2014-12-01T11:03",
            status="Assessment",
        )

    def test_should_serialize_location_object(self):
        self.disaster["date"] = "2014-12-01"
        self.serialized_disaster["date"] = "2014-12-01"
        disaster = Disaster(**self.disaster).save()
        serialized_object = DisasterSerializer(disaster)
        self.assertDictContainsSubset(self.serialized_disaster, serialized_object.data)
        self.assertIsNotNone(serialized_object.data["id"])

    def test_should_deserialize_location_object(self):
        self.serialized_disaster["name"] = self.disaster_type.id
        self.serialized_disaster["locations"] = [self.district.id]

        serializer = DisasterSerializer(data=self.serialized_disaster)
        self.assertTrue(serializer.is_valid())

        saved_disaster = serializer.save()
        self.assertTrue(isinstance(saved_disaster, Disaster))
        for attribute, value in self.disaster.items():
            self.assertEqual(value, getattr(saved_disaster, attribute))
示例#7
0
    def test_create_disaster(self):
        attributes = {"name": "Flood", "description": "a lot of water everywhere"}
        DisasterType(**attributes).save()
        disasters = DisasterType.objects(name="Flood")
        disaster = disasters[0]

        self.assertEqual(1, disasters.count())
        self.assertEqual(attributes['name'], disaster.name)
        self.assertEqual(attributes['description'], disaster.description)
class DisasterSerializerTest(MongoTestCase):
    def setUp(self):
        self.district = Location(
            **dict(name='Kampala', type='district', parent=None))
        self.district.save()

        self.disaster_type = DisasterType(
            **dict(name="Fire", description="Fire"))
        self.disaster_type.save()

        self.serialized_location = dict(created_at=self.district.created_at,
                                        type=self.district.type,
                                        name=self.district.name,
                                        id=str(self.district.id),
                                        latlong=[])

        self.serialized_disaster_type = dict(
            created_at=self.disaster_type.created_at,
            name=self.disaster_type.name,
            description=self.disaster_type.description,
            id=str(self.disaster_type.id))

        self.disaster = dict(name=self.disaster_type,
                             locations=[self.district],
                             description="Big Flood",
                             date=datetime.datetime(2014, 12, 1, 11, 3),
                             status="Assessment")

        self.serialized_disaster = dict(name=self.serialized_disaster_type,
                                        locations=[self.serialized_location],
                                        description="Big Flood",
                                        date="2014-12-01T11:03",
                                        status="Assessment")

    def test_should_serialize_location_object(self):
        self.disaster['date'] = '2014-12-01'
        self.serialized_disaster['date'] = '2014-12-01'
        disaster = Disaster(**self.disaster).save()
        serialized_object = DisasterSerializer(disaster)
        self.assertDictContainsSubset(self.serialized_disaster,
                                      serialized_object.data)
        self.assertIsNotNone(serialized_object.data['id'])

    def test_should_deserialize_location_object(self):
        self.serialized_disaster['name'] = self.disaster_type.id
        self.serialized_disaster['locations'] = [self.district.id]

        serializer = DisasterSerializer(data=self.serialized_disaster)
        self.assertTrue(serializer.is_valid())

        saved_disaster = serializer.save()
        self.assertTrue(isinstance(saved_disaster, Disaster))
        for attribute, value in self.disaster.items():
            self.assertEqual(value, getattr(saved_disaster, attribute))
示例#9
0
class LocationDisasterStatsTest(MongoTestCase):
    def setUp(self):
        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.district = Location(
            **dict(name='Kampala', type='district', parent=None))
        self.district.save()

        self.disaster_attr = dict(name=self.disaster_type,
                                  locations=[self.district],
                                  description="Big Flood",
                                  date="2014-12-01",
                                  status="Assessment")

    def test_should_retrieve_message_count_in_a_location(self):
        Disaster(**self.disaster_attr).save()
        attr2 = self.disaster_attr.copy()
        attr2["status"] = "Closed"
        Disaster(**attr2).save()

        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(2, disasters_stats.count)
        self.assertEqual(100, disasters_stats.percentage)

    def test_should_retrieve_disasters_percentage_in_a_location(self):
        Disaster(**self.disaster_attr).save()
        attr2 = self.disaster_attr.copy()
        attr2["locations"] = [
            Location(**dict(name='Location that is not Kampala',
                            type='district')).save()
        ]
        Disaster(**attr2).save()

        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(1, disasters_stats.count)
        self.assertEqual(50, disasters_stats.percentage)

    def test_should_return_0_if_no_disaster_everywhere(self):
        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(0, disasters_stats.count)
        self.assertEqual(0, disasters_stats.percentage)
示例#10
0
    def setUp(self):
        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.district = Location(
            **dict(name='Kampala', type='district', parent=None))
        self.district.save()

        self.disaster_attr = dict(name=self.disaster_type,
                                  locations=[self.district],
                                  description="Big Flood",
                                  date="2014-12-01",
                                  status="Assessment")
class LocationDisasterStatsTest(MongoTestCase):
    def setUp(self):
        self.disaster_type = DisasterType(**dict(name="Flood", description="Some flood"))
        self.disaster_type.save()

        self.district = Location(**dict(name="Kampala", type="district", parent=None))
        self.district.save()

        self.disaster_attr = dict(
            name=self.disaster_type,
            locations=[self.district],
            description="Big Flood",
            date="2014-12-01",
            status="Assessment",
        )

    def test_should_retrieve_message_count_in_a_location(self):
        Disaster(**self.disaster_attr).save()
        attr2 = self.disaster_attr.copy()
        attr2["status"] = "Closed"
        Disaster(**attr2).save()

        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(2, disasters_stats.count)
        self.assertEqual(100, disasters_stats.percentage)

    def test_should_retrieve_disasters_percentage_in_a_location(self):
        Disaster(**self.disaster_attr).save()
        attr2 = self.disaster_attr.copy()
        attr2["locations"] = [Location(**dict(name="Location that is not Kampala", type="district")).save()]
        Disaster(**attr2).save()

        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(1, disasters_stats.count)
        self.assertEqual(50, disasters_stats.percentage)

    def test_should_return_0_if_no_disaster_everywhere(self):
        location_stats_service = LocationStatsService(location=self.district)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(0, disasters_stats.count)
        self.assertEqual(0, disasters_stats.percentage)
    def test_should_filter_csv_when_date_range_is_specified(self):
        new_date_time = datetime.datetime(2015, 9, 17, 16, 0, 49, 807000)
        new_date_time = new_date_time.replace(tzinfo=pytz.utc)
        disaster_type = DisasterType(**dict(name='Fire', description="Some fire")).save()
        disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Fire",
                                  date=self.date_time,
                                  status="Assessment")
        kampala_disaster = Disaster(**disaster_attr).save()

        RapidProMessage(**self.message).save()
        self.message['received_at'] = new_date_time
        RapidProMessage(**self.message).save()
        expected_response = "phone,text,source,location,time\n" \
                            "+256775019449,NECOC.Bukoto. There is a fire,timothy,Kampala >> Bukoto,%s,Fire" % self.date_time

        response = self.client.get(self.CSV_ENDPOINT, {'dfrom' : 'undefined', 'dto': '2014-11-26', 'format': 'csv'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))

        response = self.client.get(self.CSV_ENDPOINT, {'dfrom' : '2015-01-01', 'dto': 'undefined', 'format': 'csv'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))

        response = self.client.get(self.CSV_ENDPOINT, {'dfrom' : '2014-01-01', 'dto': '2014-11-26', 'format': 'csv'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))

        response = self.client.get(self.CSV_ENDPOINT, {'dfrom' : '2014-01-01', 'dto': '2015-11-26', 'format': 'csv'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))

        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
    def setUp(self):
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        self.date_time = self.date_time.replace(tzinfo=pytz.utc)
        self.district = Location(**dict(name='Kampala', parent=None, type='district')).save()
        self.village = Location(**dict(name='Bukoto', parent=self.district, type='village')).save()
        self.mobile_user = UserProfile(**dict(name='timothy', phone="+256775019449",
                                             location=self.village, email=None)).save()

        self.fire_type = DisasterType(**dict(name="Fire", description="Fire")).save()
        disaster_attributes = dict(name=self.fire_type, locations=[self.district],
                                   description="Big Fire", date="2014-12-01 00:00:00", status="Assessment")
        self.disaster = Disaster(**disaster_attributes).save()

        self.text_format = "NECOC.%s. There is a fire"
        text = self.text_format % self.village.name
        self.expected_message = dict(phone="+256775019449", text=text, time=self.date_time, relayer=234,
                                     run=23243)
        self.message = dict(phone_no="+256775019449", text=text, received_at=self.date_time,
                            relayer_id=234, run_id=23243)

        self.api_user, created = User.objects.get_or_create(**dict(username='******'))
        self.auto_message_response = dict(phone_numbers=[u'+256775019449'], text=settings.AUTO_RESPONSE_MESSAGE)

        self.cao_group, created = Group.objects.get_or_create(name='CAO')
        self.cao_user = User.objects.create(username='******', group=self.cao_group, email='*****@*****.**')
        self.cao_user.set_password('password')
        self.login_url = '/login/'
        self.login_data = {
            'username': '******',
            'password': '******'
        }

        AdminSetting(**dict(name='enable_automatic_response')).save()
        AdminSetting(**dict(name='enable_volunteer_profiles')).save()
    def setUp(self):
        self.user = self.login_user()
        self.district = Location(**dict(name='Kampala', type='district', parent=None))
        self.district.save()
        self.disaster_type = DisasterType(**dict(name="Fire", description="Fire"))
        self.disaster_type.save()
        self.disaster_type2 = DisasterType(**dict(name="Flood", description="Flood"))
        self.disaster_type2.save()
        self.disaster_to_post = dict(name=str(self.disaster_type.id), locations=[str(self.district.id)],
                                     description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")
        self.disaster = dict(name=self.disaster_type, locations=[self.district],
                             description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")

        self.mobile_user = UserProfile(**dict(name='timothy', phone="+256775019449",
                                             location=self.district, email=None)).save()
        self.cao_group, created = Group.objects.get_or_create(name='CAO')
    def test_should_serialize_summary_stats_service_integration(self):
        disaster_type = DisasterType(**dict(name='Flood', description="Some flood"))
        disaster_type.save()

        disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Flood", date="2014-12-01",
                             status="Assessment")

        Disaster(**disaster_attr).save()

        location_stats_service = StatsSummaryService(location=self.district)
        queryset = location_stats_service.aggregate_stats()
        serialized_object = SummaryStatsSerializer(queryset)
        serialized_data = {'disasters': {'count': 1,
                                         'affected': 1, 'types': {'Flood': 1}}}

        self.assertEqual(serialized_data, serialized_object.data)
示例#16
0
class DisasterTypeListCreateView(ListCreateAPIView):
    model = DisasterType
    serializer_class = DisasterTypeSerializer
    queryset = DisasterType.objects()
    permission_classes = [
        Or(build_permission_class('dms.can_manage_disasters'), IsGetRequest)
    ]
示例#17
0
    def test_editing_existing_message_is_valid(self):
        district = Location(
            **dict(name='Kampala', type='district', parent=None)).save()
        disaster_type = DisasterType(
            **dict(name="Fire", description="Fire")).save()

        disaster_attributes = dict(name=disaster_type,
                                   locations=[district],
                                   description="Big Flood",
                                   date="2014-12-01 00:00:00",
                                   status="Assessment")
        disaster = Disaster(**disaster_attributes).save()

        message = RapidProMessage(**self.serialized_data).save()

        data = self.serialized_data.copy()
        data['disaster'] = disaster.id

        serializer = RapidProMessageSerializer(message, data=data)

        self.assertTrue(serializer.is_valid())
        new_message = serializer.save()

        self.assertTrue(message.id, new_message.id)
        self.assertEqual(disaster, new_message.disaster)
    def test_should_serialize_location_stats_service_integration(self):
        disaster_type = DisasterType(**dict(name='Flood', description="Some flood"))
        disaster_type.save()

        disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Flood", date="2014-12-01",
                             status="Assessment")

        Disaster(**disaster_attr).save()

        location_stats_service = LocationStatsService(location=self.district)
        queryset = location_stats_service.aggregate_stats()
        serialized_object = LocationStatsSerializer(queryset)
        serialized_data = {'messages': {'count': 1, 'percentage': 50, 'reporter_ratio': 0},
                           'disasters': {'count': 1, 'percentage': 100, 'reporter_ratio': 0}}

        self.assertEqual(serialized_data, serialized_object.data)
    def setUp(self):
        self.location_name = "Kampala"
        text = "NECOC.%s. fire baba fire" % self.location_name
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        phone_number = "+256775019449"
        self.message = dict(phone_no=phone_number, text=text, received_at=self.date_time, relayer_id=234, run_id=23243)
        self.kampala = Location(**dict(name=self.location_name, parent=None, type="district")).save()
        self.bukoto_name = "Bukoto"
        self.bukoto = Location(**dict(name=self.bukoto_name, parent=None, type="district")).save()
        text = "NECOC.%s. flood" % self.bukoto_name
        self.message_bukoto = dict(
            phone_no=phone_number, text=text, received_at=self.date_time, relayer_id=234, run_id=23243
        )

        self.disaster_type = DisasterType(**dict(name="Flood", description="Some flood"))
        self.disaster_type.save()

        self.disaster_attr = dict(
            name=self.disaster_type,
            locations=[self.kampala],
            description="Big Flood",
            date="2014-12-01",
            status="Assessment",
        )

        self.disaster_attr_bukoto = self.disaster_attr.copy()
        self.disaster_attr_bukoto["locations"] = [self.bukoto]
 def test_should_auto_associate_message_to_disaster_when_posted_from_subcounty(self):
     disaster_type = DisasterType(**dict(name='Flood', description="Some flood")).save()
     disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Flood",
                               date=self.date_time,
                               status="Assessment")
     kampala_disaster = Disaster(**disaster_attr).save()
     text = "NECOC.%s. flood here and allover the place!" % self.village.name
     self.message['text'] = text
     saved_message = RapidProMessage(**self.message).save()
     self.assertEqual(saved_message.disaster, kampala_disaster)
示例#21
0
    def test_should_filter_stats_in_country_by_date_and_disaster_type(self):
        kampala_disaster = Disaster(**self.disaster_attr).save()
        bukoto_disaster = Disaster(**self.disaster_attr_bukoto).save()

        expected_serialized_data = {
            'disasters': {
                'count': 2,
                'affected': 2,
                'types': {
                    'Flood': 2
                }
            }
        }

        from_ = self.date_time - datetime.timedelta(days=1)
        from_ = str(from_.date())
        to_ = self.date_time + datetime.timedelta(days=1)
        to_ = str(to_.date())

        response = self.client.get(
            self.API_ENDPOINT + '?format=json&from=%s&to=%s&disaster_type=%s' %
            (from_, to_, str(self.disaster_type.id)))
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        other_type = DisasterType(
            **dict(name='Fire', description="Some flood")).save()

        expected_serialized_data = {
            'disasters': {
                'count': 0,
                'affected': 0,
                'types': {}
            }
        }

        url = self.API_ENDPOINT + '?format=json&from=%s&to=%s&disaster_type=%s' % (
            from_, to_, str(other_type.id))
        response = self.client.get(url, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '?format=json&from=%s&disaster_type=%s' % (
            to_, str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '?format=json&to=%s&disaster_type=%s' % (
            from_, str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)
    def test_should_save_post_message_and_associate_to_disaster(self):
        disaster_type = DisasterType(**dict(name='Flood', description="Some flood")).save()
        disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Flood",
                                  date=self.date_time,
                                  status="Assessment")
        kampala_disaster = Disaster(**disaster_attr).save()
        text = "NECOC.%s. flood here and allover the place!" % self.district.name
        self.expected_message['text'] = text
        self.expected_message['time'] = self.date_time.strftime(RAPID_PRO_TIME_FORMAT)

        response = self.client.post(self.API_ENDPOINT, data=self.expected_message)
        self.assertEqual(201, response.status_code)
        self.assertEqual(response.data['disaster']['id'], str(kampala_disaster.id))
示例#23
0
    def setUp(self):
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        self.date_time = self.date_time.replace(tzinfo=pytz.utc)
        self.district = Location(
            **dict(name='Kampala', parent=None, type='district')).save()
        self.village = Location(**dict(
            name='Bukoto', parent=self.district, type='village')).save()
        self.fire_disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood")).save()
        self.flood_disaster_type = DisasterType(
            **dict(name='Fire', description="Some raging fire")).save()
        self.storm_disaster_type = DisasterType(**dict(
            name='Storm', description="Heavy rain with thunderstorms")).save()
        self.fire_disaster = Disaster(**dict(name=self.fire_disaster_type, locations=[self.village], \
                                            status=settings.DISASTER_STATUSES[0], date=self.date_time)).save()
        self.flood_disaster = Disaster(**dict(name=self.flood_disaster_type, locations=[self.village], \
                                            status=settings.DISASTER_STATUSES[1], date=self.date_time)).save()
        self.storm_disaster = Disaster(**dict(name=self.storm_disaster_type, locations=[self.village], \
                                            status=settings.DISASTER_STATUSES[0], date=self.date_time)).save()

        self.text_format = "NECOC.%s. There is a fire"
        self.text = self.text_format % self.village.name
    def test_should_return_csv_when_csv_endpoint_is_called(self):
        disaster_type = DisasterType(**dict(name='Fire', description="Some fire")).save()
        disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Fire",
                                  date=self.date_time,
                                  status="Assessment")
        kampala_disaster = Disaster(**disaster_attr).save()

        msg = RapidProMessage(**self.message).save()
        expected_response = "phone,text,source,location,time,disaster\n" \
                            "+256775019449,NECOC.Bukoto. There is a fire,timothy,Kampala >> Bukoto,%s,Fire" % msg.received_at
        response = self.client.get(self.CSV_ENDPOINT, {'format': 'csv'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
    def setUp(self):
        self.disaster_type = DisasterType(**dict(name="Flood", description="Some flood"))
        self.disaster_type.save()

        self.district = Location(**dict(name="Kampala", type="district", parent=None))
        self.district.save()

        self.disaster_attr = dict(
            name=self.disaster_type,
            locations=[self.district],
            description="Big Flood",
            date="2014-12-01",
            status="Assessment",
        )
示例#26
0
    def test_types_of_a_subcounty(self):
        Disaster(**self.disaster_attr).save()
        fire_type = DisasterType(**dict(name='Fire', description="whatever")).save()
        attr2 = self.disaster_attr.copy()
        attr2["name"] = fire_type
        Disaster(**attr2).save()

        location_stats_service = StatsSummaryService(location=self.bukoto)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(2, disasters_stats.count)

        self.assertEqual(1, disasters_stats.affected)
        self.assertEqual({'Flood': 1, 'Fire': 1}, disasters_stats.types)
示例#27
0
    def test_get_user_profile_name_if_exists(self):
        self.message['location'] = self.village
        disaster_type = DisasterType(
            **dict(name="Fire", description="Fire")).save()
        disaster_attributes = dict(name=disaster_type,
                                   locations=[self.village],
                                   description="Big Flood",
                                   date="2014-12-01 00:00:00",
                                   status="Assessment")
        disaster = Disaster(**disaster_attributes).save()
        self.message['disaster'] = disaster

        RapidProMessage(**self.message).save()

        rp_messages = RapidProMessage.objects(**self.message)
        self.assertEqual(self.mobile_user.name, rp_messages[0].source())
示例#28
0
    def test_should_retrieve_message_count_affected_types_of_a_subcounty(self):
        Disaster(**self.disaster_attr).save()
        fire_type = DisasterType(**dict(name='Fire', description="whatever")).save()
        attr2 = self.disaster_attr.copy()
        attr2["locations"] = [Location(**dict(name='Location that is not Kampala', type='district')).save()]
        attr2["name"] = fire_type
        Disaster(**attr2).save()

        location_stats_service = StatsSummaryService(location=self.bukoto)
        stats = location_stats_service.aggregate_stats()
        disasters_stats = stats.disasters

        self.assertEqual(1, disasters_stats.count)

        self.assertEqual(1, disasters_stats.affected)
        self.assertEqual({'Flood': 1}, disasters_stats.types)
示例#29
0
    def test_save_rapid_pro_message(self):
        self.message['location'] = self.village
        disaster_type = DisasterType(
            **dict(name="Fire", description="Fire")).save()
        disaster_attributes = dict(name=disaster_type,
                                   locations=[self.village],
                                   description="Big Flood",
                                   date="2014-12-01 00:00:00",
                                   status="Assessment")
        disaster = Disaster(**disaster_attributes).save()
        self.message['disaster'] = disaster

        RapidProMessage(**self.message).save()

        rp_messages = RapidProMessage.objects(**self.message)
        self.assertEqual(1, rp_messages.count())
示例#30
0
    def test_default_user_profile_name_if_profile_names_not_enabled(self):
        AdminSetting._set("enable_volunteer_profiles", False)
        self.message['location'] = self.village
        disaster_type = DisasterType(
            **dict(name="Fire", description="Fire")).save()
        disaster_attributes = dict(name=disaster_type,
                                   locations=[self.village],
                                   description="Big Flood",
                                   date="2014-12-01 00:00:00",
                                   status="Assessment")
        disaster = Disaster(**disaster_attributes).save()
        self.message['disaster'] = disaster

        RapidProMessage(**self.message).save()

        rp_messages = RapidProMessage.objects(**self.message)
        self.assertEqual("NECOC Volunteer", rp_messages[0].source())
    def test_should_filter_messages_by_disaster_type(self):
        message_attr = self.message.copy()
        message_attr['disaster'] = self.disaster
        fire_message = RapidProMessage(**message_attr).save()
        flood_type = DisasterType(**dict(name="Flood", description="Flood")).save()

        response = self.client.get(self.API_ENDPOINT, {"disaster_type": str(self.fire_type.id), "format": "json"})

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(str(fire_message.id), response.data[0]['id'])
        self.assertDictContainsSubset(self.expected_message, response.data[0])

        response = self.client.get(self.API_ENDPOINT, {"disaster_type": str(flood_type.id), "format": "json"})

        self.assertEqual(200, response.status_code)
        self.assertEqual(0, len(response.data))
示例#32
0
    def setUp(self):
        self.location_name = 'Kampala'
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        self.kampala = Location(**dict(
            name=self.location_name, parent=None, type='district')).save()
        self.bukoto_name = 'Bukoto'
        self.bukoto = Location(**dict(
            name=self.bukoto_name, parent=None, type='district')).save()
        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood")).save()
        self.disaster_attr = dict(name=self.disaster_type,
                                  locations=[self.kampala],
                                  description="Big Flood",
                                  date=self.date_time,
                                  status="Assessment")

        self.disaster_attr_bukoto = self.disaster_attr.copy()
        self.disaster_attr_bukoto["locations"] = [self.bukoto]
示例#33
0
    def test_should_filter_stats_in_country_by_disaster_types(self):
        kampala_disaster = Disaster(**self.disaster_attr).save()
        bukoto_disaster = Disaster(**self.disaster_attr_bukoto).save()

        expected_serialized_data = {
            'disasters': {
                'count': 2,
                'affected': 2,
                'types': {
                    'Flood': 2
                }
            }
        }

        response = self.client.get(self.API_ENDPOINT +
                                   '?format=json&disaster_type=%s' %
                                   str(self.disaster_type.id))

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        disaster_type2 = DisasterType(
            **dict(name='Fire', description="Some fire")).save()
        disaster_attr = self.disaster_attr.copy()
        disaster_attr['name'] = disaster_type2
        Disaster(**disaster_attr).save()

        expected_serialized_data = {
            'disasters': {
                'count': 1,
                'affected': 1,
                'types': {
                    'Fire': 1
                }
            }
        }

        response = self.client.get(self.API_ENDPOINT +
                                   '?format=json&disaster_type=%s' %
                                   str(disaster_type2.id))

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)
    def setUp(self):
        self.district = Location(**dict(name="Kampala", type="district", parent=None))
        self.district.save()

        self.disaster_type = DisasterType(**dict(name="Fire", description="Fire"))
        self.disaster_type.save()

        self.serialized_location = dict(
            created_at=self.district.created_at,
            type=self.district.type,
            name=self.district.name,
            id=str(self.district.id),
            latlong=[],
        )

        self.serialized_disaster_type = dict(
            created_at=self.disaster_type.created_at,
            name=self.disaster_type.name,
            description=self.disaster_type.description,
            id=str(self.disaster_type.id),
        )

        self.disaster = dict(
            name=self.disaster_type,
            locations=[self.district],
            description="Big Flood",
            date=datetime.datetime(2014, 12, 1, 11, 3),
            status="Assessment",
        )

        self.serialized_disaster = dict(
            name=self.serialized_disaster_type,
            locations=[self.serialized_location],
            description="Big Flood",
            date="2014-12-01T11:03",
            status="Assessment",
        )
class TestDisasterEndpoint(MongoAPITestCase):

    API_ENDPOINT = '/api/v1/disasters/'
    CSV_ENDPOINT = '/api/v1/csv-disasters/'

    def setUp(self):
        self.user = self.login_user()
        self.district = Location(**dict(name='Kampala', type='district', parent=None))
        self.district.save()
        self.disaster_type = DisasterType(**dict(name="Fire", description="Fire"))
        self.disaster_type.save()
        self.disaster_type2 = DisasterType(**dict(name="Flood", description="Flood"))
        self.disaster_type2.save()
        self.disaster_to_post = dict(name=str(self.disaster_type.id), locations=[str(self.district.id)],
                                     description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")
        self.disaster = dict(name=self.disaster_type, locations=[self.district],
                             description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")

        self.mobile_user = UserProfile(**dict(name='timothy', phone="+256775019449",
                                             location=self.district, email=None)).save()
        self.cao_group, created = Group.objects.get_or_create(name='CAO')

    def test_should_post_a_disaster(self):
        response = self.client.post(self.API_ENDPOINT, data=json.dumps(self.disaster_to_post), content_type="application/json")
        self.assertEqual(201, response.status_code)

        retrieved_disaster = Disaster.objects(description="Big Flood")
        self.assertEqual(1, retrieved_disaster.count())

    def test_should_get_a_list_of_disasters(self):
        Disaster(**self.disaster).save()
        response = self.client.get(self.API_ENDPOINT, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(self.disaster_to_post['status'], response.data[0]['status'])
        self.assertEqual(self.disaster_to_post['date'], str(response.data[0]['date']))
        self.assertEqual(self.disaster_to_post['description'], response.data[0]['description'])

    def test_can_get_a_list_of_disasters_with_no_permissions(self):
        self.login_without_permissions()
        response = self.client.get(self.API_ENDPOINT)
        self.assertEquals(response.status_code, 200)

    def test_cant_post_to_disasters_without_permission(self):
        self.assert_permission_required_for_post(self.API_ENDPOINT)

    def test_can_post_to_disasters_with_permission(self):
        self.login_with_permission('can_manage_disasters')
        response = self.client.get(self.API_ENDPOINT)
        self.assertEquals(response.status_code, 200)
        response = self.client.post(self.API_ENDPOINT, data=json.dumps(self.disaster_to_post), content_type="application/json")
        self.assertEqual(201, response.status_code)

    def test_should_get_a_single_disaster(self):
        disaster = Disaster(**self.disaster).save()
        response = self.client.get(self.API_ENDPOINT + str(disaster.id) + '/', format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(self.disaster_to_post['status'], response.data['status'])
        self.assertEqual(self.disaster_to_post['date'], str(response.data['date']))
        self.assertEqual(self.disaster_to_post['description'], response.data['description'])

    def test_cant_get_or_post_single_disaster_without_permission(self):
        disaster = Disaster(**self.disaster).save()
        self.assert_permission_required_for_get(self.API_ENDPOINT + str(disaster.id) + '/')
        self.assert_permission_required_for_post(self.API_ENDPOINT + str(disaster.id) + '/')

    def test_should_post_a_single_disaster(self):
        disaster = Disaster(**self.disaster_to_post).save()
        self.disaster_to_post['description'] = "Giant Flood"
        response = self.client.post(self.API_ENDPOINT + str(disaster.id) + '/',
                                    data=json.dumps(self.disaster_to_post),
                                    content_type="application/json")
        self.assertEqual(200, response.status_code)

        retrieved_disaster = Disaster.objects(description="Giant Flood")
        self.assertEqual(1, retrieved_disaster.count())

    def test_filter_disaster_by_status(self):
        Disaster(**self.disaster).save()
        disaster_attr2 = self.disaster.copy()
        disaster_attr2['status'] = "Closed"
        Disaster(**disaster_attr2).save()

        response = self.client.get(self.API_ENDPOINT+'?status=Closed&format=json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual('Closed', response.data[0]['status'])
        self.assertEqual(self.disaster_to_post['date'], str(response.data[0]['date']))
        self.assertEqual(self.disaster_to_post['description'], response.data[0]['description'])

    def test_filter_disaster_by_date(self):
        disaster_attr = self.disaster.copy()
        date_1_jan = "2014-01-01"
        disaster_attr['date'] = date_1_jan

        disaster_attr2 = self.disaster.copy()
        date_3_jan = "2014-01-03"
        disaster_attr2['date'] = date_3_jan

        Disaster(**disaster_attr).save()
        Disaster(**disaster_attr2).save()

        response = self.client.get(self.API_ENDPOINT+'?from=%s&to=%s&format=json' % (date_1_jan, date_3_jan))

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_1_jan, "%Y-%m-%d"), response.data[0]['date'])
        self.assertEqual(datetime.datetime.strptime(date_3_jan, "%Y-%m-%d"), response.data[1]['date'])

        response = self.client.get(self.API_ENDPOINT+'?from=%s&format=json' % date_3_jan)

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_3_jan, "%Y-%m-%d"), response.data[0]['date'])

        response = self.client.get(self.API_ENDPOINT+'?to=%s&format=json' % date_1_jan)

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_1_jan, "%Y-%m-%d"), response.data[0]['date'])

    def test_filter_disaster_by_date_and_date(self):
        disaster_attr = self.disaster.copy()
        date_1_jan = "2014-01-01"
        disaster_attr['date'] = date_1_jan

        disaster_attr2 = self.disaster.copy()
        date_3_jan = "2014-01-03"
        disaster_attr2['status'] = "Closed"
        disaster_attr2['date'] = date_3_jan

        Disaster(**disaster_attr).save()
        Disaster(**disaster_attr2).save()

        response = self.client.get(self.API_ENDPOINT+'?from=%s&to=%s&status=Closed&format=json' % (date_1_jan, date_3_jan))

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_3_jan, "%Y-%m-%d"), response.data[0]['date'])

        response = self.client.get(self.API_ENDPOINT+'?from=%s&status=closed&format=json' % date_3_jan)

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_3_jan, "%Y-%m-%d"), response.data[0]['date'])

        response = self.client.get(self.API_ENDPOINT+'?to=%s&status=assessment&format=json' % date_1_jan)

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(datetime.datetime.strptime(date_1_jan, "%Y-%m-%d"), response.data[0]['date'])

    def test_should_return_only_district_disasters_for_CAO(self):
        self.user.group = self.cao_group
        self.user.save()
        self.mobile_user.user = self.user
        self.mobile_user.save()

        masaka_district = Location(**dict(name='Masaka', parent=None, type='district')).save()

        masaka_disaster = dict(name=self.disaster_type, locations=[masaka_district],
                             description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")

        Disaster(**self.disaster).save()
        Disaster(**masaka_disaster).save()
        response = self.client.get(self.API_ENDPOINT, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(self.disaster_to_post['status'], response.data[0]['status'])
        self.assertEqual(self.disaster_to_post['date'], str(response.data[0]['date']))
        self.assertEqual(self.disaster_to_post['description'], response.data[0]['description'])
        self.assertEqual('Kampala', response.data[0]['locations'][0]['name'])

    def test_should_return_csv_when_csv_endpoint_is_called(self):
        Disaster(**self.disaster).save()
        disaster_attr2 = self.disaster.copy()
        disaster_attr2['status'] = "Closed"
        Disaster(**disaster_attr2).save()
        disaster2 = self.disaster.copy()
        disaster2['name'] = self.disaster_type2
        Disaster(**disaster2).save()

        response = self.client.get(self.CSV_ENDPOINT, format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Fire,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name,)
        expected_response = expected_response + "\r\nFire,Big Flood,%s,Closed,2014-12-01 00:00:00" % (self.district.name)
        expected_response = expected_response + "\r\nFlood,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(3, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

    def test_should_return_filtered_csv_when_csv_endpoint_is_called(self):
        Disaster(**self.disaster).save()
        disaster_attr2 = self.disaster.copy()
        disaster_attr2['status'] = "Closed"
        Disaster(**disaster_attr2).save()
        disaster2 = self.disaster.copy()
        disaster2['name'] = self.disaster_type2
        sdisaster = Disaster(**disaster2).save()

        response = self.client.get(self.CSV_ENDPOINT, format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Fire,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name,)
        expected_response = expected_response + "\r\nFire,Big Flood,%s,Closed,2014-12-01 00:00:00" % (self.district.name)
        expected_response = expected_response + "\r\nFlood,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(3, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

        response = self.client.get(self.CSV_ENDPOINT + '?status=Assessment&from=undefined', format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Fire,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name,)
        expected_response = expected_response + "\r\nFlood,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

        sdisaster.date = "2014-12-02 00:00:00"
        sdisaster.save()

        response = self.client.get(self.CSV_ENDPOINT + '?status=Assessment&from=2014-12-02 00:00:00', format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Flood,Big Flood,%s,Assessment,2014-12-02 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

        response = self.client.get(self.CSV_ENDPOINT + '?to=2014-12-01 00:00:00', format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Fire,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name,)
        expected_response = expected_response + "\r\nFire,Big Flood,%s,Closed,2014-12-01 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

    def test_should_return_csv_with_all_records_when_empty_filters_are_used_on_csv_endpoint(self):
        Disaster(**self.disaster).save()
        disaster_attr2 = self.disaster.copy()
        disaster_attr2['status'] = "Closed"
        Disaster(**disaster_attr2).save()
        disaster2 = self.disaster.copy()
        disaster2['name'] = self.disaster_type2
        sdisaster = Disaster(**disaster2).save()

        response = self.client.get(self.CSV_ENDPOINT + '?status=undefined&from=undefined&to=undefined', format='csv')

        expected_response = "name,description,location,status,date\r\n" \
                            "Fire,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name,)
        expected_response = expected_response + "\r\nFire,Big Flood,%s,Closed,2014-12-01 00:00:00" % (self.district.name)
        expected_response = expected_response + "\r\nFlood,Big Flood,%s,Assessment,2014-12-01 00:00:00" % (self.district.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(3, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)), collections.Counter(split_text(response.content)))

    @mock.patch('dms.tasks.send_email.delay')
    def test_changing_disaster_status_sends_email_to_stakeholders(self, mock_send_email):
        disaster = Disaster(**self.disaster).save()
        disaster.status = 'Closed'
        disaster.save()
        mock_send_email.assert_called_with('Status of Disaster Risk has changed',
                                           mock.ANY,
                                           settings.DEFAULT_FROM_EMAIL,
                                           settings.DISASTER_NOTIFY_STATUS)
 def validate_name(self, attrs, source):
     if len(DisasterType.objects(name=attrs[source])):
         raise rest_serializers.ValidationError('Disaster type must be unique')
     return attrs
示例#37
0
class MultiLocationStatsTest(MongoTestCase):
    def setUp(self):
        self.location_name = 'Kampala'
        text = "NECOC.%s. fire baba fire" % self.location_name
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        phone_number = "+256775019449"
        self.message = dict(phone_no=phone_number,
                            text=text,
                            received_at=self.date_time,
                            relayer_id=234,
                            run_id=23243)
        self.kampala = Location(**dict(
            name=self.location_name, parent=None, type='district')).save()
        self.bukoto_name = 'Bukoto'
        self.bukoto = Location(**dict(
            name=self.bukoto_name, parent=None, type='district')).save()
        text = "NECOC.%s. flood" % self.bukoto_name
        self.message_bukoto = dict(phone_no=phone_number,
                                   text=text,
                                   received_at=self.date_time,
                                   relayer_id=234,
                                   run_id=23243)

        self.disaster_type = DisasterType(
            **dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.disaster_attr = dict(name=self.disaster_type,
                                  locations=[self.kampala],
                                  description="Big Flood",
                                  date="2014-12-01",
                                  status="Assessment")

        self.disaster_attr_bukoto = self.disaster_attr.copy()
        self.disaster_attr_bukoto["locations"] = [self.bukoto]

    def test_should_retrieve_message_stats_in_all_locations(self):
        RapidProMessage(**self.message).save()
        RapidProMessage(**self.message_bukoto).save()
        Disaster(**self.disaster_attr).save()
        Disaster(**self.disaster_attr_bukoto).save()

        multi_location_stats_service = MultiLocationStatsService(location=None)
        stats = multi_location_stats_service.stats()
        self.assertEqual(2, len(stats))

        self.assertEqual(1, stats['Kampala'].messages.count)
        self.assertEqual(50, stats['Kampala'].messages.percentage)
        self.assertEqual(1, stats['Kampala'].disasters.count)
        self.assertEqual(50, stats['Kampala'].disasters.percentage)

        self.assertEqual(1, stats['Bukoto'].messages.count)
        self.assertEqual(50, stats['Bukoto'].messages.percentage)
        self.assertEqual(1, stats['Bukoto'].disasters.count)
        self.assertEqual(50, stats['Bukoto'].disasters.percentage)

    def test_should_retrieve_message_stats_in_subcounties_when_district_name_supplied(
            self):
        RapidProMessage(**self.message).save()

        bugolobi_name = 'Bugolobi'
        bugolobi = Location(**dict(
            name=bugolobi_name, parent=self.kampala, type='subcounty')).save()
        text = "NECOC.%s. flood" % bugolobi_name
        message_bugolobi = dict(phone_no='123444',
                                text=text,
                                received_at=self.date_time,
                                relayer_id=234,
                                run_id=23243)
        RapidProMessage(**message_bugolobi).save()

        Disaster(**self.disaster_attr).save()
        disaster_attr_bugolobi = self.disaster_attr.copy()
        disaster_attr_bugolobi["locations"] = [bugolobi]
        Disaster(**disaster_attr_bugolobi).save()

        multi_location_stats_service = MultiLocationStatsService(
            self.kampala.name)
        stats = multi_location_stats_service.stats()
        self.assertEqual(1, len(stats))

        self.assertEqual(1, stats['Bugolobi'].messages.count)
        self.assertEqual(50, stats['Bugolobi'].messages.percentage)
        self.assertEqual(1, stats['Bugolobi'].disasters.count)
        self.assertEqual(50, stats['Bugolobi'].disasters.percentage)
示例#38
0
class TestDisasterModel(MongoTestCase):
    def setUp(self):
        self.disaster_type = DisasterType(**dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.district = Location(**dict(name='Kampala', type='district', parent=None)).save()

    def test_create_disaster(self):
        attributes = dict(name=self.disaster_type, locations=[self.district], description="Big Flood",
                          date="2014-12-01", status="Assessment")
        Disaster(**attributes).save()
        disasters = Disaster.objects(name=self.disaster_type, date="2014-12-01", status="Assessment")

        self.assertEqual(1, disasters.count())

    def test_get_disaster_from_a_location(self):
        attributes = dict(name=self.disaster_type, locations=[self.district], description="Big Flood",
                          date="2014-12-01", status="Assessment")
        disaster1 = Disaster(**attributes).save()

        attr2 = attributes.copy()
        attr2["locations"] = [Location(**dict(name='Some other location', type='district', parent=None)).save()]
        disaster2 = Disaster(**attr2).save()

        location_disasters = Disaster.from_(self.district)
        self.assertEqual(1, location_disasters.count())
        self.assertIn(disaster1, location_disasters)
        self.assertNotIn(disaster2, location_disasters)

    def test_get_disasters_given_from_date_and_to_date(self):
        date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        attributes = dict(name=self.disaster_type, locations=[self.district], description="Big Flood",
                          date=date_time, status="Assessment")
        disaster1 = Disaster(**attributes).save()

        attr2 = attributes.copy()
        attr2["date"] = datetime.datetime(2014, 8, 17, 16, 0, 49, 807000)
        disaster2 = Disaster(**attr2).save()

        location_disasters = Disaster.from_(self.district, **{'from': '2014-08-17', 'to': '2014-09-17'})
        self.assertEqual(1, location_disasters.count())
        self.assertIn(disaster2, location_disasters)
        self.assertNotIn(disaster1, location_disasters)

        location_disasters = Disaster.from_(self.district, **{'from': None, 'to': None})
        self.assertEqual(2, location_disasters.count())

    def test_get_disaster_count_given_from_date_and_to_date(self):
        date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        attributes = dict(name=self.disaster_type, locations=[self.district], description="Big Flood",
                          date=date_time, status="Assessment" )
        Disaster(**attributes).save()

        location_disasters = Disaster.count_(**{'from': '2014-08-17', 'to': '2014-10-17'})
        self.assertEqual(1, location_disasters)

        location_disasters = Disaster.count_(**{'from': '2014-11-17', 'to': '2014-12-17'})
        self.assertEqual(0, location_disasters)

        location_disasters = Disaster.count_(**{'from': None, 'to': None})
        self.assertEqual(1, location_disasters)

    def test_get_messages_from_children_are_also_added(self):
        attributes = dict(name=self.disaster_type, locations=[self.district], description="Big Flood",
                          date="2014-12-01",
                          status="Assessment")
        disaster1 = Disaster(**attributes).save()

        attr2 = attributes.copy()
        attr2["locations"] = [Location(**dict(name='Kampala subcounty', type='subcounty', parent=self.district)).save()]
        disaster2 = Disaster(**attr2).save()

        location_disasters = Disaster.from_(self.district)

        self.assertEqual(2, location_disasters.count())
        self.assertIn(disaster1, location_disasters)
        self.assertIn(disaster2, location_disasters)
class MultiLocationStatsTest(MongoTestCase):
    def setUp(self):
        self.location_name = "Kampala"
        text = "NECOC.%s. fire baba fire" % self.location_name
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        phone_number = "+256775019449"
        self.message = dict(phone_no=phone_number, text=text, received_at=self.date_time, relayer_id=234, run_id=23243)
        self.kampala = Location(**dict(name=self.location_name, parent=None, type="district")).save()
        self.bukoto_name = "Bukoto"
        self.bukoto = Location(**dict(name=self.bukoto_name, parent=None, type="district")).save()
        text = "NECOC.%s. flood" % self.bukoto_name
        self.message_bukoto = dict(
            phone_no=phone_number, text=text, received_at=self.date_time, relayer_id=234, run_id=23243
        )

        self.disaster_type = DisasterType(**dict(name="Flood", description="Some flood"))
        self.disaster_type.save()

        self.disaster_attr = dict(
            name=self.disaster_type,
            locations=[self.kampala],
            description="Big Flood",
            date="2014-12-01",
            status="Assessment",
        )

        self.disaster_attr_bukoto = self.disaster_attr.copy()
        self.disaster_attr_bukoto["locations"] = [self.bukoto]

    def test_should_retrieve_message_stats_in_all_locations(self):
        RapidProMessage(**self.message).save()
        RapidProMessage(**self.message_bukoto).save()
        Disaster(**self.disaster_attr).save()
        Disaster(**self.disaster_attr_bukoto).save()

        multi_location_stats_service = MultiLocationStatsService(location=None)
        stats = multi_location_stats_service.stats()
        self.assertEqual(2, len(stats))

        self.assertEqual(1, stats["Kampala"].messages.count)
        self.assertEqual(50, stats["Kampala"].messages.percentage)
        self.assertEqual(1, stats["Kampala"].disasters.count)
        self.assertEqual(50, stats["Kampala"].disasters.percentage)

        self.assertEqual(1, stats["Bukoto"].messages.count)
        self.assertEqual(50, stats["Bukoto"].messages.percentage)
        self.assertEqual(1, stats["Bukoto"].disasters.count)
        self.assertEqual(50, stats["Bukoto"].disasters.percentage)

    def test_should_retrieve_message_stats_in_subcounties_when_district_name_supplied(self):
        RapidProMessage(**self.message).save()

        bugolobi_name = "Bugolobi"
        bugolobi = Location(**dict(name=bugolobi_name, parent=self.kampala, type="subcounty")).save()
        text = "NECOC.%s. flood" % bugolobi_name
        message_bugolobi = dict(phone_no="123444", text=text, received_at=self.date_time, relayer_id=234, run_id=23243)
        RapidProMessage(**message_bugolobi).save()

        Disaster(**self.disaster_attr).save()
        disaster_attr_bugolobi = self.disaster_attr.copy()
        disaster_attr_bugolobi["locations"] = [bugolobi]
        Disaster(**disaster_attr_bugolobi).save()

        multi_location_stats_service = MultiLocationStatsService(self.kampala.name)
        stats = multi_location_stats_service.stats()
        self.assertEqual(1, len(stats))

        self.assertEqual(1, stats["Bugolobi"].messages.count)
        self.assertEqual(50, stats["Bugolobi"].messages.percentage)
        self.assertEqual(1, stats["Bugolobi"].disasters.count)
        self.assertEqual(50, stats["Bugolobi"].disasters.percentage)
    def test_should_filter_stats_in_all_locations_by_date_and_disaster_type(
            self):
        kampala_disaster = Disaster(**self.disaster_attr).save()
        bukoto_disaster = Disaster(**self.disaster_attr_bukoto).save()

        message_attr = self.message.copy()
        message_attr['disaster'] = kampala_disaster
        RapidProMessage(**message_attr).save()
        RapidProMessage(**self.message_bukoto).save()

        expected_serialized_data = {
            'kampala': {
                'messages': {
                    'count': 1,
                    'percentage': 50,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 1,
                    'percentage': 50,
                    'reporter_ratio': 0
                }
            },
            'bukoto': {
                'messages': {
                    'count': 1,
                    'percentage': 50,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 1,
                    'percentage': 50,
                    'reporter_ratio': 0
                }
            }
        }

        from_ = self.date_time - datetime.timedelta(days=1)
        from_ = str(from_.date())
        to_ = self.date_time + datetime.timedelta(days=1)
        to_ = str(to_.date())

        response = self.client.get(
            self.API_ENDPOINT + '?format=json&from=%s&to=%s&disaster_type=%s' %
            (from_, to_, str(self.disaster_type.id)))
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        expected_serialized_data = {
            'kampala': {
                'messages': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                }
            },
            'bukoto': {
                'messages': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                }
            }
        }

        other_type = DisasterType(
            **dict(name='Fire', description="Some flood")).save()

        url = self.API_ENDPOINT + '?format=json&from=%s&to=%s&disaster_type=%s' % (
            from_, to_, str(other_type.id))
        response = self.client.get(url, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '?format=json&from=%s&disaster_type=%s' % (
            to_, str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '?format=json&to=%s&disaster_type=%s' % (
            from_, str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)
    def test_filter_stats_in_subcounties_in_district_by_date_and_disater_type(
            self):
        RapidProMessage(**self.message).save()

        bugolobi_name = 'Bugolobi'
        bugolobi = Location(**dict(
            name=bugolobi_name, parent=self.kampala, type='subcounty')).save()
        text = "NECOC.%s. flood" % bugolobi_name
        message_bugolobi = dict(phone_no='123444',
                                text=text,
                                received_at=self.date_time,
                                relayer_id=234,
                                run_id=23243)

        Disaster(**self.disaster_attr).save()
        disaster_attr_bugolobi = self.disaster_attr.copy()
        disaster_attr_bugolobi["locations"] = [bugolobi]
        disaster_bugolobi = Disaster(**disaster_attr_bugolobi).save()
        message_bugolobi['disaster'] = disaster_bugolobi

        RapidProMessage(**message_bugolobi).save()

        expected_serialized_data = {
            'bugolobi': {
                'messages': {
                    'count': 1,
                    'percentage': 100,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 1,
                    'percentage': 50,
                    'reporter_ratio': 0
                }
            }
        }

        from_ = self.date_time - datetime.timedelta(days=1)
        from_ = str(from_.date())
        to_ = self.date_time + datetime.timedelta(days=1)
        to_ = str(to_.date())

        url = self.API_ENDPOINT + '%s/?format=json&from=%s&to=%s&disaster_type=%s' % (
            str(self.kampala.name.lower()), from_, to_,
            str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        expected_serialized_data = {
            'bugolobi': {
                'messages': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                },
                'disasters': {
                    'count': 0,
                    'percentage': 0,
                    'reporter_ratio': 0
                }
            }
        }

        other_type = DisasterType(
            **dict(name='Fire', description="Some flood")).save()

        url = self.API_ENDPOINT + '%s/?format=json&from=%s&to=%s&disaster_type=%s' % (
            str(self.kampala.name.lower()), from_, to_, str(other_type.id))
        response = self.client.get(url, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '%s/?format=json&from=%s&disaster_type=%s' % (
            str(self.kampala.name.lower()), to_, str(self.disaster_type.id))
        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)

        url = self.API_ENDPOINT + '%s/?format=json&to=%s&disaster_type=%s' % (
            str(self.kampala.name.lower()), from_, str(self.disaster_type.id))

        response = self.client.get(url, format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_serialized_data, response.data)
示例#42
0
    def setUp(self):
        self.disaster_type = DisasterType(**dict(name='Flood', description="Some flood"))
        self.disaster_type.save()

        self.district = Location(**dict(name='Kampala', type='district', parent=None)).save()
示例#43
0
 def query_by_disaster_type(self, disaster_type, queryset=None):
     disaster_type = DisasterType.objects(id=disaster_type).first()
     disasters = Disaster.objects(name=disaster_type)
     return queryset.filter(disaster__in=disasters)