def test_read_negotiation(self):

        negotiation_handler = Negotiation(self)

        with self.assertRaises(BadRequest) as cm:
            negotiation_handler.read_negotiation()
        self.assertIn("The sap parameter must be a valid Service Agreement Proposal object", cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)

        with self.assertRaises(BadRequest) as cm:
            negotiation_handler.read_negotiation(sap)
        self.assertIn(
            "The Service Agreement Proposal object (sap) is missing a negotiation_id value", cm.exception.message
        )

        negotiation = Mock()
        negotiation._id = "456"

        sap.negotiation_id = negotiation._id

        self.mock_read.return_value = negotiation

        neg_obj = negotiation_handler.read_negotiation(sap)

        self.assertEqual(neg_obj, negotiation)
 def test__path_to_root(self, path_exists):
     repo = Mock(fs_path=g.tmpdir + "/")
     repo.name = "code"
     repo._id = "5057636b9c1040636b81e4b1"
     impl = SVNImplementation(repo)
     path_exists.return_value = False
     # edge cases
     assert_equal(impl._path_to_root(None), "")
     assert_equal(impl._path_to_root(""), "")
     assert_equal(impl._path_to_root("/some/path/"), "")
     assert_equal(impl._path_to_root("some/path"), "")
     # tags
     assert_equal(impl._path_to_root("/some/path/tags/1.0/some/dir"), "some/path/tags/1.0")
     assert_equal(impl._path_to_root("/some/path/tags/1.0/"), "some/path/tags/1.0")
     assert_equal(impl._path_to_root("/some/path/tags/"), "")
     # branches
     assert_equal(impl._path_to_root("/some/path/branches/b1/dir"), "some/path/branches/b1")
     assert_equal(impl._path_to_root("/some/path/branches/b1/"), "some/path/branches/b1")
     assert_equal(impl._path_to_root("/some/path/branches/"), "")
     # trunk
     assert_equal(impl._path_to_root("/some/path/trunk/some/dir/"), "some/path/trunk")
     assert_equal(impl._path_to_root("/some/path/trunk"), "some/path/trunk")
     # with fallback to trunk
     path_exists.return_value = True
     assert_equal(impl._path_to_root(""), "trunk")
     assert_equal(impl._path_to_root("/some/path/"), "trunk")
     assert_equal(impl._path_to_root("/tags/"), "trunk")
     assert_equal(impl._path_to_root("/branches/"), "trunk")
     assert_equal(impl._path_to_root("/tags/1.0"), "tags/1.0")
     assert_equal(impl._path_to_root("/branches/branch"), "branches/branch")
    def test_create_counter_proposal(self):

        with self.assertRaises(BadRequest) as cm:
            consumer_accept_sap = Negotiation.create_counter_proposal(proposal_status=ProposalStatusEnum.INITIAL)
        self.assertIn("The negotiation parameter must be a valid Negotiation object", cm.exception.message)

        negotiation_handler = Negotiation(self)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)

        negotiation = Mock()
        negotiation._id = "456"
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = [sap]

        self.mock_read.return_value = negotiation
        self.mock_create.return_value = ["456", 2]

        neg_id = negotiation_handler.create_negotiation(sap)

        sap.negotiation_id = neg_id

        consumer_accept_sap = Negotiation.create_counter_proposal(
            negotiation, proposal_status=ProposalStatusEnum.COUNTER, originator=ProposalOriginatorEnum.PROVIDER
        )

        self.assertEqual(consumer_accept_sap.negotiation_id, negotiation._id)
        self.assertEqual(len(negotiation.proposals), 1)
        self.assertEqual(consumer_accept_sap.sequence_num, len(negotiation.proposals))
        self.assertEqual(consumer_accept_sap.proposal_status, ProposalStatusEnum.COUNTER)
        self.assertEqual(consumer_accept_sap.originator, ProposalOriginatorEnum.PROVIDER)
 def test_get_last_password_updated_not_set(self):
     user = Mock()
     user._id = ObjectId()
     user.last_password_updated = None
     upd = self.provider.get_last_password_updated(user)
     gen_time = datetime.utcfromtimestamp(calendar.timegm(user._id.generation_time.utctimetuple()))
     assert_equal(upd, gen_time)
    def test__update_new_data_check_attachment_no_newdatacheck(self, rr_cli_cls):
        rr_cli = rr_cli_cls.return_value
        attachment_1 = Mock()
        attachment_1._id = "attachment_1"
        attachment_1.keywords = ["notfound"]
        attachment_1.content = "content"

        attachment_2 = Mock()
        attachment_2._id = "attachment_2"
        attachment_2.keywords = ["NewDataCheck"]
        attachment_2.content = "new_content"
        rr_cli.find_attachments.return_value = [attachment_1]
        rr_cli.create_attachment.return_value = attachment_2._id

        self._bdh._update_new_data_check_attachment(res_id="res_id", new_content=attachment_2.content)
        rr_cli.find_attachments.assert_called_once_with(resource_id="res_id", include_content=False, id_only=False)
        self.assertTrue(rr_cli.create_attachment.called)
