示例#1
0
    def setUp(self):
        # Start container
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        # Now create client to bank service
        self.resource_registry_service = ResourceRegistryServiceClient()
示例#2
0
    def is_service_available(self, service_name, local_rr_only=False):

        try:
            service_resource = None
            from pyon.core.bootstrap import container_instance
            from interface.objects import ServiceStateEnum
            # Use container direct RR connection if available, otherwise use messaging to the RR service
            if hasattr(container_instance, 'has_capability') and container_instance.has_capability('RESOURCE_REGISTRY'):
                service_resource, _ = container_instance.resource_registry.find_resources(restype='Service', name=service_name)
            elif not local_rr_only:
                from interface.services.core.iresource_registry_service import ResourceRegistryServiceClient
                rr_client = ResourceRegistryServiceClient(container_instance.node)
                service_resource, _ = rr_client.find_resources(restype='Service', name=service_name)
            else:
                log.warn("is_service_available(%s) - No RR connection" % service_name)

            # The service is available only of there is a single RR object for it and it is in one of these states:
            if service_resource and len(service_resource) > 1:
                log.warn("is_service_available(%s) - Found multiple service instances: %s", service_name, service_resource)

            # MM 2013-08-17: Added PENDING, because this means service will be there shortly
            if service_resource and service_resource[0].state in (ServiceStateEnum.READY, ServiceStateEnum.STEADY, ServiceStateEnum.PENDING):
                return True
            elif service_resource:
                log.warn("is_service_available(%s) - Service resource in invalid state", service_resource)

            return False

        except Exception as ex:
            return False
示例#3
0
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.ems = ExchangeManagementServiceClient()
        self.rr = ResourceRegistryServiceClient()

        orglist, _ = self.rr.find_resources(RT.Org)
        self.org_id = orglist[0]._id

        # we test actual exchange interaction in pyon, so it's fine to mock the broker interaction here
        self._clear_mocks()
    def setUp(self):
        # Start container
        self._start_container()
        self.container.start_rel_from_url("res/deploy/basic.yml")

        # Now create client to bank service
        self.resource_registry_service = ResourceRegistryServiceClient()
示例#5
0
    def setUp(self):
        # Start container
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.identity_management_service = IdentityManagementServiceClient()
        self.org_client = OrgManagementServiceClient()
示例#6
0
    def is_service_available(self, service_name, local_rr_only=False):

        try:
            service_resource = None
            from pyon.core.bootstrap import container_instance
            from interface.objects import ServiceStateEnum
            # Use container direct RR connection if available, otherwise use messaging to the RR service
            if hasattr(container_instance,
                       'has_capability') and container_instance.has_capability(
                           'RESOURCE_REGISTRY'):
                service_resource, _ = container_instance.resource_registry.find_resources(
                    restype='Service', name=service_name)
            elif not local_rr_only:
                from interface.services.core.iresource_registry_service import ResourceRegistryServiceClient
                rr_client = ResourceRegistryServiceClient(
                    container_instance.node)
                service_resource, _ = rr_client.find_resources(
                    restype='Service', name=service_name)
            else:
                log.warn("is_service_available(%s) - No RR connection" %
                         service_name)

            # The service is available only of there is a single RR object for it and it is in one of these states:
            if service_resource and len(service_resource) > 1:
                log.warn(
                    "is_service_available(%s) - Found multiple service instances: %s",
                    service_name, service_resource)

            # MM 2013-08-17: Added PENDING, because this means service will be there shortly
            if service_resource and service_resource[0].state in (
                    ServiceStateEnum.READY, ServiceStateEnum.STEADY,
                    ServiceStateEnum.PENDING):
                return True
            elif service_resource:
                log.warn(
                    "is_service_available(%s) - Service resource in invalid state",
                    service_resource)

            return False

        except Exception as ex:
            return False
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.ems = ExchangeManagementServiceClient()
        self.rr = ResourceRegistryServiceClient()

        orglist, _ = self.rr.find_resources(RT.Org)
        self.org_id = orglist[0]._id

        # we test actual exchange interaction in pyon, so it's fine to mock the broker interaction here
        self._clear_mocks()
示例#8
0
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.org_client = OrgManagementServiceClient()
        self.idm_client = IdentityManagementServiceClient()

        self.ui_server_proc = self.container.proc_manager.procs_by_name[
            "ui_server"]
        self.ui_base_url = self.ui_server_proc.base_url
        self.sg_base_url = self.ui_server_proc.gateway_base_url
示例#9
0
    def setUp(self):
        raise SkipTest("Process dispatcher currently not supported")
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.rr_cli = ResourceRegistryServiceClient()
        self.pd_cli = ProcessDispatcherServiceClient()


        self.process_definition = ProcessDefinition(name='test_process')
        self.process_definition.executable = {'module': 'ion.services.test.test_process_dispatcher',
                                              'class': 'TestProcess'}
        self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)

        self.waiter = ProcessStateWaiter()
