Exemplo n.º 1
0
class ViewsUtilsTestCase(TestCase):
    '''
    test the views helper functions
    '''
    def setUp(self):
        self.test_utils = TestUserUtility()
        pass

    def tearDown(self):
        User.objects.all().delete()
        pass

    def test_user_in_group(self):
        '''
        verify that user group testing works correctly
        '''
        groups = [
            'senior-data-analyst',
            'chief-data-analyst',
        ]
        self.test_utils.add_user_to_group('data-analyst')
        failed = is_user_in_groups(groups, self.test_utils.user)
        self.assertEqual(failed, False)
        self.test_utils.add_user_to_group('senior-data-analyst')
        passed = is_user_in_groups(groups, self.test_utils.user)
        self.assertEqual(passed, True)
Exemplo n.º 2
0
 def setUp(self):
     '''
     initialisation for tests
     '''
     location_fixture = AutoFixture(Location)
     location_fixture.create(1)
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
 def setUp(self):
     '''
     initialisation for tests
     '''
     bulletin_fixture = AutoFixture(Bulletin)
     bulletin_fixture.create(5)
     bull = Bulletin.objects.get(id=1)
     bull.actors_role.clear()
     bull.save()
     location_fixture = AutoFixture(Location)
     location_fixture.create(1)
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
    def setUp(self):
        super(BulletinTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()
        self.actor = Actor(fullname_en='Test Actor',
                           fullname_ar='Test name ar',
                           nickname_en='nick name',
                           nickname_ar='nick name')
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.sourceType = SourceType(source_type='test source type',
                                     description='test source description')

        self.sourceType.save()
        self.source = Source(reliability_score=0,
                             name_en='test source',
                             source_type_id=self.sourceType.pk)

        self.source.save()
        self.source = Source(reliability_score=0,
                             name_en='test source 2',
                             source_type_id=self.sourceType.pk)

        self.source.save()
        self.label = Label(name_en='test label')
        self.label.save()
        self.comment = Comment(assigned_user_id=self.user.pk,
                               status_id=3,
                               comments_en='test comment')
        self.comment.save()

        self.media = Media(media_type='Video',
                           name_en='test media',
                           media_file='')
        self.media.save()

        fixture = AutoFixture(Bulletin, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)
Exemplo n.º 5
0
 def setUp(self):
     '''
     initialisation for tests
     '''
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
     self.solr_proxy_url = 'http://localhost:8002/corroborator/solrproxy/'
 def setUp(self):
     '''
     initialisation for tests
     '''
     location_fixture = AutoFixture(Location)
     location_fixture.create(1)
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
Exemplo n.º 7
0
 def setUp(self):
     self.test_util = TestUserUtility()
     fixture = AutoFixture(VersionStatus, generate_fk=True)
     fixture.create(10)
     # we'll need to create the UserLog objects manually to ensure a valid
     # login and logout datetime
     # see line 110
     #fixture = AutoFixture(UserLog, generate_fk=True)
     #fixture.create(10)
     fixture = AutoFixture(User)
     fixture.create(1)
     fixture = AutoFixture(Bulletin)
     fixture.create(1)
     fixture = AutoFixture(Incident)
     fixture.create(1)
     fixture = AutoFixture(Actor)
     fixture.create(1)
Exemplo n.º 8
0
    def setUp(self):
        super(ActorTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        fixture = AutoFixture(Actor)
        fixture.create(10)
        self.actor = Actor(fullname_en='Test Actor',
                           fullname_ar='Test name ar',
                           nickname_en='nick name',
                           nickname_ar='nick name')
        self.actor.save()

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)
Exemplo n.º 9
0
    def setUp(self):
        super(IncidentTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()

        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name')
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.statusUpdate = StatusUpdate(status_en='test status')
        self.statusUpdate.save()

        self.crimeCategory = CrimeCategory(
            name_en='test crime category',
            level=1,
            description_en='test source incident_details')
        self.crimeCategory.save()
        self.label = Label(name_en='test label')
        self.label.save()

        self.comment = Comment(
            assigned_user_id=self.user.pk,
            status_id=self.statusUpdate.pk,
            comments_en='test comment')
        self.comment.save()

        fixture = AutoFixture(Incident, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)
class StatusUpdateModelTestCase(TestCase):
    '''
    Test the Manager of the Status Update model
    '''
    fixtures = ['status_update', ]

    def setUp(self):
        self.test_utility = TestUserUtility()
        self.user = self.test_utility.user

    def tearDown(self):
        pass

    def test_correct_statuses_returned(self):
        '''
        check that the right statuses are returned depending on a user's group
        '''
        self.test_utility.add_user_to_group('data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 2)
        self.test_utility.add_user_to_group('senior-data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 3)
        self.test_utility.add_user_to_group('chief-data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 4)
Exemplo n.º 11
0
class StatusUpdateModelTestCase(TestCase):
    '''
    Test the Manager of the Status Update model
    '''
    fixtures = [
        'status_update',
    ]

    def setUp(self):
        self.test_utility = TestUserUtility()
        self.user = self.test_utility.user

    def tearDown(self):
        pass

    def test_correct_statuses_returned(self):
        '''
        check that the right statuses are returned depending on a user's group
        '''
        self.test_utility.add_user_to_group('data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 2)
        self.test_utility.add_user_to_group('senior-data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 3)
        self.test_utility.add_user_to_group('chief-data-analyst')
        statuses =\
            StatusUpdate.filter_by_perm_objects.available_statuses(self.user)
        self.assertIs(len(statuses), 4)
 def setUp(self):
     '''
     initialisation for tests
     '''
     bulletin_fixture = AutoFixture(Bulletin)
     bulletin_fixture.create(5)
     bull = Bulletin.objects.get(id=1)
     bull.actors_role.clear()
     bull.save()
     location_fixture = AutoFixture(Location)
     location_fixture.create(1)
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
Exemplo n.º 13
0
class ViewsUtilsTestCase(TestCase):
    '''
    test the views helper functions
    '''

    def setUp(self):
        self.test_utils = TestUserUtility()
        pass

    def tearDown(self):
        User.objects.all().delete()
        pass

    def test_user_in_group(self):
        '''
        verify that user group testing works correctly
        '''
        groups = ['senior-data-analyst', 'chief-data-analyst', ]
        self.test_utils.add_user_to_group('data-analyst')
        failed = is_user_in_groups(groups, self.test_utils.user)
        self.assertEqual(failed, False)
        self.test_utils.add_user_to_group('senior-data-analyst')
        passed = is_user_in_groups(groups, self.test_utils.user)
        self.assertEqual(passed, True)
 def setUp(self):
     self.test_util = TestUserUtility()
     fixture = AutoFixture(VersionStatus, generate_fk=True)
     fixture.create(10)
     # we'll need to create the UserLog objects manually to ensure a valid
     # login and logout datetime
     # see line 110
     #fixture = AutoFixture(UserLog, generate_fk=True)
     #fixture.create(10)
     fixture = AutoFixture(User)
     fixture.create(1)
     fixture = AutoFixture(Bulletin)
     fixture.create(1)
     fixture = AutoFixture(Incident)
     fixture.create(1)
     fixture = AutoFixture(Actor)
     fixture.create(1)
    def setUp(self):
        super(ActorTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        fixture = AutoFixture(Actor)
        fixture.create(10)
        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name'
        )
        self.actor.save()

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)
 def setUp(self):
     self.client = Client()
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
Exemplo n.º 17
0
class ReportingTestCase(TestCase):
    '''
    Test the reporting view and it's supporting json ajax views
    '''
    fixtures = [
        'status_update',
    ]

    def setUp(self):
        self.test_util = TestUserUtility()
        fixture = AutoFixture(VersionStatus, generate_fk=True)
        fixture.create(10)
        # we'll need to create the UserLog objects manually to ensure a valid
        # login and logout datetime
        # see line 110
        #fixture = AutoFixture(UserLog, generate_fk=True)
        #fixture.create(10)
        fixture = AutoFixture(User)
        fixture.create(1)
        fixture = AutoFixture(Bulletin)
        fixture.create(1)
        fixture = AutoFixture(Incident)
        fixture.create(1)
        fixture = AutoFixture(Actor)
        fixture.create(1)

    def tearDown(self):
        User.objects.all().delete()
        UserLog.objects.all().delete()

    def test_reporting_page_loads(self):
        '''
        does the reporting view displays correctly
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        client = self.test_util.client_login()
        response = client.get('/corroborator/reporting/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'reporting.html')

    def test_unauthorized_access_prevented(self):
        '''
        ensure unauthorized groups return a 404
        '''
        self.test_util.add_user_to_group(['data-entry', 'data-analyst'])
        client = self.test_util.client_login()
        response = client.get('/corroborator/reporting/')
        self.assertEqual(response.status_code, 404)

    #####################################################################
    # DRYing up the tests
    #####################################################################
    def test_graphs_respond(self):
        '''
        check the graph views respond with a 200
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        self.client = self.test_util.client_login()
        graph_codes = [
            'user_login_time',
            'user_average_updates',
            'user_created_items',
            'user_edited_items',
            'user_edited_items',
        ]
        url_tpl = '/corroborator/graphs/user/{0}/'
        for graph_code in graph_codes:
            url = url_tpl.format(graph_code)
            response = self.client.get(url)
            fail_message = '{0} failed to load'.format(url_tpl)
            self.assertEqual(response.status_code, 200, fail_message)

    def test_graphs_with_user_id_respond(self):
        '''
        check the graph views that require a user_id respond with a 200
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        self.client = self.test_util.client_login()
        user_id = User.objects.all()[0].id
        graph_codes = [
            'user_login_per_day',
            'user_assigned_items_by_status',
            'user_deleted_edited_created',
        ]
        url_tpl = '/corroborator/graphs/user/{0}/{1}/'
        for graph_code in graph_codes:
            url = url_tpl.format(graph_code, user_id)
            response = self.client.get(url)
            fail_message = '{0} failed to load'.format(url_tpl)
            self.assertEqual(response.status_code, 200, fail_message)

    #####################################################################
    # tests below can now skip the login bit and test the data generation
    # directly
    # this will hopefully speed up the tests
    # I've included an example of directly testing the formatting code
    #####################################################################
    def test_user_login_time(self):
        '''
        Test correct return of user login time json
        '''
        user = User.objects.all()[0]
        values = generate_start_end_times(user)
        expected_response = json.dumps({
            'values': [{
                'value': 360,
                'label': 'user'
            }],
            'title':
            'Total login time by User'
        })
        ura = UserReportingApi()
        expected_response = json.loads(expected_response)
        json_response = json.loads(ura.total_user_login_time())
        self.assertEqual(expected_response, json_response)

    def test_user_login_per_day(self):
        '''
        Test correct return of user login
        time per day json
        '''
        user = User.objects.all()[0]
        values = generate_start_end_times(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'values': [{
                    "y": 180,
                    "x": 1370041200000.0
                }, {
                    "y": 180,
                    "x": 1370127600000.0
                }],
                'label':
                'user'
            }],
            'title':
            'Total user login time per day'
        })

        json_response = json.loads(ura.total_user_login_per_day(user.id))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_average_update(self):
        '''
        Test correct return of user
        average updates json
        '''
        user = User.objects.all()[0]
        value = average_updates_value(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'value': 0.5,
                'label': 'user'
            }],
            'title':
            'Average user updates per hour'
        })

        json_response = json.loads(ura.user_average_updates_per_hour())
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_assigned_items_by_status(self):
        '''
        Test correct return of user assigned
        items by status json
        '''
        user = User.objects.all()[0]
        precreated_bulletin = Bulletin.objects.all()[0]
        precreated_actor = Actor.objects.all()[0]
        precreated_incident = Incident.objects.all()[0]
        comment = Comment(assigned_user_id=user.id,
                          comments_en='comment',
                          status_id=5)
        comment.save()
        precreated_bulletin.assigned_user = user
        precreated_bulletin.bulletin_comments.add(comment)

        precreated_actor.assigned_user = user
        precreated_actor.actor_comments.add(comment)

        precreated_incident.assigned_user = user
        precreated_incident.incident_comments.add(comment)

        precreated_bulletin.save()
        precreated_actor.save()
        precreated_incident.save()

        status_label = StatusUpdate.objects.filter(pk=5)\
            .values('status_en')[0]['status_en']

        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'value': 3,
                'label': 'Finalized'
            }],
            'title':
            'User assigned items by status'
        })

        json_response = json.loads(ura.user_assigned_items_by_status(user.id))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_deleted_items(self):
        '''
        Test correct return of user deleted items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'value': 3,
                'label': 'user'
            }],
            'title':
            'Total deleted items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('deleted'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_created_items(self):
        '''
        Test correct return of user created items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'value': 3,
                'label': 'user'
            }],
            'title':
            'Total created items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('created'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_edited_items(self):
        '''
        Test correct return of user edited items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'value': 3,
                'label': 'user'
            }],
            'title':
            'Total edited items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('edited'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_deleted_edited_created(self):
        '''
        Test correct return of CRUD data as json
        '''
        user = User.objects.all()[0]
        items = crud_items_by_date(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [{
                'values': [{
                    "y": 3,
                    "x": 1390867200000.0
                }],
                'key': 'Deleted items by date'
            }, {
                'values': [{
                    "y": 3,
                    "x": 1390867200000.0
                }],
                'key': 'Created items by date'
            }, {
                'values': [{
                    "y": 3,
                    "x": 1390867200000.0
                }],
                'key': 'Edited items by date'
            }],
            'title':
            'Deleted, created and edited items by date'
        })
        json_response = json.loads(ura.crud_per_day(user.id))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)
