Python neutron_lib.context.Context() Examples

The following are 30 code examples of neutron_lib.context.Context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module neutron_lib.context , or try the search function .
Example #1
Source File: test_context.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def test_to_policy_values(self):
        values = {
            'user_id': 'user_id',
            'tenant_id': 'tenant_id',
            'is_admin': 'is_admin',
            'tenant_name': 'tenant_name',
            'user_name': 'user_name',
            'domain': 'domain',
            'user_domain': 'user_domain',
            'project_domain': 'project_domain',
            'user_name': 'user_name',
        }
        additional_values = {
            'user': 'user_id',
            'tenant': 'tenant_id',
            'project_id': 'tenant_id',
            'project_name': 'tenant_name',
        }
        ctx = context.Context(**values)
        # apply dict() to get a real dictionary, needed for newer oslo.context
        # that returns _DeprecatedPolicyValues object instead
        policy_values = dict(ctx.to_policy_values())
        self.assertDictSupersetOf(values, policy_values)
        self.assertDictSupersetOf(additional_values, policy_values) 
Example #2
Source File: test_vpn_db.py    From neutron-vpnaas with Apache License 2.0 6 votes vote down vote up
def _create_vpnservice(self, fmt, name,
                           admin_state_up,
                           router_id, subnet_id,
                           expected_res_status=None, **kwargs):
        tenant_id = kwargs.get('tenant_id', self._tenant_id)
        data = {'vpnservice': {'name': name,
                               'subnet_id': subnet_id,
                               'router_id': router_id,
                               'admin_state_up': admin_state_up,
                               'tenant_id': tenant_id}}
        if kwargs.get('description') is not None:
            data['vpnservice']['description'] = kwargs['description']
        if kwargs.get('flavor_id') is not None:
            data['vpnservice']['flavor_id'] = kwargs['flavor_id']
        vpnservice_req = self.new_create_request('vpnservices', data, fmt)
        if (kwargs.get('set_context') and
                'tenant_id' in kwargs):
            # create a specific auth context for this request
            vpnservice_req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])
        vpnservice_res = vpnservice_req.get_response(self.ext_api)
        if expected_res_status:
            self.assertEqual(vpnservice_res.status_int, expected_res_status)
        return vpnservice_res 
Example #3
Source File: test_context.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def test_neutron_context_overwrite(self):
        ctx1 = context.Context('user_id', 'tenant_id')
        self.assertEqual(ctx1.request_id,
                         oslo_context.get_current().request_id)

        # If overwrite is not specified, request_id should be updated.
        ctx2 = context.Context('user_id', 'tenant_id')
        self.assertNotEqual(ctx2.request_id, ctx1.request_id)
        self.assertEqual(ctx2.request_id,
                         oslo_context.get_current().request_id)

        # If overwrite is specified, request_id should be kept.
        ctx3 = context.Context('user_id', 'tenant_id', overwrite=False)
        self.assertNotEqual(ctx3.request_id, ctx2.request_id)
        self.assertEqual(ctx2.request_id,
                         oslo_context.get_current().request_id) 
Example #4
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test__validate_privileges_advsvc_other_tenant(self):
        project_id = 'fake_project'
        ctx = context.Context(project_id='fake_project2',
                              is_advsvc=True)
        res_dict = {'project_id': project_id}
        try:
            attributes._validate_privileges(ctx, res_dict)
        except exc.HTTPBadRequest:
            self.fail("HTTPBadRequest exception should not be raised.") 
Example #5
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_superclass_session(self, mocked_session):
        ctx = context.Context('user_id', 'tenant_id')
        # make sure context uses parent class session that is mocked
        self.assertEqual(mocked_session, ctx.session) 