示例#10
0
class TestResourceRegistry(IonIntegrationTestCase):
    def setUp(self):
        # Start container
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        # Now create client to bank service
        self.resource_registry_service = ResourceRegistryServiceClient()

    def test_basics(self):
        # Sequence all the tests so that we can save numerous system start and stops
        self._do_test_crud()
        self._do_test_read_mult()
        self._do_test_lifecycle()
        self._do_test_attach()
        self._do_test_association()
        self._do_test_find_resources()

    def _do_test_crud(self):
        # Some quick registry tests
        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(TypeError) as cm:
            IonObject("ActorIdentity", name="name", foo="bar")
        self.assertTrue(cm.exception.message ==
                        "__init__() got an unexpected keyword argument 'foo'")

        # TODO: This error is different than with other methods of initialization - CHANGE
        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(AttributeError) as cm:
            IonObject("ActorIdentity", {"name": "name", "foo": "bar"})
        self.assertIn("object has no attribute 'foo'", cm.exception.message)

        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(TypeError) as cm:
            IonObject("ActorIdentity", {"name": "name"}, foo="bar")
        self.assertTrue(cm.exception.message ==
                        "__init__() got an unexpected keyword argument 'foo'")

        # Instantiate an object
        obj = IonObject("ActorIdentity", name="name")

        # # Can set attributes that aren't in the object's schema
        # with self.assertRaises(AttributeError) as cm:
        #     setattr(obj, "foo", "bar")
        # self.assertTrue(cm.exception.message == "'UserInfo' object has no attribute 'foo'")

        # Cam't call update with object that hasn't been persisted
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.update(obj)
        self.assertTrue(
            cm.exception.message.startswith(
                "Object does not have required '_id' or '_rev' attribute"))

        # Persist object and read it back
        obj_id, obj_rev = self.resource_registry_service.create(obj)
        read_obj = self.resource_registry_service.read(obj_id)

        # Cannot create object with _id and _rev fields pre-set
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create(read_obj)

        # Update object
        read_obj.name = "John Doe"
        self.resource_registry_service.update(read_obj)

        # Update should fail with revision mismatch
        with self.assertRaises(Conflict) as cm:
            self.resource_registry_service.update(read_obj)

        # Re-read and update object
        read_obj = self.resource_registry_service.read(obj_id)
        self.resource_registry_service.update(read_obj)

        # Delete object
        self.resource_registry_service.delete(obj_id)

        # Make sure read, update and delete report error
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.read(obj_id)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.update(read_obj)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.delete(obj_id)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        # Owner creation tests
        user = IonObject("ActorIdentity", name='user')
        uid, _ = self.resource_registry_service.create(user)

        inst = IonObject("Resource", name='instrument')
        iid, _ = self.resource_registry_service.create(
            inst, headers={'ion-actor-id': str(uid)})

        ids, _ = self.resource_registry_service.find_objects(iid,
                                                             PRED.hasOwner,
                                                             RT.ActorIdentity,
                                                             id_only=True)
        self.assertEquals(len(ids), 1)

        assoc = self.resource_registry_service.read(ids[0])
        self.resource_registry_service.delete(iid)

        with self.assertRaises(NotFound) as ex:
            assoc = self.resource_registry_service.read(iid)

    def _do_test_read_mult(self):
        test_resource1_id, _ = self.resource_registry_service.create(
            Resource(name='test1'))
        test_resource2_id, _ = self.resource_registry_service.create(
            Resource(name='test2'))

        res_list = [test_resource1_id, test_resource2_id]

        objects = self.resource_registry_service.read_mult(res_list)

        for o in objects:
            self.assertIsInstance(o, Resource)
            self.assertTrue(o._id in res_list)

    def _do_test_lifecycle(self):
        # Lifecycle tests
        pass
        # att = IonObject("Resource", name='mine', description='desc')
        #
        # rid,rev = self.resource_registry_service.create(att)
        #
        # att1 = self.resource_registry_service.read(rid)
        # self.assertEquals(att1.name, att.name)
        # self.assertEquals(att1.lcstate, LCS.DRAFT)
        # self.assertEquals(att1.availability, AS.PRIVATE)
        #
        # new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.PLAN)
        # self.assertEquals(new_state, lcstate(LCS.PLANNED, AS.PRIVATE))
        #
        # att2 = self.resource_registry_service.read(rid)
        # self.assertEquals(att2.lcstate, LCS.PLANNED)
        # self.assertEquals(att2.availability, AS.PRIVATE)
        #
        # with self.assertRaises(BadRequest) as cm:
        #     self.resource_registry_service.execute_lifecycle_transition(rid, LCE.UNANNOUNCE)
        # self.assertIn("has no transition for event unannounce", cm.exception.message)
        #
        # new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.DEVELOP)
        # self.assertEquals(new_state, lcstate(LCS.DEVELOPED, AS.PRIVATE))
        #
        # with self.assertRaises(BadRequest):
        #     self.resource_registry_service.execute_lifecycle_transition(
        #             resource_id=rid, transition_event='NONE##')
        #
        # self.resource_registry_service.set_lifecycle_state(rid, lcstate(LCS.INTEGRATED, AS.PRIVATE))
        # att1 = self.resource_registry_service.read(rid)
        # self.assertEquals(att1.lcstate, LCS.INTEGRATED)
        # self.assertEquals(att1.availability, AS.PRIVATE)

    def _do_test_attach(self):
        binary = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x03\x00\x00\x00(-\x0fS\x00\x00\x00\x03sBIT\x08\x08\x08\xdb\xe1O\xe0\x00\x00\x00~PLTEf3\x00\xfc\xf7\xe0\xee\xcc\x00\xd3\xa0\x00\xcc\x99\x00\xec\xcdc\x9fl\x00\xdd\xb2\x00\xff\xff\xff|I\x00\xf9\xdb\x00\xdd\xb5\x19\xd9\xad\x10\xb6\x83\x00\xf8\xd6\x00\xf2\xc5\x00\xd8\xab\x00n;\x00\xff\xcc\x00\xd6\xa4\t\xeb\xb8\x00\x83Q\x00\xadz\x00\xff\xde\x00\xff\xd6\x00\xd6\xa3\x00\xdf\xaf\x00\xde\xad\x10\xbc\x8e\x00\xec\xbe\x00\xec\xd4d\xff\xe3\x00tA\x00\xf6\xc4\x00\xf6\xce\x00\xa5u\x00\xde\xa5\x00\xf7\xbd\x00\xd6\xad\x08\xdd\xaf\x19\x8cR\x00\xea\xb7\x00\xee\xe9\xdf\xc5\x00\x00\x00\tpHYs\x00\x00\n\xf0\x00\x00\n\xf0\x01B\xac4\x98\x00\x00\x00\x1ctEXtSoftware\x00Adobe Fireworks CS4\x06\xb2\xd3\xa0\x00\x00\x00\x15tEXtCreation Time\x0029/4/09Oq\xfdE\x00\x00\x00\xadIDAT\x18\x95M\x8f\x8d\x0e\x820\x0c\x84;ZdC~f\x07\xb2\x11D\x86\x89\xe8\xfb\xbf\xa0+h\xe2\x97\\\xd2^\x93\xb6\x07:1\x9f)q\x9e\xa5\x06\xad\xd5\x13\x8b\xac,\xb3\x02\x9d\x12C\xa1-\xef;M\x08*\x19\xce\x0e?\x1a\xeb4\xcc\xd4\x0c\x831\x87V\xca\xa1\x1a\xd3\x08@\xe4\xbd\xb7\x15P;\xc8\xd4{\x91\xbf\x11\x90\xffg\xdd\x8di\xfa\xb6\x0bs2Z\xff\xe8yg2\xdc\x11T\x96\xc7\x05\xa5\xef\x96+\xa7\xa59E\xae\xe1\x84cm^1\xa6\xb3\xda\x85\xc8\xd8/\x17se\x0eN^'\x8c\xc7\x8e\x88\xa8\xf6p\x8e\xc2;\xc6.\xd0\x11.\x91o\x12\x7f\xcb\xa5\xfe\x00\x89]\x10:\xf5\x00\x0e\xbf\x00\x00\x00\x00IEND\xaeB`\x82"

        # Owner creation tests
        instrument = IonObject("Resource", name='instrument')
        iid, _ = self.resource_registry_service.create(instrument)

        att = Attachment(content=binary, attachment_type=AttachmentType.BLOB)
        aid1 = self.resource_registry_service.create_attachment(iid, att)

        att1 = self.resource_registry_service.read_attachment(
            aid1, include_content=True)
        self.assertEquals(binary, att1.content)

        import base64
        att = Attachment(content=base64.encodestring(binary),
                         attachment_type=AttachmentType.ASCII)
        aid2 = self.resource_registry_service.create_attachment(iid, att)

        att1 = self.resource_registry_service.read_attachment(
            aid2, include_content=True)
        self.assertEquals(binary, base64.decodestring(att1.content))

        att_ids = self.resource_registry_service.find_attachments(iid,
                                                                  id_only=True)
        self.assertEquals(att_ids, [aid1, aid2])

        att_ids = self.resource_registry_service.find_attachments(
            iid, id_only=True, descending=True)
        self.assertEquals(att_ids, [aid2, aid1])

        att_ids = self.resource_registry_service.find_attachments(
            iid, id_only=True, descending=True, limit=1)
        self.assertEquals(att_ids, [aid2])

        atts = self.resource_registry_service.find_attachments(
            iid, id_only=False, include_content=True, limit=1)
        self.assertEquals(atts[0].content, binary)

        self.resource_registry_service.delete_attachment(aid1)

        att_ids = self.resource_registry_service.find_attachments(iid,
                                                                  id_only=True)
        self.assertEquals(att_ids, [aid2])

        self.resource_registry_service.delete_attachment(aid2)

        att_ids = self.resource_registry_service.find_attachments(iid,
                                                                  id_only=True)
        self.assertEquals(att_ids, [])

    def _do_test_association(self):
        # Instantiate ActorIdentity object
        actor_identity_obj = IonObject("ActorIdentity", name="name")
        actor_identity_obj_id, actor_identity_obj_rev = self.resource_registry_service.create(
            actor_identity_obj)
        read_actor_identity_obj = self.resource_registry_service.read(
            actor_identity_obj_id)

        # Instantiate UserInfo object
        user_info_obj = IonObject("Commitment", name="name")
        user_info_obj_id, user_info_obj_rev = self.resource_registry_service.create(
            user_info_obj)
        read_user_info_obj = self.resource_registry_service.read(
            user_info_obj_id)

        # Test create failures
        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj_id, PRED.bogus, user_info_obj_id)
        self.assertTrue(cm.exception.message == "bogus")

        # Predicate not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj_id, None, user_info_obj_id)
        self.assertTrue(
            cm.exception.message == "Association must have all elements set")

        # Subject id or object not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                None, PRED.hasResource, user_info_obj_id)
        self.assertTrue(
            cm.exception.message == "Association must have all elements set")

        # Object id or object not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj_id, PRED.hasResource, None)
        self.assertTrue(
            cm.exception.message == "Association must have all elements set")

        # Bad subject id
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.create_association(
                "bogus", PRED.hasResource, user_info_obj_id)
        self.assertTrue(
            cm.exception.message == "Object with id bogus does not exist.")

        # Bad object id
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj_id, PRED.hasResource, "bogus")
        self.assertTrue(
            cm.exception.message == "Object with id bogus does not exist.")

        # _id missing from subject
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj, PRED.hasResource, user_info_obj_id)
        self.assertTrue(cm.exception.message.startswith("Subject id"))

        # _id missing from object
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                actor_identity_obj_id, PRED.hasResource, user_info_obj)
        self.assertTrue(cm.exception.message.startswith("Object id"))

        # Wrong subject type
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                user_info_obj_id, PRED.hasMember, actor_identity_obj_id)
        self.assertEquals(
            cm.exception.message,
            "Illegal subject type Commitment for predicate hasMember")

        # Wrong object type
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(
                user_info_obj_id, PRED.hasOwner, user_info_obj_id)
        self.assertEquals(
            cm.exception.message,
            "Illegal object type Commitment for predicate hasOwner")

        # Create two different association types between the same subject and predicate
        assoc_id1, assoc_rev1 = self.resource_registry_service.create_association(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id)

        # Read object, subject
        res_obj1 = self.resource_registry_service.read_object(
            actor_identity_obj_id, PRED.hasCommitment, RT.Commitment)
        self.assertEquals(res_obj1._id, user_info_obj_id)
        res_obj1 = self.resource_registry_service.read_object(
            actor_identity_obj_id,
            PRED.hasCommitment,
            RT.Commitment,
            id_only=True)
        self.assertEquals(res_obj1, user_info_obj_id)
        res_obj2 = self.resource_registry_service.read_subject(
            RT.ActorIdentity, PRED.hasCommitment, user_info_obj_id)
        self.assertEquals(res_obj2._id, actor_identity_obj_id)
        res_obj2 = self.resource_registry_service.read_subject(
            RT.ActorIdentity,
            PRED.hasCommitment,
            user_info_obj_id,
            id_only=True)
        self.assertEquals(res_obj2, actor_identity_obj_id)

        # Search for associations (good cases)
        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id)
        ret2 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment)
        ret3 = self.resource_registry_service.find_associations(
            None, PRED.hasCommitment)
        self.assertTrue(len(ret1) == len(ret2) == len(ret3))
        self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)

        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id, None,
            False)
        ret2 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, id_only=False)
        ret3 = self.resource_registry_service.find_associations(
            predicate=PRED.hasCommitment, id_only=False)
        self.assertTrue(ret1 == ret2 == ret3)

        # Search for associations (good cases)
        ret1 = self.resource_registry_service.find_associations(
            read_actor_identity_obj, PRED.hasCommitment, read_user_info_obj)
        ret2 = self.resource_registry_service.find_associations(
            read_actor_identity_obj, PRED.hasCommitment)
        ret3 = self.resource_registry_service.find_associations(
            None, PRED.hasCommitment)
        self.assertTrue(len(ret1) == len(ret2) == len(ret3))
        self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)

        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, read_user_info_obj,
            None, True)
        ret2 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, id_only=True)
        ret3 = self.resource_registry_service.find_associations(
            predicate=PRED.hasCommitment, id_only=True)
        self.assertTrue(ret1 == ret2 == ret3)

        # Search for associations (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_associations(None, None, None)
        self.assertIn("Illegal parameters", cm.exception.message)

        # Find subjects (good cases)
        subj_ret1 = self.resource_registry_service.find_subjects(
            RT.ActorIdentity, PRED.hasCommitment, user_info_obj_id, True)
        subj_ret2 = self.resource_registry_service.find_subjects(
            RT.ActorIdentity, PRED.hasCommitment, read_user_info_obj, True)
        self.assertTrue(len(subj_ret1) == len(subj_ret2))
        self.assertTrue(subj_ret1[0] == subj_ret2[0])
        self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)

        subj_ret3 = self.resource_registry_service.find_subjects(
            None, PRED.hasCommitment, user_info_obj_id, True)
        subj_ret4 = self.resource_registry_service.find_subjects(
            None, None, read_user_info_obj, True)
        self.assertTrue(len(subj_ret3) == len(subj_ret4))
        self.assertTrue(subj_ret3[0] == subj_ret4[0])
        self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)

        subj_ret5 = self.resource_registry_service.find_subjects(
            None, PRED.hasCommitment, user_info_obj_id, False)
        subj_ret6 = self.resource_registry_service.find_subjects(
            None, None, read_user_info_obj, False)
        self.assertTrue(len(subj_ret5) == len(subj_ret6))
        self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
        self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)

        # Find subjects (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_subjects(None, None, None)
        self.assertTrue(cm.exception.message == "Must provide object")

        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.find_subjects(
                RT.Commitment, PRED.bogus, user_info_obj_id, True)
        self.assertIn("bogus", cm.exception.message)

        ret = self.resource_registry_service.find_subjects(
            RT.Commitment, PRED.hasCommitment, user_info_obj_id, True)
        self.assertTrue(len(ret[0]) == 0)

        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_subjects(
                RT.Commitment, PRED.hasCommitment, user_info_obj, True)
        self.assertTrue(
            cm.exception.message == "Object id not available in object")

        # Find objects (good cases)
        subj_ret1 = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, RT.Commitment, True)
        subj_ret2 = self.resource_registry_service.find_objects(
            read_actor_identity_obj, PRED.hasCommitment, RT.Commitment, True)
        self.assertTrue(len(subj_ret1) == len(subj_ret2))
        self.assertTrue(subj_ret1[0] == subj_ret2[0])
        self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)

        subj_ret3 = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, None, True)
        subj_ret4 = self.resource_registry_service.find_objects(
            actor_identity_obj_id, None, None, True)
        self.assertTrue(len(subj_ret3) == len(subj_ret4))
        self.assertTrue(subj_ret3[0] == subj_ret4[0])
        self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)

        subj_ret5 = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, None, False)
        subj_ret6 = self.resource_registry_service.find_objects(
            read_actor_identity_obj, None, None, False)
        self.assertTrue(len(subj_ret5) == len(subj_ret6))
        self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
        self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)

        # Find objects (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_objects(None, None, None)
        self.assertTrue(cm.exception.message == "Must provide subject")

        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.find_objects(
                actor_identity_obj_id, PRED.bogus, RT.UserCredentials, True)
        self.assertTrue(cm.exception.message == "bogus")

        ret = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, RT.ActorIdentity, True)
        self.assertTrue(len(ret[0]) == 0)

        ret = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, RT.UserRole, True)
        self.assertTrue(len(ret[0]) == 0)

        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_objects(
                actor_identity_obj, PRED.hasCommitment, RT.Commitment, True)
        self.assertTrue(
            cm.exception.message == "Object id not available in subject")

        # Get association (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.get_association(None, None, None)
        self.assertIn("Illegal parameters", cm.exception.message)

        assoc = self.resource_registry_service.get_association(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id)
        self.assertTrue(assoc._id == assoc_id1)

        # Delete (bad cases)
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.delete_association("bogus")
        self.assertTrue(
            cm.exception.message == "Object with id bogus does not exist.")

        # Delete other association
        self.resource_registry_service.delete_association(assoc_id1)

        # Delete resources
        self.resource_registry_service.delete(actor_identity_obj_id)
        self.resource_registry_service.delete(user_info_obj_id)

    def _do_test_find_resources(self):
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_resources(
                RT.ActorIdentity, LCS.DRAFT, "name", False)
        self.assertTrue(
            cm.exception.message == "find by name does not support lcstate")

        ret = self.resource_registry_service.find_resources(
            RT.ActorIdentity, None, "name", False)
        self.assertEquals(len(ret[0]), 0)

        # Instantiate an object
        obj = IonObject("ProcessDefinition", name="name")

        # Persist object and read it back
        obj_id, obj_rev = self.resource_registry_service.create(obj)
        read_obj = self.resource_registry_service.read(obj_id)

        ret = self.resource_registry_service.find_resources(
            RT.ProcessDefinition, None, "name", False)
        self.assertEquals(len(ret[0]), 1)
        self.assertEquals(ret[0][0]._id, read_obj._id)

        ret = self.resource_registry_service.find_resources(
            RT.ProcessDefinition, LCS.DEPLOYED, None, False)
        self.assertEquals(len(ret[0]), 1)
        self.assertEquals(ret[0][0]._id, read_obj._id)
