2017-02-22 17:34:14 +00:00
|
|
|
import random
|
|
|
|
|
2016-11-20 01:48:28 +00:00
|
|
|
from sanic import Sanic
|
|
|
|
from sanic.response import json
|
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_storage():
|
|
|
|
app = Sanic('test_text')
|
|
|
|
|
|
|
|
@app.middleware('request')
|
|
|
|
def store(request):
|
2016-11-20 02:26:03 +00:00
|
|
|
request['user'] = 'sanic'
|
|
|
|
request['sidekick'] = 'tails'
|
|
|
|
del request['sidekick']
|
2016-11-20 01:48:28 +00:00
|
|
|
|
|
|
|
@app.route('/')
|
|
|
|
def handler(request):
|
2017-02-22 17:34:14 +00:00
|
|
|
return json({'user': request.get('user'), 'sidekick': request.get('sidekick')})
|
2016-11-20 01:48:28 +00:00
|
|
|
|
2017-02-14 19:51:20 +00:00
|
|
|
request, response = app.test_client.get('/')
|
2016-11-20 01:48:28 +00:00
|
|
|
|
|
|
|
response_json = loads(response.text)
|
2016-11-20 02:26:03 +00:00
|
|
|
assert response_json['user'] == 'sanic'
|
2016-11-23 17:03:00 +00:00
|
|
|
assert response_json.get('sidekick') is None
|
2017-02-22 17:34:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_app_injection():
|
|
|
|
app = Sanic('test_app_injection')
|
|
|
|
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
|