Example #6
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_add_get_remove_constraint(self):
        ctx = context.Context('user_id', 'tenant_id')
        self.assertIsNone(ctx.get_transaction_constraint())
        ctx.set_transaction_constraint('networks', 'net_id', 44)
        constraint = ctx.get_transaction_constraint()
        self.assertEqual(44, constraint.if_revision_match)
        self.assertEqual('networks', constraint.resource)
        self.assertEqual('net_id', constraint.resource_id)
        ctx.clear_transaction_constraint()
        self.assertIsNone(ctx.get_transaction_constraint()) 
Example #7
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_populate_project_id_admin_req(self):
        tenant_id_1 = uuidutils.generate_uuid()
        tenant_id_2 = uuidutils.generate_uuid()
        # non-admin users can't create a res on behalf of another project
        ctx = context.Context(user_id=None, tenant_id=tenant_id_1)
        res_dict = {'tenant_id': tenant_id_2}
        attr_inst = attributes.AttributeInfo({})
        self.assertRaises(exc.HTTPBadRequest,
                          attr_inst.populate_project_id,
                          ctx, res_dict, None)
        # but admin users can
        ctx.is_admin = True
        attr_inst.populate_project_id(ctx, res_dict, is_create=False) 
Example #8
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_populate_project_id_from_context(self):
        tenant_id = uuidutils.generate_uuid()
        ctx = context.Context(user_id=None, tenant_id=tenant_id)
        # for each create request, the tenant_id should be added to the
        # req body
        res_dict = {}
        attr_inst = attributes.AttributeInfo({})
        attr_inst.populate_project_id(ctx, res_dict, is_create=True)
        self.assertEqual(
            {'tenant_id': ctx.tenant_id, 'project_id': ctx.tenant_id},
            res_dict) 
Example #9
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_populate_project_id_mandatory_not_specified(self):
        tenant_id = uuidutils.generate_uuid()
        ctx = context.Context(user_id=None, tenant_id=tenant_id)
        # if the tenant_id is mandatory for the resource and not specified
        # in the request nor in the context, an exception should be raised
        res_dict = {}
        attr_info = {'tenant_id': {'allow_post': True}}
        ctx.tenant_id = None
        attr_inst = attributes.AttributeInfo(attr_info)
        self.assertRaises(exc.HTTPBadRequest,
                          attr_inst.populate_project_id,
                          ctx, res_dict, True) 
Example #10
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_populate_project_id_not_mandatory(self):
        ctx = context.Context(user_id=None)
        # if the tenant_id is not mandatory for the resource it should be
        # OK if it is not in the request.
        res_dict = {'name': 'test_port'}
        attr_inst = attributes.AttributeInfo({})
        ctx.tenant_id = None
        attr_inst.populate_project_id(ctx, res_dict, True) 
Example #11
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test__validate_privileges_user_other_tenant(self):
        project_id = 'fake_project'
        ctx = context.Context(project_id='fake_project2')
        res_dict = {'project_id': project_id}
        self.assertRaises(
            exc.HTTPBadRequest,
            attributes._validate_privileges,
            ctx, res_dict) 
Example #12
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test__validate_privileges_admin_other_tenant(self):
        project_id = 'fake_project'
        ctx = context.Context(project_id='fake_project2',
                              is_admin=True)
        res_dict = {'project_id': project_id}
        try:
            attributes._validate_privileges(ctx, res_dict)
        except exc.HTTPBadRequest:
            self.fail("HTTPBadRequest exception should not be raised.") 
Example #13
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_neutron_context_get_admin_context_not_update_local_store(self):
        ctx = context.Context('user_id', 'tenant_id')
        req_id_before = oslo_context.get_current().request_id
        self.assertEqual(ctx.request_id, req_id_before)

        ctx_admin = context.get_admin_context()
        self.assertEqual(req_id_before, oslo_context.get_current().request_id)
        self.assertNotEqual(req_id_before, ctx_admin.request_id) 
Example #14
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_user_is_not_admin(self):
        ctx = context.Context('me', 'my_project')
        self.assertFalse(policy_engine.check_is_admin(ctx)) 
