def test_display_home(self):
     Roles.set_roles([('Allow', 'CONSORTIUM_EDUCATION_ADMINISTRATOR_1', ('view', 'logout', 'display_home'))])
     user = User()
     rel_chain = [RoleRelation('CONSORTIUM_EDUCATION_ADMINISTRATOR_1', 'CA', 'CA', '1', '2')]
     user.set_context(rel_chain)
     context = user.get_user_context()
     self.assertTrue(context['displayHome'])
 def test_role_undefined(self):
     role_rel = [RoleRelation('invalidrole', None, None, None, None)]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(1, len(roles))
     self.assertIn('DEFAULT', roles)
 def test_role_undefined(self):
     role_rel = [RoleRelation('invalidrole', None, None, None, None)]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(1, len(roles))
     self.assertIn('DEFAULT', roles)
Beispiel #4
0
 def setUp(self):
     self.dummy_uid = 'bbunny'
     self.dummy_user = User()
     self.dummy_user.set_uid(self.dummy_uid)
     self.dummy_file_path = 'tmp/filename.zip'
     self.dummy_file_name = 'ActualName.zip'
     self.__request = DummyRequest()
 def test_with_default_permission(self):
     role_rel = [RoleRelation('DEFAULT', 'tenant', 'NY', 'a', '1'),
                 RoleRelation('PII', 'tenant', 'NY', 'a', '1')]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     self.assertEqual(1, len(user.get_tenants()))
 def test__add_tenant(self):
     user = User()
     user._add_tenant('t')
     self.assertIn('t', user.get_tenants())
     user._add_tenant(None)
     self.assertEqual(1, len(user.get_tenants()))
     self.assertIn('t', user.get_tenants())
 def test__add_role(self):
     user = User()
     user._add_role('role')
     self.assertIn('role', user.get_roles())
     user._add_role(None)
     self.assertEqual(1, len(user.get_roles()))
     self.assertIn('role', user.get_roles())
 def test_display_home(self):
     Roles.set_roles([('Allow', 'CONSORTIUM_EDUCATION_ADMINISTRATOR_1',
                       ('view', 'logout', 'display_home'))])
     user = User()
     rel_chain = [
         RoleRelation('CONSORTIUM_EDUCATION_ADMINISTRATOR_1', 'CA', 'CA',
                      '1', '2')
     ]
     user.set_context(rel_chain)
     context = user.get_user_context()
     self.assertTrue(context['displayHome'])
 def test_tenantless(self):
     role_rel = [RoleRelation('badrole', None, None, None, None),
                 RoleRelation('PII', 'tenant1', 'NC', 'a', '2')]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     tenants = user.get_tenants()
     self.assertEqual(3, len(tenants))
    def test_set_user_info(self):
        user = User()
        data = {'name': {'fullName': 'Joe Doe', 'firstName': 'Joe', 'lastName': 'Doe'}, 'uid': 'joe.doe', 'junk': 'junk', 'roles': ['TEACHER'], 'stateCode': [], 'tenant': 'dog', 'displayHome': False, 'guid': '123'}

        user.set_user_info(data)
        context = user.get_user_context()
        self.assertEqual(len(context), 7)
        self.assertEqual(context['name'], data['name'])
        self.assertEqual(context['uid'], data['uid'])
        self.assertEqual(context['guid'], data['guid'])
        self.assertEqual(context['displayHome'], data['displayHome'])
 def test_default_permission_gets_added(self):
     role_rel = [RoleRelation('badrole', 'tenant', 'NY', 'a', '1'),
                 RoleRelation('PII', 'tenant', 'NY', 'a', '2'),
                 RoleRelation('badrole2', 'tenant', 'NY', 'b', None)]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     self.assertEqual(1, len(user.get_tenants()))
    def test_empty_user(self):
        user = User()
        data = {
            'name': {
                'fullName': None,
                'firstName': None,
                'lastName': None
            },
            'uid': None,
            'roles': [],
            'stateCode': [],
            'tenant': [],
            'displayHome': False,
            'guid': None
        }

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})

        uid = user.get_uid()
        self.assertEqual(uid, data['uid'])

        context = user.get_user_context()
        self.assertEqual(context, data)

        roles = user.get_roles()
        self.assertEqual(roles, data['roles'])

        tenant = user.get_tenants()
        self.assertEqual(0, len(tenant))

        guid = user.get_guid()
        self.assertIsNone(guid)
 def test__add_tenant(self):
     user = User()
     user._add_tenant('t')
     self.assertIn('t', user.get_tenants())
     user._add_tenant(None)
     self.assertEqual(1, len(user.get_tenants()))
     self.assertIn('t', user.get_tenants())
 def test__add_role(self):
     user = User()
     user._add_role('role')
     self.assertIn('role', user.get_roles())
     user._add_role(None)
     self.assertEqual(1, len(user.get_roles()))
     self.assertIn('role', user.get_roles())
 def test__create_new_task_tenant_level_json_request(self):
     with UnittestEdcoreDBConnection() as connection:
         fact = connection.get_table('fact_asmt_outcome_vw')
         query = select([fact.c.student_id], from_obj=[fact])
     params = {
         'stateCode': 'CA',
         'districtId': '341',
         'schoolId': 'asf',
         'asmtGrade': '05',
         'asmtSubject': 'UUUU',
         'asmtType': 'abc',
         'asmtYear': '2015',
         'asmtGuid': '2C2ED8DC-A51E-45D1-BB4D-D0CF03898259'
     }
     user = User()
     task = _create_new_task('request_id',
                             user,
                             'tenant',
                             params,
                             query,
                             asmt_metadata=True,
                             is_tenant_level=True)
     self.assertIsNotNone(task)
     self.assertEquals(ExtractionDataType.QUERY_JSON,
                       task[TaskConstants.EXTRACTION_DATA_TYPE])
     expected_path = os.path.join(
         self.__work_zone_dir, 'tenant', 'request_id', 'data',
         'METADATA_ASMT_2015_CA_GRADE_05_UUUU_ABC_2C2ED8DC-A51E-45D1-BB4D-D0CF03898259.json'
     )
     self.assertIn(expected_path, task[TaskConstants.TASK_FILE_NAME])
    def test__create_task_info_completion(self, amstquery_patch, aquery_patch,
                                          header_patch, util_patch):
        dummy_headers = ('H1', 'H2')

        util_patch.return_value = ''
        header_patch.return_value = dummy_headers
        aquery_patch.return_value = ''
        amstquery_patch.return_value = ''

        extract_params = {
            TaskConstants.STATE_CODE: "NC",
            TaskConstants.ACADEMIC_YEAR: 2015,
            Extract.REPORT_TYPE: 'studentAssessmentCompletion',
            TaskConstants.EXTRACTION_DATA_TYPE:
            ExtractionDataType.SR_COMPLETION
        }

        user = User()
        results = _create_task_info("request_id", user, 'tenant',
                                    extract_params)

        self.assertEqual(8, len(results))
        self.assertEquals(dummy_headers, results[TaskConstants.CSV_HEADERS])
        self.assertEqual(2, len(results[TaskConstants.TASK_QUERIES]))
        self.assertEquals('StudentAssessmentCompletionReportCSV',
                          results[TaskConstants.EXTRACTION_DATA_TYPE])
    def test__create_task_info_statistics(self, util_patch, header_patch,
                                          aquery_patch, mquery_patch):
        dummy_headers = ('H1', 'H2')

        util_patch.return_value = ''
        header_patch.return_value = dummy_headers
        aquery_patch.return_value = ''
        mquery_patch.return_value = ''

        extract_params = {
            TaskConstants.STATE_CODE: "NC",
            TaskConstants.ACADEMIC_YEAR: 2015,
            Extract.REPORT_TYPE: 'studentRegistrationStatistics',
            TaskConstants.EXTRACTION_DATA_TYPE:
            ExtractionDataType.SR_STATISTICS
        }

        user = User()
        results = _create_task_info("request_id", user, 'tenant',
                                    extract_params)

        self.assertEqual(len(results), 8)
        self.assertEqual(2, len(results[TaskConstants.TASK_QUERIES]))
        self.assertEquals('StudentRegistrationStatisticsReportCSV',
                          results[TaskConstants.EXTRACTION_DATA_TYPE])
 def setUp(self):
     self.dummy_uid = 'bbunny'
     self.dummy_user = User()
     self.dummy_user.set_uid(self.dummy_uid)
     self.dummy_file_path = 'tmp/filename.zip'
     self.dummy_file_name = 'ActualName.zip'
     self.__request = DummyRequest()
 def test__create_tasks_for_tenant_lvl(self):
     with UnittestEdcoreDBConnection() as connection:
         fact = connection.get_table('fact_asmt_outcome_vw')
         query = select([fact.c.student_id], from_obj=[fact])
     params = {
         'stateCode': 'CA',
         'districtId': '341',
         'schoolId': 'asf',
         'asmtGrade': '05',
         'asmtSubject': 'UUUU',
         'asmtType': 'abc',
         'asmtYear': '2015',
         'asmtGuid': '2C2ED8DC-A51E-45D1-BB4D-D0CF03898259'
     }
     user = User()
     results = _create_tasks('request_id',
                             user,
                             'tenant',
                             params,
                             query,
                             is_tenant_level=True)
     self.assertIsNotNone(results)
     self.assertEqual(len(results), 2)
     self.assertEquals(ExtractionDataType.QUERY_CSV,
                       results[0][TaskConstants.EXTRACTION_DATA_TYPE])
     self.assertEquals(ExtractionDataType.QUERY_JSON,
                       results[1][TaskConstants.EXTRACTION_DATA_TYPE])
     expected_path = os.path.join(self.__work_zone_dir, 'tenant',
                                  'request_id', 'data',
                                  'ASMT_2015_CA_GRADE_05')
     self.assertIn(expected_path, results[0][TaskConstants.TASK_FILE_NAME])
    def test_set_individual_names(self):
        user = User()
        data = {'name': {'fullName': 'Joe MDoe', 'firstName': 'Joe', 'lastName': 'Doe'}, 'uid': 'joe.doe', 'roles': ['TEACHER'], 'tenant': ['dog'], 'displayHome': False, 'guid': '123'}
        user.set_first_name(data['name']['firstName'])
        user.set_last_name(data['name']['lastName'])
        user.set_full_name(data['name']['fullName'])

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})
    def test_get_user_context(self):
        user = User()
        data = {'name': {'fullName': 'Joe Doe', 'firstName': 'Joe', 'lastName': 'Doe'}, 'uid': 'joe.doe', 'roles': ['TEACHER'], 'tenant': 'dog', 'guid': '123'}
        user.set_name(data['name'])
        user.set_uid(data['uid'])
        user.set_guid(data['guid'])

        context = user.get_user_context()
        self.assertEqual(context['uid'], data['uid'])
        self.assertEqual(context['name'], data['name'])
        self.assertEqual(context['guid'], data['guid'])
    def test_set_individual_names(self):
        user = User()
        data = {
            'name': {
                'fullName': 'Joe MDoe',
                'firstName': 'Joe',
                'lastName': 'Doe'
            },
            'uid': 'joe.doe',
            'roles': ['TEACHER'],
            'tenant': ['dog'],
            'displayHome': False,
            'guid': '123'
        }
        user.set_first_name(data['name']['firstName'])
        user.set_last_name(data['name']['lastName'])
        user.set_full_name(data['name']['fullName'])

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})
 def test__create_asmt_metadata_task(self):
     params = {
         'stateCode': 'CA',
         'districtId': '341',
         'schoolId': 'asf',
         'asmtGrade': '05',
         'asmtSubject': 'UUUU',
         'asmtType': 'abc',
         'asmtGuid': '2C2ED8DC-A51E-45D1-BB4D-D0CF03898259'
     }
     user = User()
     task = _create_asmt_metadata_task('request_id', user, 'tenant', params)
     self.assertIsNotNone(task)
     self.assertEquals(ExtractionDataType.QUERY_JSON,
                       task[TaskConstants.EXTRACTION_DATA_TYPE])
    def test_set_user_info(self):
        user = User()
        data = {
            'name': {
                'fullName': 'Joe Doe',
                'firstName': 'Joe',
                'lastName': 'Doe'
            },
            'uid': 'joe.doe',
            'junk': 'junk',
            'roles': ['TEACHER'],
            'stateCode': [],
            'tenant': 'dog',
            'displayHome': False,
            'guid': '123'
        }

        user.set_user_info(data)
        context = user.get_user_context()
        self.assertEqual(len(context), 7)
        self.assertEqual(context['name'], data['name'])
        self.assertEqual(context['uid'], data['uid'])
        self.assertEqual(context['guid'], data['guid'])
        self.assertEqual(context['displayHome'], data['displayHome'])
    def test_get_user_context(self):
        user = User()
        data = {
            'name': {
                'fullName': 'Joe Doe',
                'firstName': 'Joe',
                'lastName': 'Doe'
            },
            'uid': 'joe.doe',
            'roles': ['TEACHER'],
            'tenant': 'dog',
            'guid': '123'
        }
        user.set_name(data['name'])
        user.set_uid(data['uid'])
        user.set_guid(data['guid'])

        context = user.get_user_context()
        self.assertEqual(context['uid'], data['uid'])
        self.assertEqual(context['name'], data['name'])
        self.assertEqual(context['guid'], data['guid'])
 def test_with_default_permission(self):
     role_rel = [
         RoleRelation('DEFAULT', 'tenant', 'NY', 'a', '1'),
         RoleRelation('PII', 'tenant', 'NY', 'a', '1')
     ]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     self.assertEqual(1, len(user.get_tenants()))
 def test__create_tasks_with_responses_tenant_level(self):
     params = {
         'stateCode': 'NC',
         'districtId': '228',
         'schoolId': '242',
         'asmtSubject': 'Math',
         'asmtYear': '2016',
         'asmtType': 'SUMMATIVE'
     }
     user = User()
     results = _create_tasks_with_responses('request_id',
                                            user,
                                            'tenant',
                                            params,
                                            is_tenant_level=False)
     self.assertEqual(len(results[0]), 4)
     self.assertEqual(len(results[1]), 1)
     self.assertEqual(results[1][0][Extract.STATUS], Extract.OK)
 def test_tenantless(self):
     role_rel = [
         RoleRelation('badrole', None, None, None, None),
         RoleRelation('PII', 'tenant1', 'NC', 'a', '2')
     ]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     tenants = user.get_tenants()
     self.assertEqual(3, len(tenants))
 def test_default_permission_gets_added(self):
     role_rel = [
         RoleRelation('badrole', 'tenant', 'NY', 'a', '1'),
         RoleRelation('PII', 'tenant', 'NY', 'a', '2'),
         RoleRelation('badrole2', 'tenant', 'NY', 'b', None)
     ]
     user = User()
     user.set_context(role_rel)
     roles = user.get_roles()
     self.assertEqual(2, len(roles))
     self.assertIn('DEFAULT', roles)
     self.assertIn('PII', roles)
     self.assertEqual(1, len(user.get_tenants()))
 def test__create_new_task_item_level(self):
     with UnittestEdcoreDBConnection() as connection:
         fact = connection.get_table('fact_asmt_outcome_vw')
         query = select([fact.c.student_id], from_obj=[fact])
     params = {
         'stateCode': 'CA',
         'asmtYear': '2015',
         'asmtType': 'abc',
         'asmtSubject': 'UUUU',
         'asmtGrade': '05'
     }
     user = User()
     task = _create_new_task('request_id',
                             user,
                             'tenant',
                             params,
                             query,
                             extract_type=ExtractType.itemLevel,
                             is_tenant_level=True)
     self.assertIsNotNone(task)
     self.assertEquals(ExtractionDataType.QUERY_ITEMS_CSV,
                       task[TaskConstants.EXTRACTION_DATA_TYPE])
    def test_empty_user(self):
        user = User()
        data = {'name': {'fullName': None, 'firstName': None, 'lastName': None}, 'uid': None, 'roles': [], 'stateCode': [], 'tenant': [], 'displayHome': False, 'guid': None}

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})

        uid = user.get_uid()
        self.assertEqual(uid, data['uid'])

        context = user.get_user_context()
        self.assertEqual(context, data)

        roles = user.get_roles()
        self.assertEqual(roles, data['roles'])

        tenant = user.get_tenants()
        self.assertEqual(0, len(tenant))

        guid = user.get_guid()
        self.assertIsNone(guid)
