From 4c72942b95eadb6c1035b4d42f5e1e5196164a06 Mon Sep 17 00:00:00 2001 From: Syrus Akbary Date: Sat, 17 Dec 2016 16:58:01 -0800 Subject: [PATCH] Allow custom mounted classes --- graphene/types/mountedtype.py | 6 ++- graphene/types/tests/test_mountedtype.py | 60 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 graphene/types/tests/test_mountedtype.py diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index e2d0b7a3..3833646a 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -4,6 +4,8 @@ from .unmountedtype import UnmountedType class MountedType(OrderedType): + _mount_cls_override = None + @classmethod def mount(cls, unmounted): # noqa: N802 ''' @@ -13,7 +15,9 @@ class MountedType(OrderedType): '{} can\'t mount {}' ).format(cls.__name__, repr(unmounted)) - return cls( + mount_cls = cls._mount_cls_override or cls + + return mount_cls( unmounted.get_type(), *unmounted.args, _creation_counter=unmounted.creation_counter, diff --git a/graphene/types/tests/test_mountedtype.py b/graphene/types/tests/test_mountedtype.py new file mode 100644 index 00000000..de305a91 --- /dev/null +++ b/graphene/types/tests/test_mountedtype.py @@ -0,0 +1,60 @@ +import pytest + +from ..mountedtype import MountedType +from ..field import Field +from ..objecttype import ObjectType +from ..scalars import String + + +class CustomField(Field): + def __init__(self, *args, **kwargs): + self.metadata = kwargs.pop('metadata', None) + super(CustomField, self).__init__(*args, **kwargs) + + +def test_mounted_type(): + unmounted = String() + mounted = Field.mount(unmounted) + assert isinstance(mounted, Field) + assert mounted.type == String + + +def test_mounted_type_custom(): + unmounted = String(metadata={'hey': 'yo!'}) + mounted = CustomField.mount(unmounted) + assert isinstance(mounted, CustomField) + assert mounted.type == String + assert mounted.metadata == {'hey': 'yo!'} + + +@pytest.yield_fixture +def custom_field(): + # We set the override + Field._mount_cls_override = CustomField + + # Run the test + yield CustomField + + # Remove the class override (back to the original state) + Field._mount_cls_override = None + + +def test_mounted_type_overrided(custom_field): + # This function is using the custom_field yield fixture + + unmounted = String(metadata={'hey': 'yo!'}) + mounted = Field.mount(unmounted) + assert isinstance(mounted, CustomField) + assert mounted.type == String + assert mounted.metadata == {'hey': 'yo!'} + + +def test_mounted_type_overrided(custom_field): + # This function is using the custom_field yield fixture + + class Query(ObjectType): + test = String(metadata={'other': 'thing'}) + + test_field = Query._meta.fields['test'] + assert isinstance(test_field, CustomField) + assert test_field.metadata == {'other': 'thing'}