Skip to content
Myr

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

1 file+18 added−5 removed

modified:tests/test_options.py+18 added-5 removed
1 unmodified line
2import os3import re4import sys5import tempfile6from typing import Literal78if sys.version_info < (3, 11):9 enum.StrEnum = enum.Enum # type: ignore[assignment]10
1699 unmodified lines
1710 with pytest.warns(UserWarning):1711 runner.invoke(cli, [])171217131713NO_CONFIG = object()1714"""A sentinel value to indicate no configuration file is provided."""1714OBJECT_SENTINEL = object()1715"""An object-based sentinel value."""171617171718class EnumSentinel(enum.Enum):1719 FALSY_SENTINEL = object()17201721 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 False172617271728# 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 lines
1790 # --config is passed last and overrides the --no-config option.1791 (["--no-config", "--config", "foo.conf"], "foo.conf"),1792 ),1793)1781def test_dual_options_custom_type_sentinel_flag_value(runner, args, expected):1794def 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 lines
1803 class ConfigParamType(click.ParamType):1804 """A custom type that accepts a file path or a sentinel value."""18051806 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 )18131814 @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)18191820 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:
236 unmodified lines