From: Robert Coup Date: Thu, 5 May 2022 22:01:28 +0000 (+0100) Subject: Secret: add a __bool__ implementation (#1625) X-Git-Tag: 0.20.1~13 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=beb8943eef8618ccadacd24e8b4d41c7a7456f51;p=thirdparty%2Fstarlette.git Secret: add a __bool__ implementation (#1625) Allows using `if settings.A_SECRET:` to check for empty/None without needing to cast it to a str. --- diff --git a/starlette/datastructures.py b/starlette/datastructures.py index 59863282..5e724d19 100644 --- a/starlette/datastructures.py +++ b/starlette/datastructures.py @@ -206,6 +206,9 @@ class Secret: def __str__(self) -> str: return self._value + def __bool__(self) -> bool: + return bool(self._value) + class CommaSeparatedStrings(Sequence): def __init__(self, value: typing.Union[str, typing.Sequence[str]]): diff --git a/tests/test_config.py b/tests/test_config.py index cfe908bc..5ba7aefd 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -28,6 +28,8 @@ def test_config(tmpdir, monkeypatch): REQUEST_TIMEOUT = config("REQUEST_TIMEOUT", cast=int, default=10) REQUEST_HOSTNAME = config("REQUEST_HOSTNAME") SECRET_KEY = config("SECRET_KEY", cast=Secret) + UNSET_SECRET = config("UNSET_SECRET", cast=Secret, default=None) + EMPTY_SECRET = config("EMPTY_SECRET", cast=Secret, default="") assert config("BOOL_AS_INT", cast=bool) is False assert config("BOOL_AS_INT", cast=cast_to_int) == 0 assert config("DEFAULTED_BOOL", cast=cast_to_int, default=True) == 1 @@ -40,6 +42,9 @@ def test_config(tmpdir, monkeypatch): assert REQUEST_HOSTNAME == "example.com" assert repr(SECRET_KEY) == "Secret('**********')" assert str(SECRET_KEY) == "12345" + assert bool(SECRET_KEY) + assert not bool(EMPTY_SECRET) + assert not bool(UNSET_SECRET) with pytest.raises(KeyError): config.get("MISSING")