Skip to content

Commit

Permalink
Escape enum values which are python keywords
Browse files Browse the repository at this point in the history
  • Loading branch information
mat-sop committed Sep 22, 2023
1 parent 23c704d commit 7b10d5a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## UNRELEASED

- Fixed generating results for nullable fields with nullable directives.
- Added escaping of enum values which are Python keywords by appending `_` to them.


## 0.9.0 (2023-09-11)
Expand Down
13 changes: 8 additions & 5 deletions ariadne_codegen/client_generators/enums.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ast
from keyword import iskeyword
from typing import List, Optional, cast

from graphql import GraphQLEnumType, GraphQLSchema
Expand Down Expand Up @@ -48,12 +49,14 @@ def _filter_enum_types(self) -> List[GraphQLEnumType]:
]

def _parse_enum_definition(self, definition: GraphQLEnumType) -> ast.ClassDef:
fields = [
generate_assign([val_name], generate_constant(val_def.value), lineno)
for lineno, (val_name, val_def) in enumerate(
definition.values.items(), start=1
fields: List[ast.stmt] = []
for lineno, (val_name, val_def) in enumerate(
definition.values.items(), start=1
):
name = val_name if not iskeyword(val_name) else val_name + "_"
fields.append(
generate_assign([name], generate_constant(val_def.value), lineno)
)
]

class_def = generate_class_def(
name=definition.name,
Expand Down
8 changes: 8 additions & 0 deletions tests/client_generators/test_enums_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ def test_generate_returns_module_with_enum_class_definition():
enum CustomEnum {
VALUE1
VALUE2
from
import
}
"""
expected_class_def = ast.ClassDef(
Expand All @@ -45,6 +47,12 @@ def test_generate_returns_module_with_enum_class_definition():
ast.Assign(
targets=[ast.Name(id="VALUE2")], value=ast.Constant(value="VALUE2")
),
ast.Assign(
targets=[ast.Name(id="from_")], value=ast.Constant(value="from")
),
ast.Assign(
targets=[ast.Name(id="import_")], value=ast.Constant(value="import")
),
],
)
generator = EnumsGenerator(schema=build_ast_schema(parse(schema_str)))
Expand Down

0 comments on commit 7b10d5a

Please sign in to comment.