示例#1
0
    def setUp(self):
        # Initialize Request Handlers
        self.er_rh = ExternalRecordRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.es_rh = ExternalSystemRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.s_rh = SubjectRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.g_rh = GroupRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.o_rh = OrganizationRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)

        self.es_name1 = "testESNameABCD"
        self.es_name2 = "testESName1234"
        self.org_subj_id_1 = "testmrn0001"
        self.org_subj_id_2 = "testmrn0002"
        self.org_subj_id_3 = "testmrn002"
        self.recid1 = "testrecid0001"
        self.recid2 = "testrecid0002"
        self.recid3 = "testrecid0003"
        self.recid4 = "testrecid0004"
        self.path1 = "testpath1"
        self.path2 = "testpath2"
        self.path3 = 'testpath3'
        self.org_name_1 = "testOrg001"
        self.org_name_2 = "testOrg002"
        self.subj_id_label_1 = 'org_1_id'
        try:
            # Create the Organizations
            self.o1 = Organization(name=self.org_name_1,
                                   subject_id_label=self.subj_id_label_1)
            self.o2 = Organization(name=self.org_name_2,
                                   subject_id_label=self.subj_id_label_1)
            r = self.o_rh.create(self.o1, self.o2)

            # Create Subjects
            dob = datetime.date.today()
            self.s1 = Subject(first_name='FIRST_ONE', last_name="LAST_ONE",
                              organization_id=self.o1.id,
                              organization_subject_id=self.org_subj_id_1, dob=dob)
            self.s2 = Subject(first_name='FIRST_TWO', last_name="LAST_TWO",
                              organization_id=self.o1.id,
                              organization_subject_id=self.org_subj_id_2, dob=dob)
            self.s3 = Subject(first_name='FIRST_THREE', last_name="LAST_THREE",
                              organization_id=self.o2.id,
                              organization_subject_id=self.org_subj_id_3, dob=dob)
            r = self.s_rh.create(self.s1, self.s2, self.s3)

            # Create External Systems
            self.es1 = ExternalSystem(name=self.es_name1, url="http://test.com/",
                                      description='A test system')
            self.es2 = ExternalSystem(name=self.es_name2, url="http://testTwo.com/",
                                      description='Another test system')
            r = self.es_rh.create(self.es1, self.es2)

            # Create External record
            self.er1 = ExternalRecord(record_id=self.recid1, subject_id=self.s1.id,
                                      external_system_id=self.es1.id, path=self.path1,
                                      label_id=1)
            self.er2 = ExternalRecord(record_id=self.recid2, subject_id=self.s1.id,
                                      external_system_id=self.es1.id, path=self.path2,
                                      label_id=1)
            r = self.er_rh.create(self.er1, self.er2)
            self.er1 = r[0]['external_record']
            self.er2 = r[1]['external_record']
            # # Create External record link
            r = self.er_rh.link(self.er1, self.er2, 1)
            # Create test groups
            # Subject Group
            self.g1 = Group(name='testgroup1', is_locking=False,
                            client_key='ck', description='A test group')
            # ExternalRecord Group
            self.g2 = Group(name='exrecgroup', is_locking=False,
                            client_key='ck', description='An external record group')
            r = self.g_rh.create(self.g1, self.g2)

            # Add subject to test group
            r = self.g_rh.add_subjects(self.g1, [self.s1])

            # Add external record to test group
            r = self.g_rh.add_records(self.g2, [self.er1])
        except:
            pass
