2018-11-12 15:11:41 +00:00
|
|
|
from io import BytesIO
|
|
|
|
|
2020-03-25 12:35:09 +00:00
|
|
|
import pytest
|
|
|
|
|
2018-11-12 15:11:41 +00:00
|
|
|
from sanic import Sanic
|
|
|
|
from sanic.request import Request
|
|
|
|
from sanic.response import json_dumps, text
|
|
|
|
|
|
|
|
|
2020-03-25 12:35:09 +00:00
|
|
|
class DeprecCustomRequest(Request):
|
|
|
|
"""Using old API should fail when receive_body is not implemented"""
|
|
|
|
def body_push(self, data):
|
|
|
|
pass
|
|
|
|
|
2018-11-12 15:11:41 +00:00
|
|
|
class CustomRequest(Request):
|
2020-03-01 14:34:20 +00:00
|
|
|
"""Alternative implementation for loading body (non-streaming handlers)"""
|
|
|
|
async def receive_body(self):
|
|
|
|
buffer = BytesIO()
|
|
|
|
async for data in self.stream:
|
|
|
|
buffer.write(data)
|
|
|
|
self.body = buffer.getvalue().upper()
|
|
|
|
buffer.close()
|
2020-03-25 12:35:09 +00:00
|
|
|
# Old API may be implemented but won't be used here
|
|
|
|
def body_push(self, data):
|
|
|
|
assert False
|
|
|
|
|
|
|
|
|
|
|
|
def test_deprecated_custom_request():
|
|
|
|
with pytest.raises(NotImplementedError):
|
|
|
|
Sanic(request_class=DeprecCustomRequest)
|
2018-11-12 15:11:41 +00:00
|
|
|
|
|
|
|
def test_custom_request():
|
2020-03-26 04:42:46 +00:00
|
|
|
app = Sanic(name=__name__, request_class=CustomRequest)
|
2018-11-12 15:11:41 +00:00
|
|
|
|
|
|
|
@app.route("/post", methods=["POST"])
|
|
|
|
async def post_handler(request):
|
|
|
|
return text("OK")
|
|
|
|
|
|
|
|
@app.route("/get")
|
|
|
|
async def get_handler(request):
|
|
|
|
return text("OK")
|
|
|
|
|
|
|
|
payload = {"test": "OK"}
|
|
|
|
headers = {"content-type": "application/json"}
|
|
|
|
|
|
|
|
request, response = app.test_client.post(
|
|
|
|
"/post", data=json_dumps(payload), headers=headers
|
|
|
|
)
|
|
|
|
|
2020-03-01 14:34:20 +00:00
|
|
|
assert request.body == b'{"TEST":"OK"}'
|
|
|
|
assert request.json.get("TEST") == "OK"
|
2018-11-12 15:11:41 +00:00
|
|
|
assert response.text == "OK"
|
|
|
|
assert response.status == 200
|
|
|
|
|
|
|
|
request, response = app.test_client.get("/get")
|
|
|
|
|
|
|
|
assert request.body == b""
|
|
|
|
assert response.text == "OK"
|
|
|
|
assert response.status == 200
|