From 9ecd5995b6c598cee931087bf13fdd166f404034 Mon Sep 17 00:00:00 2001 From: Kiran Pawar Date: Thu, 29 Sep 2022 08:40:30 +0000 Subject: [PATCH] Use oslo_context.from_dict() for context generation Use RequestContext.from_dict in oslo_context to generate context, and add/update needed attr such as user_id, tenant_id, tenant_name and timestamp. Closes-bug: #1933802 Change-Id: I0527eb5fa8d32d97ca45e44d1b154b6529b3f847 --- neutron_lib/context.py | 16 +++++++--------- neutron_lib/tests/unit/test_context.py | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/neutron_lib/context.py b/neutron_lib/context.py index 7c9d38188..10f88258d 100644 --- a/neutron_lib/context.py +++ b/neutron_lib/context.py @@ -106,15 +106,13 @@ class ContextBase(oslo_context.RequestContext): @classmethod def from_dict(cls, values): - return cls(user_id=values.get('user_id', values.get('user')), - tenant_id=values.get('tenant_id', values.get('project_id')), - is_admin=values.get('is_admin'), - roles=values.get('roles'), - timestamp=values.get('timestamp'), - request_id=values.get('request_id'), - tenant_name=values.get('tenant_name'), - user_name=values.get('user_name'), - auth_token=values.get('auth_token')) + cls_obj = super().from_dict(values) + if values.get('timestamp'): + cls_obj.timestamp = values['timestamp'] + cls_obj.user_id = values.get('user_id', values.get('user')) + cls_obj.tenant_id = values.get('tenant_id', values.get('project_id')) + cls_obj.tenant_name = values.get('tenant_name') + return cls_obj def elevated(self): """Return a version of this context with admin flag set.""" diff --git a/neutron_lib/tests/unit/test_context.py b/neutron_lib/tests/unit/test_context.py index e63b2ff8f..ec5f24129 100644 --- a/neutron_lib/tests/unit/test_context.py +++ b/neutron_lib/tests/unit/test_context.py @@ -87,6 +87,27 @@ class TestNeutronContext(_base.BaseTestCase): self.assertEqual(owner['user_id'], ctx.user_id) self.assertEqual(owner['tenant_id'], ctx.tenant_id) + def test_neutron_context_from_dict_validate(self): + ctx = context.Context(user_id='user_id1', + user_name='user', + tenant_id='tenant_id1', + tenant_name='project1', + request_id='request_id1', + auth_token='auth_token1') + values = {'user_id': 'user_id1', + 'user_name': 'user', + 'tenant_id': 'tenant_id1', + 'tenant_name': 'project1', + 'request_id': 'request_id1', + 'auth_token': 'auth_token1'} + ctx2 = context.Context.from_dict(values) + + ctx_dict = ctx.to_dict() + ctx_dict.pop('timestamp') + ctx2_dict = ctx2.to_dict() + ctx2_dict.pop('timestamp') + self.assertEqual(ctx_dict, ctx2_dict) + def test_neutron_context_to_dict(self): ctx = context.Context('user_id', 'tenant_id') ctx_dict = ctx.to_dict()