Example #6
0
def tree(name, id, trees=None, blobs=None):
    t = Mock(tree_ids=[], blob_ids=[], other_ids=[])
    t.name = name
    t.id = id
    t._id = id
    if trees is not None:
        t.tree_ids = trees
    if blobs is not None:
        t.blob_ids = blobs
    return t
    def test__find_new_data_check_attachment_no_newdatacheck(self, rr_cli_cls):
        rr_cli = rr_cli_cls.return_value
        attachment_1 = Mock()
        attachment_1._id = "attachment_1"
        attachment_1.keywords = ["not_found"]
        attachment_1.content = "content"
        rr_cli.find_attachments.return_value = [attachment_1]

        ret = self._bdh._find_new_data_check_attachment(res_id="res_id")
        self.assertEqual(ret, None)
        rr_cli.find_attachments.assert_called_once_with(resource_id="res_id", include_content=False, id_only=False)
    def test__find_new_data_check_attachment(self, rr_cli_cls):
        rr_cli = rr_cli_cls.return_value
        attachment_1 = Mock()
        attachment_1._id = "attachment_1"
        attachment_1.keywords = ["NewDataCheck"]
        attachment_1.content = msgpack.packb("content")
        rr_cli.find_attachments.return_value = [attachment_1]

        ret = self._bdh._find_new_data_check_attachment(res_id="res_id")
        self.assertEqual(ret, "content")
        rr_cli.find_attachments.assert_called_once_with(resource_id="res_id", include_content=False, id_only=False)
    def _test_last_commit_ids(self, path):
        repo = Mock(fs_path=g.tmpdir + "/")
        repo.name = "code"
        repo._id = "5057636b9c1040636b81e4b1"
        impl = SVNImplementation(repo)
        impl._svn.info2 = Mock()
        impl._svn.info2.return_value = [("trunk", Mock()), ("foo", Mock())]
        impl._svn.info2.return_value[1][1].last_changed_rev.number = "1"
        commit = Commit()
        commit._id = "5057636b9c1040636b81e4b1:6"
        entries = impl.last_commit_ids(commit, [path])

        assert_equal(entries, {path.strip("/"): "5057636b9c1040636b81e4b1:1"})
        assert_equal(impl._svn.info2.call_args[0][0], "file://" + g.tmpdir + "/code/trunk")
Example #10
0
 def make_response(self, response_attrs=None, request_attrs=None):
     response = Mock()
     request = Mock()
     response.code = 200
     response.error = None
     response.body = json.dumps({"offsets": [{}]})
     request._id = 1
     request._topic = "test_driver"
     request._batch = [Message("test_driver", self.test_value, None, None, 0, 1)]
     for k, v in (response_attrs or {}).items():
         if k == "body":
             v = json.dumps(v)
         setattr(response, k, v)
     for k, v in (request_attrs or {}).items():
         setattr(request, k, v)
     response.request = request
     return response
