当前位置: 首页>>代码示例>>Python>>正文


Python MagicMock.args方法代码示例

本文整理汇总了Python中mock.MagicMock.args方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.args方法的具体用法?Python MagicMock.args怎么用?Python MagicMock.args使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mock.MagicMock的用法示例。


在下文中一共展示了MagicMock.args方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_read_record

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_read_record(self):
        """
        Read an existing record with ara_read
        """
        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'key': 'test-key',
        }

        action = ara_read.ActionModule(task, self.connection,
                                       self.play_context, loader=None,
                                       templar=None, shared_loader_obj=None)
        data = action.run()

        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        r_data = m.Data.query.filter_by(playbook_id=r_playbook.id,
                                        key='test-key').one()
        self.assertIsNotNone(r_data)
        self.assertEqual(r_data.playbook_id, r_playbook.id)
        self.assertEqual(r_data.key, 'test-key')
        self.assertEqual(r_data.value, 'test-value')
        self.assertEqual(r_data.type, 'text')

        self.assertEqual(data['playbook_id'], r_data.playbook_id)
        self.assertEqual(data['key'], r_data.key)
        self.assertEqual(data['value'], r_data.value)
        self.assertEqual(data['type'], r_data.type)
开发者ID:dmsimard,项目名称:ara,代码行数:33,代码来源:test_ara_read.py

示例2: test_read_record_with_no_key

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_read_record_with_no_key(self):
        """
        Read an existing record that does not exist with ara_read
        """
        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'key': 'key',
        }

        action = ara_read.ActionModule(task, self.connection,
                                       self.play_context, loader=None,
                                       templar=None, shared_loader_obj=None)
        data = action.run()

        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        # There is no exception raised in the action module, we instead
        # properly return a failure status to Ansible.
        # If there is a failure, no data will be returned so we can catch this.
        with self.assertRaises(Exception):
            m.Data.query.filter_by(playbook_id=r_playbook.id, key='key').one()

        self.assertEqual(data['failed'], True)
        self.assertEqual(data['playbook_id'], None)
        self.assertEqual(data['key'], None)
        self.assertEqual(data['value'], None)
开发者ID:dmsimard,项目名称:ara,代码行数:31,代码来源:test_ara_read.py

示例3: test_create_record_as_wrong_type

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_create_record_as_wrong_type(self):
        """
        Create a new record with ara_record.
        """
        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'key': 'test-wrongtype',
            'value': ['foo', 'bar'],
            'type': 'text'
        }

        action = ara_record.ActionModule(task, self.connection,
                                         self.play_context, loader=None,
                                         templar=None, shared_loader_obj=None)
        action.run()

        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        r_data = m.Data.query.filter_by(playbook_id=r_playbook.id,
                                        key='test-wrongtype').one()
        self.assertIsNotNone(r_data)
        self.assertEqual(r_data.playbook_id, r_playbook.id)
        self.assertEqual(r_data.key, 'test-wrongtype')
        self.assertEqual(r_data.value, ['foo', 'bar'])
        self.assertEqual(r_data.type, 'text')
开发者ID:dmsimard,项目名称:ara,代码行数:30,代码来源:test_ara_record.py

示例4: test_render_GET_bad_args

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_render_GET_bad_args(self):
        vector = [
            ({}, "Missing 'policy' parameter."),
            ({"policy": ["a", "b"]}, "Multiple 'policy' parameters unsupported."),
            ({"policy": ["best"]}, "Only 'policy=all' parameter supported."),
            ({"policy": ["all"], "format": ["a", "b"]}, "Multiple 'format' parameters unsupported."),
            ({"policy": ["all"], "format": ["foo"]}, "Only 'format=json' parameter supported."),
        ]

        for (args, errmsg) in vector:
            m_db = MagicMock()
            m_request = MagicMock()
            m_request.args = args

            lsr = lookup.LookupSimulatorResource(m_db)
            retval = lsr.render_GET(m_request)

            # Verifications:
            self.assertEqual(server.NOT_DONE_YET, retval)

            # Verify that a 400 response was sent:
            self.assertEqual(m_request.mock_calls, [call.sendJsonErrorMessage(errmsg)])

            # Verify that db was not touched:
            self.assertEqual(m_db.mock_calls, [])