Beispiel #32
0
class RegistrationTest(unittest.TestCase):
    def setUp(self):
        self.dummy_uid = 'bbunny'
        self.dummy_user = User()
        self.dummy_user.set_uid(self.dummy_uid)
        self.dummy_file_path = 'tmp/filename.zip'
        self.dummy_file_name = 'ActualName.zip'
        self.__request = DummyRequest()

    def tearDown(self):
        self.__request = None

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.info')
    def test_download_file(self, logger_patch, is_file_patch,
                           get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {
            "user_id": self.dummy_uid,
            "file_path": self.dummy_file_path,
            "file_name": self.dummy_file_name
        }
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '1234'
        self.__request.registry.settings['mode'] = 'prod'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 200)

        headers = response.headers

        self.assertEqual(len(headers), 3)
        self.assertEqual(headers['X-Sendfile'], self.dummy_file_path)
        self.assertEqual(headers['Content-Type'], '')
        self.assertEqual(headers['Content-Disposition'],
                         'attachment; filename=ActualName.zip')
        logger_patch.assert_called_once_with(
            'File %s was successfully downloaded', 'tmp/filename.zip')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_registered(self, logger_patch, is_file_patch,
                                          get_reg_info_patch,
                                          auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = None
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with(
            'No file record is registered with requested id %s', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_owner(self, logger_patch, is_file_patch,
                                     get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        reg_user_id = 'dduck'
        get_reg_info_patch.return_value = {
            "user_id": reg_user_id,
            "file_path": self.dummy_file_path,
            "file_name": self.dummy_file_name
        }
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with(
            'User %s is not owner of the file with registration id %s',
            'bbunny', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_still_processing(self, logger_patch, is_file_patch,
                                            get_reg_info_patch,
                                            auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {
            "user_id": self.dummy_uid,
            "file_path": None,
            "file_name": None
        }
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with(
            'File with registration id %s is not yet available', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_on_disk(self, logger_patch, is_file_patch,
                                       get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {
            "user_id": self.dummy_uid,
            "file_path": self.dummy_file_path,
            "file_name": self.dummy_file_name
        }
        is_file_patch.return_value = False
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with(
            'File %s is registered, but does not exist on disk',
            'tmp/filename.zip')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    def test_file_exists_file_not_exist(self, get_reg_info_patch,
                                        auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {
            "user_id": self.dummy_uid,
            "file_path": self.dummy_file_path,
            "file_name": self.dummy_file_name
        }
        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'
        response = is_file_exist(None, self.__request)
        self.assertEqual(response.status_code, 404)

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.info')
    def test_file_exists_for_valid_file(self, logger_patch, is_file_patch,
                                        get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {
            "user_id": self.dummy_uid,
            "file_path": self.dummy_file_path,
            "file_name": self.dummy_file_name
        }
        is_file_patch.return_value = True
        logger_patch.return_value = None
        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '1234'
        response = is_file_exist(None, self.__request)
        self.assertEqual(response.status_code, 200)
class RegistrationTest(unittest.TestCase):

    def setUp(self):
        self.dummy_uid = 'bbunny'
        self.dummy_user = User()
        self.dummy_user.set_uid(self.dummy_uid)
        self.dummy_file_path = 'tmp/filename.zip'
        self.dummy_file_name = 'ActualName.zip'
        self.__request = DummyRequest()

    def tearDown(self):
        self.__request = None

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.info')
    def test_download_file(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {"user_id": self.dummy_uid, "file_path": self.dummy_file_path,
                                           "file_name": self.dummy_file_name}
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '1234'
        self.__request.registry.settings['mode'] = 'prod'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 200)

        headers = response.headers

        self.assertEqual(len(headers), 3)
        self.assertEqual(headers['X-Sendfile'], self.dummy_file_path)
        self.assertEqual(headers['Content-Type'], '')
        self.assertEqual(headers['Content-Disposition'], 'attachment; filename=ActualName.zip')
        logger_patch.assert_called_once_with('File %s was successfully downloaded', 'tmp/filename.zip')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_registered(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = None
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with('No file record is registered with requested id %s', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_owner(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        reg_user_id = 'dduck'
        get_reg_info_patch.return_value = {"user_id": reg_user_id, "file_path": self.dummy_file_path,
                                           "file_name": self.dummy_file_name}
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with('User %s is not owner of the file with registration id %s', 'bbunny', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_still_processing(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {"user_id": self.dummy_uid, "file_path": None, "file_name": None}
        is_file_patch.return_value = True
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with('File with registration id %s is not yet available', '12345')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.error')
    def test_download_file_not_on_disk(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {"user_id": self.dummy_uid, "file_path": self.dummy_file_path,
                                           "file_name": self.dummy_file_name}
        is_file_patch.return_value = False
        logger_patch.return_value = None

        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'

        response = download_file(None, self.__request)

        self.assertEqual(response.status_code, 404)
        logger_patch.assert_called_once_with('File %s is registered, but does not exist on disk', 'tmp/filename.zip')

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    def test_file_exists_file_not_exist(self, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {"user_id": self.dummy_uid, "file_path": self.dummy_file_path,
                                           "file_name": self.dummy_file_name}
        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '12345'
        response = is_file_exist(None, self.__request)
        self.assertEqual(response.status_code, 404)

    @patch('hpz.swi.download_service.authenticated_userid')
    @patch('hpz.frs.registration_service.FileRegistry.get_registration_info')
    @patch('os.path.isfile')
    @patch('hpz.swi.download_service.logger.info')
    def test_file_exists_for_valid_file(self, logger_patch, is_file_patch, get_reg_info_patch, auth_userid_patch):
        auth_userid_patch.return_value = self.dummy_user
        get_reg_info_patch.return_value = {"user_id": self.dummy_uid, "file_path": self.dummy_file_path,
                                           "file_name": self.dummy_file_name}
        is_file_patch.return_value = True
        logger_patch.return_value = None
        self.__request.method = 'GET'
        self.__request.matchdict['reg_id'] = '1234'
        response = is_file_exist(None, self.__request)
        self.assertEqual(response.status_code, 200)
 def __initialize_session(self):
     self.__session = {}
     self.__user = User()
     self.__session_id = None
     self.__session['idpSessionIndex'] = None
     self.__session['nameId'] = None
class Session:
    '''
    Simple class that holds user session information, such as
    guid, user id, name, roles, and tenant
    '''
    def __init__(self):
        self.__initialize_session()
        # leave datetime only this class, not save in session context
        self.__expiration = None
        self.__last_access = None

    # initialize all session values
    def __initialize_session(self):
        self.__session = {}
        self.__user = User()
        self.__session_id = None
        self.__session['idpSessionIndex'] = None
        self.__session['nameId'] = None

    # serialize to text
    def get_session_json_context(self):
        # Get User Info and combined the dictionary
        combined_context = self.__user.get_user_context()
        combined_context.update_session(self.__session)
        return json.dumps(combined_context)

    def get_session_id(self):
        return self.__session_id

    def get_uid(self):
        return self.__user.get_uid()

    def get_email(self):
        return self.__user.get_email()

    def get_roles(self):
        return self.__user.get_roles()

    def get_tenants(self):
        return self.__user.get_tenants()

    def get_guid(self):
        return self.__user.get_guid()

    def get_name(self):
        return self.__user.get_name()

    def get_idp_session_index(self):
        return self.__session['idpSessionIndex']

    def get_name_id(self):
        return self.__session['nameId']

    def get_last_access(self):
        return self.__last_access

    def get_expiration(self):
        return self.__expiration

    def get_user(self):
        return self.__user

    def set_session_id(self, session_id):
        '''
        @param session_id: the session id
        '''
        self.__session_id = session_id

    def set_uid(self, uid):
        '''
        @param uid: the uid
        '''
        self.__user.set_uid(uid)

    def set_email(self, email):
        '''
        @param uid: the uid
        '''
        self.__user.set_email(email)

    def set_user_context(self, context):
        self.__user.set_context(context)

    def set_guid(self, guid):
        '''
        @param guid: the user guid to set
        '''
        self.__user.set_guid(guid)

    def set_fullName(self, fullName):
        '''
        @param fullName: the full name
        '''
        self.__user.set_full_name(fullName)

    def set_lastName(self, lastName):
        '''
        @param lastName: the last name
        '''
        self.__user.set_last_name(lastName)

    def set_firstName(self, firstName):
        '''
        @param firstName: the first name
        '''
        self.__user.set_first_name(firstName)

    def set_idp_session_index(self, index):
        '''
        @param index: the idp session index
        '''
        self.__session['idpSessionIndex'] = index

    def set_name_id(self, name_id):
        '''
        @param name_id: the name id
        '''
        self.__session['nameId'] = name_id

    def set_session(self, session):
        self.__session = session
        self.__set_user(session)

    def set_expiration(self, datetime):
        self.__expiration = datetime

    def set_last_access(self, datetime):
        self.__last_access = datetime

    def __set_user(self, info):
        self.__user.set_user_info(info)
    def test_non_empty_user(self):
        user = User()
        data = {'name': {'fullName': 'Joe Doe', 'firstName': 'Joe', 'lastName': 'Doe'}, 'uid': 'joe.doe', 'roles': [], 'stateCode': [None], 'tenant': None, 'displayHome': False, 'guid': '123'}
        user.set_name(data['name'])
        user.set_uid(data['uid'])
        user.set_guid(data['guid'])

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})

        uid = user.get_uid()
        self.assertEqual(uid, data['uid'])

        context = user.get_user_context()
        self.assertEqual(context['displayHome'], data['displayHome'])
        self.assertEqual(context['guid'], data['guid'])

        guid = user.get_guid()
        self.assertEqual(guid, data['guid'])
    def test_non_empty_user(self):
        user = User()
        data = {
            'name': {
                'fullName': 'Joe Doe',
                'firstName': 'Joe',
                'lastName': 'Doe'
            },
            'uid': 'joe.doe',
            'roles': [],
            'stateCode': [None],
            'tenant': None,
            'displayHome': False,
            'guid': '123'
        }
        user.set_name(data['name'])
        user.set_uid(data['uid'])
        user.set_guid(data['guid'])

        name = user.get_name()
        self.assertEqual(name, {'name': data['name']})

        uid = user.get_uid()
        self.assertEqual(uid, data['uid'])

        context = user.get_user_context()
        self.assertEqual(context['displayHome'], data['displayHome'])
        self.assertEqual(context['guid'], data['guid'])

        guid = user.get_guid()
        self.assertEqual(guid, data['guid'])