forked from encode/uvicorn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_config.py
334 lines (249 loc) · 9.3 KB
/
test_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import json
import logging
import os
import socket
from copy import deepcopy
import pytest
import yaml
from uvicorn.config import LOGGING_CONFIG, Config
from uvicorn.middleware.debug import DebugMiddleware
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from uvicorn.middleware.wsgi import WSGIMiddleware
from uvicorn.protocols.http.h11_impl import H11Protocol
@pytest.fixture
def mocked_logging_config_module(mocker):
return mocker.patch("logging.config")
@pytest.fixture(scope="function")
def logging_config():
return deepcopy(LOGGING_CONFIG)
@pytest.fixture
def json_logging_config(logging_config):
return json.dumps(logging_config)
@pytest.fixture
def yaml_logging_config(logging_config):
return yaml.dump(logging_config)
async def asgi_app(scope, receive, send):
pass # pragma: nocover
def wsgi_app(environ, start_response):
pass # pragma: nocover
def test_debug_app():
config = Config(app=asgi_app, debug=True, proxy_headers=False)
config.load()
assert config.debug is True
assert isinstance(config.loaded_app, DebugMiddleware)
@pytest.mark.parametrize(
"app, expected_should_reload",
[(asgi_app, False), ("tests.test_config:asgi_app", True)],
)
def test_config_should_reload_is_set(app, expected_should_reload):
config_debug = Config(app=app, debug=True)
assert config_debug.debug is True
assert config_debug.should_reload is expected_should_reload
config_reload = Config(app=app, reload=True)
assert config_reload.reload is True
assert config_reload.should_reload is expected_should_reload
def test_reload_dir_is_set():
config = Config(app=asgi_app, reload=True, reload_dirs="reload_me")
assert config.reload_dirs == ["reload_me"]
def test_wsgi_app():
config = Config(app=wsgi_app, interface="wsgi", proxy_headers=False)
config.load()
assert isinstance(config.loaded_app, WSGIMiddleware)
assert config.interface == "wsgi"
assert config.asgi_version == "3.0"
def test_proxy_headers():
config = Config(app=asgi_app)
config.load()
assert config.proxy_headers is True
assert isinstance(config.loaded_app, ProxyHeadersMiddleware)
def test_app_unimportable_module():
config = Config(app="no.such:app")
with pytest.raises(ImportError):
config.load()
def test_app_unimportable_other(caplog):
config = Config(app="tests.test_config:app")
with pytest.raises(SystemExit):
config.load()
error_messages = [
record.message
for record in caplog.records
if record.name == "uvicorn.error" and record.levelname == "ERROR"
]
assert (
'Error loading ASGI app. Attribute "app" not found in module "tests.test_config".' # noqa: E501
== error_messages.pop(0)
)
def test_app_factory(caplog):
def create_app():
return asgi_app
config = Config(app=create_app, factory=True, proxy_headers=False)
config.load()
assert config.loaded_app is asgi_app
# Flag not passed. In this case, successfully load the app, but issue a warning
# to indicate that an explicit flag is preferred.
caplog.clear()
config = Config(app=create_app, proxy_headers=False)
with caplog.at_level(logging.WARNING):
config.load()
assert config.loaded_app is asgi_app
assert len(caplog.records) == 1
assert "--factory" in caplog.records[0].message
# App not a no-arguments callable.
config = Config(app=asgi_app, factory=True)
with pytest.raises(SystemExit):
config.load()
def test_concrete_http_class():
config = Config(app=asgi_app, http=H11Protocol)
config.load()
assert config.http_protocol_class is H11Protocol
def test_socket_bind():
config = Config(app=asgi_app)
config.load()
sock = config.bind_socket()
assert isinstance(sock, socket.socket)
sock.close()
def test_ssl_config(tls_ca_certificate_pem_path, tls_ca_certificate_private_key_path):
config = Config(
app=asgi_app,
ssl_certfile=tls_ca_certificate_pem_path,
ssl_keyfile=tls_ca_certificate_private_key_path,
)
config.load()
assert config.is_ssl is True
def test_ssl_config_combined(tls_certificate_pem_path):
config = Config(
app=asgi_app,
ssl_certfile=tls_certificate_pem_path,
)
config.load()
assert config.is_ssl is True
def test_ssl_config_h2(tls_certificate_pem_path):
config = Config(
app=asgi_app,
http="h2",
ssl_certfile=tls_certificate_pem_path,
)
config.load()
assert config.is_ssl is True
# TODO: Should we also check HTTP/2-Specific 'ciphers' and 'options' here?
def asgi2_app(scope):
async def asgi(receive, send): # pragma: nocover
pass
return asgi # pragma: nocover
@pytest.mark.parametrize(
"app, expected_interface", [(asgi_app, "3.0"), (asgi2_app, "2.0")]
)
def test_asgi_version(app, expected_interface):
config = Config(app=app)
config.load()
assert config.asgi_version == expected_interface
@pytest.mark.parametrize(
"use_colors, expected",
[
pytest.param(None, None, id="use_colors_not_provided"),
pytest.param("invalid", None, id="use_colors_invalid_value"),
pytest.param(True, True, id="use_colors_enabled"),
pytest.param(False, False, id="use_colors_disabled"),
],
)
def test_log_config_default(mocked_logging_config_module, use_colors, expected):
"""
Test that one can specify the use_colors option when using the default logging
config.
"""
config = Config(app=asgi_app, use_colors=use_colors)
config.load()
mocked_logging_config_module.dictConfig.assert_called_once_with(LOGGING_CONFIG)
(provided_dict_config,), _ = mocked_logging_config_module.dictConfig.call_args
assert provided_dict_config["formatters"]["default"]["use_colors"] == expected
def test_log_config_json(
mocked_logging_config_module, logging_config, json_logging_config, mocker
):
"""
Test that one can load a json config from disk.
"""
mocked_open = mocker.patch(
"uvicorn.config.open", mocker.mock_open(read_data=json_logging_config)
)
config = Config(app=asgi_app, log_config="log_config.json")
config.load()
mocked_open.assert_called_once_with("log_config.json")
mocked_logging_config_module.dictConfig.assert_called_once_with(logging_config)
@pytest.mark.parametrize("config_filename", ["log_config.yml", "log_config.yaml"])
def test_log_config_yaml(
mocked_logging_config_module,
logging_config,
yaml_logging_config,
mocker,
config_filename,
):
"""
Test that one can load a yaml config from disk.
"""
mocked_open = mocker.patch(
"uvicorn.config.open", mocker.mock_open(read_data=yaml_logging_config)
)
config = Config(app=asgi_app, log_config=config_filename)
config.load()
mocked_open.assert_called_once_with(config_filename)
mocked_logging_config_module.dictConfig.assert_called_once_with(logging_config)
def test_log_config_file(mocked_logging_config_module):
"""
Test that one can load a configparser config from disk.
"""
config = Config(app=asgi_app, log_config="log_config")
config.load()
mocked_logging_config_module.fileConfig.assert_called_once_with(
"log_config", disable_existing_loggers=False
)
@pytest.fixture(params=[0, 1])
def web_concurrency(request):
yield request.param
if os.getenv("WEB_CONCURRENCY"):
del os.environ["WEB_CONCURRENCY"]
@pytest.fixture(params=["127.0.0.1", "127.0.0.2"])
def forwarded_allow_ips(request):
yield request.param
if os.getenv("FORWARDED_ALLOW_IPS"):
del os.environ["FORWARDED_ALLOW_IPS"]
def test_env_file(web_concurrency: int, forwarded_allow_ips: str, caplog, tmp_path):
"""
Test that one can load environment variables using an env file.
"""
fp = tmp_path / ".env"
content = (
f"WEB_CONCURRENCY={web_concurrency}\n"
f"FORWARDED_ALLOW_IPS={forwarded_allow_ips}\n"
)
fp.write_text(content)
with caplog.at_level(logging.INFO):
config = Config(app=asgi_app, env_file=fp)
config.load()
assert config.workers == int(os.getenv("WEB_CONCURRENCY"))
assert config.forwarded_allow_ips == os.getenv("FORWARDED_ALLOW_IPS")
assert len(caplog.records) == 1
assert f"Loading environment from '{fp}'" in caplog.records[0].message
@pytest.mark.parametrize(
"access_log, handlers",
[
pytest.param(True, 1, id="access log enabled should have single handler"),
pytest.param(False, 0, id="access log disabled shouldn't have handlers"),
],
)
def test_config_access_log(access_log: bool, handlers: int):
config = Config(app=asgi_app, access_log=access_log)
config.load()
assert len(logging.getLogger("uvicorn.access").handlers) == handlers
assert config.access_log == access_log
@pytest.mark.parametrize("log_level", [5, 10, 20, 30, 40, 50])
def test_config_log_level(log_level):
config = Config(app=asgi_app, log_level=log_level)
config.load()
assert logging.getLogger("uvicorn.error").level == log_level
assert logging.getLogger("uvicorn.access").level == log_level
assert logging.getLogger("uvicorn.asgi").level == log_level
assert config.log_level == log_level
def test_ws_max_size():
config = Config(app=asgi_app, ws_max_size=1000)
config.load()
assert config.ws_max_size == 1000