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 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)
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.º 4
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.º 5
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 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.º 7
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 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 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 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)