MCPcopy
hub / github.com/encode/starlette / test_config

Function test_config

tests/test_config.py:40–102  ·  view source on GitHub ↗
(tmpdir: Path, monkeypatch: pytest.MonkeyPatch)

Source from the content-addressed store, hash-verified

38
39
40def test_config(tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
41 path = os.path.join(tmpdir, ".env")
42 with open(path, "w") as file:
43 file.write("# Do not commit to source control\n")
44 file.write("DATABASE_URL=postgres://user:pass@localhost/dbname\n")
45 file.write("REQUEST_HOSTNAME=example.com\n")
46 file.write("SECRET_KEY=12345\n")
47 file.write("BOOL_AS_INT=0\n")
48 file.write("\n")
49 file.write("\n")
50
51 config = Config(path, environ={"DEBUG": "true"})
52
53 def cast_to_int(v: Any) -> int:
54 return int(v)
55
56 DEBUG = config("DEBUG", cast=bool)
57 DATABASE_URL = config("DATABASE_URL", cast=URL)
58 REQUEST_TIMEOUT = config("REQUEST_TIMEOUT", cast=int, default=10)
59 REQUEST_HOSTNAME = config("REQUEST_HOSTNAME")
60 MAIL_HOSTNAME = config("MAIL_HOSTNAME", default=None)
61 SECRET_KEY = config("SECRET_KEY", cast=Secret)
62 UNSET_SECRET = config("UNSET_SECRET", cast=Secret, default=None)
63 EMPTY_SECRET = config("EMPTY_SECRET", cast=Secret, default="")
64 assert config("BOOL_AS_INT", cast=bool) is False
65 assert config("BOOL_AS_INT", cast=cast_to_int) == 0
66 assert config("DEFAULTED_BOOL", cast=cast_to_int, default=True) == 1
67
68 assert DEBUG is True
69 assert DATABASE_URL.path == "/dbname"
70 assert DATABASE_URL.password == "pass"
71 assert DATABASE_URL.username == "user"
72 assert REQUEST_TIMEOUT == 10
73 assert REQUEST_HOSTNAME == "example.com"
74 assert MAIL_HOSTNAME is None
75 assert repr(SECRET_KEY) == "Secret('**********')"
76 assert str(SECRET_KEY) == "12345"
77 assert bool(SECRET_KEY)
78 assert not bool(EMPTY_SECRET)
79 assert not bool(UNSET_SECRET)
80
81 with pytest.raises(KeyError):
82 config.get("MISSING")
83
84 with pytest.raises(ValueError):
85 config.get("DEBUG", cast=int)
86
87 with pytest.raises(ValueError):
88 config.get("REQUEST_HOSTNAME", cast=bool)
89
90 config = Config(Path(path))
91 REQUEST_HOSTNAME = config("REQUEST_HOSTNAME")
92 assert REQUEST_HOSTNAME == "example.com"
93
94 config = Config()
95 monkeypatch.setenv("STARLETTE_EXAMPLE_TEST", "123")
96 monkeypatch.setenv("BOOL_AS_INT", "1")
97 assert config.get("STARLETTE_EXAMPLE_TEST", cast=int) == 123

Callers

nothing calls this directly

Calls 3

getMethod · 0.95
ConfigClass · 0.90
writeMethod · 0.45

Tested by

no test coverage detected