class AppViewTestCase(TestCase):
    '''
    test that the correct js app get's loaded depending on the user's
    permissions
    '''
    fixtures = ['test_data_role.json', 'status_update', ]

    def setUp(self):
        self.client = Client()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        User.objects.all().delete()
        pass

    def test_normal_app_redirects_for_unauthorized_users(self):
        response = self.client.get('/corroborator/')
        self.assertRedirects(
            response,
            '/accounts/login/?next=/corroborator/',
            msg_prefix='unauthorized user not redirected')

    def test_normal_app_loads_for_authorized_users(self):
        '''
        check that the normal js app loads correctly
        '''
        self.test_user_util.add_user_to_group('data-analyst')
        client = self.test_user_util.client_login()
        response = client.get('/corroborator/')
        self.assertTemplateUsed(
            response, 'new_base.html', 'base template not loaded')
        self.assertTemplateUsed(
            response, 'new_search.html', 'search template not loaded')

    def test_data_entry_users_redirected(self):
        '''
        test that the data entry users are redirected
        '''
        self.test_user_util.add_user_to_group(group_name='data-entry')
        self.client.login(username='******', password='******')
        response = self.client.get('/corroborator/')
        self.assertRedirects(
            response,
            '/data-entry/',
            msg_prefix='data-entry user not redirected')

    def test_data_entry_view_returned(self):
        '''
        test that the data entry url returns a page
        '''
        self.test_user_util.add_user_to_group(group_name='data-entry')
        self.client.login(username='******', password='******')
        response = self.client.get('/data-entry/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response, 'includes/bootstrap.html', 'search template not loaded')

    def test_assigned_user_perm(self):
        '''
        check that the permission for assigned user is respected, in that
        only valid users receive the list of assigned users
        '''
        self.test_user_util.add_user_to_group(group_name='data-analyst')
        has_perm = can_assign_users(self.user)
        self.assertEqual(has_perm, False)
        self.test_user_util.add_user_to_group(group_name='chief-data-analyst')
        has_perm = can_assign_users(self.user)
        self.assertEqual(has_perm, True)
Exemplo n.º 19
0
class BulletinTestCase(ResourceTestCase):

    fixtures = ['status_update', ]

    def setUp(self):
        super(BulletinTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()
        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name'
        )
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.sourceType = SourceType(
            source_type='test source type',
            description='test source description'
        )

        self.sourceType.save()
        self.source = Source(
            reliability_score=0,
            name_en='test source',
            source_type_id=self.sourceType.pk
        )

        self.source.save()
        self.source = Source(
            reliability_score=0,
            name_en='test source 2',
            source_type_id=self.sourceType.pk
        )

        self.source.save()
        self.label = Label(name_en='test label')
        self.label.save()
        self.comment = Comment(
            assigned_user_id=self.user.pk,
            status_id=3,
            comments_en='test comment'
        )
        self.comment.save()

        self.media = Media(
            media_type='Video',
            name_en='test media',
            media_file=''
        )
        self.media.save()

        fixture = AutoFixture(Bulletin, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        User.objects.all().delete()
        Actor.objects.all().delete()
        ActorRole.objects.all().delete()
        Location.objects.all().delete()
        TimeInfo.objects.all().delete()
        Media.objects.all().delete()
        Comment.objects.all().delete()
        StatusUpdate.objects.all().delete()
        Bulletin.objects.all().delete()

    def test_bulletin_get(self):
        url = '/api/v1/bulletin/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/bulletin/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)

    def test_bulletin_post(self):
        post_data = {
            'title_en': "Test Bulletin",
            'description_ar': "description Arabic",
            'confidence_score': 73,
            'sources': ['/api/v1/source/1/', ],
            'bulletin_imported_comments': ['/api/v1/comment/1/', ],
            'assigned_user': '******',
            'actors_role': [],
            'times': [],
            'medias': [],
            'locations': [],
            'labels': [],
            'ref_bulletins': [],
            'comment': 'new bulletin',
        }
        url = '/api/v1/bulletin/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        new_bulletin_dict = json.loads(response.content)
        new_bulletin = Bulletin(id=new_bulletin_dict['id'])
        bulletin_comments = new_bulletin.bulletin_comments.all()
        self.assertEqual(len(bulletin_comments), 1)
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_bulletin_put(self):
        self.test_user_util.add_user_to_group('data-analyst')
        b = Bulletin.objects.all()[1]
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            b.id,
            self.auth_string
        )
        put_data = create_put_data(5)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.check_dehydrated_data(response)
        self.assertEqual(retrieve_last_comment_status(response), 'Updated')
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_data_entry_put(self):
        self.test_user_util.add_user_to_group('data-entry')
        b = Bulletin.objects.all()[0]
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            b.id,
            self.auth_string
        )
        put_data = create_put_data(3)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Updated')
        b.assigned_user = None
        b.save()
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_senior_data_analyst_put(self):
        self.test_user_util.add_user_to_group('senior-data-analyst')
        b = Bulletin.objects.all()[0]
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            b.id,
            self.auth_string
        )
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Reviewed')

    def test_chief_data_analyst_put(self):
        self.test_user_util.add_user_to_group('chief-data-analyst')
        b = Bulletin.objects.all()[0]
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            b.id,
            self.auth_string
        )
        put_data = create_put_data(5)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Finalized')

    def test_finalized_is_not_updated(self):
        precreated_bulletin = Bulletin.objects.all()[0]
        comment = Comment(
            assigned_user_id=1,
            comments_en='comment',
            status_id=5
        )
        comment.save()
        precreated_bulletin.bulletin_comments.add(comment)
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            precreated_bulletin.id, self.auth_string)

        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_assigned_user_perm_enforced(self):
        self.test_user_util.add_user_to_group('data-analyst')
        fixture = AutoFixture(User)
        fixture.create(1)
        precreated_bulletin = Bulletin.objects.all()[0]
        precreated_bulletin.assigned_user = User.objects.get(id=2)
        precreated_bulletin.save()
        url = '/api/v1/bulletin/{0}/?format=json{1}'.format(
            precreated_bulletin.id, self.auth_string)
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 2)
        self.test_user_util.add_user_to_group('chief-data-analyst')
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 1)

    def check_dehydrated_data(self, response):
        """
        Test that returned data contains required dehydrated fields.
        New fields should be added to this method as they are added to the
        API to ensure that consistency between front and back end.
        """
        dehydrate_keys = [
            'bulletin_comments',
            'bulletin_imported_comments',
            'bulletin_locations',
            'bulletin_labels',
            'bulletin_times',
            'bulletin_sources',
            'most_recent_status_bulletin',
            'count_actors',
            'actor_roles_status',
            'actors',
            'actors_role'
        ]
        content = json.loads(response.content)
        self.assertEqual(
            all(
                test in content for test in dehydrate_keys
            ),
            True
        )