开发者ID:hellais,项目名称:ooni-support,代码行数:27,代码来源:test_lookup.py

示例5: test_create_text_record_with_playbook

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_create_text_record_with_playbook(self):
        """
        Create a new record with ara_record on a specified playbook
        """
        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'playbook': r_playbook.id,
            'key': 'test-text',
            'value': 'test-with-playbook',
            'type': 'text'
        }

        action = ara_record.ActionModule(task, self.connection,
                                         self.play_context, loader=None,
                                         templar=None, shared_loader_obj=None)
        action.run()

        r_data = m.Data.query.filter_by(playbook_id=r_playbook.id,
                                        key='test-text').one()
        self.assertIsNotNone(r_data)
        self.assertEqual(r_data.playbook_id, r_playbook.id)
        self.assertEqual(r_data.key, 'test-text')
        self.assertEqual(r_data.value, 'test-with-playbook')
        self.assertEqual(r_data.type, 'text')
开发者ID:dmsimard,项目名称:ara,代码行数:31,代码来源:test_ara_record.py

示例6: test_update_record

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_update_record(self):
        """
        Update an existing record by running ara_record a second time on the
        same key.
        """
        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'key': 'test-update',
            'value': 'test-value',
            'type': 'text'
        }

        action = ara_record.ActionModule(task, self.connection,
                                         self.play_context, loader=None,
                                         templar=None, shared_loader_obj=None)
        action.run()

        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        r_data = m.Data.query.filter_by(playbook_id=r_playbook.id,
                                        key='test-update').one()
        self.assertIsNotNone(r_data)
        self.assertEqual(r_data.playbook_id, r_playbook.id)
        self.assertEqual(r_data.key, 'test-update')
        self.assertEqual(r_data.value, 'test-value')
        self.assertEqual(r_data.type, 'text')

        task.args = {
            'key': 'test-update',
            'value': 'http://another-value',
            'type': 'url'
        }
        action = ara_record.ActionModule(task, self.connection,
                                         self.play_context, loader=None,
                                         templar=None, shared_loader_obj=None)
        action.run()

        r_data = m.Data.query.filter_by(playbook_id=r_playbook.id,
                                        key='test-update').one()

        self.assertEqual(r_data.value, 'http://another-value')
        self.assertEqual(r_data.type, 'url')
开发者ID:dmsimard,项目名称:ara,代码行数:47,代码来源:test_ara_record.py

