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

Fixed bug with is_flag and type inference #2

Merged
merged 1 commit into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion dataclass_click/dataclass_click.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def _patch_click_types(
for key, annotation in annotations.items():
hint: typing.Type[Any]
_, hint = _strip_optional(type_hints[key])
if "type" not in annotation.kwargs:
if "type" not in annotation.kwargs and not annotation.kwargs.get("is_flag", False):
if hint in complete_type_inferences:
annotation.kwargs["type"] = complete_type_inferences[hint]
else:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_end_to_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,42 @@ def main(*args, **kwargs):
assert isinstance(results[0][0][0].foo, inferrable_type)


@pytest.mark.parametrize("args", [{}, {"is_flag": False}], ids=["no_args", "is_flag_false"])
def test_type_inference_raises(args: dict[str, Any]):

class UnknownClass:
pass

@dataclass
class Config:
foo: Annotated[UnknownClass, option(**args)]

with pytest.raises(TypeError):

@click.command()
@dataclass_click(Config)
def main(*args, **kwargs):
pass


@pytest.mark.parametrize("args", [{"type": click.INT}, {"is_flag": True}], ids=["type", "is_flag_true"])
def test_types_not_inferred(args: dict[str, Any]):

class UnknownClass:
pass

@dataclass
class Config:
foo: Annotated[UnknownClass, option(**args)]

# Make sure no exception is raised.
# See test_type_inference_raises() for the counter example
@click.command()
@dataclass_click(Config)
def main(*args, **kwargs):
pass


def test_inferred_option_name():
"""Test that the option name can be inferred from the attribute name"""

Expand Down