Example #1
0
    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__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')
Example #3
0
    def test_notify_event(self):
        couch_user = Mock()
        couch_user._id = '123'
        couch_user.username = '******'
        with patch('corehq.apps.app_manager.views.notifications.RedisMessage'), \
                patch('corehq.apps.app_manager.views.notifications.RedisPublisher'), \
                patch('corehq.apps.app_manager.views.notifications.json_format_datetime') as format_patch, \
                patch('corehq.apps.app_manager.views.notifications.json') as json_patch:
            format_patch.return_value = 'maintenant'

            message = u'Émilie, vous avez de nouveaux messages.'
            notify_event('domain', couch_user, 'app_id', 'unique_form_id',
                         message)

            notification = (
                u'Émilie, vous avez de nouveaux messages. (<a href="https://confluence.dimagi.com/'
                u'display/internal/App+Builder+Notifications" target="_blank">what is this?</a>)'
            )
            json_patch.dumps.assert_called_with({
                'domain': 'domain',
                'user_id': '123',
                'username': '******',
                'text': notification,
                'timestamp': 'maintenant',
            })
 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')
Example #5
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 #6
0
    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__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)
    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 #9
0
 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 = dt.datetime.utcfromtimestamp(
         calendar.timegm(user._id.generation_time.utctimetuple()))
     assert_equal(upd, gen_time)
Example #10
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
Example #11
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
Example #12
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)
    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)
    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 = '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)
Example #15
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)
    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__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)
Example #18
0
    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=True,
                                                        id_only=False)
Example #19
0
    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=True,
                                                        id_only=False)
Example #20
0
def test_write_html_to_tempfile():
    block = Mock()
    block._id = 'test_id'
    content = 'dummy'

    file_name = HTMLConverter.write_html_to_tempfile(block, text_type(content))
    assert os.path.split(file_name)[-1].startswith('test_id')
    assert file_name.endswith('html')
    with open(file_name, 'r') as f:
        assert f.read() == content

    # Cleanup
    os.remove(file_name)
Example #21
0
    def test_should_update_entity_field_in_submission_index(self):
        self.dbm.database_name = 'db_name'
        entity_type = ['clinic']
        subject_details = {'q2': 'bangalore', 'q6': 'cli001'}
        with patch(
                "datawinners.search.submission_index._get_submissions_for_unique_id_entry"
        ) as _get_submissions_for_unique_id_entry_mock:
            with patch.object(
                    self.dbm,
                    "load_all_rows_in_view") as load_all_rows_in_view:
                load_all_rows_in_view.return_value = [{
                    'doc': {
                        'name':
                        "project name",
                        "form_code":
                        "cli001",
                        "json_fields": [{
                            "name": "unique_id_field",
                            "type": "unique_id",
                            "unique_id_type": 'clinic',
                            "code": 'q1'
                        }],
                        "_id":
                        "form_model_id"
                    }
                }]
                survey_response_index1 = Mock(_id='id1')
                filtered_query = Mock(spec=elasticutils.S)
                filtered_query.all.return_value = [survey_response_index1]

                submission1 = Mock()
                submission1._id = "id1"
                query_mock = Mock()
                query_mock.values_dict.return_value = [submission1]
                _get_submissions_for_unique_id_entry_mock.return_value = query_mock

                with patch.object(SubmissionIndexUpdateHandler,
                                  'update_field_in_submission_index'
                                  ) as update_field_in_submission_index:
                    update_submission_search_for_subject_edition(
                        self.dbm, entity_type, subject_details)

                    # _get_submissions_for_unique_id_entry_mock.assert_called_with(**{'form_model_id_q1_unique_code': 'cli001'})
                    update_field_in_submission_index.assert_called_with(
                        'id1', {
                            'form_model_id_q1_details': {
                                'q2': 'bangalore',
                                'q6': 'cli001'
                            },
                            'form_model_id_q1': 'bangalore'
                        })
    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 #23