class ReportingTestCase(TestCase):
    '''
    Test the reporting view and it's supporting json ajax views
    '''
    fixtures = ['status_update', ]

    def setUp(self):
        self.test_util = TestUserUtility()
        fixture = AutoFixture(VersionStatus, generate_fk=True)
        fixture.create(10)
        # we'll need to create the UserLog objects manually to ensure a valid
        # login and logout datetime
        # see line 110
        #fixture = AutoFixture(UserLog, generate_fk=True)
        #fixture.create(10)
        fixture = AutoFixture(User)
        fixture.create(1)
        fixture = AutoFixture(Bulletin)
        fixture.create(1)
        fixture = AutoFixture(Incident)
        fixture.create(1)
        fixture = AutoFixture(Actor)
        fixture.create(1)

    def tearDown(self):
        User.objects.all().delete()
        UserLog.objects.all().delete()

    def test_reporting_page_loads(self):
        '''
        does the reporting view displays correctly
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        client = self.test_util.client_login()
        response = client.get('/corroborator/reporting/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'reporting.html')

    def test_unauthorized_access_prevented(self):
        '''
        ensure unauthorized groups return a 404
        '''
        self.test_util.add_user_to_group([
            'data-entry',
            'data-analyst'
        ])
        client = self.test_util.client_login()
        response = client.get('/corroborator/reporting/')
        self.assertEqual(response.status_code, 404)

    #####################################################################
    # DRYing up the tests
    #####################################################################
    def test_graphs_respond(self):
        '''
        check the graph views respond with a 200
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        self.client = self.test_util.client_login()
        graph_codes = [
            'user_login_time', 'user_average_updates', 'user_created_items',
            'user_edited_items', 'user_edited_items',
        ]
        url_tpl = '/corroborator/graphs/user/{0}/'
        for graph_code in graph_codes:
            url = url_tpl.format(graph_code)
            response = self.client.get(url)
            fail_message = '{0} failed to load'.format(url_tpl)
            self.assertEqual(response.status_code, 200, fail_message)

    def test_graphs_with_user_id_respond(self):
        '''
        check the graph views that require a user_id respond with a 200
        '''
        self.test_util.add_user_to_group('senior-data-analyst')
        self.client = self.test_util.client_login()
        user_id = User.objects.all()[0].id
        graph_codes = [
            'user_login_per_day', 'user_assigned_items_by_status',
            'user_deleted_edited_created',
        ]
        url_tpl = '/corroborator/graphs/user/{0}/{1}/'
        for graph_code in graph_codes:
            url = url_tpl.format(graph_code, user_id)
            response = self.client.get(url)
            fail_message = '{0} failed to load'.format(url_tpl)
            self.assertEqual(response.status_code, 200, fail_message)

    #####################################################################
    # tests below can now skip the login bit and test the data generation
    # directly
    # this will hopefully speed up the tests
    # I've included an example of directly testing the formatting code
    #####################################################################
    def test_user_login_time(self):
        '''
        Test correct return of user login time json
        '''
        user = User.objects.all()[0]
        values = generate_start_end_times(user)
        expected_response = json.dumps({
            'values': [
                {
                    'value': 360,
                    'label': 'user'
                }
            ],
            'title': 'Total login time by User'
        })
        ura = UserReportingApi()
        expected_response = json.loads(expected_response)
        json_response = json.loads(ura.total_user_login_time())
        self.assertEqual(expected_response, json_response)

    def test_user_login_per_day(self):
        '''
        Test correct return of user login
        time per day json
        '''
        user = User.objects.all()[0]
        values = generate_start_end_times(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'values': [
                        {
                            "y": 180, 
                            "x": 1370041200000.0
                        },
                        {
                            "y": 180, 
                            "x": 1370127600000.0
                        }],
                    'label': 'user'
                }
            ],
            'title': 'Total user login time per day'
        })

        json_response = json.loads(ura.total_user_login_per_day(user.id))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_average_update(self):
        '''
        Test correct return of user
        average updates json
        '''
        user = User.objects.all()[0]
        value = average_updates_value(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'value': 0.5,
                    'label': 'user'
                }
            ],
            'title': 'Average user updates per hour'
        })

        json_response = json.loads(ura.user_average_updates_per_hour())
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_assigned_items_by_status(self):
        '''
        Test correct return of user assigned
        items by status json
        '''
        user = User.objects.all()[0]
        precreated_bulletin = Bulletin.objects.all()[0]
        precreated_actor = Actor.objects.all()[0]
        precreated_incident = Incident.objects.all()[0]
        comment = Comment(
            assigned_user_id=user.id,
            comments_en='comment',
            status_id=5
        )
        comment.save()
        precreated_bulletin.assigned_user = user
        precreated_bulletin.bulletin_comments.add(comment)

        precreated_actor.assigned_user = user
        precreated_actor.actor_comments.add(comment)

        precreated_incident.assigned_user = user
        precreated_incident.incident_comments.add(comment)

        precreated_bulletin.save()
        precreated_actor.save()
        precreated_incident.save()

        status_label = StatusUpdate.objects.filter(pk=5)\
            .values('status_en')[0]['status_en']

        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'value': 3,
                    'label': 'Finalized'
                }
            ],
            'title': 'User assigned items by status'
        })

        json_response = json.loads(ura.user_assigned_items_by_status(user.id))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_deleted_items(self):
        '''
        Test correct return of user deleted items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'value': 3,
                    'label': 'user'
                }
            ],
            'title': 'Total deleted items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('deleted'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_created_items(self):
        '''
        Test correct return of user created items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'value': 3,
                    'label': 'user'
                }
            ],
            'title': 'Total created items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('created'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_edited_items(self):
        '''
        Test correct return of user edited items
        json
        '''
        user = User.objects.all()[0]
        total_updates = create_version_status_entries_for_user(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'value': 3,
                    'label': 'user'
                }
            ],
            'title': 'Total edited items by User'
        })
        json_response = json.loads(ura.total_user_items_by_crud('edited'))
        expected_response = json.loads(expected_response)
        self.assertEqual(expected_response, json_response)

    def test_user_deleted_edited_created(self):
        '''
        Test correct return of CRUD data as json
        '''
        user = User.objects.all()[0]
        items = crud_items_by_date(user)
        ura = UserReportingApi()
        expected_response = json.dumps({
            'values': [
                {
                    'values': [{
                            "y": 3, 
                            "x": 1390867200000.0
                    }],
                    'key': 'Deleted items by date'
                },
                {
                    'values': [{
                            "y": 3, 
                            "x": 1390867200000.0
                    }],
                    'key': 'Created items by date'
                },
                {
                    'values': [{
                            "y": 3, 
                            "x": 1390867200000.0
                    }],
                    'key': 'Edited items by date'
                }
            ],
            'title': 'Deleted, created and edited items by date'
        })
        json_response = json.loads(ura.crud_per_day(user.id))
        expected_response = json.loads(expected_response)
        self.maxDiff = None
        self.assertEqual(expected_response, json_response)
