Skip to content

Commit

Permalink
Merge pull request sanic-org#1146 from yunstanford/upgrade-test-client
Browse files Browse the repository at this point in the history
Upgrade test client
  • Loading branch information
r0fls authored Mar 2, 2018
2 parents 7f36d20 + a2fc371 commit 3619b07
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 34 deletions.
13 changes: 12 additions & 1 deletion sanic/testing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import traceback
from json import JSONDecodeError

from sanic.log import logger
from sanic.exceptions import MethodNotSupported
from sanic.response import text


HOST = '127.0.0.1'
PORT = 42101
Expand Down Expand Up @@ -54,6 +56,15 @@ def _collect_request(request):
results[0] = request
self.app.request_middleware.appendleft(_collect_request)

@self.app.exception(MethodNotSupported)
async def error_handler(request, exception):
if request.method in ['HEAD', 'PATCH', 'PUT', 'DELETE']:
return text(
'', exception.status_code, headers=exception.headers
)
else:
return self.app.error_handler.default(request, exception)

@self.app.listener('after_server_start')
async def _collect_response(sanic, loop):
try:
Expand Down
37 changes: 25 additions & 12 deletions tests/test_keep_alive_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,30 @@ def __init__(self, *args, **kwargs):
super(ReuseableTCPConnector, self).__init__(*args, **kwargs)
self.old_proto = None

@asyncio.coroutine
def connect(self, req):
new_conn = yield from super(ReuseableTCPConnector, self)\
.connect(req)
if self.old_proto is not None:
if self.old_proto != new_conn._protocol:
raise RuntimeError(
"We got a new connection, wanted the same one!")
print(new_conn.__dict__)
self.old_proto = new_conn._protocol
return new_conn
if aiohttp.__version__ >= '3.0':

async def connect(self, req, traces=None):
new_conn = await super(ReuseableTCPConnector, self)\
.connect(req, traces=traces)
if self.old_proto is not None:
if self.old_proto != new_conn._protocol:
raise RuntimeError(
"We got a new connection, wanted the same one!")
print(new_conn.__dict__)
self.old_proto = new_conn._protocol
return new_conn
else:

async def connect(self, req):
new_conn = await super(ReuseableTCPConnector, self)\
.connect(req)
if self.old_proto is not None:
if self.old_proto != new_conn._protocol:
raise RuntimeError(
"We got a new connection, wanted the same one!")
print(new_conn.__dict__)
self.old_proto = new_conn._protocol
return new_conn


class ReuseableSanicTestClient(SanicTestClient):
Expand Down Expand Up @@ -168,7 +181,7 @@ async def _local_request(self, method, uri, cookies=None, *args,

response.body = await response.read()
if do_kill_session:
session.close()
await session.close()
self._session = None
return response

Expand Down
52 changes: 32 additions & 20 deletions tests/test_request_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,18 @@ def __getattr__(self, item):
acting_as = self._acting_as
return getattr(acting_as, item)

@asyncio.coroutine
def start(self, connection, read_until_eof=False):
async def start(self, connection, read_until_eof=False):
if self.send_task is None:
raise RuntimeError("do a send() before you do a start()")
resp = yield from self.send_task
resp = await self.send_task
self.send_task = None
self.resp = resp
self._acting_as = self.resp
self.orig_start = getattr(resp, 'start')

try:
ret = yield from self.orig_start(connection,
read_until_eof)
ret = await self.orig_start(connection,
read_until_eof)
except Exception as e:
raise e
return ret
Expand All @@ -51,12 +50,11 @@ def close(self):
if self.send_task is not None:
self.send_task.cancel()

@asyncio.coroutine
def delayed_send(self, *args, **kwargs):
async def delayed_send(self, *args, **kwargs):
req = self.req
if self.delay and self.delay > 0:
#sync_sleep(self.delay)
_ = yield from asyncio.sleep(self.delay)
await asyncio.sleep(self.delay)
t = req.loop.time()
print("sending at {}".format(t), flush=True)
conn = next(iter(args)) # first arg is connection
Expand All @@ -80,18 +78,32 @@ def __init__(self, *args, **kwargs):
self._post_connect_delay = _post_connect_delay
self._pre_request_delay = _pre_request_delay

@asyncio.coroutine
def connect(self, req):
d_req = DelayableTCPConnector.\
RequestContextManager(req, self._pre_request_delay)
conn = yield from super(DelayableTCPConnector, self).connect(req)
if self._post_connect_delay and self._post_connect_delay > 0:
_ = yield from asyncio.sleep(self._post_connect_delay,
loop=self._loop)
req.send = d_req.send
t = req.loop.time()
print("Connected at {}".format(t), flush=True)
return conn
if aiohttp.__version__ >= '3.0':

async def connect(self, req, traces=None):
d_req = DelayableTCPConnector.\
RequestContextManager(req, self._pre_request_delay)
conn = await super(DelayableTCPConnector, self).connect(req, traces=traces)
if self._post_connect_delay and self._post_connect_delay > 0:
await asyncio.sleep(self._post_connect_delay,
loop=self._loop)
req.send = d_req.send
t = req.loop.time()
print("Connected at {}".format(t), flush=True)
return conn
else:

async def connect(self, req):
d_req = DelayableTCPConnector.\
RequestContextManager(req, self._pre_request_delay)
conn = await super(DelayableTCPConnector, self).connect(req)
if self._post_connect_delay and self._post_connect_delay > 0:
await asyncio.sleep(self._post_connect_delay,
loop=self._loop)
req.send = d_req.send
t = req.loop.time()
print("Connected at {}".format(t), flush=True)
return conn


class DelayableSanicTestClient(SanicTestClient):
Expand Down
9 changes: 9 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ async def test(request):
request, response = app.test_client.head('/')
assert response.headers['Allow'] == 'GET'

request, response = app.test_client.post('/')
assert response.headers['Allow'] == 'GET'


@app.post('/')
async def test(request):
return response.json({'hello': 'world'})
Expand All @@ -54,6 +58,11 @@ async def test(request):
assert set(response.headers['Allow'].split(', ')) == set(['GET', 'POST'])
assert response.headers['Content-Length'] == '0'

request, response = app.test_client.patch('/')
assert response.status == 405
assert set(response.headers['Allow'].split(', ')) == set(['GET', 'POST'])
assert response.headers['Content-Length'] == '0'


@pytest.fixture
def json_app():
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ deps =
pytest-sanic
pytest-sugar
pytest-xdist
aiohttp==1.3.5
aiohttp>=2.3
chardet<=2.3.0
beautifulsoup4
gunicorn
Expand Down

0 comments on commit 3619b07

Please sign in to comment.