2018-12-05 11:53:38 +00:00
|
|
|
import os
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
2018-12-05 12:28:18 +00:00
|
|
|
from starlette.config import Config, Environ, EnvironError
|
2019-02-19 12:54:57 +00:00
|
|
|
from starlette.datastructures import URL, Secret
|
2018-12-05 11:53:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_config(tmpdir):
|
|
|
|
path = os.path.join(tmpdir, ".env")
|
|
|
|
with open(path, "w") as file:
|
|
|
|
file.write("# Do not commit to source control\n")
|
|
|
|
file.write(
|
|
|
|
"DATABASE_URL=postgres://username:password@localhost/database_name\n"
|
|
|
|
)
|
|
|
|
file.write("REQUEST_HOSTNAME=example.com\n")
|
2018-12-05 12:38:54 +00:00
|
|
|
file.write("SECRET_KEY=12345\n")
|
2018-12-05 11:53:38 +00:00
|
|
|
file.write("\n")
|
|
|
|
file.write("\n")
|
|
|
|
|
|
|
|
config = Config(path, environ={"DEBUG": "true"})
|
|
|
|
|
2018-12-05 16:38:45 +00:00
|
|
|
DEBUG = config("DEBUG", cast=bool)
|
2019-02-19 12:54:57 +00:00
|
|
|
DATABASE_URL = config("DATABASE_URL", cast=URL)
|
2018-12-05 16:38:45 +00:00
|
|
|
REQUEST_TIMEOUT = config("REQUEST_TIMEOUT", cast=int, default=10)
|
|
|
|
REQUEST_HOSTNAME = config("REQUEST_HOSTNAME")
|
|
|
|
SECRET_KEY = config("SECRET_KEY", cast=Secret)
|
2018-12-05 11:53:38 +00:00
|
|
|
|
|
|
|
assert DEBUG is True
|
2019-02-19 12:54:57 +00:00
|
|
|
assert DATABASE_URL.path == "/database_name"
|
2018-12-05 11:53:38 +00:00
|
|
|
assert REQUEST_TIMEOUT == 10
|
|
|
|
assert REQUEST_HOSTNAME == "example.com"
|
2018-12-05 12:38:54 +00:00
|
|
|
assert repr(SECRET_KEY) == "Secret('**********')"
|
|
|
|
assert str(SECRET_KEY) == "12345"
|
2018-12-05 11:53:38 +00:00
|
|
|
|
|
|
|
with pytest.raises(KeyError):
|
|
|
|
config.get("MISSING")
|
|
|
|
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
config.get("DEBUG", cast=int)
|
|
|
|
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
config.get("REQUEST_HOSTNAME", cast=bool)
|
|
|
|
|
|
|
|
os.environ["STARLETTE_EXAMPLE_TEST"] = "123"
|
|
|
|
config = Config()
|
|
|
|
assert config.get("STARLETTE_EXAMPLE_TEST", cast=int) == 123
|
2018-12-05 12:28:18 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_environ():
|
|
|
|
environ = Environ()
|
|
|
|
|
|
|
|
# We can mutate the environ at this point.
|
|
|
|
environ["TESTING"] = "True"
|
|
|
|
environ["GONE"] = "123"
|
|
|
|
del environ["GONE"]
|
|
|
|
|
|
|
|
# We can read the environ.
|
|
|
|
assert environ["TESTING"] == "True"
|
|
|
|
assert "GONE" not in environ
|
|
|
|
|
|
|
|
# We cannot mutate these keys now that we've read them.
|
|
|
|
with pytest.raises(EnvironError):
|
|
|
|
environ["TESTING"] = "False"
|
|
|
|
|
|
|
|
with pytest.raises(EnvironError):
|
|
|
|
del environ["GONE"]
|
|
|
|
|
|
|
|
# Test coverage of abstract methods for MutableMapping.
|
|
|
|
environ = Environ()
|
|
|
|
assert list(iter(environ)) == list(iter(os.environ))
|
|
|
|
assert len(environ) == len(os.environ)
|