Exemplo n.º 21
0
 def setUp(self):
     self.test_utility = TestUserUtility()
     self.user = self.test_utility.user
class IncidentTestCase(ResourceTestCase):
    fixtures = [
        'test_data_role.json',
        'status_update',
    ]

    def setUp(self):
        super(IncidentTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()

        self.actor = Actor(fullname_en='Test Actor',
                           fullname_ar='Test name ar',
                           nickname_en='nick name',
                           nickname_ar='nick name')
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.statusUpdate = StatusUpdate(status_en='test status')
        self.statusUpdate.save()

        self.crimeCategory = CrimeCategory(
            name_en='test crime category',
            level=1,
            description_en='test source incident_details')
        self.crimeCategory.save()
        self.label = Label(name_en='test label')
        self.label.save()

        self.comment = Comment(assigned_user_id=self.user.pk,
                               status_id=self.statusUpdate.pk,
                               comments_en='test comment')
        self.comment.save()

        fixture = AutoFixture(Incident, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        User.objects.all().delete()
        Incident.objects.all().delete()
        Actor.objects.all().delete()
        ActorRole.objects.all().delete()
        Location.objects.all().delete()
        TimeInfo.objects.all().delete()
        Comment.objects.all().delete()
        StatusUpdate.objects.all().delete()
        CrimeCategory.objects.all().delete()

    def test_incident_get(self):
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/incident/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)

    def test_incident_post(self):
        post_data = {
            'title_en': "Test Incident",
            'incident_details_ar': "incident_details Arabic",
            'confidence_score': 11,
            'assigned_user': '******',
            'incident_comments': [
                '/api/v1/comment/1/',
            ],
            'bulletins': [],
            'actors_role': [],
            'crimes': [],
            'labels': [],
            'times': [],
            'locations': [],
            'ref_incidents': [],
            'status': '/api/v1/statusUpdate/1/',
            'comment': 'Comment',
            'status_uri': '/api/v1/statusUpdate/1/'
        }
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        new_incident_dict = json.loads(response.content)
        new_incident = Incident(id=new_incident_dict['id'])
        incident_comments = new_incident.incident_comments.all()
        self.assertEqual(len(incident_comments), 1)
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_incident_put(self):
        i = Incident.objects.all()[0]
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            i.id, self.auth_string)

        put_data = create_put_data()
        response = self.api_client.put(url, data=put_data)
        self.check_dehydrated_data(response)
        self.assertEqual(response.status_code, 200)
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_finalized_is_not_updated(self):
        precreated_incident = Incident.objects.all()[0]
        comment = Comment(assigned_user_id=1,
                          comments_en='comment',
                          status_id=5)
        comment.save()
        precreated_incident.incident_comments.add(comment)
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            precreated_incident.id, self.auth_string)

        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_assigned_user_perm_enforced(self):
        self.test_user_util.add_user_to_group('data-analyst')
        fixture = AutoFixture(User)
        fixture.create(1)
        precreated_incident = Incident.objects.all()[0]
        precreated_incident.assigned_user = User.objects.get(id=2)
        precreated_incident.save()
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            precreated_incident.id, self.auth_string)
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 2)
        self.test_user_util.add_user_to_group('chief-data-analyst')
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 1)

    def check_dehydrated_data(self, response):
        """
        Test that returned data contains required dehydrated fields.
        New fields should be added to this method as they are added to the
        API to ensure that consistency between front and back end.
        """
        dehydrate_keys = [
            'incident_locations', 'incident_labels', 'incident_times',
            'incident_crimes', 'most_recent_status_incident', 'count_actors',
            'count_bulletins', 'count_incidents', 'actor_roles_status',
            'actors', 'actors_role'
        ]
        content = json.loads(response.content)
        self.assertEqual(all(test in content for test in dehydrate_keys), True)