0
 def test__tarball_path_clean(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._tarball_path_clean(None), '')
     assert_equal(impl._tarball_path_clean(''), '')
     # common
     assert_equal(impl._tarball_path_clean('/some/path/'), 'some/path')
     assert_equal(impl._tarball_path_clean('some/path'), 'some/path')
     assert_equal(impl._tarball_path_clean('/some/path/tags/1.0/some/dir'), 'some/path/tags/1.0/some/dir')
     # with fallback to trunk
     path_exists.return_value = True
     assert_equal(impl._tarball_path_clean(None), 'trunk')
     assert_equal(impl._tarball_path_clean(''), 'trunk')
Example #24
0
 def test__tarball_path_clean(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._tarball_path_clean(None), '')
     assert_equal(impl._tarball_path_clean(''), '')
     # common
     assert_equal(impl._tarball_path_clean('/some/path/'), 'some/path')
     assert_equal(impl._tarball_path_clean('some/path'), 'some/path')
     assert_equal(impl._tarball_path_clean('/some/path/tags/1.0/some/dir'),
                  'some/path/tags/1.0/some/dir')
     # with fallback to trunk
     path_exists.return_value = True
     assert_equal(impl._tarball_path_clean(None), 'trunk')
     assert_equal(impl._tarball_path_clean(''), 'trunk')
Example #25
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 #26
0
    def test_notify_event(self):
        couch_user = Mock()
        couch_user._id = '123'
        couch_user.username = '******'
        with patch('corehq.apps.app_manager.views.notifications.RedisMessage'), \
                patch('corehq.apps.app_manager.views.notifications.RedisPublisher'), \
                patch('corehq.apps.app_manager.views.notifications.json_format_datetime') as format_patch, \
                patch('corehq.apps.app_manager.views.notifications.json') as json_patch:
            format_patch.return_value = 'maintenant'

            message = 'Émilie, vous avez de nouveaux messages.'
            notify_event('domain', couch_user, 'app_id', 'form_unique_id', message)

            notification = ('Émilie, vous avez de nouveaux messages.')
            json_patch.dumps.assert_called_with({
                'domain': 'domain',
                'user_id': '123',
                'username': '******',
                'text': notification,
                'timestamp': 'maintenant',
            })
Example #27
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 #28
0
    def test_notify_event(self):
        couch_user = Mock()
        couch_user._id = '123'
        couch_user.username = '******'
        with patch('corehq.apps.app_manager.views.notifications.RedisMessage'), \
                patch('corehq.apps.app_manager.views.notifications.RedisPublisher'), \
                patch('corehq.apps.app_manager.views.notifications.json_format_datetime') as format_patch, \
                patch('corehq.apps.app_manager.views.notifications.json') as json_patch:
            format_patch.return_value = 'maintenant'

            message = 'Émilie, vous avez de nouveaux messages.'
            notify_event('domain', couch_user, 'app_id', 'form_unique_id', message)

            notification = ('Émilie, vous avez de nouveaux messages.')
            json_patch.dumps.assert_called_with({
                'domain': 'domain',
                'user_id': '123',
                'username': '******',
                'text': notification,
                'timestamp': 'maintenant',
            })
Example #29
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('v1.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 #30
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 #31
0
    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)
Example #32
0
    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)
Example #33
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 = "*****@*****.**"
        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 = "*****@*****.**"
        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 #34
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 = "*****@*****.**"
        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 #35
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 #36
0
    def xtest_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.TestInstrument
        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.TestInstrument

        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 = "*****@*****.**"
        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 = "*****@*****.**"
        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.TestInstrument
        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.TestInstrument
        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.TestInstrument)
        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.TestInstrument)
        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.TestInstrument)

        #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.TestInstrument)

        #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')
Example #37
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)

        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 #38
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 = "*****@*****.**"
        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 = "*****@*****.**"
        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')
Example #39
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 #40
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 = "*****@*****.**"
        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 = "*****@*****.**"
        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)


        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])
        mock_clients.resource_registry.find_subjects.return_value = (None,None)

        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)

        #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)