示例7: test_parameter_validator

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
def test_parameter_validator(monkeypatch):
    request = MagicMock(name='request')
    request.args = {}
    request.headers = {}
    request.params = {}
    app = MagicMock(name='app')

    app.response_class = flask.Response
    monkeypatch.setattr('flask.request', request)
    monkeypatch.setattr('flask.current_app', app)

    def orig_handler(*args, **kwargs):
        return 'OK'

    params = [{'name': 'p1', 'in': 'path', 'type': 'integer', 'required': True},
              {'name': 'h1', 'in': 'header', 'type': 'string', 'enum': ['a', 'b']},
              {'name': 'q1', 'in': 'query', 'type': 'integer', 'maximum': 3},
              {'name': 'a1', 'in': 'query', 'type': 'array', 'minItems': 2, 'maxItems': 3,
               'items': {'type': 'integer', 'minimum': 0}}]
    validator = ParameterValidator(params, FlaskApi)
    handler = validator(orig_handler)

    kwargs = {'query': {}, 'headers': {}}
    request = MagicMock(path_params={}, **kwargs)
    assert json.loads(handler(request).data.decode())['detail'] == "Missing path parameter 'p1'"
    request = MagicMock(path_params={'p1': '123'}, **kwargs)
    assert handler(request) == 'OK'
    request = MagicMock(path_params={'p1': ''}, **kwargs)
    assert json.loads(handler(request).data.decode())['detail'] == "Wrong type, expected 'integer' for path parameter 'p1'"
    request = MagicMock(path_params={'p1': 'foo'}, **kwargs)
    assert json.loads(handler(request).data.decode())['detail'] == "Wrong type, expected 'integer' for path parameter 'p1'"
    request = MagicMock(path_params={'p1': '1.2'}, **kwargs)
    assert json.loads(handler(request).data.decode())['detail'] == "Wrong type, expected 'integer' for path parameter 'p1'"

    request = MagicMock(path_params={'p1': 1}, query={'q1': '4'}, headers={})
    assert json.loads(handler(request).data.decode())['detail'].startswith('4 is greater than the maximum of 3')
    request = MagicMock(path_params={'p1': 1}, query={'q1': '3'}, headers={})
    assert handler(request) == 'OK'

    request = MagicMock(path_params={'p1': 1}, query={'a1': ['1', '2']}, headers={})
    assert handler(request) == "OK"
    request = MagicMock(path_params={'p1': 1}, query={'a1': ['1', 'a']}, headers={})
    assert json.loads(handler(request).data.decode())['detail'].startswith("'a' is not of type 'integer'")
    request = MagicMock(path_params={'p1': 1}, query={'a1': ['1', '-1']}, headers={})
    assert json.loads(handler(request).data.decode())['detail'].startswith("-1 is less than the minimum of 0")
    request = MagicMock(path_params={'p1': 1}, query={'a1': ['1']}, headers={})
    assert json.loads(handler(request).data.decode())['detail'].startswith("[1] is too short")
    request = MagicMock(path_params={'p1': 1}, query={'a1': ['1', '2', '3', '4']}, headers={})
    assert json.loads(handler(request).data.decode())['detail'].startswith("[1, 2, 3, 4] is too long")

    request = MagicMock(path_params={'p1': '123'}, query={}, headers={'h1': 'a'})
    assert handler(request) == 'OK'

    request = MagicMock(path_params={'p1': '123'}, query={}, headers={'h1': 'x'})
    assert json.loads(handler(request).data.decode())['detail'].startswith("'x' is not one of ['a', 'b']")
开发者ID:crunk1,项目名称:connexion,代码行数:57,代码来源:test_validation.py

示例8: test_parameter_validator

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
def test_parameter_validator(monkeypatch):
    request = MagicMock(name='request')
    request.args = {}
    request.headers = {}
    request.params = {}
    app = MagicMock(name='app')
    app.response_class = lambda a, mimetype, status: json.loads(''.join(a))['detail']
    monkeypatch.setattr('flask.request', request)
    monkeypatch.setattr('flask.current_app', app)

    def orig_handler(*args, **kwargs):
        return 'OK'

    params = [{'name': 'p1', 'in': 'path', 'type': 'integer', 'required': True},
              {'name': 'h1', 'in': 'header', 'type': 'string', 'enum': ['a', 'b']},
              {'name': 'q1', 'in': 'query', 'type': 'integer', 'maximum': 3},
              {'name': 'a1', 'in': 'query', 'type': 'array', 'minItems': 2, 'maxItems': 3,
               'items': {'type': 'integer', 'minimum': 0}}]
    validator = ParameterValidator(params)
    handler = validator(orig_handler)

    assert handler() == "Missing path parameter 'p1'"
    assert handler(p1='123') == 'OK'
    assert handler(p1='') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='foo') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='1.2') == "Wrong type, expected 'integer' for path parameter 'p1'"

    request.args = {'q1': '4'}
    assert handler(p1=1).startswith('4 is greater than the maximum of 3')
    request.args = {'q1': '3'}
    assert handler(p1=1) == 'OK'

    request.args = {'a1': "1,2"}
    assert handler(p1=1) == "OK"
    request.args = {'a1': "1,a"}
    assert handler(p1=1).startswith("'a' is not of type 'integer'")
    request.args = {'a1': "1,-1"}
    assert handler(p1=1).startswith("-1 is less than the minimum of 0")
    request.args = {'a1': "1"}
    assert handler(p1=1).startswith("[1] is too short")
    request.args = {'a1': "1,2,3,4"}
    assert handler(p1=1).startswith("[1, 2, 3, 4] is too long")
    del request.args['a1']

    request.headers = {'h1': 'a'}
    assert handler(p1='123') == 'OK'

    request.headers = {'h1': 'x'}
    assert handler(p1='123').startswith("'x' is not one of ['a', 'b']")