Example #15
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_user_elevated_is_admin(self):
        ctx = context.Context('me', 'my_project', roles=['user']).elevated()
        self.assertTrue(policy_engine.check_is_admin(ctx)) 
Example #16
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_user_elevated_is_admin_with_default_policy(self):
        policy_engine.init(policy_file='no_policy.json')
        ctx = context.Context('me', 'my_project', roles=['user']).elevated()
        self.assertTrue(policy_engine.check_is_admin(ctx)) 
Example #17
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_is_advsvc_role(self):
        ctx = context.Context('me', 'my_project', roles=['advsvc'])
        self.assertTrue(policy_engine.check_is_advsvc(ctx)) 
Example #18
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_is_not_advsvc_user(self):
        ctx = context.Context('me', 'my_project', roles=['user'])
        self.assertFalse(policy_engine.check_is_advsvc(ctx)) 
Example #19
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_is_not_advsvc_admin(self):
        ctx = context.Context('me', 'my_project').elevated()
        self.assertTrue(policy_engine.check_is_admin(ctx))
        self.assertFalse(policy_engine.check_is_advsvc(ctx)) 
Example #20
Source File: test__engine.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_check_is_advsvc_no_roles_no_advsvc(self):
        policy_engine.init(policy_file='dummy_policy.json')
        ctx = context.Context('me', 'my_project', roles=['advsvc'])
        # No advsvc role in the policy file, so cannot assume the role.
        self.assertFalse(policy_engine.check_is_advsvc(ctx)) 
Example #21
Source File: test_model_base.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestModelBase, self).setUp()
        self.ctx = context.Context('user', 'project')
        self.session = self.ctx.session 
Example #22
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_neutron_context_create_with_request_id(self):
        ctx = context.Context('user_id', 'tenant_id', request_id='req_id_xxx')
        self.assertEqual('req_id_xxx', ctx.request_id) 
Example #23
Source File: test_ipsec.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def test_store_gw_ips_on_service_create(self):
        vpnservice = mock.Mock()
        self.svc_plugin._get_vpnservice.return_value = vpnservice
        vpnservice.router.gw_port = {'fixed_ips': [{'ip_address': '10.0.0.99'},
                                                   {'ip_address': '2001::1'}]}
        ctxt = n_ctx.Context('', 'somebody')
        vpnservice_dict = {'id': FAKE_SERVICE_ID,
                           'router_id': FAKE_ROUTER_ID}
        self.driver.create_vpnservice(ctxt, vpnservice_dict)
        self.svc_plugin.set_external_tunnel_ips.assert_called_once_with(
            ctxt, FAKE_SERVICE_ID, v4_ip='10.0.0.99', v6_ip='2001::1') 
Example #24
Source File: test_vpn_validator.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestVpnValidation, self).setUp()
        self.l3_plugin = mock.Mock()
        self.core_plugin = mock.Mock()
        directory.add_plugin(nconstants.CORE, self.core_plugin)
        directory.add_plugin(nconstants.L3, self.l3_plugin)
        self.context = n_ctx.Context('some_user', 'some_tenant')
        self.validator = vpn_validator.VpnReferenceValidator()
        self.router = mock.Mock()
        self.router.gw_port = {'fixed_ips': [{'ip_address': '10.0.0.99'}]} 
Example #25
Source File: test_periodic_task.py    From networking-odl with Apache License 2.0 5 votes vote down vote up
def test_context_is_passed_as_args(self, _):
        operation = mock.MagicMock()
        operation.__name__ = 'test'
        self.thread.register_operation(operation)

        self.thread.execute_ops(forced=True)

        # This tests that only ONE args is passed, and no kwargs
        operation.assert_called_with(mock.ANY)

        # This tests that it's a context
        kall = operation.call_args
        args, kwargs = kall
        self.assertIsInstance(args[0], context.Context) 
