예제 #1
0
    def setUp(self):
        self.location_name = 'Kampala'
        text = "NECOC.%s. fire baba fire" % self.location_name
        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=date_time,
                            relayer_id=234,
                            run_id=23243)
        self.district = 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=date_time,
                                   relayer_id=234,
                                   run_id=23243)

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

        self.disaster_attr = dict(name=disaster_type,
                                  locations=[self.district],
                                  description="Big Flood",
                                  date="2014-12-01",
                                  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)
    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))
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))
예제 #6
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)
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_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 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)
    def setUp(self):
        self.location_name = 'Kampala'
        text = "NECOC.%s. fire baba fire" % self.location_name
        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=date_time, relayer_id=234, run_id=23243)
        self.district = 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=date_time, relayer_id=234,
                                   run_id=23243)

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

        self.disaster_attr = dict(name=disaster_type, locations=[self.district], description="Big Flood",
                                  date="2014-12-01",
                                  status="Assessment")
예제 #11
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)
예제 #12
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)
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)
예제 #14
0
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)
예제 #15
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)