Example #11
0
    def test_auth_transaction(self, get_ids, get_id, create_authorization_hold, request, bidding_request):
        """Test auth_transaction"""
        link = Mock(spec=Link)
        link._id = 99
        amount = 100
        payment_method_id = 50
        campaign_id = 99
        request.ip = bidding_request.ip = "127.0.0.1"
        authorize_response = Mock()
        authorize_response.trans_id = 123

        # If get_ids is empty, assert that the proper value is returned
        get_ids.return_value = []
        return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id)
        self.assertEqual(return_value, (None, "invalid payment method"))

        # Make get_ids return a valid payment_method_id
        get_ids.return_value.append(payment_method_id)
        # Assign arbitrary CustomerID, which comes from Authorize
        get_id.return_value = 1000
        create_authorization_hold.return_value = (authorize_response.trans_id, authorize_response)

        # Scenario: create_authorization_hold raises DuplicateTransactionError
        duplicate_transaction_error = DuplicateTransactionError(transaction_id=authorize_response.trans_id)
        create_authorization_hold.side_effect = duplicate_transaction_error
        # Why does patch.multiple return an AttributeError?
        with patch("r2.lib.authorize.interaction.Bid.one") as one:
            one.side_effect = NotFound()
            return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id)
            # If create_authorization_hold raises NotFound, assert return value
            self.assertEqual(return_value, (authorize_response.trans_id, None))

        # Scenario: create_authorization_hold successfully returns
        with patch("r2.lib.authorize.interaction.Bid._new") as _new:
            return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id)
            self.assertTrue(_new.called)
            # If create_authorization_hold works, assert return value
            self.assertEqual(return_value, (authorize_response.trans_id, None))

        # Scenario: create_authorization_hold raises TransactionError
        create_authorization_hold.side_effect = TransactionError("", authorize_response)
        return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id)
        # If create_authorization_hold raises TransactionError, assert return
        self.assertEqual(return_value[0], None)
Example #12
0
    def test_auth_freebie_transaction(self, _new):
        """Test auth_freebie_transaction"""
        link = Mock(spec=Link)
        link._id = 99
        amount = 100
        campaign_id = 99

        # Can't test that NotFound is thrown since the exception is handled,
        # so assert that _new is called
        return_value = auth_freebie_transaction(amount, self.user, link, campaign_id)
        self.assertTrue(_new.called)
        # Assert that return value of auth_freebie_transaction is correct
        self.assertEqual(return_value, (-link._id, ""))

        # When a Bid is found, assert that auth is called
        with patch("r2.lib.authorize.interaction.Bid.one") as one:
            one_mock = MagicMock()
            one.return_value = one_mock
            auth_freebie_transaction(amount, self.user, link, campaign_id)
            self.assertTrue(one_mock.auth.called)
Example #13
0
    def test_create_negotiation_fail_precondition(self):

        self.preconditions.check_method1.return_value = False
        self.accept_actions.accept_method.return_value = None

        negotiation_rules = {
            OT.EnrollmentProposal: {
                "pre_conditions": [
                    "preconditions.check_method1(sap.consumer)",
                    "not preconditions.check_method2(sap.provider,sap.consumer)",
                ],
                "accept_action": "accept_actions.accept_method(sap.provider,sap.consumer)",
            }
        }
        negotiation_handler = Negotiation(self, negotiation_rules)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)

        negotiation = Mock()
        negotiation._id = "456"
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = []

        self.mock_read.return_value = negotiation
        self.mock_create.return_value = ["456", 2]

        with self.assertRaises(BadRequest) as cm:
            neg_id = negotiation_handler.create_negotiation(sap)
        self.assertIn(
            "A precondition for this request has not been satisfied: preconditions.check_method1(sap.consumer)",
            cm.exception.message,
        )

        self.assertEqual(len(negotiation.proposals), 0)

        self.assertEqual(self.preconditions.check_method1.called, True)
        self.assertEqual(self.preconditions.check_method2.called, False)
        self.assertEqual(self.accept_actions.accept_method.called, False)
