From ef4aecec064fb8ff6dce9104926bf2177906ac5a Mon Sep 17 00:00:00 2001 From: Philip Couling Date: Tue, 13 Feb 2024 11:26:56 +0000 Subject: [PATCH] Fixed bug with is_flag and type inference --- dataclass_click/dataclass_click.py | 2 +- tests/test_end_to_end.py | 36 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/dataclass_click/dataclass_click.py b/dataclass_click/dataclass_click.py index d81ec39..9e24f96 100644 --- a/dataclass_click/dataclass_click.py +++ b/dataclass_click/dataclass_click.py @@ -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: diff --git a/tests/test_end_to_end.py b/tests/test_end_to_end.py index 542f945..e7c36ad 100644 --- a/tests/test_end_to_end.py +++ b/tests/test_end_to_end.py @@ -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"""