class MultiSaveIncidentTestCase(TestCase):
    '''
    verify that multiple incident updates are happening correctly
    '''
    fixtures = [
        'test_data_role', 'status_update', 'bulletin', 'incident', ]
    api_url = '/corroborator/incident/0/multisave/'

    def setUp(self):
        '''
        initialisation for tests
        '''
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        initialisation for tests
        '''
        Incident.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()

    def test_incidents_updated(self):
        '''
        basic test to ensure that end to end functionality is in place
        '''
        client = self.test_user_util.client_login()
        post_data = create_incident_data()
        response = client.post(
            self.api_url,
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        incident_1 = Incident.objects.get(pk=1)
        incident_2 = Incident.objects.get(pk=2)
        self.assertEqual(len(incident_1.actors_role.all()), 1)
        self.assertEqual(len(incident_1.ref_bulletins.all()), 2)
        self.assertEqual(len(incident_1.ref_incidents.all()), 1)
        self.assertEqual(len(incident_2.actors_role.all()), 2)
        response_data = json.loads(response.content)
        self.assertEqual(
            response_data[0]['most_recent_status_incident'],
            u'/api/v1/statusUpdate/3/')
        revision = Version.objects.filter(object_id=1)        
        self.assertNotEqual(revision, None)


    def test_incidents_updated_with_empty_relations(self):
        client = self.test_user_util.client_login()
        post_data = create_incident_data(empty_data=True)
        response = client.post(
            self.api_url,
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)

    def test_statusless_update_fails(self):
        client = self.test_user_util.client_login()
        post_data = create_incident_data(version_info=False)
        response = client.post(
            self.api_url,
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 403)

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_incident = Incident.objects.get(id=1)
        finalized_incident.incident_comments.add(
            create_comment('A finalizing comment', 5, user)
        )
        client = self.test_user_util.client_login()
        post_data = create_incident_data(
            empty_data=False,
            version_info=True
        )
        response = client.post(
            '/corroborator/incident/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        finalized_incident_comments =\
            Incident.objects.get(id=1).incident_comments.all()

        self.assertEqual(len(finalized_incident_comments), 1)
Exemplo n.º 24
0
class AppViewTestCase(TestCase):
    '''
    test that the correct js app get's loaded depending on the user's
    permissions
    '''
    fixtures = [
        'test_data_role.json',
        'status_update',
    ]

    def setUp(self):
        self.client = Client()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        User.objects.all().delete()
        pass

    def test_normal_app_redirects_for_unauthorized_users(self):
        response = self.client.get('/corroborator/')
        self.assertRedirects(response,
                             '/accounts/login/?next=/corroborator/',
                             msg_prefix='unauthorized user not redirected')

    def test_normal_app_loads_for_authorized_users(self):
        '''
        check that the normal js app loads correctly
        '''
        self.test_user_util.add_user_to_group('data-analyst')
        client = self.test_user_util.client_login()
        response = client.get('/corroborator/')
        self.assertTemplateUsed(response, 'new_base.html',
                                'base template not loaded')
        self.assertTemplateUsed(response, 'new_search.html',
                                'search template not loaded')

    def test_data_entry_users_redirected(self):
        '''
        test that the data entry users are redirected
        '''
        self.test_user_util.add_user_to_group(group_name='data-entry')
        self.client.login(username='******', password='******')
        response = self.client.get('/corroborator/')
        self.assertRedirects(response,
                             '/data-entry/',
                             msg_prefix='data-entry user not redirected')

    def test_data_entry_view_returned(self):
        '''
        test that the data entry url returns a page
        '''
        self.test_user_util.add_user_to_group(group_name='data-entry')
        self.client.login(username='******', password='******')
        response = self.client.get('/data-entry/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'includes/bootstrap.html',
                                'search template not loaded')

    def test_assigned_user_perm(self):
        '''
        check that the permission for assigned user is respected, in that
        only valid users receive the list of assigned users
        '''
        self.test_user_util.add_user_to_group(group_name='data-analyst')
        has_perm = can_assign_users(self.user)
        self.assertEqual(has_perm, False)
        self.test_user_util.add_user_to_group(group_name='chief-data-analyst')
        has_perm = can_assign_users(self.user)
        self.assertEqual(has_perm, True)
Exemplo n.º 25
0
    def setUp(self):
        super(BulletinTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()
        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name'
        )
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.sourceType = SourceType(
            source_type='test source type',
            description='test source description'
        )

        self.sourceType.save()
        self.source = Source(
            reliability_score=0,
            name_en='test source',
            source_type_id=self.sourceType.pk
        )

        self.source.save()
        self.source = Source(
            reliability_score=0,
            name_en='test source 2',
            source_type_id=self.sourceType.pk
        )

        self.source.save()
        self.label = Label(name_en='test label')
        self.label.save()
        self.comment = Comment(
            assigned_user_id=self.user.pk,
            status_id=3,
            comments_en='test comment'
        )
        self.comment.save()

        self.media = Media(
            media_type='Video',
            name_en='test media',
            media_file=''
        )
        self.media.save()

        fixture = AutoFixture(Bulletin, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)
class MultiSaveBulletinTestCase(TestCase):
    '''
    verify that multiple bulletin updates are happening correctly
    '''
    fixtures = [
        'test_data_role.json',
        'status_update',
    ]

    def setUp(self):
        '''
        initialisation for tests
        '''
        bulletin_fixture = AutoFixture(Bulletin)
        bulletin_fixture.create(5)
        bull = Bulletin.objects.get(id=1)
        bull.actors_role.clear()
        bull.save()
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        initialisation for tests
        '''
        User.objects.all().delete()
        Bulletin.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()

    def test_bulletins_updated(self):
        '''
        basic test to ensure that end to end functionality is in place
        '''
        client = Client()
        client.login(username='******', password='******')
        post_data = create_bulletin_data()
        response = client.post('/corroborator/bulletin/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        post_data = create_bulletin_data(empty_data=True)
        response = client.post('/corroborator/bulletin/0/multisave/',
                               post_data,
                               content_type='application/json')
        response_data = json.loads(response.content)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_data[0]['most_recent_status_bulletin'],
                         u'/api/v1/statusUpdate/3/')
        revision = Version.objects.filter(object_id=1)
        self.assertNotEqual(revision, None)

    def test_statusless_update_fails(self):
        client = Client()
        post_data = create_bulletin_data(version_info=False)
        response = client.post('/corroborator/bulletin/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 403)

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_bulletin = Bulletin.objects.get(id=1)
        finalized_bulletin.bulletin_comments.add(
            create_comment('A finalizing comment', 5, user))
        client = self.test_user_util.client_login()
        post_data = create_bulletin_data(empty_data=False, version_info=True)
        response = client.post('/corroborator/bulletin/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        finalized_bulletin_comments =\
            Bulletin.objects.get(id=1).bulletin_comments.all()

        self.assertEqual(len(finalized_bulletin_comments), 1)
class MultiSaveActorTestCase(TestCase):
    '''
    test the updating of multiple actors
    '''
    fixtures = ['test_data_role.json', 'status_update', ]

    def setUp(self):
        '''
        initialisation for tests
        '''
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        cleanup for tests
        '''
        Actor.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()
        User.objects.all().delete()

    def test_actors_updated(self):
        '''
        broad test to verify that actors are getting updated
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data()

        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )

        self.assertEqual(response.status_code, 200)
        post_data = create_actor_data(empty_data=True)

        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        revision = Version.objects.filter(object_id=1)        
        self.assertNotEqual(revision, None)

    def test_extract_ids(self):
        '''
        test that actor ids are returned correctly
        TODO: move to common test suite
        '''
        json_dict = json.loads(create_actor_data())
        actor_ids = extract_ids(json_dict, 'selectedActors')
        self.assertEqual(actor_ids, ['1', '2', ])

    def test_actor_update_from_query_dict(self):
        '''
        test that the actor gets updated correctly from the query dict
        passed in the request
        '''
        json_dict = json.loads(create_actor_data())
        json_dict['user'] = self.user
        json_dict = process_actor_data(json_dict)
        actor_ids = extract_ids(json_dict, 'selectedActors')
        actor = Actor.objects.get(id=1)
        actor.position_en = u'position'
        actor.save()
        actor_objects = Actor.objects.filter(
            id__in=actor_ids
        )
        update_entities(json_dict, actor_objects, [])
        actor_1 = Actor.objects.get(id=1)
        actor_2 = Actor.objects.get(id=2)
        self.assertEqual(actor_1.occupation_en, 'Farmer')
        self.assertEqual(actor_1.position_en, 'position')
        self.assertEqual(actor_1.current_location.id, 1)
        self.assertEqual(actor_2.occupation_en, 'Farmer')

    def test_actor_role_update(self):
        '''
        test that actor roles are getting updated correctly
        '''
        json_dict = json.loads(create_actor_data())
        request = HttpRequest()
        request.user = self.user
        multi_save_actors(request, json_dict, self.user.username)

        actor_1 = Actor.objects.get(id=1)
        actor_2 = Actor.objects.get(id=2)
        actor_role_1 = actor_1.actors_role.all()[0]
        self.assertEqual(actor_role_1.role_status, 'T')
        self.assertEqual(len(actor_2.actors_role.all()), 1)

    def test_version_update(self):
        '''
        test that the version get's updated for all actors
        and fails if not present
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data(version_info=False)
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 403)
        post_data = create_actor_data()
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)

    def test_content_returned(self):
        '''
        test that we are returning the correct content
        '''
        client = Client()
        client.login(username='******', password='******')
        post_data = create_actor_data()
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        response_data = json.loads(response.content)
        #actor = Actor.objects.get(id=1)
        self.assertEqual(response_data[0]['occupation_en'], u'Farmer')
        self.assertEqual(
            response_data[0]['most_recent_status_actor'],
            u'/api/v1/statusUpdate/3/')
        self.assertEqual(response.status_code, 200)

    def test_actors_status_update_analyst(self):
        '''
        test that status gets set to updated no matter what id is sent
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data(
            empty_data=False,
            version_info=True,
            status_id=1
        )
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(get_status_from_response(response), 'Updated')
        post_data = create_actor_data(
            empty_data=False,
            version_info=True,
            status_id=4
        )
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(get_status_from_response(response), 'Updated')

    def test_actors_status_update_senior(self):
        '''
        test that reviewed status can be added by senior
        '''
        self.test_user_util.add_user_to_group('senior-data-analyst')
        client = self.test_user_util.client_login()
        post_data = create_actor_data(
            empty_data=False,
            version_info=True,
            status_id=4
        )
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(get_status_from_response(response), 'Reviewed')

    def test_actors_status_update_chief(self):
        '''
        test that finalized status can be added by chief
        '''
        self.test_user_util.add_user_to_group('chief-data-analyst')
        client = self.test_user_util.client_login()
        post_data = create_actor_data(
            empty_data=False,
            version_info=True,
            status_id=5
        )
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(get_status_from_response(response), 'Finalized')

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_actor = Actor.objects.get(id=1)
        finalized_actor.actor_comments.add(
            create_comment('A finalizing comment', 5, user)
        )
        client = self.test_user_util.client_login()
        post_data = create_actor_data(
            empty_data=False,
            version_info=True,
            status_id=3
        )
        response = client.post(
            '/corroborator/actor/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        finalized_actor_comments = Actor.objects.get(id=1).actor_comments.all()

        self.assertEqual(len(finalized_actor_comments), 1)
class MultiSaveActorTestCase(TestCase):
    '''
    test the updating of multiple actors
    '''
    fixtures = [
        'test_data_role.json',
        'status_update',
    ]

    def setUp(self):
        '''
        initialisation for tests
        '''
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        cleanup for tests
        '''
        Actor.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()
        User.objects.all().delete()

    def test_actors_updated(self):
        '''
        broad test to verify that actors are getting updated
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data()

        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')

        self.assertEqual(response.status_code, 200)
        post_data = create_actor_data(empty_data=True)

        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        revision = Version.objects.filter(object_id=1)
        self.assertNotEqual(revision, None)

    def test_extract_ids(self):
        '''
        test that actor ids are returned correctly
        TODO: move to common test suite
        '''
        json_dict = json.loads(create_actor_data())
        actor_ids = extract_ids(json_dict, 'selectedActors')
        self.assertEqual(actor_ids, [
            '1',
            '2',
        ])

    def test_actor_update_from_query_dict(self):
        '''
        test that the actor gets updated correctly from the query dict
        passed in the request
        '''
        json_dict = json.loads(create_actor_data())
        json_dict['user'] = self.user
        json_dict = process_actor_data(json_dict)
        actor_ids = extract_ids(json_dict, 'selectedActors')
        actor = Actor.objects.get(id=1)
        actor.position_en = u'position'
        actor.save()
        actor_objects = Actor.objects.filter(id__in=actor_ids)
        update_entities(json_dict, actor_objects, [])
        actor_1 = Actor.objects.get(id=1)
        actor_2 = Actor.objects.get(id=2)
        self.assertEqual(actor_1.occupation_en, 'Farmer')
        self.assertEqual(actor_1.position_en, 'position')
        self.assertEqual(actor_1.current_location.id, 1)
        self.assertEqual(actor_2.occupation_en, 'Farmer')

    def test_actor_role_update(self):
        '''
        test that actor roles are getting updated correctly
        '''
        json_dict = json.loads(create_actor_data())
        request = HttpRequest()
        request.user = self.user
        multi_save_actors(request, json_dict, self.user.username)

        actor_1 = Actor.objects.get(id=1)
        actor_2 = Actor.objects.get(id=2)
        actor_role_1 = actor_1.actors_role.all()[0]
        self.assertEqual(actor_role_1.role_status, 'T')
        self.assertEqual(len(actor_2.actors_role.all()), 1)

    def test_version_update(self):
        '''
        test that the version get's updated for all actors
        and fails if not present
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data(version_info=False)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 403)
        post_data = create_actor_data()
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)

    def test_content_returned(self):
        '''
        test that we are returning the correct content
        '''
        client = Client()
        client.login(username='******', password='******')
        post_data = create_actor_data()
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        response_data = json.loads(response.content)
        #actor = Actor.objects.get(id=1)
        self.assertEqual(response_data[0]['occupation_en'], u'Farmer')
        self.assertEqual(response_data[0]['most_recent_status_actor'],
                         u'/api/v1/statusUpdate/3/')
        self.assertEqual(response.status_code, 200)

    def test_actors_status_update_analyst(self):
        '''
        test that status gets set to updated no matter what id is sent
        '''
        client = self.test_user_util.client_login()
        post_data = create_actor_data(empty_data=False,
                                      version_info=True,
                                      status_id=1)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(get_status_from_response(response), 'Updated')
        post_data = create_actor_data(empty_data=False,
                                      version_info=True,
                                      status_id=4)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(get_status_from_response(response), 'Updated')

    def test_actors_status_update_senior(self):
        '''
        test that reviewed status can be added by senior
        '''
        self.test_user_util.add_user_to_group('senior-data-analyst')
        client = self.test_user_util.client_login()
        post_data = create_actor_data(empty_data=False,
                                      version_info=True,
                                      status_id=4)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(get_status_from_response(response), 'Reviewed')

    def test_actors_status_update_chief(self):
        '''
        test that finalized status can be added by chief
        '''
        self.test_user_util.add_user_to_group('chief-data-analyst')
        client = self.test_user_util.client_login()
        post_data = create_actor_data(empty_data=False,
                                      version_info=True,
                                      status_id=5)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(get_status_from_response(response), 'Finalized')

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_actor = Actor.objects.get(id=1)
        finalized_actor.actor_comments.add(
            create_comment('A finalizing comment', 5, user))
        client = self.test_user_util.client_login()
        post_data = create_actor_data(empty_data=False,
                                      version_info=True,
                                      status_id=3)
        response = client.post('/corroborator/actor/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        finalized_actor_comments = Actor.objects.get(id=1).actor_comments.all()

        self.assertEqual(len(finalized_actor_comments), 1)
Exemplo n.º 29
0
class ActorTestCase(ResourceTestCase):
    '''
    test the actor tastypie api
    '''
    fixtures = [
        'test_data_role.json',
        'status_update',
    ]

    def setUp(self):
        super(ActorTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        fixture = AutoFixture(Actor)
        fixture.create(10)
        self.actor = Actor(fullname_en='Test Actor',
                           fullname_ar='Test name ar',
                           nickname_en='nick name',
                           nickname_ar='nick name')
        self.actor.save()

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        Actor.objects.all().delete()
        User.objects.all().delete()

    def test_actor_get(self):
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/actor/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)

    def test_actor_post(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        # test that a comment get added
        new_actor_dict = json.loads(response.content)
        new_actor = Actor(id=new_actor_dict['id'])
        actor_comments = new_actor.actor_comments.all()
        self.assertEqual(len(actor_comments), 1)
        self.assertEqual(actor_comments[0].status.status_en, 'Human Created')
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_actor_bulletin_related(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actor_dict = json.loads(response.content)

        post_data = {
            'role_status': "K",
            'actor': "/api/v1/actor/{0}/".format(new_actor_dict['id'])
        }
        url = '/api/v1/actorRole/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actorrole_dict = json.loads(response.content)
        post_data = {
            'title_en':
            "Test Bulletin",
            'description_ar':
            "description Arabic",
            'confidence_score':
            73,
            'sources': [],
            'bulletin_imported_comments': [],
            'assigned_user':
            '******',
            'actors_role':
            ['/api/v1/actorRole/{0}/'.format(new_actorrole_dict['id'])],
            'times': [],
            'medias': [],
            'locations': [],
            'labels': [],
            'ref_bulletins': [],
            'comment':
            'new bulletin',
        }
        url = '/api/v1/bulletin/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        request_url = '/api/v1/actor/{0}/?format=json{1}'.format(
            new_actor_dict['id'], self.auth_string)
        response = self.api_client.get(request_url)
        actor_dict_post = json.loads(response.content)
        self.assertEqual(actor_dict_post['related_bulletins'][0],
                         '/api/v1/bulletin/1/')

    def test_actor_incident_related(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actor_dict = json.loads(response.content)

        post_data = {
            'role_status': "K",
            'actor': "/api/v1/actor/{0}/".format(new_actor_dict['id'])
        }
        url = '/api/v1/actorRole/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actorrole_dict = json.loads(response.content)
        post_data = {
            'title_en':
            "Test Incident",
            'incident_details_ar':
            "incident_details Arabic",
            'confidence_score':
            11,
            'assigned_user':
            '******',
            'incident_comments': [
                '/api/v1/comment/1/',
            ],
            'bulletins': [],
            'actors_role':
            ['/api/v1/actorRole/{0}/'.format(new_actorrole_dict['id'])],
            'crimes': [],
            'labels': [],
            'times': [],
            'locations': [],
            'ref_incidents': [],
            'status':
            '/api/v1/statusUpdate/1/',
            'comment':
            'Comment',
            'status_uri':
            '/api/v1/statusUpdate/1/'
        }
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        request_url = '/api/v1/actor/{0}/?format=json{1}'.format(
            new_actor_dict['id'], self.auth_string)
        response = self.api_client.get(request_url)
        actor_dict_post = json.loads(response.content)
        self.assertEqual(actor_dict_post['related_incidents'][0],
                         '/api/v1/incident/1/')

    def test_actor_put(self):
        '''
        create and actor and attach a comment to it, then send a put to create
        a new one. check that the comment get's appended and that for
        data-analyst users it can only be updated
        '''

        self.test_user_util.add_user_to_group('data-analyst')
        post_data = {
            'assigned_user': '******',
            'comments_en': "Test Comment",
            'comments_ar': "Test Comment Arabic",
        }
        url = '/api/v1/comment/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)

        comment_uri = json.loads(response.content)['resource_uri']

        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)
        actor_comments = [
            comment_uri,
        ]
        put_data = create_put_data(1, actor_comments)
        response = self.api_client.put(url, data=put_data)
        self.check_dehydrated_data(response)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Updated')

    def test_senior_data_analyst_put(self):
        self.test_user_util.add_user_to_group('senior-data-analyst')
        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Reviewed')

    def test_chief_data_analyst_put(self):
        self.test_user_util.add_user_to_group('chief-data-analyst')
        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        put_data = create_put_data(5)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 202)
        self.assertEqual(retrieve_last_comment_status(response), 'Finalized')

    def test_finalized_is_not_updated(self):
        precreated_actor = Actor.objects.all()[0]
        comment = Comment(assigned_user_id=1,
                          comments_en='comment',
                          status_id=5)
        comment.save()
        precreated_actor.actor_comments.add(comment)
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        print url
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_assigned_user_perm_enforced(self):
        self.test_user_util.add_user_to_group('data-analyst')
        fixture = AutoFixture(User)
        fixture.create(1)
        precreated_actor = Actor.objects.all()[0]
        precreated_actor.assigned_user = User.objects.get(id=2)
        precreated_actor.save()
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)
        put_data = create_put_data(4)
        put_data['assigned_user'] = '******'
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 2)
        self.test_user_util.add_user_to_group('chief-data-analyst')
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 1)

    def check_dehydrated_data(self, response):
        """
        Test that returned data contains required dehydrated fields.
        New fields should be added to this method as they are added to the
        API to ensure that consistency between front and back end.
        """
        dehydrate_keys = {
            'related_bulletins', 'related_incidents', 'count_incidents',
            'count_bulletins', 'roles', 'actors_role', 'actors',
            'thumbnail_url', 'actor_roles_status', 'most_recent_status_actor'
        }
        content = json.loads(response.content)
        self.assertEqual(all(test in content for test in dehydrate_keys), True)
 def setUp(self):
     self.test_utility = TestUserUtility()
     self.user = self.test_utility.user
Exemplo n.º 31
0
 def setUp(self):
     self.client = Client()
     self.test_user_util = TestUserUtility()
     self.user = self.test_user_util.user
Exemplo n.º 32
0
 def setUp(self):
     self.test_utils = TestUserUtility()
     pass
Exemplo n.º 33
0
class MultiSaveIncidentTestCase(TestCase):
    '''
    verify that multiple incident updates are happening correctly
    '''
    fixtures = [
        'test_data_role',
        'status_update',
        'bulletin',
        'incident',
    ]
    api_url = '/corroborator/incident/0/multisave/'

    def setUp(self):
        '''
        initialisation for tests
        '''
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        initialisation for tests
        '''
        Incident.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()

    def test_incidents_updated(self):
        '''
        basic test to ensure that end to end functionality is in place
        '''
        client = self.test_user_util.client_login()
        post_data = create_incident_data()
        response = client.post(self.api_url,
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        incident_1 = Incident.objects.get(pk=1)
        incident_2 = Incident.objects.get(pk=2)
        self.assertEqual(len(incident_1.actors_role.all()), 1)
        self.assertEqual(len(incident_1.ref_bulletins.all()), 2)
        self.assertEqual(len(incident_1.ref_incidents.all()), 1)
        self.assertEqual(len(incident_2.actors_role.all()), 2)
        response_data = json.loads(response.content)
        self.assertEqual(response_data[0]['most_recent_status_incident'],
                         u'/api/v1/statusUpdate/3/')
        revision = Version.objects.filter(object_id=1)
        self.assertNotEqual(revision, None)

    def test_incidents_updated_with_empty_relations(self):
        client = self.test_user_util.client_login()
        post_data = create_incident_data(empty_data=True)
        response = client.post(self.api_url,
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)

    def test_statusless_update_fails(self):
        client = self.test_user_util.client_login()
        post_data = create_incident_data(version_info=False)
        response = client.post(self.api_url,
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 403)

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_incident = Incident.objects.get(id=1)
        finalized_incident.incident_comments.add(
            create_comment('A finalizing comment', 5, user))
        client = self.test_user_util.client_login()
        post_data = create_incident_data(empty_data=False, version_info=True)
        response = client.post('/corroborator/incident/0/multisave/',
                               post_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 200)
        finalized_incident_comments =\
            Incident.objects.get(id=1).incident_comments.all()

        self.assertEqual(len(finalized_incident_comments), 1)
class ActorTestCase(ResourceTestCase):
    '''
    test the actor tastypie api
    '''
    fixtures = ['test_data_role.json', 'status_update', ]

    def setUp(self):
        super(ActorTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user
        fixture = AutoFixture(Actor)
        fixture.create(10)
        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name'
        )
        self.actor.save()

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        Actor.objects.all().delete()
        User.objects.all().delete()

    def test_actor_get(self):
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/actor/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)

    def test_actor_post(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        # test that a comment get added
        new_actor_dict = json.loads(response.content)
        new_actor = Actor(id=new_actor_dict['id'])
        actor_comments = new_actor.actor_comments.all()
        self.assertEqual(len(actor_comments), 1)
        self.assertEqual(actor_comments[0].status.status_en, 'Human Created')
        vs = VersionStatus.objects.filter(
            user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_actor_bulletin_related(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actor_dict = json.loads(response.content)

        post_data = {
            'role_status': "K",
            'actor': "/api/v1/actor/{0}/".format(
                new_actor_dict['id']
            )
        }
        url = '/api/v1/actorRole/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actorrole_dict = json.loads(response.content)
        post_data = {
            'title_en': "Test Bulletin",
            'description_ar': "description Arabic",
            'confidence_score': 73,
            'sources': [],
            'bulletin_imported_comments': [],
            'assigned_user': '******',
            'actors_role': [
                '/api/v1/actorRole/{0}/'.format(
                    new_actorrole_dict['id']
                )
            ],
            'times': [],
            'medias': [],
            'locations': [],
            'labels': [],
            'ref_bulletins': [],
            'comment': 'new bulletin',
        }
        url = '/api/v1/bulletin/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        request_url = '/api/v1/actor/{0}/?format=json{1}'.format(
            new_actor_dict['id'],
            self.auth_string
        )
        response = self.api_client.get(request_url)
        actor_dict_post = json.loads(response.content)
        self.assertEqual(
            actor_dict_post['related_bulletins'][0],
            '/api/v1/bulletin/1/'
        )

    def test_actor_incident_related(self):
        post_data = {
            'fullname_en': "Test Actor",
            'fullname_ar': "Test Actor Arabic",
            'nickname_en': "Nickname en",
            'nickname_ar': "Nickname Arabic",
            'comment': 'created'
        }
        url = '/api/v1/actor/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actor_dict = json.loads(response.content)

        post_data = {
            'role_status': "K",
            'actor': "/api/v1/actor/{0}/".format(
                new_actor_dict['id']
            )
        }
        url = '/api/v1/actorRole/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)

        new_actorrole_dict = json.loads(response.content)
        post_data = {
            'title_en': "Test Incident",
            'incident_details_ar': "incident_details Arabic",
            'confidence_score': 11,
            'assigned_user': '******',
            'incident_comments': ['/api/v1/comment/1/', ],
            'bulletins': [],
            'actors_role': [
                '/api/v1/actorRole/{0}/'.format(
                    new_actorrole_dict['id']
                )
            ],
            'crimes': [],
            'labels': [],
            'times': [],
            'locations': [],
            'ref_incidents': [],
            'status': '/api/v1/statusUpdate/1/',
            'comment': 'Comment',
            'status_uri': '/api/v1/statusUpdate/1/'
        }
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        request_url = '/api/v1/actor/{0}/?format=json{1}'.format(
            new_actor_dict['id'],
            self.auth_string
        )
        response = self.api_client.get(request_url)
        actor_dict_post = json.loads(response.content)
        self.assertEqual(
            actor_dict_post['related_incidents'][0],
            '/api/v1/incident/1/'
        )

    def test_actor_put(self):
        '''
        create and actor and attach a comment to it, then send a put to create
        a new one. check that the comment get's appended and that for
        data-analyst users it can only be updated
        '''

        self.test_user_util.add_user_to_group('data-analyst')
        post_data = {
            'assigned_user': '******',
            'comments_en': "Test Comment",
            'comments_ar': "Test Comment Arabic",
        }
        url = '/api/v1/comment/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)

        comment_uri = json.loads(response.content)['resource_uri']

        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)
        actor_comments = [comment_uri, ]
        put_data = create_put_data(1, actor_comments)
        response = self.api_client.put(url, data=put_data)
        self.check_dehydrated_data(response)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(retrieve_last_comment_status(response), 'Updated')

    def test_senior_data_analyst_put(self):
        self.test_user_util.add_user_to_group('senior-data-analyst')
        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(retrieve_last_comment_status(response), 'Reviewed')

    def test_chief_data_analyst_put(self):
        self.test_user_util.add_user_to_group('chief-data-analyst')
        precreated_actor = Actor.objects.all()[0]
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        put_data = create_put_data(5)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(retrieve_last_comment_status(response), 'Finalized')

    def test_finalized_is_not_updated(self):
        precreated_actor = Actor.objects.all()[0]
        comment = Comment(
            assigned_user_id=1,
            comments_en='comment',
            status_id=5
        )
        comment.save()
        precreated_actor.actor_comments.add(comment)
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)

        print url
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_assigned_user_perm_enforced(self):
        self.test_user_util.add_user_to_group('data-analyst')
        fixture = AutoFixture(User)
        fixture.create(1)
        precreated_actor = Actor.objects.all()[0]
        precreated_actor.assigned_user = User.objects.get(id=2)
        precreated_actor.save()
        url = '/api/v1/actor/{0}/?format=json{1}'.format(
            precreated_actor.id, self.auth_string)
        put_data = create_put_data(4)
        put_data['assigned_user'] = '******'
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 2)
        self.test_user_util.add_user_to_group('chief-data-analyst')
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 1)

    def check_dehydrated_data(self, response):
        """
        Test that returned data contains required dehydrated fields.
        New fields should be added to this method as they are added to the
        API to ensure that consistency between front and back end.
        """
        dehydrate_keys = {
            'related_bulletins',
            'related_incidents',
            'count_incidents',
            'count_bulletins',
            'roles',
            'actors_role',
            'actors',
            'thumbnail_url',
            'actor_roles_status',
            'most_recent_status_actor'
        }
        content = json.loads(response.content)
        self.assertEqual(
            all(
                test in content for test in dehydrate_keys
            ),
            True
        )
