From bd88f2327ed186d897a6b87ca09d1618faf7f64b Mon Sep 17 00:00:00 2001 From: Syrus Akbary Date: Fri, 1 Apr 2016 23:39:10 -0700 Subject: [PATCH] Added to_const str converter utility --- graphene/utils/__init__.py | 4 ++-- graphene/utils/str_converters.py | 4 ++++ graphene/utils/tests/test_str_converter.py | 8 +++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/graphene/utils/__init__.py b/graphene/utils/__init__.py index 3fcd988c..34e4ad9a 100644 --- a/graphene/utils/__init__.py +++ b/graphene/utils/__init__.py @@ -1,4 +1,4 @@ -from .str_converters import to_camel_case, to_snake_case +from .str_converters import to_camel_case, to_snake_case, to_const from .proxy_snake_dict import ProxySnakeDict from .caching import cached_property, memoize from .maybe_func import maybe_func @@ -7,6 +7,6 @@ from .resolve_only_args import resolve_only_args from .lazylist import LazyList -__all__ = ['to_camel_case', 'to_snake_case', 'ProxySnakeDict', +__all__ = ['to_camel_case', 'to_snake_case', 'to_const', 'ProxySnakeDict', 'cached_property', 'memoize', 'maybe_func', 'enum_to_graphql_enum', 'resolve_only_args', 'LazyList'] diff --git a/graphene/utils/str_converters.py b/graphene/utils/str_converters.py index bb9b2885..3b06ee05 100644 --- a/graphene/utils/str_converters.py +++ b/graphene/utils/str_converters.py @@ -15,3 +15,7 @@ def to_camel_case(snake_str): def to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + + +def to_const(string): + return re.sub('[\W|^(?=\d)]+', '_', string).upper() diff --git a/graphene/utils/tests/test_str_converter.py b/graphene/utils/tests/test_str_converter.py index 19f691af..622acfec 100644 --- a/graphene/utils/tests/test_str_converter.py +++ b/graphene/utils/tests/test_str_converter.py @@ -1,4 +1,5 @@ -from ..str_converters import to_camel_case, to_snake_case +# coding: utf-8 +from ..str_converters import to_camel_case, to_snake_case, to_const def test_snake_case(): @@ -15,3 +16,8 @@ def test_camel_case(): assert to_camel_case('snakes_on_a_plane') == 'snakesOnAPlane' assert to_camel_case('snakes_on_a__plane') == 'snakesOnA_Plane' assert to_camel_case('i_phone_hysteria') == 'iPhoneHysteria' + + +def test_to_const(): + assert to_const('snakes on a plane') == 'SNAKES_ON_A_PLANE' + assert to_const('weirdñáunicode$# word') == 'WEIRD_UNICODE_WORD'