开发者ID:rafaelcaricio,项目名称:connexion,代码行数:51,代码来源:test_validation.py

示例9: test_injection

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
def test_injection(monkeypatch):
    request = MagicMock(name='request', path_params={'p1': '123'})
    request.args = {}
    request.headers = {}
    request.params = {}

    func = MagicMock()

    def handler(**kwargs):
        func(**kwargs)

    parameter_to_arg({}, [], handler)(request)

    func.assert_called_with(p1='123')
开发者ID:liamdiprose,项目名称:connexion,代码行数:16,代码来源:test_parameter.py

示例10: test_render_GET_valid_parameters

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_render_GET_valid_parameters(self):
        # Test data:
        entries = [
            {
                "fqdn": "blah",
                "city": "Somewheresville",
                "country": "US",
                "ip": ["127.2.3.4", "::1"],
                "port": 8421,
                "site": "mlab01",
                "tool_extra": {"collector_onion": "testfakenotreal.onion"},
            },
            {
                "fqdn": "blorp",
                "city": "Elsewhereton",
                "country": "US",
                "ip": ["127.2.3.8", "::7"],
                "port": 1248,
                "site": "mlab02",
                "tool_extra": {"collector_onion": "yetanother.onion"},
            },
        ]

        # Mocks:
        db = dict((entry["fqdn"], entry) for entry in entries)
        m_request = MagicMock()

        # Fake a request with sufficient parameters:
        m_request.args = {"format": ["json"], "policy": ["all"]}

        # Execute the code under test:
        lsr = lookup.LookupSimulatorResource(db)
        retval = lsr.render_GET(m_request)

        # Verifications:
        self.assertEqual(server.NOT_DONE_YET, retval)

        # Verify that a 200 response was sent:
        self.assertEqual(m_request.mock_calls, [call.sendJsonResponse(entries)])
开发者ID:hellais,项目名称:ooni-support,代码行数:41,代码来源:test_lookup.py

示例11: test_parameter_validator

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
def test_parameter_validator(monkeypatch):
    request = MagicMock(name='request')
    request.args = {}
    request.headers = {}
    request.params = {}
    app = MagicMock(name='app')
    app.response_class = lambda a, mimetype, status: json.loads(a)['detail']
    monkeypatch.setattr('flask.request', request)
    monkeypatch.setattr('flask.current_app', app)

    def orig_handler(*args, **kwargs):
        return 'OK'

    params = [{'name': 'p1', 'in': 'path', 'type': 'integer', 'required': True},
              {'name': 'h1', 'in': 'header', 'type': 'string', 'enum': ['a', 'b']},
              {'name': 'q1', 'in': 'query', 'type': 'integer', 'maximum': 3},
              {'name': 'a1', 'in': 'query', 'type': 'array', 'items': {'type': 'integer', 'minimum': 0}}]
    validator = ParameterValidator(params)
    handler = validator(orig_handler)

    assert handler() == "Missing path parameter 'p1'"
    assert handler(p1='123') == 'OK'
    assert handler(p1='') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='foo') == "Wrong type, expected 'integer' for path parameter 'p1'"
    assert handler(p1='1.2') == "Wrong type, expected 'integer' for path parameter 'p1'"

    request.args = {'q1': '4'}
    assert handler(p1=1) == 'Invalid value, must be at most 3'
    request.args = {'q1': '3'}
    assert handler(p1=1) == 'OK'

    request.args = {'a1': '1,2'}
    assert handler(p1=1) == "OK"
    request.args = {'a1': '1,a'}
    assert handler(p1=1) == "Wrong type, expected 'integer' for query parameter 'a1'"
    request.args = {'a1': '1,-1'}
    assert handler(p1=1) == "Invalid value, must be at least 0"
    del request.args['a1']

    request.headers = {'h1': 'a'}
    assert handler(p1='123') == 'OK'

    request.headers = {'h1': 'x'}
    assert handler(p1='123') == "Enum value must be one of ['a', 'b']"