Example #26
Source File: test_bagpipe.py    From networking-bgpvpn with Apache License 2.0 5 votes vote down vote up
def setUp(self, plugin=None,
              driver=('networking_bgpvpn.neutron.services.service_drivers.'
                      'bagpipe.bagpipe.BaGPipeBGPVPNDriver')):
        self.mocked_rpc = mock.patch(
            'networking_bagpipe.agent.bgpvpn.rpc_client'
            '.BGPVPNAgentNotifyApi').start().return_value

        self.mock_attach_rpc = self.mocked_rpc.attach_port_on_bgpvpn
        self.mock_detach_rpc = self.mocked_rpc.detach_port_from_bgpvpn
        self.mock_update_rpc = self.mocked_rpc.update_bgpvpn
        self.mock_delete_rpc = self.mocked_rpc.delete_bgpvpn

        mock.patch(
            'neutron_lib.rpc.get_client').start().return_value

        if not plugin:
            plugin = '%s.%s' % (__name__, TestCorePluginWithAgents.__name__)

        super(TestBagpipeCommon, self).setUp(service_provider=driver,
                                             core_plugin=plugin)

        self.ctxt = n_context.Context('fake_user', self._tenant_id)

        n_dict = {"name": "netfoo",
                  "tenant_id": self._tenant_id,
                  "admin_state_up": True,
                  "router:external": True,
                  "shared": True}

        self.external_net = {'network':
                             self.plugin.create_network(self.ctxt,
                                                        {'network': n_dict})} 
Example #27
Source File: test_l3_router_plugin.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def test_create_floatingip_with_normal_user(self):
        normal_context = nctx.Context(is_admin=False, overwrite=False)
        kwargs = {'arg_list': ('router:external',),
                  'router:external': True}
        with self.network(**kwargs) as n:
            with self.subnet(network=n):
                floatingip = self.l3p.create_floatingip(
                    normal_context,
                    {'floatingip': {'floating_network_id': n['network']['id'],
                                    'tenant_id': n['network']['tenant_id']}})
                self.assertTrue(floatingip) 
Example #28
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_neutron_context_create(self):
        ctx = context.Context('user_id', 'tenant_id')
        self.assertEqual('user_id', ctx.user_id)
        self.assertEqual('tenant_id', ctx.project_id)
        self.assertEqual('tenant_id', ctx.tenant_id)
        request_id = ctx.request_id
        if isinstance(request_id, bytes):
            request_id = request_id.decode('utf-8')
        self.assertThat(request_id, matchers.StartsWith('req-'))
        self.assertEqual('user_id', ctx.user)
        self.assertEqual('tenant_id', ctx.tenant)
        self.assertIsNone(ctx.user_name)
        self.assertIsNone(ctx.tenant_name)
        self.assertIsNone(ctx.project_name)
        self.assertIsNone(ctx.auth_token) 
Example #29
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_neutron_context_getter_setter(self):
        ctx = context.Context('Anakin', 'Skywalker')
        self.assertEqual('Anakin', ctx.user_id)
        self.assertEqual('Skywalker', ctx.tenant_id)
        ctx.user_id = 'Darth'
        ctx.tenant_id = 'Vader'
        self.assertEqual('Darth', ctx.user_id)
        self.assertEqual('Vader', ctx.tenant_id) 
Example #30
Source File: test_context.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_neutron_context_create_with_name(self):
        ctx = context.Context('user_id', 'tenant_id',
                              tenant_name='tenant_name', user_name='user_name')
        # Check name is set
        self.assertEqual('user_name', ctx.user_name)
        self.assertEqual('tenant_name', ctx.tenant_name)
        self.assertEqual('tenant_name', ctx.project_name)
        # Check user/tenant contains its ID even if user/tenant_name is passed
        self.assertEqual('user_id', ctx.user)
        self.assertEqual('tenant_id', ctx.tenant)