forked from aio-libs/aiohttp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_worker.py
More file actions
297 lines (232 loc) · 8.54 KB
/
Copy pathtest_worker.py
File metadata and controls
297 lines (232 loc) · 8.54 KB
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
"""Tests for aiohttp/worker.py"""
import asyncio
import pathlib
import ssl
from unittest import mock
import pytest
from aiohttp import helpers
from aiohttp.test_utils import make_mocked_coro
base_worker = pytest.importorskip('aiohttp.worker')
try:
import uvloop
except ImportError:
uvloop = None
WRONG_LOG_FORMAT = '%a "%{Referrer}i" %(h)s %(l)s %s'
ACCEPTABLE_LOG_FORMAT = '%a "%{Referrer}i" %s'
class BaseTestWorker:
def __init__(self):
self.servers = {}
self.exit_code = 0
self.cfg = mock.Mock()
self.cfg.graceful_timeout = 100
class AsyncioWorker(BaseTestWorker, base_worker.GunicornWebWorker):
pass
PARAMS = [AsyncioWorker]
if uvloop is not None:
class UvloopWorker(BaseTestWorker, base_worker.GunicornUVLoopWebWorker):
pass
PARAMS.append(UvloopWorker)
@pytest.fixture(params=PARAMS)
def worker(request):
ret = request.param()
ret.notify = mock.Mock()
return ret
def test_init_process(worker):
with mock.patch('aiohttp.worker.asyncio') as m_asyncio:
try:
worker.init_process()
except TypeError:
pass
assert m_asyncio.get_event_loop.return_value.close.called
assert m_asyncio.new_event_loop.called
assert m_asyncio.set_event_loop.called
def test_run(worker, loop):
worker.wsgi = mock.Mock()
worker.loop = loop
worker._run = mock.Mock(
wraps=asyncio.coroutine(lambda: None))
worker.wsgi.startup = make_mocked_coro(None)
with pytest.raises(SystemExit):
worker.run()
assert worker._run.called
worker.wsgi.startup.assert_called_once_with()
assert loop.is_closed()
def test_handle_quit(worker):
worker.handle_quit(object(), object())
assert not worker.alive
assert worker.exit_code == 0
def test_handle_abort(worker):
worker.handle_abort(object(), object())
assert not worker.alive
assert worker.exit_code == 1
def test_init_signals(worker):
worker.loop = mock.Mock()
worker.init_signals()
assert worker.loop.add_signal_handler.called
def test_make_handler(worker, mocker):
worker.wsgi = mock.Mock()
worker.loop = mock.Mock()
worker.log = mock.Mock()
worker.cfg = mock.Mock()
worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT
mocker.spy(worker, '_get_valid_log_format')
f = worker.make_handler(worker.wsgi)
assert f is worker.wsgi.make_handler.return_value
assert worker._get_valid_log_format.called
@pytest.mark.parametrize('source,result', [
(ACCEPTABLE_LOG_FORMAT, ACCEPTABLE_LOG_FORMAT),
(AsyncioWorker.DEFAULT_GUNICORN_LOG_FORMAT,
AsyncioWorker.DEFAULT_AIOHTTP_LOG_FORMAT),
])
def test__get_valid_log_format_ok(worker, source, result):
assert result == worker._get_valid_log_format(source)
def test__get_valid_log_format_exc(worker):
with pytest.raises(ValueError) as exc:
worker._get_valid_log_format(WRONG_LOG_FORMAT)
assert '%(name)s' in str(exc)
@asyncio.coroutine
def test__run_ok(worker, loop):
worker.ppid = 1
worker.alive = True
worker.servers = {}
sock = mock.Mock()
sock.cfg_addr = ('localhost', 8080)
worker.sockets = [sock]
worker.wsgi = mock.Mock()
worker.close = make_mocked_coro(None)
worker.log = mock.Mock()
worker.loop = loop
loop.create_server = make_mocked_coro(sock)
worker.wsgi.make_handler.return_value.requests_count = 1
worker.cfg.max_requests = 100
worker.cfg.is_ssl = True
worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT
ssl_context = mock.Mock()
with mock.patch('ssl.SSLContext', return_value=ssl_context):
with mock.patch('aiohttp.worker.asyncio') as m_asyncio:
m_asyncio.sleep = mock.Mock(
wraps=asyncio.coroutine(lambda *a, **kw: None))
yield from worker._run()
worker.notify.assert_called_with()
worker.log.info.assert_called_with("Parent changed, shutting down: %s",
worker)
args, kwargs = loop.create_server.call_args
assert 'ssl' in kwargs
ctx = kwargs['ssl']
assert ctx is ssl_context
@asyncio.coroutine
def test__run_exc(worker, loop):
with mock.patch('aiohttp.worker.os') as m_os:
m_os.getpid.return_value = 1
m_os.getppid.return_value = 1
handler = mock.Mock()
handler.requests_count = 0
worker.servers = {mock.Mock(): handler}
worker.ppid = 1
worker.alive = True
worker.sockets = []
worker.log = mock.Mock()
worker.loop = loop
worker.cfg.is_ssl = False
worker.cfg.max_redirects = 0
worker.cfg.max_requests = 100
with mock.patch('aiohttp.worker.asyncio.sleep') as m_sleep:
slp = helpers.create_future(loop)
slp.set_exception(KeyboardInterrupt)
m_sleep.return_value = slp
worker.close = make_mocked_coro(None)
yield from worker._run()
m_sleep.assert_called_with(1.0, loop=loop)
worker.close.assert_called_with()
@asyncio.coroutine
def test_close(worker, loop):
srv = mock.Mock()
srv.wait_closed = make_mocked_coro(None)
handler = mock.Mock()
worker.servers = {srv: handler}
worker.log = mock.Mock()
worker.loop = loop
app = worker.wsgi = mock.Mock()
app.cleanup = make_mocked_coro(None)
handler.connections = [object()]
handler.finish_connections.return_value = helpers.create_future(loop)
handler.finish_connections.return_value.set_result(1)
app.shutdown.return_value = helpers.create_future(loop)
app.shutdown.return_value.set_result(None)
yield from worker.close()
app.shutdown.assert_called_with()
app.cleanup.assert_called_with()
handler.finish_connections.assert_called_with(timeout=95.0)
srv.close.assert_called_with()
assert worker.servers is None
yield from worker.close()
@asyncio.coroutine
def test__run_ok_no_max_requests(worker, loop):
worker.ppid = 1
worker.alive = True
worker.servers = {}
sock = mock.Mock()
sock.cfg_addr = ('localhost', 8080)
worker.sockets = [sock]
worker.wsgi = mock.Mock()
worker.close = make_mocked_coro(None)
worker.log = mock.Mock()
worker.loop = loop
loop.create_server = make_mocked_coro(sock)
worker.wsgi.make_handler.return_value.requests_count = 1
worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT
worker.cfg.max_requests = 0
worker.cfg.is_ssl = True
ssl_context = mock.Mock()
with mock.patch('ssl.SSLContext', return_value=ssl_context):
with mock.patch('aiohttp.worker.asyncio') as m_asyncio:
m_asyncio.sleep = mock.Mock(
wraps=asyncio.coroutine(lambda *a, **kw: None))
yield from worker._run()
worker.notify.assert_called_with()
worker.log.info.assert_called_with("Parent changed, shutting down: %s",
worker)
args, kwargs = loop.create_server.call_args
assert 'ssl' in kwargs
ctx = kwargs['ssl']
assert ctx is ssl_context
@asyncio.coroutine
def test__run_ok_max_requests_exceeded(worker, loop):
worker.ppid = 1
worker.alive = True
worker.servers = {}
sock = mock.Mock()
sock.cfg_addr = ('localhost', 8080)
worker.sockets = [sock]
worker.wsgi = mock.Mock()
worker.close = make_mocked_coro(None)
worker.log = mock.Mock()
worker.loop = loop
loop.create_server = make_mocked_coro(sock)
worker.wsgi.make_handler.return_value.requests_count = 15
worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT
worker.cfg.max_requests = 10
worker.cfg.is_ssl = True
ssl_context = mock.Mock()
with mock.patch('ssl.SSLContext', return_value=ssl_context):
with mock.patch('aiohttp.worker.asyncio') as m_asyncio:
m_asyncio.sleep = mock.Mock(
wraps=asyncio.coroutine(lambda *a, **kw: None))
yield from worker._run()
worker.notify.assert_called_with()
worker.log.info.assert_called_with("Max requests, shutting down: %s",
worker)
args, kwargs = loop.create_server.call_args
assert 'ssl' in kwargs
ctx = kwargs['ssl']
assert ctx is ssl_context
def test__create_ssl_context_without_certs_and_ciphers(worker):
here = pathlib.Path(__file__).parent
worker.cfg.ssl_version = ssl.PROTOCOL_SSLv23
worker.cfg.cert_reqs = ssl.CERT_OPTIONAL
worker.cfg.certfile = str(here / 'sample.crt')
worker.cfg.keyfile = str(here / 'sample.key')
worker.cfg.ca_certs = None
worker.cfg.ciphers = None
crt = worker._create_ssl_context(worker.cfg)
assert isinstance(crt, ssl.SSLContext)