Skip to content

Commit ae23a11

Browse files
committed
Merge pull request #139 from graphql-python/features/enum-improvements
Enum Improvements
2 parents 13ca2fe + e1a693e commit ae23a11

File tree

8 files changed

+43
-8
lines changed

8 files changed

+43
-8
lines changed

graphene/contrib/django/converter.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,24 @@
22

33
from ...core.types.scalars import ID, Boolean, Float, Int, String
44
from ...core.classtypes.enum import Enum
5+
from ...utils import to_const
56
from .compat import RelatedObject, UUIDField
67
from .utils import get_related_model, import_single_dispatch
78

89
singledispatch = import_single_dispatch()
910

1011

12+
def convert_choices(choices):
13+
for value, name in choices:
14+
yield to_const(name), value
15+
16+
1117
def convert_django_field_with_choices(field):
1218
choices = getattr(field, 'choices', None)
1319
if choices:
1420
meta = field.model._meta
1521
name = '{}_{}_{}'.format(meta.app_label, meta.object_name, field.name)
16-
return Enum(name.upper(), choices, description=field.help_text)
22+
return Enum(name.upper(), list(convert_choices(choices)), description=field.help_text)
1723
return convert_django_field(field)
1824

1925

graphene/contrib/django/tests/models.py

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ class Article(models.Model):
3030
('es', 'Spanish'),
3131
('en', 'English')
3232
], default='es')
33+
importance = models.IntegerField('Importance', null=True, blank=True,
34+
choices=[(1, u'Very important'), (2, u'Not as important')])
3335

3436
def __str__(self): # __unicode__ on Python 2
3537
return self.headline

graphene/contrib/django/tests/test_converter.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,8 @@ class Meta:
103103
assert issubclass(graphene_type, graphene.Enum)
104104
assert graphene_type._meta.type_name == 'TEST_TRANSLATEDMODEL_LANGUAGE'
105105
assert graphene_type._meta.description == 'Language'
106-
assert graphene_type.__enum__.__members__['es'].value == 'Spanish'
107-
assert graphene_type.__enum__.__members__['en'].value == 'English'
106+
assert graphene_type.__enum__.__members__['SPANISH'].value == 'es'
107+
assert graphene_type.__enum__.__members__['ENGLISH'].value == 'en'
108108

109109

110110
def test_should_float_convert_float():

graphene/core/classtypes/enum.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from graphql.core.type import GraphQLEnumType, GraphQLEnumValue
33

44
from .base import ClassTypeMeta, ClassType
5+
from ..types.base import MountedType
56
from ...utils.enum import Enum as PyEnum
67

78

@@ -17,7 +18,12 @@ def construct(cls, bases, attrs):
1718
attrs[k] = v.value
1819
return super(EnumMeta, cls).construct(bases, attrs)
1920

20-
def __call__(cls, name, names=None, description=None):
21+
def __call__(cls, *args, **kwargs):
22+
if cls is Enum:
23+
return cls.create_enum(*args, **kwargs)
24+
return super(EnumMeta, cls).__call__(*args, **kwargs)
25+
26+
def create_enum(cls, name, names=None, description=None):
2127
attrs = {
2228
'__enum__': PyEnum(name, names)
2329
}
@@ -26,7 +32,7 @@ def __call__(cls, name, names=None, description=None):
2632
return type(name, (Enum,), attrs)
2733

2834

29-
class Enum(six.with_metaclass(EnumMeta, ClassType)):
35+
class Enum(six.with_metaclass(EnumMeta, ClassType, MountedType)):
3036

3137
class Meta:
3238
abstract = True

graphene/core/classtypes/tests/test_enum.py

+12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from graphene.core.schema import Schema
44

55
from ..enum import Enum
6+
from ..objecttype import ObjectType
67

78

89
def test_enum():
@@ -35,3 +36,14 @@ def test_enum_values():
3536
assert RGB.RED == 0
3637
assert RGB.GREEN == 1
3738
assert RGB.BLUE == 2
39+
40+
41+
def test_enum_instance():
42+
RGB = Enum('RGB', dict(RED=0, GREEN=1, BLUE=2))
43+
RGB_field = RGB(description='RGB enum description')
44+
45+
class ObjectWithColor(ObjectType):
46+
color = RGB_field
47+
48+
object_field = ObjectWithColor._meta.fields_map['color']
49+
assert object_field.description == 'RGB enum description'

graphene/utils/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .str_converters import to_camel_case, to_snake_case
1+
from .str_converters import to_camel_case, to_snake_case, to_const
22
from .proxy_snake_dict import ProxySnakeDict
33
from .caching import cached_property, memoize
44
from .maybe_func import maybe_func
@@ -7,6 +7,6 @@
77
from .lazylist import LazyList
88

99

10-
__all__ = ['to_camel_case', 'to_snake_case', 'ProxySnakeDict',
10+
__all__ = ['to_camel_case', 'to_snake_case', 'to_const', 'ProxySnakeDict',
1111
'cached_property', 'memoize', 'maybe_func', 'enum_to_graphql_enum',
1212
'resolve_only_args', 'LazyList']

graphene/utils/str_converters.py

+4
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,7 @@ def to_camel_case(snake_str):
1515
def to_snake_case(name):
1616
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
1717
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
18+
19+
20+
def to_const(string):
21+
return re.sub('[\W|^(?=\d)]+', '_', string).upper()

graphene/utils/tests/test_str_converter.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from ..str_converters import to_camel_case, to_snake_case
1+
# coding: utf-8
2+
from ..str_converters import to_camel_case, to_snake_case, to_const
23

34

45
def test_snake_case():
@@ -15,3 +16,7 @@ def test_camel_case():
1516
assert to_camel_case('snakes_on_a_plane') == 'snakesOnAPlane'
1617
assert to_camel_case('snakes_on_a__plane') == 'snakesOnA_Plane'
1718
assert to_camel_case('i_phone_hysteria') == 'iPhoneHysteria'
19+
20+
21+
def test_to_const():
22+
assert to_const('snakes $1. on a "#plane') == 'SNAKES_ON_A_PLANE'

0 commit comments

Comments
 (0)