Add get_context helper method

The context.get_admin_context is used in places that it's not necessary,
and that's likely because there's no helper method to retrieve a non
admin context. This adds such a helper method and adds a note to
get_admin_context warning that it's not usually the right choice.

Change-Id: I2e6a2efa4bcdf3f8688897972a6cf8a5af3f90d6
This commit is contained in:
Andrew Laski 2016-09-28 13:50:36 -04:00
parent 33dd4d827b
commit 5fe5185443
2 changed files with 33 additions and 0 deletions

View File

@ -286,7 +286,25 @@ class RequestContext(context.RequestContext):
return "<Context %s>" % self.to_dict()
def get_context():
"""A helper method to get a blank context.
Note that overwrite is False here so this context will not update the
greenthread-local stored context that is used when logging.
"""
return RequestContext(user_id=None,
project_id=None,
is_admin=False,
overwrite=False)
def get_admin_context(read_deleted="no"):
# NOTE(alaski): This method should only be used when an admin context is
# necessary for the entirety of the context lifetime. If that's not the
# case please use get_context(), or create the RequestContext manually, and
# use context.elevated() where necessary. Some periodic tasks may use
# get_admin_context so that their database calls are not filtered on
# project_id.
return RequestContext(user_id=None,
project_id=None,
is_admin=True,

View File

@ -146,6 +146,15 @@ class ContextTestCase(test.NoDBTestCase):
overwrite=False)
self.assertIs(o_context.get_current(), ctx1)
def test_get_context_no_overwrite(self):
# If there is already a context in the cache creating another context
# should not overwrite it.
ctx1 = context.RequestContext('111',
'222',
overwrite=True)
context.get_context()
self.assertIs(ctx1, o_context.get_current())
def test_admin_no_overwrite(self):
# If there is already a context in the cache creating an admin
# context will not overwrite it.
@ -290,3 +299,9 @@ class ContextTestCase(test.NoDBTestCase):
with context.target_cell(ctxt, mapping):
self.assertEqual(ctxt.db_connection, mock.sentinel.cm)
self.assertEqual(mock.sentinel.db_conn, ctxt.db_connection)
def test_get_context(self):
ctxt = context.get_context()
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.project_id)
self.assertFalse(ctxt.is_admin)