Example #14
0
    def test_create_extended_resource_container(self):

        mock_clients = self._create_service_mock("resource_registry")

        self.clients = mock_clients

        extended_resource_handler = ExtendedResourceContainer(self, mock_clients.resource_registry)

        instrument_device = Mock()
        instrument_device._id = "123"
        instrument_device.name = "MyInstrument"
        instrument_device.type_ = RT.InstrumentDevice

        actor_identity = Mock()
        actor_identity._id = "111"
        actor_identity.name = "Foo"
        actor_identity.type_ = RT.ActorIdentity

        user_info = Mock()
        user_info.name = "John Doe"
        user_info.email = "John.Doe@devnull.com"
        user_info.phone = "555-555-5555"
        user_info.variables = [{"name": "subscribeToMailingList", "value": "False"}]

        # ActorIdentity to UserInfo association
        actor_identity_to_info_association = Mock()
        actor_identity_to_info_association._id = "555"
        actor_identity_to_info_association.s = "111"
        actor_identity_to_info_association.st = RT.ActorIdentity
        actor_identity_to_info_association.p = PRED.hasInfo
        actor_identity_to_info_association.o = "444"
        actor_identity_to_info_association.ot = RT.UserInfo

        # ActorIdentity to UserInfo association
        Instrument_device_to_actor_identity_association = Mock()
        Instrument_device_to_actor_identity_association._id = "666"
        Instrument_device_to_actor_identity_association.s = "123"
        Instrument_device_to_actor_identity_association.st = RT.InstumentDevice
        Instrument_device_to_actor_identity_association.p = PRED.hasOwner
        Instrument_device_to_actor_identity_association.o = "111"
        Instrument_device_to_actor_identity_association.ot = RT.ActorIdentity

        with self.assertRaises(BadRequest) as cm:
            extended_user = extended_resource_handler.create_extended_resource_container(RT.ActorIdentity, "111")
        self.assertIn("Requested resource ActorIdentity is not extended from ResourceContainer", cm.exception.message)

        obj = IonObject(OT.TestExtendedResource)
        list_objs = ["123", "456", "789"]
        extended_resource_handler.set_field_associations(obj, "policies", list_objs)
        extended_resource_handler.set_field_associations(obj, "policy_count", list_objs)
        extended_resource_handler.set_field_associations(obj, "resource_object", list_objs)

        self.assertEquals(obj.policies, list_objs)
        self.assertEquals(obj.policy_count, 3)
        self.assertEquals(obj.resource_object, "123")

        mock_clients.resource_registry.read.return_value = instrument_device
        mock_clients.resource_registry.find_objects.return_value = (
            [actor_identity],
            [Instrument_device_to_actor_identity_association],
        )

        extended_res = extended_resource_handler.create_extended_resource_container(OT.TestExtendedResource, "123")
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 1)

        # Test field exclusion
        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResource, "123", ext_exclude=["owners"]
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 0)
Example #15
0
    def test_update_negotiation(self):

        self.preconditions.check_method1.return_value = True
        self.preconditions.check_method2.return_value = False
        self.accept_actions.accept_method.return_value = None

        negotiation_rules = {
            OT.EnrollmentProposal: {
                "pre_conditions": [
                    "preconditions.check_method1(sap.consumer)",
                    "not preconditions.check_method2(sap.provider,sap.consumer)",
                ],
                "accept_action": "accept_actions.accept_method(sap.provider,sap.consumer)",
            }
        }

        negotiation_handler = Negotiation(self, negotiation_rules, self.event_pub)

        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.update_negotiation()
        self.assertIn(
            "The Service Agreement Proposal must have a negotiation resource id associated with it",
            cm.exception.message,
        )

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)

        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.update_negotiation(sap)
        self.assertIn(
            "The Service Agreement Proposal must have a negotiation resource id associated with it",
            cm.exception.message,
        )

        negotiation = Mock()
        negotiation._id = "456"
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = []

        sap.negotiation_id = negotiation._id

        self.mock_read.return_value = negotiation
        self.mock_update.return_value = ["456", 2]

        neg_id = negotiation_handler.update_negotiation(sap)

        self.assertEqual(self.event_pub.publish_event.called, True)

        self.assertEqual(neg_id, negotiation._id)
        self.assertEqual(len(negotiation.proposals), 1)

        counter_sap = Negotiation.create_counter_proposal(
            negotiation, ProposalStatusEnum.REJECTED, ProposalOriginatorEnum.PROVIDER
        )

        neg_id = negotiation_handler.update_negotiation(counter_sap, "Fake rejection reason")

        self.assertEqual(len(negotiation.proposals), 2)
        self.assertEqual(negotiation.negotiation_status, NegotiationStatusEnum.REJECTED)
        self.assertEquals(negotiation.reason, "Fake rejection reason")

        counter_sap = Negotiation.create_counter_proposal(
            negotiation, ProposalStatusEnum.ACCEPTED, ProposalOriginatorEnum.PROVIDER
        )

        neg_id = negotiation_handler.update_negotiation(counter_sap)
        self.assertEqual(len(negotiation.proposals), 3)
        self.assertEqual(negotiation.negotiation_status, NegotiationStatusEnum.REJECTED)

        counter_sap = Negotiation.create_counter_proposal(
            negotiation, ProposalStatusEnum.ACCEPTED, ProposalOriginatorEnum.CONSUMER
        )

        neg_id = negotiation_handler.update_negotiation(counter_sap)
        self.assertEqual(len(negotiation.proposals), 4)
        self.assertEqual(negotiation.negotiation_status, NegotiationStatusEnum.ACCEPTED)

        self.assertEqual(self.accept_actions.accept_method.called, True)