开发者ID:kleijnweb,项目名称:connexion,代码行数:46,代码来源:test_validation.py

示例12: test_record_with_no_value

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_record_with_no_value(self):
        """
        Trying to use ara_record with no value parameter should properly fail
        """
        task = MagicMock(Task)
        task.async_ = 0
        task.async_val = False
        task.args = {
            'key': 'test-key',
        }

        action = ara_record.ActionModule(task, self.connection,
                                         self.play_context, loader=None,
                                         templar=None, shared_loader_obj=None)
        action.run()

        r_playbook = m.Playbook.query.first()
        self.assertIsNotNone(r_playbook)

        # There is no exception raised in the action module, we instead
        # properly return a failure status to Ansible.
        # If there is a failure, no data will be recorded so we can catch this.
        with self.assertRaises(Exception):
            m.Data.query.filter_by(playbook_id=r_playbook.id).one()
开发者ID:dmsimard,项目名称:ara,代码行数:26,代码来源:test_ara_record.py

示例13: test_resource_policies

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_resource_policies(self):
        gc = Mock()
        resource_id = "resource_key"
        pdpm = PolicyDecisionPointManager(gc)
        # see that the PDP for resource is empty
        self.assertEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)

        pdpm.set_resource_policy_rules(resource_id, self.permit_SUPERUSER_rule)

        # see that the PDP for resource is not empty anymore
        self.assertNotEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)

        # check request without a resource_id raises NotFound error
        invocation = MagicMock()
        invocation.message_annotations = {}
        with self.assertRaises(NotFound) as chk_res:
            pdpm.check_resource_request_policies(invocation, None)
        self.assertIn(chk_res.exception.message, "The resource_id is not set")

        # (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with)
        mock_header = Mock()

        def get_header_value(key, default):
            return invocation.headers.get(key, default)

        mock_header.side_effect = get_header_value
        invocation.get_header_value = mock_header
        mock_args = Mock()

        class MockProcess(Mock):
            def check_test_value(self, process, message, headers):
                if message["argument1"] > 3:
                    return False, "The value of argument1 is larger than 3"
                return True, ""

        mock_process = MockProcess()
        mock_process.org_governance_name = "org_name"
        invocation.args = {"process": mock_process}

        def get_arg_value(key, default):
            return invocation.args.get(key, default)

        mock_args.side_effect = get_arg_value
        invocation.get_arg_value = mock_args

        # check that, because actor does not have SUPERUSER role, policy evaluates to a denial

        invocation.message_annotations = {}
        invocation.message = {"argument1": 0}
        invocation.headers = {
            "op": "op",
            "process": mock_process,
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "sender-service",
            "ion-actor-roles": {"org_name": ["ion-actor-roles"]},
        }

        invocation.get_message_sender.return_value = ["Unknown", "Unknown"]

        gc.system_root_org_name = "sys_org_name"

        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "NotApplicable")

        # check that policy evaluates to Permit because actor has SUPERUSER role
        invocation.headers = {
            "op": "op",
            "process": mock_process,
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "sender-service",
            "ion-actor-roles": {"sys_org_name": ["SUPERUSER"]},
        }
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Permit")

        pdpm.set_resource_policy_rules(resource_id, self.deny_message_parameter_rule)

        invocation.message = {"argument1": 0}
        invocation.headers = {
            "op": "op",
            "process": mock_process,
            "request": "request",
            "ion-actor-id": "ion-actor-id",
            "receiver": "resource-registry",
            "sender-type": "sender-type",
            "sender-service": "sender-service",
            "ion-actor-roles": {"sys_org_name": ["SUPERUSER"]},
        }
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Deny")
        self.assertTrue("POLICY_STATUS_REASON" in invocation.message_annotations)
        self.assertEqual(
#.........这里部分代码省略.........
开发者ID:scion-network,项目名称:scioncc,代码行数:103,代码来源:test_policy_decision.py

示例14: test_resource_policies

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import args [as 别名]
    def test_resource_policies(self):
        gc = Mock()
        resource_id = 'resource_key'
        pdpm = PolicyDecisionPointManager(gc)
        # see that the PDP for resource is empty
        self.assertEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)

        pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule )

        # see that the PDP for resource is not empty anymore
        self.assertNotEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)

        # check request without a resource_id raises NotFound error
        invocation = MagicMock()
        invocation.message_annotations = {}
        with self.assertRaises(NotFound) as chk_res:
            pdpm.check_resource_request_policies(invocation, None)
        self.assertIn(chk_res.exception.message, 'The resource_id is not set')

        # (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with)
        mock_header = Mock()

        def get_header_value(key, default):
            return invocation.headers.get(key, default)
        mock_header.side_effect = get_header_value
        invocation.get_header_value = mock_header
        mock_args = Mock()

        class MockProcess(Mock):
            def check_test_value(self, process, message, headers):
                if message['argument1'] > 3:
                    return False, 'The value of argument1 is larger than 3'
                return True, ''

        mock_process = MockProcess()
        mock_process.org_governance_name = 'org_name'
        invocation.args = {'process': mock_process}

        def get_arg_value(key, default):
            return invocation.args.get(key, default)
        mock_args.side_effect = get_arg_value
        invocation.get_arg_value = mock_args

        # check that, because actor does not have ION_MANAGER role, policy evaluates to a denial

        invocation.message_annotations = {}
        invocation.message = {'argument1': 0}
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'org_name': ['ion-actor-roles']}}

        invocation.get_message_sender.return_value = ['Unknown','Unknown']

        gc.system_root_org_name = 'sys_org_name'

        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "NotApplicable")

        # check that policy evaluates to Permit because actor has ION_MANAGER role
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Permit")


        pdpm.load_resource_policy_rules(resource_id, self.deny_message_parameter_rule)

        invocation.message = {'argument1': 0}
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Deny")
        self.assertEqual(invocation.message_annotations.has_key('POLICY_STATUS_REASON'), True)
        self.assertEqual(invocation.message_annotations['POLICY_STATUS_REASON'],'The value of argument1 is less than or equal to 3')

        invocation.message = {'argument1': 5}
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Permit")
        self.assertEqual(invocation.message_annotations.has_key('POLICY_STATUS_REASON'), False)


        pdpm.load_resource_policy_rules(resource_id, self.deny_message_parameter_function_rule)

        invocation.message = {'argument1': 0}
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
        self.assertEqual(response.value, "Permit")
        self.assertEqual(invocation.message_annotations.has_key('POLICY_STATUS_REASON'), False)

        invocation.message = {'argument1': 5}
        invocation.headers = {'op': 'op', 'process': mock_process, 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
                                   'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
        invocation.message_annotations = {}
        response = pdpm.check_resource_request_policies(invocation, resource_id)
#.........这里部分代码省略.........
开发者ID:ateranishi,项目名称:pyon,代码行数:103,代码来源:test_policy_decision.py


注:本文中的mock.MagicMock.args方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。