2017-09-11 08:17:33 +01:00
|
|
|
from json import JSONDecodeError
|
|
|
|
from sanic import Sanic
|
|
|
|
import asyncio
|
2017-09-12 04:40:43 +01:00
|
|
|
from asyncio import sleep as aio_sleep
|
2017-09-11 08:17:33 +01:00
|
|
|
from sanic.response import text
|
|
|
|
from sanic.config import Config
|
2017-09-12 04:09:42 +01:00
|
|
|
from sanic import server
|
2017-09-11 08:17:33 +01:00
|
|
|
import aiohttp
|
|
|
|
from aiohttp import TCPConnector
|
2017-11-27 18:56:05 +00:00
|
|
|
from sanic.testing import SanicTestClient, HOST
|
2017-09-11 08:17:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ReuseableTCPConnector(TCPConnector):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(ReuseableTCPConnector, self).__init__(*args, **kwargs)
|
2017-09-12 04:09:42 +01:00
|
|
|
self.old_proto = None
|
2017-09-11 08:17:33 +01:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
2018-02-27 06:18:21 +00:00
|
|
|
def connect(self, req, traces=None):
|
2017-09-12 04:09:42 +01:00
|
|
|
new_conn = yield from super(ReuseableTCPConnector, self)\
|
2018-02-27 06:18:21 +00:00
|
|
|
.connect(req, traces=traces)
|
2017-09-12 04:09:42 +01:00
|
|
|
if self.old_proto is not None:
|
2017-09-13 01:18:36 +01:00
|
|
|
if self.old_proto != new_conn._protocol:
|
2017-09-12 04:09:42 +01:00
|
|
|
raise RuntimeError(
|
|
|
|
"We got a new connection, wanted the same one!")
|
2017-09-13 01:18:36 +01:00
|
|
|
print(new_conn.__dict__)
|
|
|
|
self.old_proto = new_conn._protocol
|
2017-09-12 04:09:42 +01:00
|
|
|
return new_conn
|
2017-09-11 08:17:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ReuseableSanicTestClient(SanicTestClient):
|
2017-09-12 04:09:42 +01:00
|
|
|
def __init__(self, app, loop=None):
|
2017-11-27 18:56:05 +00:00
|
|
|
super().__init__(app, port=app.test_port)
|
2017-09-12 04:09:42 +01:00
|
|
|
if loop is None:
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
self._loop = loop
|
|
|
|
self._server = None
|
2017-09-11 08:17:33 +01:00
|
|
|
self._tcp_connector = None
|
|
|
|
self._session = None
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
# Copied from SanicTestClient, but with some changes to reuse the
|
|
|
|
# same loop for the same app.
|
2017-09-11 08:17:33 +01:00
|
|
|
def _sanic_endpoint_test(
|
|
|
|
self, method='get', uri='/', gather_request=True,
|
|
|
|
debug=False, server_kwargs={},
|
|
|
|
*request_args, **request_kwargs):
|
2017-09-12 04:09:42 +01:00
|
|
|
loop = self._loop
|
2017-09-11 08:17:33 +01:00
|
|
|
results = [None, None]
|
|
|
|
exceptions = []
|
2017-09-12 04:09:42 +01:00
|
|
|
do_kill_server = request_kwargs.pop('end_server', False)
|
2017-09-11 08:17:33 +01:00
|
|
|
if gather_request:
|
|
|
|
def _collect_request(request):
|
|
|
|
if results[0] is None:
|
|
|
|
results[0] = request
|
|
|
|
|
|
|
|
self.app.request_middleware.appendleft(_collect_request)
|
|
|
|
|
|
|
|
@self.app.listener('after_server_start')
|
2017-09-12 04:09:42 +01:00
|
|
|
async def _collect_response(loop):
|
2017-09-11 08:17:33 +01:00
|
|
|
try:
|
2017-09-12 04:09:42 +01:00
|
|
|
if do_kill_server:
|
|
|
|
request_kwargs['end_session'] = True
|
2017-09-11 08:17:33 +01:00
|
|
|
response = await self._local_request(
|
|
|
|
method, uri, *request_args,
|
|
|
|
**request_kwargs)
|
|
|
|
results[-1] = response
|
2017-09-12 04:40:43 +01:00
|
|
|
except Exception as e2:
|
2017-09-13 01:18:36 +01:00
|
|
|
import traceback
|
|
|
|
traceback.print_tb(e2.__traceback__)
|
2017-09-12 04:40:43 +01:00
|
|
|
exceptions.append(e2)
|
2017-11-27 18:56:05 +00:00
|
|
|
# Don't stop here! self.app.stop()
|
2017-09-12 04:09:42 +01:00
|
|
|
|
|
|
|
if self._server is not None:
|
|
|
|
_server = self._server
|
|
|
|
else:
|
|
|
|
_server_co = self.app.create_server(host=HOST, debug=debug,
|
2017-11-27 18:56:05 +00:00
|
|
|
port=self.app.test_port,
|
|
|
|
**server_kwargs)
|
2017-09-12 04:09:42 +01:00
|
|
|
|
|
|
|
server.trigger_events(
|
|
|
|
self.app.listeners['before_server_start'], loop)
|
2017-09-11 08:17:33 +01:00
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
try:
|
|
|
|
loop._stopping = False
|
|
|
|
http_server = loop.run_until_complete(_server_co)
|
2017-09-12 04:40:43 +01:00
|
|
|
except Exception as e1:
|
2017-09-13 01:18:36 +01:00
|
|
|
import traceback
|
|
|
|
traceback.print_tb(e1.__traceback__)
|
2017-09-12 04:40:43 +01:00
|
|
|
raise e1
|
2017-09-12 04:09:42 +01:00
|
|
|
self._server = _server = http_server
|
|
|
|
server.trigger_events(
|
2017-11-27 18:56:05 +00:00
|
|
|
self.app.listeners['after_server_start'], loop)
|
2017-09-11 08:17:33 +01:00
|
|
|
self.app.listeners['after_server_start'].pop()
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
if do_kill_server:
|
|
|
|
try:
|
|
|
|
_server.close()
|
|
|
|
self._server = None
|
|
|
|
loop.run_until_complete(_server.wait_closed())
|
|
|
|
self.app.stop()
|
2017-09-12 04:40:43 +01:00
|
|
|
except Exception as e3:
|
2017-09-13 01:18:36 +01:00
|
|
|
import traceback
|
|
|
|
traceback.print_tb(e3.__traceback__)
|
|
|
|
exceptions.append(e3)
|
2017-09-11 08:17:33 +01:00
|
|
|
if exceptions:
|
|
|
|
raise ValueError(
|
|
|
|
"Exception during request: {}".format(exceptions))
|
|
|
|
|
|
|
|
if gather_request:
|
2017-09-12 04:09:42 +01:00
|
|
|
self.app.request_middleware.pop()
|
2017-09-11 08:17:33 +01:00
|
|
|
try:
|
|
|
|
request, response = results
|
|
|
|
return request, response
|
|
|
|
except:
|
|
|
|
raise ValueError(
|
|
|
|
"Request and response object expected, got ({})".format(
|
|
|
|
results))
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
return results[-1]
|
|
|
|
except:
|
|
|
|
raise ValueError(
|
|
|
|
"Request object expected, got ({})".format(results))
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
# Copied from SanicTestClient, but with some changes to reuse the
|
|
|
|
# same TCPConnection and the sane ClientSession more than once.
|
|
|
|
# Note, you cannot use the same session if you are in a _different_
|
|
|
|
# loop, so the changes above are required too.
|
2017-09-11 08:17:33 +01:00
|
|
|
async def _local_request(self, method, uri, cookies=None, *args,
|
|
|
|
**kwargs):
|
2017-09-12 04:09:42 +01:00
|
|
|
request_keepalive = kwargs.pop('request_keepalive',
|
|
|
|
Config.KEEP_ALIVE_TIMEOUT)
|
2017-09-11 08:17:33 +01:00
|
|
|
if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://' '//')):
|
|
|
|
url = uri
|
|
|
|
else:
|
|
|
|
url = 'http://{host}:{port}{uri}'.format(
|
2017-11-27 18:56:05 +00:00
|
|
|
host=HOST, port=self.port, uri=uri)
|
2017-09-12 04:09:42 +01:00
|
|
|
do_kill_session = kwargs.pop('end_session', False)
|
2017-09-11 08:17:33 +01:00
|
|
|
if self._session:
|
|
|
|
session = self._session
|
|
|
|
else:
|
|
|
|
if self._tcp_connector:
|
|
|
|
conn = self._tcp_connector
|
|
|
|
else:
|
2017-09-12 04:09:42 +01:00
|
|
|
conn = ReuseableTCPConnector(verify_ssl=False,
|
2017-09-12 04:40:43 +01:00
|
|
|
loop=self._loop,
|
2017-09-12 04:09:42 +01:00
|
|
|
keepalive_timeout=
|
|
|
|
request_keepalive)
|
2017-09-11 08:17:33 +01:00
|
|
|
self._tcp_connector = conn
|
|
|
|
session = aiohttp.ClientSession(cookies=cookies,
|
2017-09-12 04:40:43 +01:00
|
|
|
connector=conn,
|
|
|
|
loop=self._loop)
|
2017-09-11 08:17:33 +01:00
|
|
|
self._session = session
|
|
|
|
|
|
|
|
async with getattr(session, method.lower())(
|
|
|
|
url, *args, **kwargs) as response:
|
|
|
|
try:
|
|
|
|
response.text = await response.text()
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
response.text = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
response.json = await response.json()
|
|
|
|
except (JSONDecodeError,
|
|
|
|
UnicodeDecodeError,
|
|
|
|
aiohttp.ClientResponseError):
|
|
|
|
response.json = None
|
|
|
|
|
|
|
|
response.body = await response.read()
|
2017-09-12 04:09:42 +01:00
|
|
|
if do_kill_session:
|
2018-02-27 06:18:21 +00:00
|
|
|
await session.close()
|
2017-09-12 04:09:42 +01:00
|
|
|
self._session = None
|
|
|
|
return response
|
2017-09-11 08:17:33 +01:00
|
|
|
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
Config.KEEP_ALIVE_TIMEOUT = 2
|
2017-09-11 08:17:33 +01:00
|
|
|
Config.KEEP_ALIVE = True
|
2017-09-12 04:09:42 +01:00
|
|
|
keep_alive_timeout_app_reuse = Sanic('test_ka_timeout_reuse')
|
|
|
|
keep_alive_app_client_timeout = Sanic('test_ka_client_timeout')
|
|
|
|
keep_alive_app_server_timeout = Sanic('test_ka_server_timeout')
|
|
|
|
|
|
|
|
|
|
|
|
@keep_alive_timeout_app_reuse.route('/1')
|
|
|
|
async def handler1(request):
|
|
|
|
return text('OK')
|
2017-09-11 08:17:33 +01:00
|
|
|
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
@keep_alive_app_client_timeout.route('/1')
|
|
|
|
async def handler2(request):
|
2017-09-11 08:17:33 +01:00
|
|
|
return text('OK')
|
|
|
|
|
|
|
|
|
2017-09-12 04:09:42 +01:00
|
|
|
@keep_alive_app_server_timeout.route('/1')
|
|
|
|
async def handler3(request):
|
|
|
|
return text('OK')
|
|
|
|
|
|
|
|
|
2018-02-27 06:18:21 +00:00
|
|
|
def test_keep_alive_timeout_reuse():
|
|
|
|
"""If the server keep-alive timeout and client keep-alive timeout are
|
|
|
|
both longer than the delay, the client _and_ server will successfully
|
|
|
|
reuse the existing connection."""
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
client = ReuseableSanicTestClient(keep_alive_timeout_app_reuse, loop)
|
|
|
|
headers = {
|
|
|
|
'Connection': 'keep-alive'
|
|
|
|
}
|
|
|
|
request, response = client.get('/1', headers=headers)
|
|
|
|
assert response.status == 200
|
|
|
|
assert response.text == 'OK'
|
|
|
|
loop.run_until_complete(aio_sleep(1))
|
|
|
|
request, response = client.get('/1', end_server=True)
|
|
|
|
assert response.status == 200
|
|
|
|
assert response.text == 'OK'
|
|
|
|
|
|
|
|
|
|
|
|
def test_keep_alive_client_timeout():
|
|
|
|
"""If the server keep-alive timeout is longer than the client
|
|
|
|
keep-alive timeout, client will try to create a new connection here."""
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
client = ReuseableSanicTestClient(keep_alive_app_client_timeout,
|
|
|
|
loop)
|
|
|
|
headers = {
|
|
|
|
'Connection': 'keep-alive'
|
|
|
|
}
|
|
|
|
request, response = client.get('/1', headers=headers,
|
|
|
|
request_keepalive=1)
|
|
|
|
assert response.status == 200
|
|
|
|
assert response.text == 'OK'
|
|
|
|
loop.run_until_complete(aio_sleep(2))
|
|
|
|
exception = None
|
|
|
|
try:
|
|
|
|
request, response = client.get('/1', end_server=True,
|
|
|
|
request_keepalive=1)
|
|
|
|
except ValueError as e:
|
|
|
|
exception = e
|
|
|
|
assert exception is not None
|
|
|
|
assert isinstance(exception, ValueError)
|
|
|
|
assert "got a new connection" in exception.args[0]
|
|
|
|
|
|
|
|
|
|
|
|
def test_keep_alive_server_timeout():
|
|
|
|
"""If the client keep-alive timeout is longer than the server
|
|
|
|
keep-alive timeout, the client will either a 'Connection reset' error
|
|
|
|
_or_ a new connection. Depending on how the event-loop handles the
|
|
|
|
broken server connection."""
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
client = ReuseableSanicTestClient(keep_alive_app_server_timeout,
|
|
|
|
loop)
|
|
|
|
headers = {
|
|
|
|
'Connection': 'keep-alive'
|
|
|
|
}
|
|
|
|
request, response = client.get('/1', headers=headers,
|
|
|
|
request_keepalive=60)
|
|
|
|
assert response.status == 200
|
|
|
|
assert response.text == 'OK'
|
|
|
|
loop.run_until_complete(aio_sleep(3))
|
|
|
|
exception = None
|
|
|
|
try:
|
|
|
|
request, response = client.get('/1', request_keepalive=60,
|
|
|
|
end_server=True)
|
|
|
|
except ValueError as e:
|
|
|
|
exception = e
|
|
|
|
assert exception is not None
|
|
|
|
assert isinstance(exception, ValueError)
|
|
|
|
assert "Connection reset" in exception.args[0] or \
|
|
|
|
"got a new connection" in exception.args[0]
|
2017-09-12 04:09:42 +01:00
|
|
|
|