Example #16
0
    def test_create_negotiation(self):

        self.preconditions.check_method1.return_value = True
        self.preconditions.check_method2.return_value = False
        self.accept_actions.accept_method.return_value = None

        negotiation_rules = {
            OT.EnrollmentProposal: {
                "pre_conditions": [
                    "preconditions.check_method1(sap.consumer)",
                    "not preconditions.check_method2(sap.provider,sap.consumer)",
                ],
                "accept_action": "accept_actions.accept_method(sap.provider,sap.consumer)",
            }
        }

        negotiation_handler = Negotiation(self, negotiation_rules)

        with self.assertRaises(BadRequest) as cm:
            negotiation_handler.create_negotiation()
        self.assertIn("The sap parameter must be a valid Service Agreement Proposal object", cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)
        sap.sequence_num = 1  # Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn("The specified Service Agreement Proposal has inconsistent status fields", cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)
        sap.proposal_status = ProposalStatusEnum.COUNTER  # Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn("The specified Service Agreement Proposal has inconsistent status fields", cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)
        sap.negotiation_id = "efefeff"  # Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn(
            "The specified Service Agreement Proposal cannot have a negotiation_id for an initial proposal",
            cm.exception.message,
        )

        sap = IonObject(OT.EnrollmentProposal, consumer=self.actor_identity._id, provider=self.org._id)

        negotiation = Mock()
        negotiation._id = "456"
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = []

        self.mock_read.return_value = negotiation
        self.mock_create.return_value = ["456", 2]

        neg_id = negotiation_handler.create_negotiation(sap)

        self.assertEqual(neg_id, negotiation._id)
        self.assertEqual(len(negotiation.proposals), 0)

        self.assertEqual(self.preconditions.check_method1.called, True)
        self.assertEqual(self.preconditions.check_method2.called, True)
        self.assertEqual(self.accept_actions.accept_method.called, False)
