Skip to content

Commit 43a8e48

Browse files
committed
avoid conflict between uppercase/lowercase enum values
1 parent 3fb5fb2 commit 43a8e48

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

openapi_python_client/parser/properties/enum_property.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,23 @@ def values_from_list(values: list[str] | list[int]) -> dict[str, ValueType]:
187187
"""Convert a list of values into dict of {name: value}, where value can sometimes be None"""
188188
output: dict[str, ValueType] = {}
189189

190+
# We normally would like to make nice-looking Python constant names for enum values, so that "myValue"
191+
# becomes MY_VALUE, etc. However, that won't work if an enum has two values that differ only by case
192+
# (which is allowed in OpenAPI).
193+
use_case_sensitive_names = False
194+
for i, value1 in enumerate(values):
195+
if use_case_sensitive_names:
196+
break
197+
for j, value2 in enumerate(values):
198+
if (
199+
i != j
200+
and isinstance(value1, str)
201+
and isinstance(value2, str)
202+
and value1.upper() == value2.upper()
203+
):
204+
use_case_sensitive_names = True
205+
break
206+
190207
for i, value in enumerate(values):
191208
value = cast(Union[str, int], value)
192209
if isinstance(value, int):
@@ -196,11 +213,14 @@ def values_from_list(values: list[str] | list[int]) -> dict[str, ValueType]:
196213
output[f"VALUE_{value}"] = value
197214
continue
198215
if value and value[0].isalpha():
199-
key = value.upper()
216+
key = value
200217
else:
201218
key = f"VALUE_{i}"
202219
if key in output:
203220
raise ValueError(f"Duplicate key {key} in Enum")
204-
sanitized_key = utils.snake_case(key).upper()
221+
if use_case_sensitive_names:
222+
sanitized_key = utils.sanitize(key.replace(" ", "_"))
223+
else:
224+
sanitized_key = utils.snake_case(key.upper()).upper()
205225
output[sanitized_key] = utils.remove_string_escapes(value)
206226
return output

tests/test_parser/test_properties/test_init.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,19 @@ def test_values_from_list_duplicate(self):
372372
with pytest.raises(ValueError):
373373
EnumProperty.values_from_list(data)
374374

375+
def test_values_from_list_with_case_sensitive_names(self):
376+
from openapi_python_client.parser.properties import EnumProperty
377+
378+
data = ["abc", "123", "ABC", "thing with spaces"]
379+
380+
result = EnumProperty.values_from_list(data)
381+
382+
assert result == {
383+
"abc": "abc",
384+
"VALUE_1": "123",
385+
"ABC": "ABC",
386+
"thing_with_spaces": "thing with spaces",
387+
}
375388

376389
class TestPropertyFromData:
377390
def test_property_from_data_str_enum(self, enum_property_factory, config):

0 commit comments

Comments
 (0)