class ServiceClient(object):
    '''
    This class provides access to the ehb-client api
    '''
    SERVICE_CLIENT_SETTINGS = settings.SERVICE_CLIENT_SETTINGS
    host = SERVICE_CLIENT_SETTINGS['HOST']
    root_path = SERVICE_CLIENT_SETTINGS['ROOT_PATH']
    self_root_path = SERVICE_CLIENT_SETTINGS['SELF_ROOT_PATH']
    isSecure = SERVICE_CLIENT_SETTINGS['ISSECURE']
    APP_URL = SERVICE_CLIENT_SETTINGS['APP_URL']
    api_key = SERVICE_CLIENT_SETTINGS['API_KEY']
    ext_rec_client = ExternalRecordRequestHandler(host, root_path, isSecure,
                                                  api_key)
    ext_rec_rel_client = ExternalRecordRelationRequestHandler(
        host, root_path, isSecure, api_key)
    ext_rec_label_client = ExternalRecordLabelRequestHandler(
        host, root_path, isSecure, api_key)
    ext_sys_client = ExternalSystemRequestHandler(host, root_path, isSecure,
                                                  api_key)
    subj_client = SubjectRequestHandler(host, root_path, isSecure, api_key)
    org_client = OrganizationRequestHandler(host, root_path, isSecure, api_key)
    group_client = GroupRequestHandler(host, root_path, isSecure, api_key)
    SUBJECT = 0
    EXTERNAL_SYSTEM = 1
    EXTERNAL_RECORD = 2
    ORGANIZATION = 3
    GROUP = 4
    EXTERNAL_RECORD_LABEL = 5
    EXTERNAL_RECORD_RELATION = 6
    req_handlers = {
        EXTERNAL_SYSTEM: ext_sys_client,
        EXTERNAL_RECORD: ext_rec_client,
        EXTERNAL_RECORD_LABEL: ext_rec_label_client,
        EXTERNAL_RECORD_RELATION: ext_rec_rel_client,
        SUBJECT: subj_client,
        ORGANIZATION: org_client,
        GROUP: group_client
    }

    @staticmethod
    def get_rh_for(**kwargs):
        '''
        Expected kwargs are:
        * record: value of an appropriate ehb_client IdentityBase instance
        * record_type:  value from one of ServiceClient predefined int values
        '''
        rec_type = kwargs.pop('record_type', -1)
        record = kwargs.pop('record', None)
        if rec_type in ServiceClient.req_handlers:
            return ServiceClient.req_handlers.get(rec_type)
        elif record:
            for c in type(record).__bases__:
                if c.__name__ == 'Subject':
                    return ServiceClient.subj_client
                elif c.__name__ == 'ExternalSystem':
                    return ServiceClient.ext_sys_client
                elif c.__name__ == 'ExternalRecord':
                    return ServiceClient.ext_rec_client
                elif c.__name__ == 'ExternalRecordLabel':
                    return ServiceClient.ext_rec_label_client
                elif c.__name__ == 'ExternalRecordRelation':
                    return ServiceClient.ext_rec_rel_client
                elif c.__name__ == 'Organization':
                    return ServiceClient.org_client
                elif c.__name__ == 'Group':
                    return ServiceClient.group_client
        else:
            return None

    @staticmethod
    def create(record, f_success, f_errors, f_except=None):
        rh = ServiceClient.get_rh_for(record)
        if rh:
            try:
                r = rh.create(record)[0]
                s = r.get('success')
                if s:
                    f_success(r.get(record.identityLabel))
                else:
                    f_errors(r.get('errors'))
            except Exception as e:
                if f_except is None:
                    raise e
                else:
                    f_except(e)
        else:
            msg = 'No request handler found for record of type: ' + str(
                type(record))
            raise Exception(msg)
