sanic/tests/test_request_data.py

100 lines
2.7 KiB
Python
Raw Normal View History

import random
2016-11-20 01:48:28 +00:00
from sanic.response import json
2017-05-15 02:49:25 +01:00
2017-05-15 02:49:25 +01:00
try:
from ujson import loads
except ImportError:
from json import loads
2016-11-20 01:48:28 +00:00
def test_custom_context(app):
@app.middleware("request")
def store(request):
request.ctx.user = "sanic"
request.ctx.session = None
@app.route("/")
def handler(request):
# Accessing non-existant key should fail with AttributeError
try:
invalid = request.ctx.missing
except AttributeError as e:
invalid = str(e)
return json(
{
"user": request.ctx.user,
"session": request.ctx.session,
"has_user": hasattr(request.ctx, "user"),
"has_session": hasattr(request.ctx, "session"),
"has_missing": hasattr(request.ctx, "missing"),
"invalid": invalid,
}
)
request, response = app.test_client.get("/")
assert response.json == {
"user": "sanic",
"session": None,
"has_user": True,
"has_session": True,
"has_missing": False,
"invalid": "'types.SimpleNamespace' object has no attribute 'missing'",
}
2016-11-20 01:48:28 +00:00
# Remove this once the deprecated API is abolished.
def test_custom_context_old(app):
2018-12-30 11:18:06 +00:00
@app.middleware("request")
2016-11-20 01:48:28 +00:00
def store(request):
try:
request["foo"]
except KeyError:
pass
2018-12-30 11:18:06 +00:00
request["user"] = "sanic"
sidekick = request.get("sidekick", "tails") # Item missing -> default
request["sidekick"] = sidekick
request["bar"] = request["sidekick"]
2018-12-30 11:18:06 +00:00
del request["sidekick"]
2016-11-20 01:48:28 +00:00
2018-12-30 11:18:06 +00:00
@app.route("/")
2016-11-20 01:48:28 +00:00
def handler(request):
2018-12-30 11:18:06 +00:00
return json(
{
"user": request.get("user"),
"sidekick": request.get("sidekick"),
"has_bar": "bar" in request,
"has_sidekick": "sidekick" in request,
}
2018-12-30 11:18:06 +00:00
)
2016-11-20 01:48:28 +00:00
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/")
2016-11-20 01:48:28 +00:00
assert response.json == {
"user": "sanic",
"sidekick": None,
"has_bar": True,
"has_sidekick": False,
}
2016-11-20 01:48:28 +00:00
response_json = loads(response.text)
2018-12-30 11:18:06 +00:00
assert response_json["user"] == "sanic"
assert response_json.get("sidekick") is None
2018-08-26 15:43:14 +01:00
def test_app_injection(app):
expected = random.choice(range(0, 100))
2018-12-30 11:18:06 +00:00
@app.listener("after_server_start")
async def inject_data(app, loop):
app.injected = expected
2018-12-30 11:18:06 +00:00
@app.get("/")
async def handler(request):
2018-12-30 11:18:06 +00:00
return json({"injected": request.app.injected})
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/")
response_json = loads(response.text)
2018-12-30 11:18:06 +00:00
assert response_json["injected"] == expected