Allow class methods to be used as a field source

This commit is contained in:
James Pollock 2017-01-27 21:16:05 +00:00
parent 02eb6856ed
commit f728542ce7
2 changed files with 10 additions and 1 deletions

View File

@ -13,7 +13,7 @@ base_type = type
def source_resolver(source, root, args, context, info): def source_resolver(source, root, args, context, info):
resolved = getattr(root, source, None) resolved = getattr(root, source, None)
if inspect.isfunction(resolved): if inspect.isfunction(resolved) or inspect.ismethod(resolved):
return resolved() return resolved()
return resolved return resolved

View File

@ -10,6 +10,9 @@ class MyInstance(object):
value = 'value' value = 'value'
value_func = staticmethod(lambda: 'value_func') value_func = staticmethod(lambda: 'value_func')
def value_method(self):
return 'value_method'
def test_field_basic(): def test_field_basic():
MyType = object() MyType = object()
@ -76,6 +79,12 @@ def test_field_source_func():
assert field.resolver(MyInstance(), {}, None, None) == MyInstance.value_func() assert field.resolver(MyInstance(), {}, None, None) == MyInstance.value_func()
def test_field_source_method():
MyType = object()
field = Field(MyType, source='value_method')
assert field.resolver(MyInstance(), {}, None, None) == MyInstance().value_method()
def test_field_source_as_argument(): def test_field_source_as_argument():
MyType = object() MyType = object()
field = Field(MyType, source=String()) field = Field(MyType, source=String())