Example #17
0
    def test_create_extended_resource_container(self):

        mock_clients = self._create_service_mock("resource_registry")

        self.clients = mock_clients
        self.container = Mock()

        extended_resource_handler = ExtendedResourceContainer(self, mock_clients.resource_registry)

        instrument_device = Mock()
        instrument_device._id = "123"
        instrument_device.name = "MyInstrument"
        instrument_device.type_ = RT.InstrumentDevice

        instrument_device2 = Mock()
        instrument_device2._id = "456"
        instrument_device2.name = "MyInstrument2"
        instrument_device2.type_ = RT.InstrumentDevice

        actor_identity = Mock()
        actor_identity._id = "111"
        actor_identity.name = "Foo"
        actor_identity.type_ = RT.ActorIdentity

        user_info = Mock()
        user_info._id = "444"
        user_info.name = "John Doe"
        user_info.email = "John.Doe@devnull.com"
        user_info.phone = "555-555-5555"
        user_info.variables = [{"name": "subscribeToMailingList", "value": "False"}]

        user_info2 = Mock()
        user_info2._id = "445"
        user_info2.name = "aka Evil Twin"
        user_info2.email = "Evil.Twin@devnull.com"
        user_info2.phone = "555-555-5555"
        user_info2.variables = [{"name": "subscribeToMailingList", "value": "False"}]

        # ActorIdentity to UserInfo association
        actor_identity_to_info_association = Mock()
        actor_identity_to_info_association._id = "555"
        actor_identity_to_info_association.s = "111"
        actor_identity_to_info_association.st = RT.ActorIdentity
        actor_identity_to_info_association.p = PRED.hasInfo
        actor_identity_to_info_association.o = "444"
        actor_identity_to_info_association.ot = RT.UserInfo

        # ActorIdentity to UserInfo association
        actor_identity_to_info_association2 = Mock()
        actor_identity_to_info_association2._id = "556"
        actor_identity_to_info_association2.s = "111"
        actor_identity_to_info_association2.st = RT.ActorIdentity
        actor_identity_to_info_association2.p = PRED.hasInfo
        actor_identity_to_info_association2.o = "445"
        actor_identity_to_info_association2.ot = RT.UserInfo

        # ActorIdentity to Instrument Device association
        Instrument_device_to_actor_identity_association = Mock()
        Instrument_device_to_actor_identity_association._id = "666"
        Instrument_device_to_actor_identity_association.s = "123"
        Instrument_device_to_actor_identity_association.st = RT.InstumentDevice
        Instrument_device_to_actor_identity_association.p = PRED.hasOwner
        Instrument_device_to_actor_identity_association.o = "111"
        Instrument_device_to_actor_identity_association.ot = RT.ActorIdentity

        # ActorIdentity to Instrument Device association
        Instrument_device_to_actor_identity_association2 = Mock()
        Instrument_device_to_actor_identity_association2._id = "667"
        Instrument_device_to_actor_identity_association2.s = "456"
        Instrument_device_to_actor_identity_association2.st = RT.InstumentDevice
        Instrument_device_to_actor_identity_association2.p = PRED.hasOwner
        Instrument_device_to_actor_identity_association2.o = "111"
        Instrument_device_to_actor_identity_association2.ot = RT.ActorIdentity

        with self.assertRaises(BadRequest) as cm:
            extended_user = extended_resource_handler.create_extended_resource_container(RT.ActorIdentity, "111")
        self.assertIn(
            "The requested resource ActorIdentity is not extended from ResourceContainer", cm.exception.message
        )

        mock_clients.resource_registry.read.return_value = instrument_device
        mock_clients.resource_registry.find_objects.return_value = (
            [actor_identity],
            [Instrument_device_to_actor_identity_association],
        )
        mock_clients.resource_registry.find_subjects.return_value = (None, None)
        mock_clients.resource_registry.find_associations.return_value = [
            actor_identity_to_info_association,
            Instrument_device_to_actor_identity_association,
        ]
        mock_clients.resource_registry.read_mult.return_value = [user_info]

        extended_res = extended_resource_handler.create_extended_resource_container(OT.TestExtendedResource, "123")
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 1)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)
        self.assertEquals(extended_res.resource_object.name, "TestSystem_Resource")

        # Test adding extra paramaters to methods
        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResource, "123", resource_name="AltSystem_Resource"
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 1)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)
        self.assertEquals(extended_res.resource_object.name, "AltSystem_Resource")

        # Test field exclusion
        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResource, "123", ext_exclude=["owners"]
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 0)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)

        # Test the list of ids interface
        extended_res_list = extended_resource_handler.create_extended_resource_container_list(
            OT.TestExtendedResource, ["123", "456"]
        )
        self.assertEqual(len(extended_res_list), 2)
        self.assertEquals(extended_res_list[0].resource, instrument_device)
        self.assertEquals(len(extended_res_list[0].owners), 1)
        self.assertEquals(extended_res_list[0].resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)