Exemplo n.º 35
0
class IncidentTestCase(ResourceTestCase):
    fixtures = ['test_data_role.json', 'status_update', ]

    def setUp(self):
        super(IncidentTestCase, self).setUp()
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

        self.location = Location(name_en='test location', loc_type='Village')
        self.location.save()

        self.actor = Actor(
            fullname_en='Test Actor',
            fullname_ar='Test name ar',
            nickname_en='nick name',
            nickname_ar='nick name')
        self.actor.save()
        self.role = ActorRole(role_status='Detained', actor_id=self.actor.pk)
        self.role.save()

        self.statusUpdate = StatusUpdate(status_en='test status')
        self.statusUpdate.save()

        self.crimeCategory = CrimeCategory(
            name_en='test crime category',
            level=1,
            description_en='test source incident_details')
        self.crimeCategory.save()
        self.label = Label(name_en='test label')
        self.label.save()

        self.comment = Comment(
            assigned_user_id=self.user.pk,
            status_id=self.statusUpdate.pk,
            comments_en='test comment')
        self.comment.save()

        fixture = AutoFixture(Incident, generate_m2m={1, 5})
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        User.objects.all().delete()
        Incident.objects.all().delete()
        Actor.objects.all().delete()
        ActorRole.objects.all().delete()
        Location.objects.all().delete()
        TimeInfo.objects.all().delete()
        Comment.objects.all().delete()
        StatusUpdate.objects.all().delete()
        CrimeCategory.objects.all().delete()

    def test_incident_get(self):
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/incident/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)

    def test_incident_post(self):
        post_data = {
            'title_en': "Test Incident",
            'incident_details_ar': "incident_details Arabic",
            'confidence_score': 11,
            'assigned_user': '******',
            'incident_comments': ['/api/v1/comment/1/', ],
            'bulletins': [],
            'actors_role': [],
            'crimes': [],
            'labels': [],
            'times': [],
            'locations': [],
            'ref_incidents': [],
            'status': '/api/v1/statusUpdate/1/',
            'comment': 'Comment',
            'status_uri': '/api/v1/statusUpdate/1/'
        }
        url = '/api/v1/incident/?format=json{}'.format(self.auth_string)
        response = self.api_client.post(url, data=post_data)
        self.assertEqual(response.status_code, 201)
        new_incident_dict = json.loads(response.content)
        new_incident = Incident(id=new_incident_dict['id'])
        incident_comments = new_incident.incident_comments.all()
        self.assertEqual(len(incident_comments), 1)
        vs = VersionStatus.objects.filter(user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)

    def test_incident_put(self):
        i = Incident.objects.all()[0]
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            i.id, self.auth_string)

        put_data = create_put_data()
        response = self.api_client.put(url, data=put_data)
        self.check_dehydrated_data(response)
        self.assertEqual(response.status_code, 202)
        vs = VersionStatus.objects.filter(user_id=self.user.id).order_by('version_timestamp')
        self.assertEqual(len(vs), 1)


    def test_finalized_is_not_updated(self):
        precreated_incident = Incident.objects.all()[0]
        comment = Comment(
            assigned_user_id=1,
            comments_en='comment',
            status_id=5
        )
        comment.save()
        precreated_incident.incident_comments.add(comment)
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            precreated_incident.id, self.auth_string)

        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        self.assertEqual(response.status_code, 403)

    def test_assigned_user_perm_enforced(self):
        self.test_user_util.add_user_to_group('data-analyst')
        fixture = AutoFixture(User)
        fixture.create(1)
        precreated_incident = Incident.objects.all()[0]
        precreated_incident.assigned_user = User.objects.get(id=2)
        precreated_incident.save()
        url = '/api/v1/incident/{0}/?format=json{1}'.format(
            precreated_incident.id, self.auth_string)
        put_data = create_put_data(4)
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 2)
        self.test_user_util.add_user_to_group('chief-data-analyst')
        response = self.api_client.put(url, data=put_data)
        assigned_user_id = retrieve_user_id(response)
        self.assertEqual(assigned_user_id, 1)

    def check_dehydrated_data(self, response):
        """
        Test that returned data contains required dehydrated fields.
        New fields should be added to this method as they are added to the
        API to ensure that consistency between front and back end.
        """
        dehydrate_keys = [
            'incident_locations',
            'incident_labels',
            'incident_times',
            'incident_crimes',
            'most_recent_status_incident',
            'count_actors',
            'count_bulletins',
            'count_incidents',
            'actor_roles_status',
            'actors',
            'actors_role'
        ]
        content = json.loads(response.content)
        self.assertEqual(
            all(
                test in content for test in dehydrate_keys
            ),
            True
        )
