Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix preserving case in enum values #571

Merged
merged 18 commits into from
Mar 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions tests/test_enum_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
Regresion test for
Enum values that differ in case get conflated #570
https://github.com/tiangolo/typer/discussions/570
"""
from enum import Enum

import pytest
import typer
from typer.testing import CliRunner

runner = CliRunner()
app = typer.Typer()


class Case(str, Enum):
UPPER = "CASE"
TITLE = "Case"
LOWER = "case"

def __str__(self) -> str:
return self.value


@app.command()
def enum_case(case: Case):
print(case)


@pytest.mark.parametrize("case", Case)
def test_enum_case(case: Case):
result = runner.invoke(app, [f"{case}"])
assert result.exit_code == 0
assert case in result.output
8 changes: 4 additions & 4 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,13 +618,13 @@ def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:


def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:
lower_val_map = {str(val.value).lower(): val for val in enum}
val_map = {str(val.value): val for val in enum}

def convertor(value: Any) -> Any:
if value is not None:
low = str(value).lower()
if low in lower_val_map:
key = lower_val_map[low]
val = str(value)
if val in val_map:
key = val_map[val]
return enum(key)

return convertor
Expand Down