Example #18
0
    def test_create_extended_resource_container(self):

        mock_clients = self._create_service_mock("resource_registry")

        self.clients = mock_clients
        self.container = Mock()

        extended_resource_handler = ExtendedResourceContainer(self, mock_clients.resource_registry)

        instrument_device = Mock()
        instrument_device._id = "123"
        instrument_device.name = "MyInstrument"
        instrument_device.type_ = RT.InstrumentDevice
        instrument_device.lcstate = LCS.DRAFT
        instrument_device.availability = AS.PRIVATE

        instrument_device2 = Mock()
        instrument_device2._id = "456"
        instrument_device2.name = "MyInstrument2"
        instrument_device2.type_ = RT.InstrumentDevice

        actor_identity = Mock()
        actor_identity._id = "111"
        actor_identity.name = "Foo"
        actor_identity.type_ = RT.ActorIdentity

        actor_identity = Mock()
        actor_identity._id = "1112"
        actor_identity.name = "Foo2"
        actor_identity.type_ = RT.ActorIdentity

        user_info = Mock()
        user_info._id = "444"
        user_info.name = "John Doe"
        user_info.email = "John.Doe@devnull.com"
        user_info.phone = "555-555-5555"
        user_info.variables = [{"name": "subscribeToMailingList", "value": "False"}]

        user_info2 = Mock()
        user_info2._id = "445"
        user_info2.name = "aka Evil Twin"
        user_info2.email = "Evil.Twin@devnull.com"
        user_info2.phone = "555-555-5555"
        user_info2.variables = [{"name": "subscribeToMailingList", "value": "False"}]

        # ActorIdentity to UserInfo association
        actor_identity_to_info_association = Mock()
        actor_identity_to_info_association._id = "555"
        actor_identity_to_info_association.s = "111"
        actor_identity_to_info_association.st = RT.ActorIdentity
        actor_identity_to_info_association.p = PRED.hasInfo
        actor_identity_to_info_association.o = "444"
        actor_identity_to_info_association.ot = RT.UserInfo

        # ActorIdentity to UserInfo association
        actor_identity_to_info_association2 = Mock()
        actor_identity_to_info_association2._id = "556"
        actor_identity_to_info_association2.s = "1112"
        actor_identity_to_info_association2.st = RT.ActorIdentity
        actor_identity_to_info_association2.p = PRED.hasInfo
        actor_identity_to_info_association2.o = "445"
        actor_identity_to_info_association2.ot = RT.UserInfo

        # ActorIdentity to Instrument Device association
        Instrument_device_to_actor_identity_association = Mock()
        Instrument_device_to_actor_identity_association._id = "666"
        Instrument_device_to_actor_identity_association.s = "123"
        Instrument_device_to_actor_identity_association.st = RT.InstrumentDevice
        Instrument_device_to_actor_identity_association.p = PRED.hasOwner
        Instrument_device_to_actor_identity_association.o = "111"
        Instrument_device_to_actor_identity_association.ot = RT.ActorIdentity

        # ActorIdentity to Instrument Device association
        Instrument_device_to_actor_identity_association2 = Mock()
        Instrument_device_to_actor_identity_association2._id = "667"
        Instrument_device_to_actor_identity_association2.s = "456"
        Instrument_device_to_actor_identity_association2.st = RT.InstrumentDevice
        Instrument_device_to_actor_identity_association2.p = PRED.hasOwner
        Instrument_device_to_actor_identity_association2.o = "111"
        Instrument_device_to_actor_identity_association2.ot = RT.ActorIdentity

        with self.assertRaises(BadRequest) as cm:
            extended_user = extended_resource_handler.create_extended_resource_container(RT.ActorIdentity, "111")
        self.assertIn(
            "The requested resource ActorIdentity is not extended from ResourceContainer", cm.exception.message
        )

        mock_clients.resource_registry.read.return_value = instrument_device
        mock_clients.resource_registry.find_objects.return_value = (
            [actor_identity],
            [Instrument_device_to_actor_identity_association],
        )
        mock_clients.resource_registry.find_subjects.return_value = (None, None)
        mock_clients.resource_registry.find_associations.return_value = [
            actor_identity_to_info_association,
            Instrument_device_to_actor_identity_association,
        ]
        mock_clients.resource_registry.read_mult.return_value = [user_info]

        extended_res = extended_resource_handler.create_extended_resource_container(OT.TestExtendedResource, "123")
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 2)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)
        self.assertEquals(extended_res.resource_object.name, "TestSystem_Resource")
        self.assertEquals(extended_res.owner_count, 2)
        self.assertEquals(extended_res.single_owner.name, user_info.name)
        self.assertEquals(len(extended_res.lcstate_transitions), 6)
        self.assertEquals(
            set(extended_res.lcstate_transitions.keys()),
            set(["develop", "deploy", "retire", "plan", "integrate", "delete"]),
        )
        self.assertEquals(len(extended_res.availability_transitions), 2)
        self.assertEquals(set(extended_res.availability_transitions.keys()), set(["enable", "announce"]))

        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResourceDevice, "123"
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 2)

        with self.assertRaises(Inconsistent) as cm:
            extended_res = extended_resource_handler.create_extended_resource_container(
                OT.TestExtendedResourceBad, "123"
            )

        # Test adding extra paramaters to methods
        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResource, "123", resource_name="AltSystem_Resource"
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 2)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)
        self.assertEquals(extended_res.resource_object.name, "AltSystem_Resource")

        # Test field exclusion
        extended_res = extended_resource_handler.create_extended_resource_container(
            OT.TestExtendedResource, "123", ext_exclude=["owners"]
        )
        self.assertEquals(extended_res.resource, instrument_device)
        self.assertEquals(len(extended_res.owners), 0)
        self.assertEquals(extended_res.resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)

        # Test the list of ids interface
        extended_res_list = extended_resource_handler.create_extended_resource_container_list(
            OT.TestExtendedResource, ["123", "456"]
        )
        self.assertEqual(len(extended_res_list), 2)
        self.assertEquals(extended_res_list[0].resource, instrument_device)
        self.assertEquals(len(extended_res_list[0].owners), 2)
        self.assertEquals(extended_res_list[0].resource_object.type_, RT.SystemResource)
        self.assertEquals(extended_res.remote_resource_object.type_, RT.InstrumentDevice)

        # Test create_prepare_update_resource
        prepare_create = extended_resource_handler.create_prepare_resource_support(
            prepare_resource_type=OT.TestPrepareUpdateResource
        )
        self.assertEqual(prepare_create.type_, OT.TestPrepareUpdateResource)
        self.assertEqual(prepare_create._id, "")

        prepare_update = extended_resource_handler.create_prepare_resource_support(
            resource_id="123", prepare_resource_type=OT.TestPrepareUpdateResource
        )
        self.assertEqual(prepare_update.type_, OT.TestPrepareUpdateResource)
        self.assertEqual(prepare_update._id, "123")