示例#3
0
class ehbTestClass(TestCase):
    '''
    The ehbTestClass is a base class for all ehb-client tests. Its main purpose
    is to create test objects for our different request handlers to manipulate,
    and to tear down those objects when the tests are finished.

    In the rare case that the setUp of a test class fails you may be left with
    artifacts in the eHB. Make sure to delete any "test" organizations left over
    and try running the tests again.
    '''
    def setUp(self):
        # Initialize Request Handlers
        self.er_rh = ExternalRecordRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.es_rh = ExternalSystemRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.s_rh = SubjectRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.g_rh = GroupRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)
        self.o_rh = OrganizationRequestHandler(
            RequestResources.host,
            RequestResources.root_path,
            RequestResources.isSecure,
            RequestResources.api_key)

        self.es_name1 = "testESNameABCD"
        self.es_name2 = "testESName1234"
        self.org_subj_id_1 = "testmrn0001"
        self.org_subj_id_2 = "testmrn0002"
        self.org_subj_id_3 = "testmrn002"
        self.recid1 = "testrecid0001"
        self.recid2 = "testrecid0002"
        self.recid3 = "testrecid0003"
        self.recid4 = "testrecid0004"
        self.path1 = "testpath1"
        self.path2 = "testpath2"
        self.path3 = 'testpath3'
        self.org_name_1 = "testOrg001"
        self.org_name_2 = "testOrg002"
        self.subj_id_label_1 = 'org_1_id'
        try:
            # Create the Organizations
            self.o1 = Organization(name=self.org_name_1,
                                   subject_id_label=self.subj_id_label_1)
            self.o2 = Organization(name=self.org_name_2,
                                   subject_id_label=self.subj_id_label_1)
            r = self.o_rh.create(self.o1, self.o2)

            # Create Subjects
            dob = datetime.date.today()
            self.s1 = Subject(first_name='FIRST_ONE', last_name="LAST_ONE",
                              organization_id=self.o1.id,
                              organization_subject_id=self.org_subj_id_1, dob=dob)
            self.s2 = Subject(first_name='FIRST_TWO', last_name="LAST_TWO",
                              organization_id=self.o1.id,
                              organization_subject_id=self.org_subj_id_2, dob=dob)
            self.s3 = Subject(first_name='FIRST_THREE', last_name="LAST_THREE",
                              organization_id=self.o2.id,
                              organization_subject_id=self.org_subj_id_3, dob=dob)
            r = self.s_rh.create(self.s1, self.s2, self.s3)

            # Create External Systems
            self.es1 = ExternalSystem(name=self.es_name1, url="http://test.com/",
                                      description='A test system')
            self.es2 = ExternalSystem(name=self.es_name2, url="http://testTwo.com/",
                                      description='Another test system')
            r = self.es_rh.create(self.es1, self.es2)

            # Create External record
            self.er1 = ExternalRecord(record_id=self.recid1, subject_id=self.s1.id,
                                      external_system_id=self.es1.id, path=self.path1,
                                      label_id=1)
            self.er2 = ExternalRecord(record_id=self.recid2, subject_id=self.s1.id,
                                      external_system_id=self.es1.id, path=self.path2,
                                      label_id=1)
            r = self.er_rh.create(self.er1, self.er2)
            self.er1 = r[0]['external_record']
            self.er2 = r[1]['external_record']
            # # Create External record link
            r = self.er_rh.link(self.er1, self.er2, 1)
            # Create test groups
            # Subject Group
            self.g1 = Group(name='testgroup1', is_locking=False,
                            client_key='ck', description='A test group')
            # ExternalRecord Group
            self.g2 = Group(name='exrecgroup', is_locking=False,
                            client_key='ck', description='An external record group')
            r = self.g_rh.create(self.g1, self.g2)

            # Add subject to test group
            r = self.g_rh.add_subjects(self.g1, [self.s1])

            # Add external record to test group
            r = self.g_rh.add_records(self.g2, [self.er1])
        except:
            pass

    def tearDown(self):
        try:
            self.es_rh.delete(name=self.es_name1)
        except PageNotFound:
            pass
        try:
            self.es_rh.delete(name=self.es_name2)
        except PageNotFound:
            pass
        try:
            self.es_rh.delete(name='testESNameCreate')
        except PageNotFound:
            pass
        try:
            o1 = self.o_rh.get(name=self.org_name_1)
            self.s_rh.delete(organization_id=o1.id,
                             organization_subject_id=self.org_subj_id_1)
            self.s_rh.delete(organization_id=o1.id,
                             organization_subject_id=self.org_subj_id_2)
        except PageNotFound:
            pass

        try:
            o2 = self.o_rh.get(name=self.org_name_2)
            self.s_rh.delete(organization_id=o2.id,
                             organization_subject_id=self.org_subj_id_3)
        except PageNotFound:
            pass

        try:
            self.er_rh.delete(external_system_name=self.es_name1)
        except PageNotFound:
            pass
        try:
            self.er_rh.delete(external_system_name=self.es_name2)
        except PageNotFound:
            pass

        try:
            self.o_rh.delete(name=self.org_name_1)
        except PageNotFound:
            pass
        try:
            self.o_rh.delete(name=self.org_name_2)
        except PageNotFound:
            pass
        try:
            self.o_rh.delete(name='testorg1')
        except PageNotFound:
            pass
        try:
            self.o_rh.delete(name='testorg2')
        except PageNotFound:
            pass
        try:
            self.o_rh.delete(name='testorg99')
        except PageNotFound:
            pass
        try:
            self.er_rh.create(self.er1)
        except PageNotFound:
            pass

        try:
            self.g_rh.delete(name='testgroup1', client_key='ck')
        except PageNotFound:
            pass
        try:
            self.g_rh.delete(name='exrecgroup', client_key='ck')
        except PageNotFound:
            pass
        try:
            self.g_rh.delete(name='testgroup2', client_key='ck')
        except PageNotFound:
            pass
        try:
            self.g_rh.delete(name='testgroup3', client_key='ck')
        except PageNotFound:
            pass
        try:
            self.g_rh.delete(name='testgroup1xyz', client_key='ck')
        except PageNotFound:
            pass

    def createAndCheck(self, rh, *records):
        r = rh.create(*records)
        b = True

        for i in range(r.__len__()):
            b = b and r[i].get('success')

        self.assertTrue(b, 'External record create failed')