Exemplo n.º 36
0
 def setUp(self):
     self.test_utils = TestUserUtility()
     pass
class MultiSaveBulletinTestCase(TestCase):
    '''
    verify that multiple bulletin updates are happening correctly
    '''
    fixtures = ['test_data_role.json', 'status_update', ]

    def setUp(self):
        '''
        initialisation for tests
        '''
        bulletin_fixture = AutoFixture(Bulletin)
        bulletin_fixture.create(5)
        bull = Bulletin.objects.get(id=1)
        bull.actors_role.clear()
        bull.save()
        location_fixture = AutoFixture(Location)
        location_fixture.create(1)
        self.test_user_util = TestUserUtility()
        self.user = self.test_user_util.user

    def tearDown(self):
        '''
        initialisation for tests
        '''
        User.objects.all().delete()
        Bulletin.objects.all().delete()
        Location.objects.all().delete()
        ActorRole.objects.all().delete()

    def test_bulletins_updated(self):
        '''
        basic test to ensure that end to end functionality is in place
        '''
        client = Client()
        client.login(username='******', password='******')
        post_data = create_bulletin_data()
        response = client.post(
            '/corroborator/bulletin/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        post_data = create_bulletin_data(empty_data=True)
        response = client.post(
            '/corroborator/bulletin/0/multisave/',
            post_data,
            content_type='application/json'
        )
        response_data = json.loads(response.content)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response_data[0]['most_recent_status_bulletin'],
            u'/api/v1/statusUpdate/3/')
        revision = Version.objects.filter(object_id=1)        
        self.assertNotEqual(revision, None)


    def test_statusless_update_fails(self):
        client = Client()
        post_data = create_bulletin_data(version_info=False)
        response = client.post(
            '/corroborator/bulletin/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 403)

    def test_finalized_entities_are_not_updated(self):
        '''
        finalized entities should not be updated
        '''
        user = User.objects.get(id=1)
        finalized_bulletin = Bulletin.objects.get(id=1)
        finalized_bulletin.bulletin_comments.add(
            create_comment('A finalizing comment', 5, user)
        )
        client = self.test_user_util.client_login()
        post_data = create_bulletin_data(
            empty_data=False,
            version_info=True
        )
        response = client.post(
            '/corroborator/bulletin/0/multisave/',
            post_data,
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)
        finalized_bulletin_comments =\
            Bulletin.objects.get(id=1).bulletin_comments.all()

        self.assertEqual(len(finalized_bulletin_comments), 1)