Allow access to reflection 'get_members'

This also adds some basic tests to ensure the get*members
functions continue to work as expected under basic situations.

Change-Id: Iad9821dca01839b3d9662a16be68225ce99c432c
This commit is contained in:
Joshua Harlow 2015-07-17 15:53:37 -07:00 committed by Joshua Harlow
parent dc23ed6cc3
commit b7130e0a5e
2 changed files with 34 additions and 2 deletions

View File

@ -30,7 +30,7 @@ except AttributeError:
_BUILTIN_MODULES = ('builtins', '__builtin__', '__builtins__', 'exceptions')
def _get_members(obj, exclude_hidden):
def get_members(obj, exclude_hidden=True):
"""Yields the members of an object, filtering by hidden/not hidden."""
for (name, value) in inspect.getmembers(obj):
if name.startswith("_") and exclude_hidden:
@ -40,7 +40,8 @@ def _get_members(obj, exclude_hidden):
def get_member_names(obj, exclude_hidden=True):
"""Get all the member names for a object."""
return [name for (name, _obj) in _get_members(obj, exclude_hidden)]
return [name for (name, _obj) in
get_members(obj, exclude_hidden=exclude_hidden)]
def get_class_name(obj, fully_qualified=True):

View File

@ -50,6 +50,14 @@ def function_with_kwargs(a, b, **kwargs):
pass
class TestObject(object):
def _hello(self):
pass
def hi(self):
pass
class Class(object):
def method(self, c, d):
@ -74,6 +82,29 @@ class ClassWithInit(object):
pass
class MemberGetTest(test_base.BaseTestCase):
def test_get_members_exclude_hidden(self):
obj = TestObject()
members = list(reflection.get_members(obj, exclude_hidden=True))
self.assertEqual(1, len(members))
def test_get_members_no_exclude_hidden(self):
obj = TestObject()
members = list(reflection.get_members(obj, exclude_hidden=False))
self.assertGreater(len(members), 1)
def test_get_members_names_exclude_hidden(self):
obj = TestObject()
members = list(reflection.get_member_names(obj, exclude_hidden=True))
self.assertEqual(["hi"], members)
def test_get_members_names_no_exclude_hidden(self):
obj = TestObject()
members = list(reflection.get_member_names(obj, exclude_hidden=False))
members = [member for member in members if not member.startswith("__")]
self.assertEqual(["_hello", "hi"], sorted(members))
class CallbackEqualityTest(test_base.BaseTestCase):
def test_different_simple_callbacks(self):