]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Secret: add a __bool__ implementation (#1625)
authorRobert Coup <robert@coup.net.nz>
Thu, 5 May 2022 22:01:28 +0000 (23:01 +0100)
committerGitHub <noreply@github.com>
Thu, 5 May 2022 22:01:28 +0000 (00:01 +0200)
Allows using `if settings.A_SECRET:` to check for empty/None without needing to
cast it to a str.

starlette/datastructures.py
tests/test_config.py

index 59863282ae7afa140d22f8da0ac4c3ce77846ad1..5e724d19da217612109b7dd1635994839ce745bb 100644 (file)
@@ -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]]):
index cfe908bc0dfb4829e4059202c4714679aecf7fc3..5ba7aefd78e159cf7a7059ef9f33c43aa7cd5bda 100644 (file)
@@ -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")