Check falsy sentinels
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent c498ced · Browse files · 1 file·+18 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+18 added−5 removed
- tests:+18 added−5 removed
Provenance
- Commit
f9ec2ea- Tree
9117947- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
c498ced
1 file changed+18 added−5 removed
modified:tests/test_options.py+18 added-5 removed
1 unmodified line2 import os3 import re4 import sys5 import tempfile6+from typing import Literal7 8 if sys.version_info < (3, 11):9 enum.StrEnum = enum.Enum # type: ignore[assignment]10 1699 unmodified lines1710 with pytest.warns(UserWarning):1711 runner.invoke(cli, [])1712 1713 1713-NO_CONFIG = object()1714-"""A sentinel value to indicate no configuration file is provided."""1714+OBJECT_SENTINEL = object()1715+"""An object-based sentinel value."""1716 1717 1718+class EnumSentinel(enum.Enum):1719+ FALSY_SENTINEL = object()1720+1721+ def __bool__(self) -> Literal[False]:1722+ """Force the sentinel to be falsy to make sure it is not caught by Click internal1723+ implementation.1724+ """1725+ return False1726+1727+1728+# Any kind of sentinel value is recognized by Click as a valid flag value.1729+@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1730 @pytest.mark.parametrize(1731 ("args", "expected"),1732 (1733 # Option default to None.56 unmodified lines1790 # --config is passed last and overrides the --no-config option.1791 (["--no-config", "--config", "foo.conf"], "foo.conf"),1792 ),1793 )1781-def test_dual_options_custom_type_sentinel_flag_value(runner, args, expected):1794+def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1795 """Check that an object-based sentinel, used as a flag value, is returned as-is1796 to a custom type that is shared by two options, competing for the same variable1797 name.1798 4 unmodified lines1803 class ConfigParamType(click.ParamType):1804 """A custom type that accepts a file path or a sentinel value."""1805 1806 def convert(self, value, param, ctx):1794- if value is NO_CONFIG:1807+ if value is sentinel:1808 return "No configuration file provided."1809 else:1810 return click.Path(exists=True, dir_okay=False).convert(1811 value, param, ctx1812 )1813 1814 @click.command()1815 @click.option("-c", "--config", type=ConfigParamType())1803- @click.option("--no-config", "config", flag_value=NO_CONFIG, type=ConfigParamType())1816+ @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1817 def main(config):1818 click.echo(repr(config), nl=False)1819 1820 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:236 unmodified lines