示例#4
0
class ServiceClient(object):
    """This class provides access to the ehb-client api.

    The various request handlers are initialized using auth settings. They
    can be accessed using the `get_rh_for` method with either the record_type
    constant or a record instance itself. The `create` method tries to create
    a passed record in the EHB, using the passed functions on success, error,
    and exception.
    """

    SERVICE_CLIENT_SETTINGS = settings.SERVICE_CLIENT_SETTINGS
    host = SERVICE_CLIENT_SETTINGS['HOST']
    # This is for calls to the eHB
    root_path = SERVICE_CLIENT_SETTINGS['ROOT_PATH']
    # This is needed for react UI to connect to the BRP dataentry Backend
    self_root_path = SERVICE_CLIENT_SETTINGS['SELF_ROOT_PATH']
    isSecure = SERVICE_CLIENT_SETTINGS['ISSECURE']
    APP_URL = SERVICE_CLIENT_SETTINGS['APP_URL']
    api_key = SERVICE_CLIENT_SETTINGS['API_KEY']
    client_key = settings.PROTOCOL_PROPS['CLIENT_KEY']

    ext_rec_client = ExternalRecordRequestHandler(host, root_path, isSecure,
                                                  api_key)

    ext_rec_rel_client = ExternalRecordRelationRequestHandler(
        host, root_path, isSecure, api_key)

    ext_rec_label_client = ExternalRecordLabelRequestHandler(
        host, root_path, isSecure, api_key)

    ext_sys_client = ExternalSystemRequestHandler(host, root_path, isSecure,
                                                  api_key)

    subj_client = SubjectRequestHandler(host, root_path, isSecure, api_key)
    org_client = OrganizationRequestHandler(host, root_path, isSecure, api_key)
    group_client = GroupRequestHandler(host, root_path, isSecure, api_key)
    relationship_client = SubjFamRelationshipRequestHandeler(
        host, root_path, isSecure, api_key)
    relationship_type_client = RelationshipTypeRequestHandler(
        host, root_path, isSecure, api_key)

    SUBJECT = 0
    EXTERNAL_SYSTEM = 1
    EXTERNAL_RECORD = 2
    ORGANIZATION = 3
    GROUP = 4
    EXTERNAL_RECORD_LABEL = 5
    EXTERNAL_RECORD_RELATION = 6
    RELATIONSHIP = 7
    RELATIONSHIP_TYPE = 8

    req_handlers = {
        EXTERNAL_SYSTEM: ext_sys_client,
        EXTERNAL_RECORD: ext_rec_client,
        EXTERNAL_RECORD_LABEL: ext_rec_label_client,
        EXTERNAL_RECORD_RELATION: ext_rec_rel_client,
        SUBJECT: subj_client,
        ORGANIZATION: org_client,
        GROUP: group_client,
        RELATIONSHIP: relationship_client,
        RELATIONSHIP_TYPE: relationship_type_client
    }

    @staticmethod
    def get_rh_for(**kwargs):
        """Get the request handler for the given record instance or constant.

        Args:
            record: value of an appropriate ehb_client IdentityBase instance
            record_type: value from one of ServiceClient predefined int values

        Returns:
            An auth-configured instance of the appropriate EHB client request
            handler or None if the appropriate client can't be found.
        """

        rec_type = kwargs.pop('record_type', -1)
        record = kwargs.pop('record', None)

        if rec_type in ServiceClient.req_handlers:
            return ServiceClient.req_handlers.get(rec_type)

        elif record:

            # TODO: Could the `isinstance()` builtin function work here?
            for c in type(record).__bases__:

                if c.__name__ == 'Subject':
                    return ServiceClient.subj_client
                elif c.__name__ == 'ExternalSystem':
                    return ServiceClient.ext_sys_client
                elif c.__name__ == 'ExternalRecord':
                    return ServiceClient.ext_rec_client
                elif c.__name__ == 'ExternalRecordLabel':
                    return ServiceClient.ext_rec_label_client
                elif c.__name__ == 'ExternalRecordRelation':
                    return ServiceClient.ext_rec_rel_client
                elif c.__name__ == 'Organization':
                    return ServiceClient.org_client
                elif c.__name__ == 'Group':
                    return ServiceClient.group_client
                elif c.__name__ == 'Relationship':
                    return ServiceClient.relationship_client
                elif c.__name__ == 'Relationship_type':
                    return ServiceClient.relationship_type_client

        else:
            return None

    @staticmethod
    def create(record, f_success, f_errors, f_except=None):
        """Create a record in the EHB using the provided callbacks."""

        rh = ServiceClient.get_rh_for(record)

        if rh:
            try:

                r = rh.create(record)[0]
                s = r.get('success')

                if s:
                    f_success(r.get(record.identityLabel))

                else:
                    f_errors(r.get('errors'))

            except Exception as e:

                if f_except is None:
                    raise e

                else:
                    f_except(e)

        else:

            msg = ('No request handler found for record of type:'
                   ' {0}').format(str(type(record)))

            raise Exception(msg)

    @staticmethod
    def ehb_api(url, request_type, payload=None):
        url = ServiceClient.APP_URL + url
        headers = {
            'Content-Type': "application/json",
            'Api-token': ServiceClient.api_key,
            'GROUP-CLIENT-KEY': ServiceClient.client_key['key'],
            'cache-control': "no-cache",
            'Accept': "application/json"
        }

        return requests.request(request_type,
                                url,
                                data=json.dumps(payload),
                                headers=headers)

    @staticmethod
    def user_audit(payload):
        url = ServiceClient.APP_URL + "/api/auditlog/"
        headers = {
            'Content-Type': "application/json",
            'Api-token': ServiceClient.api_key,
            'cache-control': "no-cache"
        }

        response = requests.request("POST",
                                    url,
                                    data=json.dumps(payload),
                                    headers=headers)