forked from sanic-org/sanic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_request_data.py
80 lines (65 loc) · 2.2 KB
/
test_request_data.py
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
import random
from sanic.response import json
try:
from ujson import loads
except ImportError:
from json import loads
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,
}
)
@app.middleware("response")
def modify(request, response):
# Using response-middleware to access request ctx
try:
user = request.ctx.user
except AttributeError as e:
user = str(e)
try:
invalid = request.ctx.missing
except AttributeError as e:
invalid = str(e)
j = loads(response.body)
j["response_mw_valid"] = user
j["response_mw_invalid"] = invalid
return json(j)
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'",
"response_mw_valid": "sanic",
"response_mw_invalid": "'types.SimpleNamespace' object has no attribute 'missing'",
}
def test_app_injection(app):
expected = random.choice(range(0, 100))
@app.listener("after_server_start")
async def inject_data(app, loop):
app.injected = expected
@app.get("/")
async def handler(request):
return json({"injected": request.app.injected})
request, response = app.test_client.get("/")
response_json = loads(response.text)
assert response_json["injected"] == expected