Agnostic approach to construct context from_dict
Replace the existing argument specified values in from_dict() method to be argument agnostic for any future arguments. Based from version found in Solum. All current boolean values match instantiation defaults. Change-Id: I17c76881aa662de7ff245b3f6bfca309896ddf24
This commit is contained in:
parent
01aaeae060
commit
0327388695
|
@ -26,6 +26,7 @@ context or provide additional information in their specific WSGI pipeline
|
|||
or logging context.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import itertools
|
||||
import threading
|
||||
import uuid
|
||||
|
@ -114,20 +115,13 @@ class RequestContext(object):
|
|||
return values
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, ctx):
|
||||
def from_dict(cls, values):
|
||||
"""Construct a context object from a provided dictionary."""
|
||||
return cls(
|
||||
auth_token=ctx.get("auth_token"),
|
||||
user=ctx.get("user"),
|
||||
tenant=ctx.get("tenant"),
|
||||
domain=ctx.get("domain"),
|
||||
user_domain=ctx.get("user_domain"),
|
||||
project_domain=ctx.get("project_domain"),
|
||||
is_admin=ctx.get("is_admin", False),
|
||||
read_only=ctx.get("read_only", False),
|
||||
show_deleted=ctx.get("show_deleted", False),
|
||||
request_id=ctx.get("request_id"),
|
||||
resource_uuid=ctx.get("resource_uuid"))
|
||||
allowed = [arg for arg in
|
||||
inspect.getargspec(RequestContext.__init__).args
|
||||
if arg != 'self']
|
||||
kwargs = {k: v for (k, v) in values.items() if k in allowed}
|
||||
return cls(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_environ(cls, environ, **kwargs):
|
||||
|
|
|
@ -104,6 +104,23 @@ class ContextTest(test_base.BaseTestCase):
|
|||
self.assertEqual("request1", ctx.request_id)
|
||||
self.assertEqual("instance1", ctx.resource_uuid)
|
||||
|
||||
def test_from_dict_unknown_keys(self):
|
||||
dct = {
|
||||
"auth_token": "token1",
|
||||
"user": "user1",
|
||||
"read_only": True,
|
||||
"roles": "role1,role2,role3", # future review provides this
|
||||
"color": "red",
|
||||
"unknown": ""
|
||||
}
|
||||
ctx = context.RequestContext.from_dict(dct)
|
||||
self.assertEqual("token1", ctx.auth_token)
|
||||
self.assertEqual("user1", ctx.user)
|
||||
self.assertIsNone(ctx.tenant)
|
||||
self.assertFalse(ctx.is_admin)
|
||||
self.assertTrue(ctx.read_only)
|
||||
self.assertRaises(KeyError, lambda: ctx.__dict__['color'])
|
||||
|
||||
def test_is_user_context(self):
|
||||
self.assertFalse(context.is_user_context(None))
|
||||
ctx = context.RequestContext(is_admin=True)
|
||||
|
|
Loading…
Reference in New Issue