class TestExchangeManagementServiceInt(IonIntegrationTestCase):

    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.ems = ExchangeManagementServiceClient()
        self.rr = ResourceRegistryServiceClient()

        orglist, _ = self.rr.find_resources(RT.Org)
        self.org_id = orglist[0]._id

        # we test actual exchange interaction in pyon, so it's fine to mock the broker interaction here
        self._clear_mocks()

    def _clear_mocks(self):
        self.container.ex_manager.create_xs = Mock()
        self.container.ex_manager.delete_xs = Mock()
        self.container.ex_manager.create_xp = Mock()
        self.container.ex_manager.delete_xp = Mock()
        self.container.ex_manager._create_xn = Mock()
        self.container.ex_manager.delete_xn = Mock()

    def test_exchange_management(self):
        # TEST: XS management
        self._do_test_xs()

        # TEST: XP management
        self._do_test_xp()

        # TEST: XN management
        self._do_test_xn()

    def _do_test_xs(self):
        exchange_space = ExchangeSpace(name="bobo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        # should have an exchange declared on the broker
        self.container.ex_manager.create_xs.assert_called_once_with('bobo')

        # should be able to pull from RR an exchange space
        es2 = self.rr.read(esid)
        self.assertEquals(exchange_space.name, es2.name)

        es3 = self.ems.read_exchange_space(esid)
        self.assertEquals(es3.name, es2.name)

        # should have an assoc to an org
        orglist, _ = self.rr.find_subjects(RT.Org, PRED.hasExchangeSpace, esid, id_only=True)
        self.assertEquals(len(orglist), 1)
        self.assertEquals(orglist[0], self.org_id)

        self.container.ex_manager.create_xs.return_value = "xs1"
        self.ems.delete_exchange_space(esid)

        # should no longer have that id in the RR
        with self.assertRaises(NotFound):
            self.rr.read(esid)

        # should no longer have an assoc to an org
        orglist2, _ = self.rr.find_subjects(RT.Org, PRED.hasExchangeSpace, esid, id_only=True)
        self.assertEquals(len(orglist2), 0)

        # should no longer have that exchange declared
        self.assertEquals(self.container.ex_manager.delete_xs.call_count, 1)
        self.assertEquals("xs1", self.container.ex_manager.delete_xs.call_args[0][0])

        with self.assertRaises(NotFound):
            self.ems.delete_exchange_space('123')

    def _do_test_xp(self):
        self._clear_mocks()

        # xp needs an xs first
        exchange_space = ExchangeSpace(name="doink")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_point = ExchangePoint(name="hammer")
        epid = self.ems.create_exchange_point(exchange_point, esid)

        # should be in RR
        ep2 = self.rr.read(epid)
        self.assertEquals(exchange_point.name, ep2.name)

        ep3 = self.ems.read_exchange_point(epid)
        self.assertEquals(ep3.name, ep2.name)

        # should be associated to the XS as well
        xslist, _ = self.rr.find_subjects(RT.ExchangeSpace, PRED.hasExchangePoint, epid, id_only=True)
        self.assertEquals(len(xslist), 1)
        self.assertEquals(xslist[0], esid)

        # should exist on broker (both xp and xs)
        self.assertEquals(self.container.ex_manager.create_xs.call_count, 2)
        self.assertEquals(self.container.ex_manager.create_xs.call_args[0][0], 'doink')
        # TODO: Weird mock reaction here - code bug?
        # self.assertEquals(self.container.ex_manager.create_xs.call_args[1][0], 'doink')
        self.assertIn('hammer', self.container.ex_manager.create_xp.call_args[0])

        self.ems.delete_exchange_point(epid)
        self.ems.delete_exchange_space(esid)

        # should no longer be in RR
        with self.assertRaises(NotFound):
            self.rr.read(epid)

        # should no longer be associated
        xslist2, _ = self.rr.find_subjects(RT.ExchangeSpace, PRED.hasExchangePoint, epid, id_only=True)
        self.assertEquals(len(xslist2), 0)

        # should no longer exist on broker (both xp and xs)

        # TEST: xp create then delete xs

        # xp needs an xs first
        exchange_space = ExchangeSpace(name="doink")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_point = ExchangePoint(name="hammer")
        epid = self.ems.create_exchange_point(exchange_point, esid)

        # delete xs
        self.ems.delete_exchange_space(esid)

        # should no longer have an association
        xslist2, _ = self.rr.find_subjects(RT.ExchangeSpace, PRED.hasExchangePoint, epid, id_only=True)
        self.assertEquals(len(xslist2), 0)

        self.ems.delete_exchange_point(epid)

    def _do_test_xn(self):
        self._clear_mocks()

        # xn needs an xs first
        exchange_space = ExchangeSpace(name="bozo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_name = ExchangeName(name='shoes', xn_type="process")
        enid = self.ems.declare_exchange_name(exchange_name, esid)

        # should be in RR
        en2 = self.rr.read(enid)
        self.assertEquals(exchange_name.name, en2.name)

        # should have an assoc from XN to XS
        xnlist, _ = self.rr.find_subjects(RT.ExchangeSpace, PRED.hasExchangeName, enid, id_only=True)
        self.assertEquals(len(xnlist), 1)
        self.assertEquals(xnlist[0], esid)

        # container API got called, will have declared a queue
        self.ems.undeclare_exchange_name(enid)      # canonical name = xn id in current impl

        # TEST: xn_declare_no_xs(self):
        exchange_name = ExchangeName(name="shoez", xn_type='process')
        self.assertRaises(NotFound, self.ems.declare_exchange_name, exchange_name, '11')

        # TEST: xn_undeclare_without_declare(self):
        self.assertRaises(NotFound, self.ems.undeclare_exchange_name, 'some_non_id')

        # TEST: xn_declare_then_delete_xs(self):

        # xn needs an xs first
        exchange_space = ExchangeSpace(name="bozo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_name = ExchangeName(name='shnoz', xn_type="process")
        enid = self.ems.declare_exchange_name(exchange_name, esid)

        # delete the XS
        self.ems.delete_exchange_space(esid)

        # no longer should have assoc from XS to XN
        xnlist, _ = self.rr.find_subjects(RT.ExchangeSpace, PRED.hasExchangeName, enid, id_only=True)
        self.assertEquals(len(xnlist), 0)

        self.ems.undeclare_exchange_name(enid)
示例#12
0
class ProcessDispatcherServiceIntTest(IonIntegrationTestCase):

    def setUp(self):
        raise SkipTest("Process dispatcher currently not supported")
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.rr_cli = ResourceRegistryServiceClient()
        self.pd_cli = ProcessDispatcherServiceClient()


        self.process_definition = ProcessDefinition(name='test_process')
        self.process_definition.executable = {'module': 'ion.services.test.test_process_dispatcher',
                                              'class': 'TestProcess'}
        self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)

        self.waiter = ProcessStateWaiter()

    def tearDown(self):
        self.waiter.stop()

    def test_create_schedule_cancel(self):
        process_schedule = ProcessSchedule()
        process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS

        proc_name = 'myreallygoodname'
        pid = self.pd_cli.create_process(self.process_definition_id)
        self.waiter.start(pid)

        pid2 = self.pd_cli.schedule_process(self.process_definition_id,
            process_schedule, configuration={}, process_id=pid, name=proc_name)
        self.assertEqual(pid, pid2)

        # verifies L4-CI-CEI-RQ141 and L4-CI-CEI-RQ142
        self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)

        proc = self.pd_cli.read_process(pid)
        self.assertEqual(proc.process_id, pid)
        self.assertEqual(proc.process_configuration, {})
        self.assertEqual(proc.process_state, ProcessStateEnum.RUNNING)

        # make sure process is readable directly from RR (mirrored)
        # verifies L4-CI-CEI-RQ63
        # verifies L4-CI-CEI-RQ64
        proc = self.rr_cli.read(pid)
        self.assertEqual(proc.process_id, pid)

        # now try communicating with the process to make sure it is really running
        test_client = TestClient()
        for i in range(5):
            self.assertEqual(i + 1, test_client.count(timeout=10))

        # verifies L4-CI-CEI-RQ147

        # check the process name was set in container
        got_proc_name = test_client.get_process_name(pid=pid2)
        self.assertEqual(proc_name, got_proc_name)

        # kill the process and start it again
        self.pd_cli.cancel_process(pid)

        self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)

        pid2 = self.pd_cli.schedule_process(self.process_definition_id,
            process_schedule, configuration={}, process_id=pid)
        self.assertEqual(pid, pid2)

        self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)

        for i in range(5):
            self.assertEqual(i + 1, test_client.count(timeout=10))

        # kill the process for good
        self.pd_cli.cancel_process(pid)
        self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)

    def test_schedule_with_config(self):

        process_schedule = ProcessSchedule()
        process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS

        pid = self.pd_cli.create_process(self.process_definition_id)
        self.waiter.start(pid)

        # verifies L4-CI-CEI-RQ66

        # feed in a string that the process will return -- verifies that
        # configuration actually makes it to the instantiated process
        test_response = uuid.uuid4().hex
        configuration = {"test_response": test_response}

        pid2 = self.pd_cli.schedule_process(self.process_definition_id,
            process_schedule, configuration=configuration, process_id=pid)
        self.assertEqual(pid, pid2)

        self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)

        test_client = TestClient()

        # verifies L4-CI-CEI-RQ139
        # assure that configuration block (which can contain inputs, outputs,
        # and arbitrary config) 1) makes it to the process and 2) is returned
        # in process queries

        self.assertEqual(test_client.query(), test_response)

        proc = self.pd_cli.read_process(pid)
        self.assertEqual(proc.process_id, pid)
        self.assertEqual(proc.process_configuration, configuration)

        # kill the process for good
        self.pd_cli.cancel_process(pid)
        self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)

    def test_schedule_bad_config(self):

        process_schedule = ProcessSchedule()

        # a non-JSON-serializable IonObject
        o = ProcessTarget()

        with self.assertRaises(BadRequest) as ar:
            self.pd_cli.schedule_process(self.process_definition_id,
                process_schedule, configuration={"bad": o})
        self.assertTrue(ar.exception.message.startswith("bad configuration"))

    def test_cancel_notfound(self):
        with self.assertRaises(NotFound):
            self.pd_cli.cancel_process("not-a-real-process-id")

    def test_create_invalid_definition(self):
        # create process definition missing module and class
        # verifies L4-CI-CEI-RQ137
        executable = dict(url="http://somewhere.com/something.py")
        definition = ProcessDefinition(name="test_process", executable=executable)
        with self.assertRaises(BadRequest):
            self.pd_cli.create_process_definition(definition)
示例#13
0
class TestExchangeManagementServiceInt(IonIntegrationTestCase):
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.ems = ExchangeManagementServiceClient()
        self.rr = ResourceRegistryServiceClient()

        orglist, _ = self.rr.find_resources(RT.Org)
        self.org_id = orglist[0]._id

        # we test actual exchange interaction in pyon, so it's fine to mock the broker interaction here
        self._clear_mocks()

    def _clear_mocks(self):
        self.container.ex_manager.create_xs = Mock()
        self.container.ex_manager.delete_xs = Mock()
        self.container.ex_manager.create_xp = Mock()
        self.container.ex_manager.delete_xp = Mock()
        self.container.ex_manager._create_xn = Mock()
        self.container.ex_manager.delete_xn = Mock()

    def test_exchange_management(self):
        # TEST: XS management
        self._do_test_xs()

        # TEST: XP management
        self._do_test_xp()

        # TEST: XN management
        self._do_test_xn()

    def _do_test_xs(self):
        exchange_space = ExchangeSpace(name="bobo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        # should have an exchange declared on the broker
        self.container.ex_manager.create_xs.assert_called_once_with('bobo')

        # should be able to pull from RR an exchange space
        es2 = self.rr.read(esid)
        self.assertEquals(exchange_space.name, es2.name)

        es3 = self.ems.read_exchange_space(esid)
        self.assertEquals(es3.name, es2.name)

        # should have an assoc to an org
        orglist, _ = self.rr.find_subjects(RT.Org,
                                           PRED.hasExchangeSpace,
                                           esid,
                                           id_only=True)
        self.assertEquals(len(orglist), 1)
        self.assertEquals(orglist[0], self.org_id)

        self.container.ex_manager.create_xs.return_value = "xs1"
        self.ems.delete_exchange_space(esid)

        # should no longer have that id in the RR
        with self.assertRaises(NotFound):
            self.rr.read(esid)

        # should no longer have an assoc to an org
        orglist2, _ = self.rr.find_subjects(RT.Org,
                                            PRED.hasExchangeSpace,
                                            esid,
                                            id_only=True)
        self.assertEquals(len(orglist2), 0)

        # should no longer have that exchange declared
        self.assertEquals(self.container.ex_manager.delete_xs.call_count, 1)
        self.assertEquals("xs1",
                          self.container.ex_manager.delete_xs.call_args[0][0])

        with self.assertRaises(NotFound):
            self.ems.delete_exchange_space('123')

    def _do_test_xp(self):
        self._clear_mocks()

        # xp needs an xs first
        exchange_space = ExchangeSpace(name="doink")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_point = ExchangePoint(name="hammer")
        epid = self.ems.create_exchange_point(exchange_point, esid)

        # should be in RR
        ep2 = self.rr.read(epid)
        self.assertEquals(exchange_point.name, ep2.name)

        ep3 = self.ems.read_exchange_point(epid)
        self.assertEquals(ep3.name, ep2.name)

        # should be associated to the XS as well
        xslist, _ = self.rr.find_subjects(RT.ExchangeSpace,
                                          PRED.hasExchangePoint,
                                          epid,
                                          id_only=True)
        self.assertEquals(len(xslist), 1)
        self.assertEquals(xslist[0], esid)

        # should exist on broker (both xp and xs)
        self.assertEquals(self.container.ex_manager.create_xs.call_count, 2)
        self.assertEquals(self.container.ex_manager.create_xs.call_args[0][0],
                          'doink')
        # TODO: Weird mock reaction here - code bug?
        # self.assertEquals(self.container.ex_manager.create_xs.call_args[1][0], 'doink')
        self.assertIn('hammer',
                      self.container.ex_manager.create_xp.call_args[0])

        self.ems.delete_exchange_point(epid)
        self.ems.delete_exchange_space(esid)

        # should no longer be in RR
        with self.assertRaises(NotFound):
            self.rr.read(epid)

        # should no longer be associated
        xslist2, _ = self.rr.find_subjects(RT.ExchangeSpace,
                                           PRED.hasExchangePoint,
                                           epid,
                                           id_only=True)
        self.assertEquals(len(xslist2), 0)

        # should no longer exist on broker (both xp and xs)

        # TEST: xp create then delete xs

        # xp needs an xs first
        exchange_space = ExchangeSpace(name="doink")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_point = ExchangePoint(name="hammer")
        epid = self.ems.create_exchange_point(exchange_point, esid)

        # delete xs
        self.ems.delete_exchange_space(esid)

        # should no longer have an association
        xslist2, _ = self.rr.find_subjects(RT.ExchangeSpace,
                                           PRED.hasExchangePoint,
                                           epid,
                                           id_only=True)
        self.assertEquals(len(xslist2), 0)

        self.ems.delete_exchange_point(epid)

    def _do_test_xn(self):
        self._clear_mocks()

        # xn needs an xs first
        exchange_space = ExchangeSpace(name="bozo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_name = ExchangeName(name='shoes', xn_type="process")
        enid = self.ems.declare_exchange_name(exchange_name, esid)

        # should be in RR
        en2 = self.rr.read(enid)
        self.assertEquals(exchange_name.name, en2.name)

        # should have an assoc from XN to XS
        xnlist, _ = self.rr.find_subjects(RT.ExchangeSpace,
                                          PRED.hasExchangeName,
                                          enid,
                                          id_only=True)
        self.assertEquals(len(xnlist), 1)
        self.assertEquals(xnlist[0], esid)

        # container API got called, will have declared a queue
        self.ems.undeclare_exchange_name(
            enid)  # canonical name = xn id in current impl

        # TEST: xn_declare_no_xs(self):
        exchange_name = ExchangeName(name="shoez", xn_type='process')
        self.assertRaises(NotFound, self.ems.declare_exchange_name,
                          exchange_name, '11')

        # TEST: xn_undeclare_without_declare(self):
        self.assertRaises(NotFound, self.ems.undeclare_exchange_name,
                          'some_non_id')

        # TEST: xn_declare_then_delete_xs(self):

        # xn needs an xs first
        exchange_space = ExchangeSpace(name="bozo")
        esid = self.ems.create_exchange_space(exchange_space, self.org_id)

        exchange_name = ExchangeName(name='shnoz', xn_type="process")
        enid = self.ems.declare_exchange_name(exchange_name, esid)

        # delete the XS
        self.ems.delete_exchange_space(esid)

        # no longer should have assoc from XS to XN
        xnlist, _ = self.rr.find_subjects(RT.ExchangeSpace,
                                          PRED.hasExchangeName,
                                          enid,
                                          id_only=True)
        self.assertEquals(len(xnlist), 0)

        self.ems.undeclare_exchange_name(enid)
class TestOrgManagementServiceInt(IonIntegrationTestCase):
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.org_management_service = OrgManagementServiceClient()

    def test_org_management(self):
        # CRUD
        with self.assertRaises(BadRequest) as br:
            self.org_management_service.create_org(
                Org(name="Test Facility", org_governance_name="Test Facility"))
        self.assertTrue("contains invalid characters" in br.exception.message)

        with self.assertRaises(BadRequest):
            self.org_management_service.create_org()

        org_obj = Org(name="Test Facility")
        org_id = self.org_management_service.create_org(org_obj)
        self.assertNotEqual(org_id, None)

        org = self.org_management_service.read_org(org_id)
        self.assertNotEqual(org, None)
        self.assertEqual(org.org_governance_name, 'Test_Facility')

        # Check that the roles got associated to them
        role_list = self.org_management_service.list_org_roles(org_id)
        self.assertEqual(len(role_list), 3)

        with self.assertRaises(BadRequest):
            self.org_management_service.update_org()
        org.name = 'Updated Test Facility'
        self.org_management_service.update_org(org)

        org = None
        org = self.org_management_service.read_org(org_id)
        self.assertNotEqual(org, None)
        self.assertEqual(org.name, 'Updated Test Facility')
        self.assertEqual(org.org_governance_name, 'Test_Facility')

        user_role = self.org_management_service.find_org_role_by_name(
            org_id, MODERATOR_ROLE)
        self.assertNotEqual(user_role, None)

        self.org_management_service.remove_org_role(org_id, MODERATOR_ROLE)
        with self.assertRaises(NotFound) as cm:
            user_role = self.org_management_service.find_org_role_by_name(
                org_id, MODERATOR_ROLE)
        self.assertIn("Role MODERATOR not found in Org", cm.exception.message)

        self._do_test_membership(org_id)

        self._do_test_share_and_commitments(org_id)

        self._do_test_containers()

        self._do_test_affiliation(org_id)

        # Org deletion
        with self.assertRaises(BadRequest):
            self.org_management_service.delete_org()
        self.org_management_service.delete_org(org_id)

        with self.assertRaises(NotFound) as cm:
            self.org_management_service.read_org(org_id)
        self.assertIn("does not exist", cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.org_management_service.delete_org(org_id)
        self.assertIn("does not exist", cm.exception.message)

    def _do_test_membership(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.assertTrue(self.org_management_service.is_registered(actor_id))
        self.assertFalse(
            self.org_management_service.is_enrolled(org_id, actor_id))

        self.assertFalse(self.org_management_service.is_registered(org_id))
        self.assertFalse(self.org_management_service.is_registered("FOOBAR"))
        self.assertTrue(
            self.org_management_service.is_enrolled(root_org._id, actor_id))
        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(0, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(1, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(0, len(role_objs))
        self.assertFalse(
            self.org_management_service.has_role(org_id, actor_id,
                                                 MEMBER_ROLE))

        self.org_management_service.enroll_member(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasMember,
                                                         RT.ActorIdentity,
                                                         id_only=True)
        self.assertEquals(1, len(res_ids))

        self.assertTrue(
            self.org_management_service.is_enrolled(org_id, actor_id))
        self.assertTrue(
            self.org_management_service.has_role(org_id, actor_id,
                                                 MEMBER_ROLE))
        self.assertFalse(
            self.org_management_service.has_role(org_id, actor_id,
                                                 OPERATOR_ROLE))

        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(1, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(2, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.grant_role(org_id, actor_id, OPERATOR_ROLE)

        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(2, len(role_objs))
        self.assertTrue(
            self.org_management_service.has_role(org_id, actor_id,
                                                 OPERATOR_ROLE))

        self.org_management_service.revoke_role(org_id, actor_id,
                                                OPERATOR_ROLE)
        role_objs = self.org_management_service.list_actor_roles(
            actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.cancel_member_enrollment(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasMember,
                                                         RT.ActorIdentity,
                                                         id_only=True)
        self.assertEquals(0, len(res_ids))

        self.assertFalse(
            self.org_management_service.is_enrolled(org_id, actor_id))

        self.resource_registry.delete(actor_id)

    def _do_test_share_and_commitments(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.org_management_service.enroll_member(org_id, actor_id)

        inst_obj = TestInstrument(name="Test instrument")
        inst_id, _ = self.resource_registry.create(inst_obj)

        self.assertFalse(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))

        self.org_management_service.share_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasResource,
                                                         id_only=True)
        self.assertEquals(1, len(res_ids))

        cmt_id = self.org_management_service.create_resource_commitment(
            org_id, actor_id, inst_id)

        self.assertTrue(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))
        self.assertFalse(
            self.org_management_service.is_resource_acquired_exclusively(
                resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            resource_id=inst_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            actor_id=actor_id)
        self.assertEquals(1, len(cmt_objs))

        res_objs = self.org_management_service.find_acquired_resources(
            org_id=org_id)
        self.assertEquals(1, len(res_objs))
        res_objs = self.org_management_service.find_acquired_resources(
            actor_id=actor_id)
        self.assertEquals(1, len(res_objs))

        cmt_id = self.org_management_service.create_resource_commitment(
            org_id,
            actor_id,
            inst_id,
            exclusive=True,
            expiration=get_ion_ts_millis() + 1000)

        self.assertTrue(
            self.org_management_service.is_resource_acquired(
                resource_id=inst_id))
        self.assertTrue(
            self.org_management_service.is_resource_acquired_exclusively(
                resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id,
                                                                exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            resource_id=inst_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(
            actor_id=actor_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))

        self.org_management_service.unshare_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id,
                                                         PRED.hasResource,
                                                         id_only=True)
        self.assertEquals(0, len(res_ids))

        self.resource_registry.delete(inst_id)
        self.resource_registry.delete(actor_id)

    def _do_test_containers(self):
        # Org containers
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        containers = self.org_management_service.find_org_containers(
            root_org._id)

        all_containers, _ = self.resource_registry.find_resources(
            restype=RT.CapabilityContainer, id_only=True)

        self.assertEqual(len(containers), len(all_containers))

    def _do_test_affiliation(self, org_id):
        # Org affiliation
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        self.org_management_service.affiliate_org(root_org._id, org_id)

        self.org_management_service.unaffiliate_org(root_org._id, org_id)
class TestOrgManagementServiceInt(IonIntegrationTestCase):

    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.org_management_service = OrgManagementServiceClient()

    def test_org_management(self):
        # CRUD
        with self.assertRaises(BadRequest) as br:
            self.org_management_service.create_org(Org(name="Test Facility", org_governance_name="Test Facility"))
        self.assertTrue("contains invalid characters" in br.exception.message)

        with self.assertRaises(BadRequest):
            self.org_management_service.create_org()

        org_obj = Org(name="Test Facility")
        org_id = self.org_management_service.create_org(org_obj)
        self.assertNotEqual(org_id, None)

        org = self.org_management_service.read_org(org_id)
        self.assertNotEqual(org, None)
        self.assertEqual(org.org_governance_name, 'Test_Facility')

        # Check that the roles got associated to them
        role_list = self.org_management_service.list_org_roles(org_id)
        self.assertEqual(len(role_list), 3)

        with self.assertRaises(BadRequest):
            self.org_management_service.update_org()
        org.name = 'Updated Test Facility'
        self.org_management_service.update_org(org)

        org = None
        org = self.org_management_service.read_org(org_id)
        self.assertNotEqual(org, None)
        self.assertEqual(org.name, 'Updated Test Facility')
        self.assertEqual(org.org_governance_name, 'Test_Facility')

        user_role = self.org_management_service.find_org_role_by_name(org_id, MODERATOR_ROLE)
        self.assertNotEqual(user_role, None)

        self.org_management_service.remove_org_role(org_id, MODERATOR_ROLE)
        with self.assertRaises(NotFound) as cm:
            user_role = self.org_management_service.find_org_role_by_name(org_id, MODERATOR_ROLE)
        self.assertIn("Role MODERATOR not found in Org", cm.exception.message)

        self._do_test_membership(org_id)

        self._do_test_share_and_commitments(org_id)

        self._do_test_containers()

        self._do_test_affiliation(org_id)

        # Org deletion
        with self.assertRaises(BadRequest):
            self.org_management_service.delete_org()
        self.org_management_service.delete_org(org_id)

        with self.assertRaises(NotFound) as cm:
            self.org_management_service.read_org(org_id)
        self.assertIn("does not exist", cm.exception.message)

        with self.assertRaises(NotFound) as cm:
            self.org_management_service.delete_org(org_id)
        self.assertIn("does not exist", cm.exception.message)

    def _do_test_membership(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.assertTrue(self.org_management_service.is_registered(actor_id))
        self.assertFalse(self.org_management_service.is_enrolled(org_id, actor_id))

        self.assertFalse(self.org_management_service.is_registered(org_id))
        self.assertFalse(self.org_management_service.is_registered("FOOBAR"))
        self.assertTrue(self.org_management_service.is_enrolled(root_org._id, actor_id))
        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(0, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(1, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(actor_id, org_id)
        self.assertEquals(0, len(role_objs))
        self.assertFalse(self.org_management_service.has_role(org_id, actor_id, MEMBER_ROLE))

        self.org_management_service.enroll_member(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id, PRED.hasMember, RT.ActorIdentity, id_only=True)
        self.assertEquals(1, len(res_ids))

        self.assertTrue(self.org_management_service.is_enrolled(org_id, actor_id))
        self.assertTrue(self.org_management_service.has_role(org_id, actor_id, MEMBER_ROLE))
        self.assertFalse(self.org_management_service.has_role(org_id, actor_id, OPERATOR_ROLE))

        actor_objs = self.org_management_service.list_enrolled_actors(org_id)
        self.assertEquals(1, len(actor_objs))
        org_objs = self.org_management_service.list_orgs_for_actor(actor_id)
        self.assertEquals(2, len(org_objs))

        role_objs = self.org_management_service.list_actor_roles(actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.grant_role(org_id, actor_id, OPERATOR_ROLE)

        role_objs = self.org_management_service.list_actor_roles(actor_id, org_id)
        self.assertEquals(2, len(role_objs))
        self.assertTrue(self.org_management_service.has_role(org_id, actor_id, OPERATOR_ROLE))

        self.org_management_service.revoke_role(org_id, actor_id, OPERATOR_ROLE)
        role_objs = self.org_management_service.list_actor_roles(actor_id, org_id)
        self.assertEquals(1, len(role_objs))

        self.org_management_service.cancel_member_enrollment(org_id, actor_id)
        res_ids, _ = self.resource_registry.find_objects(org_id, PRED.hasMember, RT.ActorIdentity, id_only=True)
        self.assertEquals(0, len(res_ids))

        self.assertFalse(self.org_management_service.is_enrolled(org_id, actor_id))

        self.resource_registry.delete(actor_id)

    def _do_test_share_and_commitments(self, org_id):
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        actor_obj = ActorIdentity(name="Test user")
        actor_id, _ = self.resource_registry.create(actor_obj)

        self.org_management_service.enroll_member(org_id, actor_id)

        inst_obj = TestInstrument(name="Test instrument")
        inst_id, _ = self.resource_registry.create(inst_obj)

        self.assertFalse(self.org_management_service.is_resource_acquired(resource_id=inst_id))

        self.org_management_service.share_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id, PRED.hasResource, id_only=True)
        self.assertEquals(1, len(res_ids))

        cmt_id = self.org_management_service.create_resource_commitment(org_id, actor_id, inst_id)

        self.assertTrue(self.org_management_service.is_resource_acquired(resource_id=inst_id))
        self.assertFalse(self.org_management_service.is_resource_acquired_exclusively(resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(resource_id=inst_id)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(actor_id=actor_id)
        self.assertEquals(1, len(cmt_objs))

        res_objs = self.org_management_service.find_acquired_resources(org_id=org_id)
        self.assertEquals(1, len(res_objs))
        res_objs = self.org_management_service.find_acquired_resources(actor_id=actor_id)
        self.assertEquals(1, len(res_objs))

        cmt_id = self.org_management_service.create_resource_commitment(org_id, actor_id, inst_id, exclusive=True,
                                                                        expiration=get_ion_ts_millis()+1000)

        self.assertTrue(self.org_management_service.is_resource_acquired(resource_id=inst_id))
        self.assertTrue(self.org_management_service.is_resource_acquired_exclusively(resource_id=inst_id))

        cmt_objs = self.org_management_service.find_commitments(org_id=org_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(resource_id=inst_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))
        cmt_objs = self.org_management_service.find_commitments(actor_id=actor_id, exclusive=True)
        self.assertEquals(1, len(cmt_objs))

        self.org_management_service.unshare_resource(org_id, inst_id)
        res_ids, _ = self.resource_registry.find_objects(org_id, PRED.hasResource, id_only=True)
        self.assertEquals(0, len(res_ids))

        self.resource_registry.delete(inst_id)
        self.resource_registry.delete(actor_id)

    def _do_test_containers(self):
        # Org containers
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        containers = self.org_management_service.find_org_containers(root_org._id)

        all_containers, _ = self.resource_registry.find_resources(restype=RT.CapabilityContainer, id_only=True)

        self.assertEqual(len(containers), len(all_containers))

    def _do_test_affiliation(self, org_id):
        # Org affiliation
        root_org = self.org_management_service.find_org()
        self.assertNotEqual(root_org, None)

        self.org_management_service.affiliate_org(root_org._id, org_id)

        self.org_management_service.unaffiliate_org(root_org._id, org_id)
    def setUp(self):
        self._start_container()
        self.container.start_rel_from_url('res/deploy/basic.yml')

        self.resource_registry = ResourceRegistryServiceClient()
        self.org_management_service = OrgManagementServiceClient()
class TestResourceRegistry(IonIntegrationTestCase):
    def setUp(self):
        # Start container
        self._start_container()
        self.container.start_rel_from_url("res/deploy/basic.yml")

        # Now create client to bank service
        self.resource_registry_service = ResourceRegistryServiceClient()

    def test_basics(self):
        # Sequence all the tests so that we can save numerous system start and stops
        self._do_test_crud()
        self._do_test_read_mult()
        self._do_test_lifecycle()
        self._do_test_attach()
        self._do_test_association()
        self._do_test_find_resources()

    def _do_test_crud(self):
        # Some quick registry tests
        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(TypeError) as cm:
            IonObject("ActorIdentity", name="name", foo="bar")
        self.assertTrue(cm.exception.message == "__init__() got an unexpected keyword argument 'foo'")

        # TODO: This error is different than with other methods of initialization - CHANGE
        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(AttributeError) as cm:
            IonObject("ActorIdentity", {"name": "name", "foo": "bar"})
        self.assertIn("object has no attribute 'foo'", cm.exception.message)

        # Can't call new with fields that aren't defined in the object's schema
        with self.assertRaises(TypeError) as cm:
            IonObject("ActorIdentity", {"name": "name"}, foo="bar")
        self.assertTrue(cm.exception.message == "__init__() got an unexpected keyword argument 'foo'")

        # Instantiate an object
        obj = IonObject("ActorIdentity", name="name")

        # # Can set attributes that aren't in the object's schema
        # with self.assertRaises(AttributeError) as cm:
        #     setattr(obj, "foo", "bar")
        # self.assertTrue(cm.exception.message == "'UserInfo' object has no attribute 'foo'")

        # Cam't call update with object that hasn't been persisted
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.update(obj)
        self.assertTrue(cm.exception.message.startswith("Object does not have required '_id' or '_rev' attribute"))

        # Persist object and read it back
        obj_id, obj_rev = self.resource_registry_service.create(obj)
        read_obj = self.resource_registry_service.read(obj_id)

        # Cannot create object with _id and _rev fields pre-set
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create(read_obj)

        # Update object
        read_obj.name = "John Doe"
        self.resource_registry_service.update(read_obj)

        # Update should fail with revision mismatch
        with self.assertRaises(Conflict) as cm:
            self.resource_registry_service.update(read_obj)

        # Re-read and update object
        read_obj = self.resource_registry_service.read(obj_id)
        self.resource_registry_service.update(read_obj)

        # Delete object
        self.resource_registry_service.delete(obj_id)

        # Make sure read, update and delete report error
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.read(obj_id)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.update(read_obj)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.delete(obj_id)
        self.assertTrue(cm.exception.message.startswith("Object with id"))

        # Owner creation tests
        user = IonObject("ActorIdentity", name="user")
        uid, _ = self.resource_registry_service.create(user)

        inst = IonObject("Resource", name="instrument")
        iid, _ = self.resource_registry_service.create(inst, headers={"ion-actor-id": str(uid)})

        ids, _ = self.resource_registry_service.find_objects(iid, PRED.hasOwner, RT.ActorIdentity, id_only=True)
        self.assertEquals(len(ids), 1)

        assoc = self.resource_registry_service.read(ids[0])
        self.resource_registry_service.delete(iid)

        with self.assertRaises(NotFound) as ex:
            assoc = self.resource_registry_service.read(iid)

    def _do_test_read_mult(self):
        test_resource1_id, _ = self.resource_registry_service.create(Resource(name="test1"))
        test_resource2_id, _ = self.resource_registry_service.create(Resource(name="test2"))

        res_list = [test_resource1_id, test_resource2_id]

        objects = self.resource_registry_service.read_mult(res_list)

        for o in objects:
            self.assertIsInstance(o, Resource)
            self.assertTrue(o._id in res_list)

    def _do_test_lifecycle(self):
        # Lifecycle tests
        pass
        # att = IonObject("Resource", name='mine', description='desc')
        #
        # rid,rev = self.resource_registry_service.create(att)
        #
        # att1 = self.resource_registry_service.read(rid)
        # self.assertEquals(att1.name, att.name)
        # self.assertEquals(att1.lcstate, LCS.DRAFT)
        # self.assertEquals(att1.availability, AS.PRIVATE)
        #
        # new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.PLAN)
        # self.assertEquals(new_state, lcstate(LCS.PLANNED, AS.PRIVATE))
        #
        # att2 = self.resource_registry_service.read(rid)
        # self.assertEquals(att2.lcstate, LCS.PLANNED)
        # self.assertEquals(att2.availability, AS.PRIVATE)
        #
        # with self.assertRaises(BadRequest) as cm:
        #     self.resource_registry_service.execute_lifecycle_transition(rid, LCE.UNANNOUNCE)
        # self.assertIn("has no transition for event unannounce", cm.exception.message)
        #
        # new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.DEVELOP)
        # self.assertEquals(new_state, lcstate(LCS.DEVELOPED, AS.PRIVATE))
        #
        # with self.assertRaises(BadRequest):
        #     self.resource_registry_service.execute_lifecycle_transition(
        #             resource_id=rid, transition_event='NONE##')
        #
        # self.resource_registry_service.set_lifecycle_state(rid, lcstate(LCS.INTEGRATED, AS.PRIVATE))
        # att1 = self.resource_registry_service.read(rid)
        # self.assertEquals(att1.lcstate, LCS.INTEGRATED)
        # self.assertEquals(att1.availability, AS.PRIVATE)

    def _do_test_attach(self):
        binary = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x03\x00\x00\x00(-\x0fS\x00\x00\x00\x03sBIT\x08\x08\x08\xdb\xe1O\xe0\x00\x00\x00~PLTEf3\x00\xfc\xf7\xe0\xee\xcc\x00\xd3\xa0\x00\xcc\x99\x00\xec\xcdc\x9fl\x00\xdd\xb2\x00\xff\xff\xff|I\x00\xf9\xdb\x00\xdd\xb5\x19\xd9\xad\x10\xb6\x83\x00\xf8\xd6\x00\xf2\xc5\x00\xd8\xab\x00n;\x00\xff\xcc\x00\xd6\xa4\t\xeb\xb8\x00\x83Q\x00\xadz\x00\xff\xde\x00\xff\xd6\x00\xd6\xa3\x00\xdf\xaf\x00\xde\xad\x10\xbc\x8e\x00\xec\xbe\x00\xec\xd4d\xff\xe3\x00tA\x00\xf6\xc4\x00\xf6\xce\x00\xa5u\x00\xde\xa5\x00\xf7\xbd\x00\xd6\xad\x08\xdd\xaf\x19\x8cR\x00\xea\xb7\x00\xee\xe9\xdf\xc5\x00\x00\x00\tpHYs\x00\x00\n\xf0\x00\x00\n\xf0\x01B\xac4\x98\x00\x00\x00\x1ctEXtSoftware\x00Adobe Fireworks CS4\x06\xb2\xd3\xa0\x00\x00\x00\x15tEXtCreation Time\x0029/4/09Oq\xfdE\x00\x00\x00\xadIDAT\x18\x95M\x8f\x8d\x0e\x820\x0c\x84;ZdC~f\x07\xb2\x11D\x86\x89\xe8\xfb\xbf\xa0+h\xe2\x97\\\xd2^\x93\xb6\x07:1\x9f)q\x9e\xa5\x06\xad\xd5\x13\x8b\xac,\xb3\x02\x9d\x12C\xa1-\xef;M\x08*\x19\xce\x0e?\x1a\xeb4\xcc\xd4\x0c\x831\x87V\xca\xa1\x1a\xd3\x08@\xe4\xbd\xb7\x15P;\xc8\xd4{\x91\xbf\x11\x90\xffg\xdd\x8di\xfa\xb6\x0bs2Z\xff\xe8yg2\xdc\x11T\x96\xc7\x05\xa5\xef\x96+\xa7\xa59E\xae\xe1\x84cm^1\xa6\xb3\xda\x85\xc8\xd8/\x17se\x0eN^'\x8c\xc7\x8e\x88\xa8\xf6p\x8e\xc2;\xc6.\xd0\x11.\x91o\x12\x7f\xcb\xa5\xfe\x00\x89]\x10:\xf5\x00\x0e\xbf\x00\x00\x00\x00IEND\xaeB`\x82"

        # Owner creation tests
        instrument = IonObject("Resource", name="instrument")
        iid, _ = self.resource_registry_service.create(instrument)

        att = Attachment(content=binary, attachment_type=AttachmentType.BLOB)
        aid1 = self.resource_registry_service.create_attachment(iid, att)

        att1 = self.resource_registry_service.read_attachment(aid1, include_content=True)
        self.assertEquals(binary, att1.content)

        import base64

        att = Attachment(content=base64.encodestring(binary), attachment_type=AttachmentType.ASCII)
        aid2 = self.resource_registry_service.create_attachment(iid, att)

        att1 = self.resource_registry_service.read_attachment(aid2, include_content=True)
        self.assertEquals(binary, base64.decodestring(att1.content))

        att_ids = self.resource_registry_service.find_attachments(iid, id_only=True)
        self.assertEquals(att_ids, [aid1, aid2])

        att_ids = self.resource_registry_service.find_attachments(iid, id_only=True, descending=True)
        self.assertEquals(att_ids, [aid2, aid1])

        att_ids = self.resource_registry_service.find_attachments(iid, id_only=True, descending=True, limit=1)
        self.assertEquals(att_ids, [aid2])

        atts = self.resource_registry_service.find_attachments(iid, id_only=False, include_content=True, limit=1)
        self.assertEquals(atts[0].content, binary)

        self.resource_registry_service.delete_attachment(aid1)

        att_ids = self.resource_registry_service.find_attachments(iid, id_only=True)
        self.assertEquals(att_ids, [aid2])

        self.resource_registry_service.delete_attachment(aid2)

        att_ids = self.resource_registry_service.find_attachments(iid, id_only=True)
        self.assertEquals(att_ids, [])

    def _do_test_association(self):
        # Instantiate ActorIdentity object
        actor_identity_obj = IonObject("ActorIdentity", name="name")
        actor_identity_obj_id, actor_identity_obj_rev = self.resource_registry_service.create(actor_identity_obj)
        read_actor_identity_obj = self.resource_registry_service.read(actor_identity_obj_id)

        # Instantiate UserInfo object
        user_info_obj = IonObject("Commitment", name="name")
        user_info_obj_id, user_info_obj_rev = self.resource_registry_service.create(user_info_obj)
        read_user_info_obj = self.resource_registry_service.read(user_info_obj_id)

        # Test create failures
        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.create_association(actor_identity_obj_id, PRED.bogus, user_info_obj_id)
        self.assertTrue(cm.exception.message == "bogus")

        # Predicate not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(actor_identity_obj_id, None, user_info_obj_id)
        self.assertTrue(cm.exception.message == "Association must have all elements set")

        # Subject id or object not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(None, PRED.hasResource, user_info_obj_id)
        self.assertTrue(cm.exception.message == "Association must have all elements set")

        # Object id or object not provided
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(actor_identity_obj_id, PRED.hasResource, None)
        self.assertTrue(cm.exception.message == "Association must have all elements set")

        # Bad subject id
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.create_association("bogus", PRED.hasResource, user_info_obj_id)
        self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")

        # Bad object id
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.create_association(actor_identity_obj_id, PRED.hasResource, "bogus")
        self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")

        # _id missing from subject
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(actor_identity_obj, PRED.hasResource, user_info_obj_id)
        self.assertTrue(cm.exception.message.startswith("Subject id"))

        # _id missing from object
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(actor_identity_obj_id, PRED.hasResource, user_info_obj)
        self.assertTrue(cm.exception.message.startswith("Object id"))

        # Wrong subject type
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(user_info_obj_id, PRED.hasMember, actor_identity_obj_id)
        self.assertEquals(cm.exception.message, "Illegal subject type Commitment for predicate hasMember")

        # Wrong object type
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.create_association(user_info_obj_id, PRED.hasOwner, user_info_obj_id)
        self.assertEquals(cm.exception.message, "Illegal object type Commitment for predicate hasOwner")

        # Create two different association types between the same subject and predicate
        assoc_id1, assoc_rev1 = self.resource_registry_service.create_association(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id
        )

        # Read object, subject
        res_obj1 = self.resource_registry_service.read_object(actor_identity_obj_id, PRED.hasCommitment, RT.Commitment)
        self.assertEquals(res_obj1._id, user_info_obj_id)
        res_obj1 = self.resource_registry_service.read_object(
            actor_identity_obj_id, PRED.hasCommitment, RT.Commitment, id_only=True
        )
        self.assertEquals(res_obj1, user_info_obj_id)
        res_obj2 = self.resource_registry_service.read_subject(RT.ActorIdentity, PRED.hasCommitment, user_info_obj_id)
        self.assertEquals(res_obj2._id, actor_identity_obj_id)
        res_obj2 = self.resource_registry_service.read_subject(
            RT.ActorIdentity, PRED.hasCommitment, user_info_obj_id, id_only=True
        )
        self.assertEquals(res_obj2, actor_identity_obj_id)

        # Search for associations (good cases)
        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id
        )
        ret2 = self.resource_registry_service.find_associations(actor_identity_obj_id, PRED.hasCommitment)
        ret3 = self.resource_registry_service.find_associations(None, PRED.hasCommitment)
        self.assertTrue(len(ret1) == len(ret2) == len(ret3))
        self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)

        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id, None, False
        )
        ret2 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, id_only=False
        )
        ret3 = self.resource_registry_service.find_associations(predicate=PRED.hasCommitment, id_only=False)
        self.assertTrue(ret1 == ret2 == ret3)

        # Search for associations (good cases)
        ret1 = self.resource_registry_service.find_associations(
            read_actor_identity_obj, PRED.hasCommitment, read_user_info_obj
        )
        ret2 = self.resource_registry_service.find_associations(read_actor_identity_obj, PRED.hasCommitment)
        ret3 = self.resource_registry_service.find_associations(None, PRED.hasCommitment)
        self.assertTrue(len(ret1) == len(ret2) == len(ret3))
        self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)

        ret1 = self.resource_registry_service.find_associations(
            actor_identity_obj_id, PRED.hasCommitment, read_user_info_obj, None, True
        )
        ret2 = self.resource_registry_service.find_associations(actor_identity_obj_id, PRED.hasCommitment, id_only=True)
        ret3 = self.resource_registry_service.find_associations(predicate=PRED.hasCommitment, id_only=True)
        self.assertTrue(ret1 == ret2 == ret3)

        # Search for associations (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_associations(None, None, None)
        self.assertIn("Illegal parameters", cm.exception.message)

        # Find subjects (good cases)
        subj_ret1 = self.resource_registry_service.find_subjects(
            RT.ActorIdentity, PRED.hasCommitment, user_info_obj_id, True
        )
        subj_ret2 = self.resource_registry_service.find_subjects(
            RT.ActorIdentity, PRED.hasCommitment, read_user_info_obj, True
        )
        self.assertTrue(len(subj_ret1) == len(subj_ret2))
        self.assertTrue(subj_ret1[0] == subj_ret2[0])
        self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)

        subj_ret3 = self.resource_registry_service.find_subjects(None, PRED.hasCommitment, user_info_obj_id, True)
        subj_ret4 = self.resource_registry_service.find_subjects(None, None, read_user_info_obj, True)
        self.assertTrue(len(subj_ret3) == len(subj_ret4))
        self.assertTrue(subj_ret3[0] == subj_ret4[0])
        self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)

        subj_ret5 = self.resource_registry_service.find_subjects(None, PRED.hasCommitment, user_info_obj_id, False)
        subj_ret6 = self.resource_registry_service.find_subjects(None, None, read_user_info_obj, False)
        self.assertTrue(len(subj_ret5) == len(subj_ret6))
        self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
        self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)

        # Find subjects (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_subjects(None, None, None)
        self.assertTrue(cm.exception.message == "Must provide object")

        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.find_subjects(RT.Commitment, PRED.bogus, user_info_obj_id, True)
        self.assertIn("bogus", cm.exception.message)

        ret = self.resource_registry_service.find_subjects(RT.Commitment, PRED.hasCommitment, user_info_obj_id, True)
        self.assertTrue(len(ret[0]) == 0)

        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_subjects(RT.Commitment, PRED.hasCommitment, user_info_obj, True)
        self.assertTrue(cm.exception.message == "Object id not available in object")

        # Find objects (good cases)
        subj_ret1 = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, RT.Commitment, True
        )
        subj_ret2 = self.resource_registry_service.find_objects(
            read_actor_identity_obj, PRED.hasCommitment, RT.Commitment, True
        )
        self.assertTrue(len(subj_ret1) == len(subj_ret2))
        self.assertTrue(subj_ret1[0] == subj_ret2[0])
        self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)

        subj_ret3 = self.resource_registry_service.find_objects(actor_identity_obj_id, PRED.hasCommitment, None, True)
        subj_ret4 = self.resource_registry_service.find_objects(actor_identity_obj_id, None, None, True)
        self.assertTrue(len(subj_ret3) == len(subj_ret4))
        self.assertTrue(subj_ret3[0] == subj_ret4[0])
        self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)

        subj_ret5 = self.resource_registry_service.find_objects(actor_identity_obj_id, PRED.hasCommitment, None, False)
        subj_ret6 = self.resource_registry_service.find_objects(read_actor_identity_obj, None, None, False)
        self.assertTrue(len(subj_ret5) == len(subj_ret6))
        self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
        self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)

        # Find objects (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_objects(None, None, None)
        self.assertTrue(cm.exception.message == "Must provide subject")

        with self.assertRaises(AttributeError) as cm:
            self.resource_registry_service.find_objects(actor_identity_obj_id, PRED.bogus, RT.UserCredentials, True)
        self.assertTrue(cm.exception.message == "bogus")

        ret = self.resource_registry_service.find_objects(
            actor_identity_obj_id, PRED.hasCommitment, RT.ActorIdentity, True
        )
        self.assertTrue(len(ret[0]) == 0)

        ret = self.resource_registry_service.find_objects(actor_identity_obj_id, PRED.hasCommitment, RT.UserRole, True)
        self.assertTrue(len(ret[0]) == 0)

        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_objects(actor_identity_obj, PRED.hasCommitment, RT.Commitment, True)
        self.assertTrue(cm.exception.message == "Object id not available in subject")

        # Get association (bad cases)
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.get_association(None, None, None)
        self.assertIn("Illegal parameters", cm.exception.message)

        assoc = self.resource_registry_service.get_association(
            actor_identity_obj_id, PRED.hasCommitment, user_info_obj_id
        )
        self.assertTrue(assoc._id == assoc_id1)

        # Delete (bad cases)
        with self.assertRaises(NotFound) as cm:
            self.resource_registry_service.delete_association("bogus")
        self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")

        # Delete other association
        self.resource_registry_service.delete_association(assoc_id1)

        # Delete resources
        self.resource_registry_service.delete(actor_identity_obj_id)
        self.resource_registry_service.delete(user_info_obj_id)

    def _do_test_find_resources(self):
        with self.assertRaises(BadRequest) as cm:
            self.resource_registry_service.find_resources(RT.ActorIdentity, LCS.DRAFT, "name", False)
        self.assertTrue(cm.exception.message == "find by name does not support lcstate")

        ret = self.resource_registry_service.find_resources(RT.ActorIdentity, None, "name", False)
        self.assertEquals(len(ret[0]), 0)

        # Instantiate an object
        obj = IonObject("ProcessDefinition", name="name")

        # Persist object and read it back
        obj_id, obj_rev = self.resource_registry_service.create(obj)
        read_obj = self.resource_registry_service.read(obj_id)

        ret = self.resource_registry_service.find_resources(RT.ProcessDefinition, None, "name", False)
        self.assertEquals(len(ret[0]), 1)
        self.assertEquals(ret[0][0]._id, read_obj._id)

        ret = self.resource_registry_service.find_resources(RT.ProcessDefinition, LCS.DEPLOYED, None, False)
        self.assertEquals(len(ret[0]), 1)
        self.assertEquals(ret[0][0]._id, read_obj._id)